def contribute_to_context(self, context, request, *args, **kwargs):
     current_survey = None
     if settings.CURRENT_SURVEY:
         current_survey = Survey.objects.current_survey()
     context.update({
         'current_survey': current_survey,
         'current_community': str(site_mappers.get_current_mapper()),
         'mapper_name': site_mappers.get_current_mapper().map_area,
         'CONFIRMED': CONFIRMED})
     return context
    def setUp(self):

        site_mappers.autodiscover()

        try:
            site_lab_profiles.register(BcppSubjectProfile())
        except AlreadyRegisteredLabProfile:
            pass
        bcpp_app_configuration.prepare()
        site_lab_tracker.autodiscover()
        BcppSubjectVisitSchedule().build()
        site_rule_groups.autodiscover()

        self.household_structure = None
        self.registered_subject = None
        self.representative_eligibility = None
        self.study_site = None
        self.intervention = None

        self.community = site_mappers.get_current_mapper().map_area
        self.study_site = StudySite.objects.get(
            site_code=site_mappers.get_current_mapper().map_code)
        self.site_code = self.study_site
        self.intervention = site_mappers.get_current_mapper().intervention
        self.survey1 = Survey.objects.get(
            survey_name='BCPP Year 1')  # see app_configuration
        self.survey2 = Survey.objects.get(
            survey_name='BCPP Year 2')  # see app_configuration
        plot = PlotFactory(community=self.community,
                           household_count=1,
                           status='residential_habitable')
        household = Household.objects.get(plot=plot)
        self.create_baseline(household)

        self.data = {
            'household_member': self.household_member_male.id,
            'report_datetime': datetime.today(),
            'first_name': 'SETS',
            'initials': 'SA',
            'dob': datetime.today() + relativedelta(years=-20),
            'guardian': NO,
            'gender': MALE,
            'has_identity': YES,
            'identity': '317918515',
            'identity_type': 'OMANG',
            'citizen': YES,
            'part_time_resident': YES,
            'literacy': YES,
            'guardian': YES,
            'inability_to_participate': 'N/A',
            'hiv_status': 'NEG',
            'legal_marriage': 'N/A',
            'marriage_certificate': 'N/A'
        }
Example #3
0
    def study_site_setup(self):
        """Returns a dictionary of the the site code and site name.

        Plot checks are bypassed if:
            * CURRENT_COMMUNITY == 'BHP'
            * SITE_CODE=='00'
            * DEVICE_ID in [device.central_server_id, ]

        Confirms:
            * mapper name an code match that in settings.
            * plot identifier community prefix is the same as the site code.
        """
        try:
            map_code = site_mappers.get_current_mapper().map_code
        except AttributeError:
            map_code = '00'
        if self.confirm_site_code_in_settings:  # default is True, set to False for tests
            if map_code != settings.SITE_CODE:
                raise ImproperlyConfigured(
                    'Community code \'{}\' returned by mapper does not equal '
                    'settings.SITE_CODE \'{}\'.'.format(
                        map_code, settings.SITE_CODE))
        try:
            map_area = site_mappers.get_current_mapper().map_area
        except AttributeError:
            map_area = 'BHP'
        if self.confirm_community_in_settings:  # default is True, set to False for tests
            if map_area != settings.CURRENT_COMMUNITY:
                raise ImproperlyConfigured(
                    'Current community {} returned by mapper does not equal '
                    'settings.CURRENT_COMMUNITY {}.'.format(
                        map_area, settings.CURRENT_COMMUNITY))
        try:
            community_check = settings.CURRENT_COMMUNITY_CHECK
        except AttributeError:
            community_check = True
        if str(device) not in [
                device.central_server_id,
        ] and community_check:
            try:
                if Plot.objects.all()[0].plot_identifier[:2] != map_code:
                    raise ImproperlyConfigured(
                        'Community code {2} does not correspond with community code segment '
                        'in Plot identifier {0}. Got {1} != {2}'.format(
                            Plot.objects.all()[0].plot_identifier,
                            Plot.objects.all()[0].plot_identifier[:2],
                            map_code))
            except IndexError:
                pass
        return {'site_name': map_area, 'site_code': map_code}
Example #4
0
 def get_queryset(self):
     if settings.LIMIT_EDIT_TO_CURRENT_COMMUNITY:
         community = site_mappers.get_current_mapper().map_area
         if PlotIdentifier.get_notebook_plot_lists():
             community = site_mappers.get_current_mapper().map_area
             return super(CallListManager, self).get_queryset().filter(
                 household_member__household_structure__household__plot__community
                 =community,
                 household_member__household_structure__household__plot__plot_identifier__in
                 =PlotIdentifier.get_notebook_plot_lists())
         else:
             return super(CallListManager, self).get_queryset().filter(
                 household_member__household_structure__household__plot__community
                 =community)
     return super(CallListManager, self).get_queryset()
Example #5
0
 def get_queryset(self):
     if settings.LIMIT_EDIT_TO_CURRENT_COMMUNITY:
         community = site_mappers.get_current_mapper().map_area
         return super(PreOrderManager, self).get_queryset().filter(
             subject_visit__household_member__household_structure__household__plot__community
             =community)
     return super(PreOrderManager, self).get_queryset()
Example #6
0
 def get_queryset(self):
     if settings.LIMIT_EDIT_TO_CURRENT_COMMUNITY:
         community = site_mappers.get_current_mapper().map_area
         return super(CallLogEntryManager, self).get_queryset().filter(
             call_log__household_member__household_structure__household__plot__community
             =community)
     return super(CallLogEntryManager, self).get_queryset()
Example #7
0
 def save(self, *args, **kwargs):
     using = kwargs.get('using')
     update_fields = kwargs.get('update_fields')
     if not self.plot_identifier == site_mappers.get_current_mapper(
     ).clinic_plot_identifier:
         self.allow_enrollment(using, update_fields=update_fields)
     if self.replaced_by and update_fields != ['replaced_by', 'htc']:
         raise AlreadyReplaced(
             'Plot {0} is no longer part of BHS. It has been replaced '
             'by plot {1}.'.format(self.plot_identifier, self.replaced_by))
     if not self.community:
         # plot data is imported and not entered, so community must be provided on import
         raise ValidationError(
             'Attribute \'community\' may not be None for model {0}'.format(
                 self))
     if self.household_count > settings.MAX_HOUSEHOLDS_PER_PLOT:
         raise ValidationError('Number of households cannot exceed {}. '
                               'Perhaps catch this in the forms.py. See '
                               'settings.MAX_HOUSEHOLDS_PER_PLOT'.format(
                                   settings.MAX_HOUSEHOLDS_PER_PLOT))
     # unless overridden, if self.community != to mapper.map_area, raise
     self.verify_plot_community_with_current_mapper(self.community)
     # if self.community does not get valid mapper, will raise an error that should be caught in forms.pyx
     mapper_cls = site_mappers.registry.get(self.community)
     mapper = mapper_cls()
     if not self.plot_identifier:
         self.plot_identifier = PlotIdentifier(mapper.map_code,
                                               using).get_identifier()
         if not self.plot_identifier:
             raise IdentifierError(
                 'Expected a value for plot_identifier. Got None')
     # if user added/updated gps_degrees_[es] and gps_minutes_[es], update gps_lat, gps_lon
     if (self.gps_degrees_e and self.gps_degrees_s and self.gps_minutes_e
             and self.gps_minutes_s):
         self.gps_lat = mapper.get_gps_lat(self.gps_degrees_s,
                                           self.gps_minutes_s)
         self.gps_lon = mapper.get_gps_lon(self.gps_degrees_e,
                                           self.gps_minutes_e)
         mapper.verify_gps_location(self.gps_lat, self.gps_lon, MapperError)
         mapper.verify_gps_to_target(
             self.gps_lat,
             self.gps_lon,
             self.gps_target_lat,
             self.gps_target_lon,
             self.target_radius,
             MapperError,
             radius_bypass_instance=self.increase_radius_instance)
         self.distance_from_target = mapper.gps_distance_between_points(
             self.gps_lat, self.gps_lon, self.gps_target_lat,
             self.gps_target_lon) * 1000
     self.action = self.get_action()
     try:
         update_fields = update_fields + [
             'action', 'distance_from_target', 'plot_identifier',
             'user_modified'
         ]
         kwargs.update({'update_fields': update_fields})
     except TypeError:
         pass
     super(Plot, self).save(*args, **kwargs)
Example #8
0
 def allow_enrollment(self,
                      using,
                      exception_cls=None,
                      plot_instance=None,
                      update_fields=None):
     """Raises an exception if an attempt is made to edit a plot after
     the BHS_FULL_ENROLLMENT_DATE or if the plot has been allocated to HTC."""
     plot_instance = plot_instance or self
     using = using or 'default'
     update_fields = update_fields or []
     exception_cls = exception_cls or ValidationError
     if using == 'default':  # do not check on remote systems
         mapper_instance = site_mappers.get_current_mapper()
         if plot_instance.id:
             if plot_instance.htc and 'htc' not in update_fields:
                 raise exception_cls(
                     'Modifications not allowed, this plot has been assigned to the HTC campaign.'
                 )
         if settings.ALLOW_ENROLLMENT:
             if not mapper_instance.map_code == '00' and not plot_instance.bhs and date.today(
             ) > mapper_instance.current_survey_dates.full_enrollment_date:
                 raise exception_cls(
                     'BHS enrollment for {0} ended on {1}. This plot, and the '
                     'data related to it, may not be modified. '
                     'See site_mappers'.format(
                         self.community, mapper_instance.
                         current_survey_dates.full_enrollment_date))
     return True
Example #9
0
 def format_for_console(self):
     Survey = get_model('bcpp_survey', 'Survey')
     site_mappers.sort_by_code()
     for mapper in site_mappers:
         if mapper.map_code not in [
                 '00',
         ]:
             print '\n{}'.format(str(mapper()))
             print '--------------'
             for item, values in mapper().survey_dates.iteritems():
                 print '  {}'.format(item)
                 for name in values._fields:
                     print '    {}: {}'.format(name,
                                               str(getattr(values, name)))
     try:
         current_survey = Survey.objects.current_survey()
         print '\nCurrent survey: {} from {} to {}.'.format(
             current_survey, current_survey.datetime_start,
             current_survey.datetime_end)
     except ImproperlyConfigured as err_message:
         print 'Survey configuration is invalid. Got {}'.format(
             err_message.message)
     print 'Current Mapper: {}'.format(
         str(site_mappers.get_current_mapper()))
     print('\nBHP066 Edc {} ({})\n'.format(site_revision.tag,
                                           site_revision.branch))
    def tests_hiv_result4b(self):
        """Other record confirms a verbal positive as evidence of HIV infection not on ART."""
        from ..classes import SubjectStatusHelper
        site_mappers.get_current_mapper().intervention = False
        print Survey.objects.current_survey()
        self.startup()
        today_date = date.today()
        last_year_date = today_date - timedelta(days=365)
        HivTestingHistoryFactory(subject_visit=self.subject_visit_male,
                                 verbal_hiv_result='POS',
                                 has_record='No',
                                 other_record='Yes')
        HivCareAdherenceFactory(subject_visit=self.subject_visit_male,
                                on_arv='No',
                                arv_evidence='No')
        HivResultDocumentationFactory(subject_visit=self.subject_visit_male,
                                      result_recorded='POS',
                                      result_date=last_year_date,
                                      result_doc_type='ART Prescription')
        subject_referral = SubjectStatusHelper(self.subject_visit_male)
        self.assertEqual('POS', subject_referral.hiv_result)
        self.assertFalse(subject_referral.new_pos)
        self.assertTrue(subject_referral.on_art is False)
        self.assertTrue(
            ScheduledEntryMetaData.objects.filter(
                appointment=self.subject_visit_male.appointment,
                entry__model_name='hivresult',
                entry_status=REQUIRED).count() == 1)

        self.assertTrue(
            ScheduledEntryMetaData.objects.filter(
                appointment=self.subject_visit_male.appointment,
                entry__model_name='pima',
                entry_status=NOT_REQUIRED).count() == 1)
    def setUp(self):

        from bhp066.apps.bcpp.app_configuration.classes import BcppAppConfiguration

        self.household_structure = None
        self.registered_subject = None
        self.representative_eligibility = None
        self.study_site = None
        self.intervention = None

        try:
            site_lab_profiles.register(BcppSubjectProfile())
        except AlreadyRegisteredLabProfile:
            pass
        BcppAppConfiguration().prepare()
        site_lab_tracker.autodiscover()
        BcppSubjectVisitSchedule().build()

        self.survey1 = Survey.objects.get(survey_name='BCPP Year 2')  # see app_configuration
        plot = PlotFactory(community='digawana', household_count=1, status='residential_habitable')
        household = Household.objects.get(plot=plot)
        self.household_structure = HouseholdStructure.objects.get(household=household, survey=self.survey1)
        self.representative_eligibility = RepresentativeEligibilityFactory(household_structure=self.household_structure)
        self.study_site = StudySite.objects.get(site_code=site_mappers.get_current_mapper().map_code)
        self.intervention = site_mappers.get_registry(settings.CURRENT_COMMUNITY)().intervention
Example #12
0
 def get_queryset(self):
     if settings.LIMIT_EDIT_TO_CURRENT_COMMUNITY:
         community = site_mappers.get_current_mapper().map_area
         return super(ReplacementHistoryManager,
                      self).get_queryset().filter(
                          replacing_item__startswith=community)
     return super(ReplacementHistoryManager, self).get_queryset()
Example #13
0
    def clinic_household_member(self):
        """Returns the household_member and will create if one does not exist.

        ClinicHouseholdMember is a proxy model of HouseholdMember."""
        try:
            clinic_household_member = ClinicHouseholdMember.objects.get(pk=self.household_member.pk)
        except (ClinicHouseholdMember.DoesNotExist, AttributeError):
            household_structure = HouseholdStructure.objects.get(
                household__plot=site_mappers.get_current_mapper().clinic_plot,
                survey=Survey.objects.current_survey())
            clinic_household_member = ClinicHouseholdMember.objects.create(
                household_structure=household_structure,
                first_name=self.first_name,
                initials=self.initials,
                age_in_years=self.age_in_years,
                gender=self.gender,
                present_today='N/A',
                inability_to_participate=self.inability_to_participate,
                study_resident=self.part_time_resident,
                member_status=CLINIC_RBD,
                is_consented=False,
                relation='UNKNOWN',
                eligible_member=True,
                eligible_subject=True,
                additional_key=self.additional_key,
            )
        if not self.household_member:
            # only set if self.household_member was None
            self.household_member = clinic_household_member
        return self.household_member
Example #14
0
 def return_site_name():
     from edc.map.classes import site_mappers
     mapper = site_mappers.get_registry(site_mappers.get_current_mapper().map_area)()
     if mapper:
         site_name = mapper.get_map_area()
     else:
         site_name = 'NO_MAPPER'
     return site_name
 def save(self, *args, **kwargs):
     if not self.id:
         self.registered_subject = RegisteredSubject.objects.get(
             identity=self.identity)
         self.household_member = HouseholdMember.objects.get(
             registered_subject=self.registered_subject)
         self.survey = self.household_member.household_structure.survey
     self.community = site_mappers.get_current_mapper().map_area
     # self.clinic_subject_identifier()
     super(ClinicConsent, self).save(*args, **kwargs)
    def startup(self):

        site_mappers.autodiscover()

        try:
            site_lab_profiles.register(BcppSubjectProfile())
        except AlreadyRegisteredLabProfile:
            pass
        bcpp_app_configuration.prepare()
        site_lab_tracker.autodiscover()
        BcppSubjectVisitSchedule().build()
        site_rule_groups.autodiscover()
        #         site_visit_schedules.autodiscover()
        #         site_visit_schedules.build_all()

        self.household_structure = None
        self.registered_subject = None
        self.representative_eligibility = None
        self.study_site = None
        self.intervention = None
        #         try:
        #             site_lab_profiles.register(BcppSubjectProfile())
        #         except AlreadyRegisteredLabProfile:
        #             pass
        #         BcppAppConfiguration()
        #         site_lab_tracker.autodiscover()
        #         BcppSubjectVisitSchedule().build()

        self.community = site_mappers.get_current_mapper().map_area
        self.study_site = StudySite.objects.get(
            site_code=site_mappers.get_current_mapper().map_code)
        self.site_code = self.study_site
        self.intervention = site_mappers.get_current_mapper().intervention
        self.survey1 = Survey.objects.get(
            survey_name='BCPP Year 1')  # see app_configuration
        self.survey2 = Survey.objects.get(
            survey_name='BCPP Year 2')  # see app_configuration
        plot = PlotFactory(community=self.community,
                           household_count=1,
                           status='residential_habitable')
        household = Household.objects.get(plot=plot)
        self.create_baseline(household)
        self.create_annual(household)
Example #17
0
    def setUp(self):
        site_mappers.autodiscover()
        try:
            site_lab_profiles.register(BcppSubjectProfile())
        except AlreadyRegisteredLabProfile:
            pass
        self.app_config = BcppAppConfiguration()
        self.app_config.prepare()
        site_lab_tracker.autodiscover()
        BcppSubjectVisitSchedule().build()
        site_rule_groups.autodiscover()
        self.mapper = site_mappers.get_current_mapper()
#         self.app_config.prep_survey_for_tests()

        self.community = 'test_community'
        plot = PlotFactory(community=self.community, household_count=1, status='residential_habitable')

        survey = Survey.objects.all().order_by('datetime_start')[0]

        self.study_site = StudySite.objects.get(site_code='01')

        self.household_structure = HouseholdStructure.objects.get(household__plot=plot, survey=survey)
        RepresentativeEligibilityFactory(household_structure=self.household_structure)

        self.male_dob = date.today() - relativedelta(years=25)
        self.male_age_in_years = 25
        self.male_first_name = 'ERIK'
        self.male_initials = "EW"

        self.household_member_male_T0 = HouseholdMemberFactory(
            household_structure=self.household_structure, gender='M',
            age_in_years=self.male_age_in_years, first_name=self.male_first_name,
            initials=self.male_initials
        )

        EnrollmentChecklistFactory(
            household_member=self.household_member_male_T0,
            gender='M',
            citizen='Yes',
            dob=self.male_dob,
            guardian='No',
            initials=self.household_member_male_T0.initials,
            part_time_resident='Yes'
        )

        self.subject_consent_male = SubjectConsentFactory(household_member=self.household_member_male_T0, study_site=self.study_site, gender='M', dob=self.male_dob, first_name=self.male_first_name, initials=self.male_initials)

        self.registered_subject_male = RegisteredSubject.objects.get(subject_identifier=self.subject_consent_male.subject_identifier)

        self.appointment_male_T0 = Appointment.objects.get(registered_subject=self.registered_subject_male, visit_definition__code='T0')

        self.subject_visit_male_T0 = SubjectVisitFactory(appointment=self.appointment_male_T0, household_member=self.household_member_male_T0)
        SubjectLocatorFactory(registered_subject=self.subject_visit_male_T0.appointment.registered_subject, subject_visit=self.subject_visit_male_T0)
        self.household_member_T1 = None
        self.update_call_list_class = UpdateCallList()
    def setUp(self):

        from bhp066.apps.bcpp.app_configuration.classes import BcppAppConfiguration

        self.household_structure = None
        self.registered_subject = None
        self.representative_eligibility = None
        self.study_site = None
        self.intervention = None

        try:
            site_lab_profiles.register(BcppSubjectProfile())
        except AlreadyRegisteredLabProfile:
            pass
        site_mappers.autodiscover()
        # set current community manually (not from settings)
        site_mappers.current_community = 'test_community'
        BcppAppConfiguration.study_start_datetime = datetime.today(
        ) + relativedelta(days=-2)
        BcppAppConfiguration.study_end_datetime = datetime.today(
        ) + relativedelta(days=45)
        bcpp_app_configuration = BcppAppConfiguration()
        # bypass any check of site_code and community against settings
        bcpp_app_configuration.confirm_site_code_in_settings = False
        bcpp_app_configuration.confirm_community_in_settings = False
        bcpp_app_configuration.prepare()
        site_lab_tracker.autodiscover()
        BcppSubjectVisitSchedule().build()

        self.survey1 = Survey.objects.get(
            survey_name='BCPP Year 1')  # see app_configuration
        plot = PlotFactory(community='test_community',
                           household_count=1,
                           status='residential_habitable')
        household = Household.objects.get(plot=plot)
        self.household_structure = HouseholdStructure.objects.get(
            household=household, survey=self.survey1)
        self.representative_eligibility = RepresentativeEligibilityFactory(
            household_structure=self.household_structure)
        self.study_site = StudySite.objects.get(
            site_code=site_mappers.get_current_mapper().map_code)
        self.intervention = site_mappers.get_current_mapper().intervention
Example #19
0
    def setUp(self):
        self.household_member = None
        self.subject_consent = None
        self.registered_subject = None
        try:
            site_lab_profiles.register(BcppSubjectProfile())
        except AlreadyRegisteredLabProfile:
            pass
        bcpp_app_configuration.prepare()
        site_lab_tracker.autodiscover()
        site_visit_schedules.autodiscover()
        site_visit_schedules.build_all()

        self.survey = Survey.objects.current_survey()
        self.plot = PlotFactory(community='oodi', household_count=1, status='bcpp_clinic')
        self.household = HouseholdFactory(plot=self.plot)
        self.household_structure = HouseholdStructure.objects.get(household=self.household, survey=self.survey)
        self.study_site = StudySite.objects.get(site_code=site_mappers.get_current_mapper().map_code)
        self.intervention = site_mappers.get_current_mapper().intervention
        site_mappers.get_current_mapper().verify_survey_dates()
 def search_queryset(self, request=None):
     """Returns a filtered search model queryset."""
     mapper = site_mappers.get_current_mapper()
     options = {mapper.map_area_field_attr: mapper.map_area}
     if request:
         search_attrvalue = request.GET.get(
             self.get_search_attrname())  # e.g. identifier
         if search_attrvalue:
             options.update({self.get_search_attrname(): search_attrvalue})
     return self.get_search_model_cls().objects.filter(
         **{mapper.map_area_field_attr: mapper.map_area})
 def contribute_to_context(self, context, request, *args, **kwargs):
     current_survey = None
     if settings.CURRENT_SURVEY:
         current_survey = Survey.objects.current_survey()
     context.update({
         'current_survey':
         current_survey,
         'current_community':
         str(site_mappers.get_current_mapper()),
         'mapper_name':
         site_mappers.get_current_mapper().map_area,
         'gps_search_form':
         GpsSearchForm(initial={'radius': 100}),
         'use_gps_to_target_verification':
         settings.VERIFY_GPS,
         'search_term':
         kwargs.get('search_term'),
     })
     context.update()
     return context
Example #22
0
    def verify_plot_community_with_current_mapper(self,
                                                  community,
                                                  exception_cls=None):
        """Returns True if the plot.community = the current mapper.map_area.

        This check can be disabled using the settings attribute VERIFY_PLOT_COMMUNITY_WITH_CURRENT_MAPPER.
        """
        verify_plot_community_with_current_mapper = True  # default
        exception_cls = exception_cls or ValidationError
        try:
            verify_plot_community_with_current_mapper = settings.VERIFY_PLOT_COMMUNITY_WITH_CURRENT_MAPPER
        except AttributeError:
            pass
        if verify_plot_community_with_current_mapper:
            if community != site_mappers.get_current_mapper().map_area:
                raise exception_cls(
                    'Plot community does not correspond with the current mapper '
                    'community of \'{}\'. Got \'{}\'. '
                    'See settings.VERIFY_PLOT_COMMUNITY_WITH_CURRENT_MAPPER'.
                    format(site_mappers.get_current_mapper().map_area,
                           community))
Example #23
0
def export_outgoing_to_usb(request, **kwargs):
    """Sets the path and then calls the edc export view 'export_outgoing_to_file'."""
    site_name = site_mappers.get_current_mapper().map_area
    app_name = settings.APP_NAME.lower()
    if platform.system() == 'Darwin':
        usb_path = '/Volumes/{}_usb/'.format(app_name)
    else:
        usb_path = '/media/{}_usb/'.format(app_name)
    filename = '{}_{}_{}.json'.format(
        app_name, site_name, str(datetime.now().strftime("%Y%m%d%H%M")))
    path = os.path.join(usb_path, filename)
    return export_outgoing_to_file(request, path, target_name='USB Drive')
Example #24
0
 def get_queryset(self):
     if settings.LIMIT_EDIT_TO_CURRENT_COMMUNITY:
         community = site_mappers.get_current_mapper().map_area
         if PlotIdentifier.get_notebook_plot_lists():
             return super(PlotManager, self).get_queryset().filter(
                 community=community,
                 plot_identifier__in=PlotIdentifier.get_notebook_plot_lists(
                 ))
         else:
             return super(PlotManager,
                          self).get_queryset().filter(community=community)
     return super(PlotManager, self).get_queryset()
Example #25
0
 def contribute_to_context(self, context, request, *args, **kwargs):
     try:
         daily_log = DailyLog.objects.get(report_date=date.today())
     except DailyLog.DoesNotExist:
         daily_log = None
     current_survey = Survey.objects.current_survey()
     context.update({
         'current_survey':
         current_survey,
         'current_community':
         str(site_mappers.get_current_mapper()),
         'daily_log':
         daily_log,
         'subject_dashboard_url':
         self.dashboard_url_name,
     })
     return context
 def limit_edit_to_current_community(self, cleaned_data):
     """Raises an exception if the instance does not refer to the
     current community OR does nothing,"""
     try:
         if settings.LIMIT_EDIT_TO_CURRENT_COMMUNITY:
             configured_community = site_mappers.get_current_mapper(
             ).map_area
             community = cleaned_data.get(
                 'subject_visit'
             ).household_member.household_structure.household.plot.community
             if community != configured_community:
                 raise forms.ValidationError(
                     'Form may not be saved. Only data from \'{}\' may be added/changed on '
                     'this device. Got {}. (LIMIT_EDIT_TO_CURRENT_COMMUNITY)'
                     .format(configured_community, community))
     except AttributeError:
         pass
     return cleaned_data
 def search_result(self, request, **kwargs):
     """Returns an iterable search_result ordered by distance from a given gps point."""
     search_result = []
     gps_form = self.search_form(request.POST)
     mapper = site_mappers.get_current_mapper()
     if gps_form.is_valid():
         radius = gps_form.data.get('radius') / 1000
         lat = mapper.get_gps_lat(
             gps_form.data.get('degrees_s'),
             float('{0}'.format(gps_form.data.get('minutes_s'))))
         lon = mapper.get_gps_lon(
             gps_form.data.get('degrees_e'),
             float('{0}'.format(gps_form.data.get('minutes_e'))))
         items_as_dct, ordered_list_of_keys = self.get_items_ordered_by_distance(
             self.search_queryset(), lat, lon, radius)
         for distance_from_gps in ordered_list_of_keys:
             search_result.append(items_as_dct[distance_from_gps])
     return search_result
Example #28
0
 def limit_edit_to_current_community(self):
     household_member = self.cleaned_data.get("household_member")
     if household_member:
         try:
             limit = settings.LIMIT_EDIT_TO_CURRENT_COMMUNITY
         except AttributeError:
             limit = False
         if limit:
             mapper_community = site_mappers.get_current_mapper().map_area
             community = household_member.household_structure.household.plot.community
             if community != mapper_community:
                 raise forms.ValidationError(
                     'Form may not be saved. Only data from \'%(mapper_community)s\' may be added/changed on '
                     'this device. Got %(community)s. (LIMIT_EDIT_TO_CURRENT_COMMUNITY)',
                     params={
                         'mapper_community': mapper_community,
                         'community': community
                     },
                     code='invalid')
Example #29
0
 def save(self, *args, **kwargs):
     update_fields = kwargs.get('update_fields', [])
     if 'is_consented' in update_fields or 'is_refused' in update_fields:
         pass
     else:
         if not self.identity:
             self.additional_key = uuid4()
         else:
             self.additional_key = None
         self.check_for_consent(self.identity)
         if self.identity:
             if not self.id:
                 self.check_for_known_identity(self.identity)
         self.age_in_years = relativedelta(self.report_datetime.date(), self.dob).years
         self.is_eligible, self.loss_reason = self.passes_enrollment_criteria()
         self.community = site_mappers.get_current_mapper().map_area
         if not self.household_member:
             self.household_member = self.clinic_household_member
     super(ClinicEligibility, self).save(*args, **kwargs)
Example #30
0
def date_in_survey(value):
    if not value:
        pass
    else:
        value_datetime = datetime.combine(value, time.min)
        current_survey = Survey.objects.current_survey(
            report_datetime=value_datetime)
        mapper = site_mappers.get_current_mapper()
        start_date = mapper.survey_dates.get(
            current_survey.survey_slug).start_date
        end_date = mapper.survey_dates.get(current_survey.survey_slug).end_date
        if value < start_date or value > end_date:
            raise ValidationError(
                'Appointment must fall within survey {} (from {} to {}). You entered {}'
                .format(
                    current_survey.survey_slug,
                    start_date,
                    end_date,
                    value,
                ))
 def __init__(self, subject_referral=None):
     self._circumcised = None
     self._enrollment_checklist_instance = None
     self._pregnant = None
     self._referral_clinic = None
     self._referral_code = None
     self._referral_code_list = []
     self._subject_consent_instance = None
     self._subject_referral = None
     self._subject_referral_dict = {}
     self._subject_status_helper = None
     self.community_code = site_mappers.get_current_mapper().map_code
     # self.models dict is also used in the signal
     self.models = copy(SubjectStatusHelper.models)
     self.models[BASELINE].update({
         'subject_locator': SubjectLocator,
         'circumcision': Circumcision,
         'reproductive_health': ReproductiveHealth,
         'residency_mobility': ResidencyMobility,
         'subject_consent': SubjectConsent,
     })
     self.models[ANNUAL].update({
         'subject_locator': SubjectLocator,
         'circumcision': Circumcision,
         'reproductive_health': ReproductiveHealth,
         'residency_mobility': ResidencyMobility,
         'subject_consent': SubjectConsent,
     })
     self.models[BASELINE].update({
         'subject_requisition':
         get_model('bcpp_lab', 'SubjectRequisition')
     })
     self.models[ANNUAL].update({
         'subject_requisition':
         get_model('bcpp_lab', 'SubjectRequisition')
     })
     self.previous_subject_referrals = []
     if subject_referral:
         self.subject_referral = subject_referral