Пример #1
0
def survey_completion_summary(request, household_id, batch_id):
    household = get_object_or_404(Household, pk=household_id)
    batch = get_object_or_404(Batch, pk=batch_id)
    survey = batch.survey
    ea = household.listing.ea
    allocations = SurveyAllocation.objects.filter(allocation_ea=ea, survey=batch.survey)
    context = {}
    if allocations.exists():
        completion_rates = BatchLocationCompletionRates(batch, ea=ea, specific_households=[household_id, ])
        result_service = ResultsDownloadService(batch=batch, specific_households=[household_id, ])
        reports = result_service.generate_interview_reports()
        reports_headers = reports.pop(0)
        context.update({
        'household' : household,
        'batch': batch,
        'reports_headers': reports_headers,
        'reports': reports,
        'completion_rates': completion_rates,
        'interviewer': allocations[0].interviewer
        })
    request.breadcrumbs([
        ('Completion Rates', reverse('survey_completion_rates', )),
        ('EA Completion', reverse('ea_completion_summary', args=(ea.pk, batch.pk))),
    ])
    return render(request, 'aggregates/household_completion_report.html', context)
    def test_should_repeat_questions_in_general_for_all_members(self):
        AGE = '24'
        general_group = HouseholdMemberGroup.objects.create(name="GENERAL", order=2)

        general_condition = GroupCondition.objects.create(attribute="GENERAL", value="HEAD", condition='EQUALS')
        general_group.conditions.add(general_condition)

        general_question_1 = Question.objects.create(group=general_group, text="General Question 1",
                                                     answer_type=Question.NUMBER,
                                                     order=4, identifier='Q31')
        general_question_2 = Question.objects.create(group=general_group, text="General Question 2",
                                                     answer_type=Question.NUMBER,
                                                     order=5, identifier='Q41')

        general_question_1.batches.add(self.batch)
        general_question_2.batches.add(self.batch)

        BatchQuestionOrder.objects.create(question=general_question_1, batch=self.batch, order=4)
        BatchQuestionOrder.objects.create(question=general_question_2, batch=self.batch, order=5)

        household_head_1 = self.create_household_head(0, self.investigator, self.batch.survey)
        household_head_2 = self.create_household_head(1, self.investigator, self.batch.survey)

        member_1 = HouseholdMember.objects.create(surname="Member 1", date_of_birth=date(1999, 2, 9),
                                                  household=household_head_1.household)
        member_2 = HouseholdMember.objects.create(surname="Member 2", date_of_birth=date(1999, 2, 9),
                                                  household=household_head_2.household)

        self.investigator.member_answered(self.question_1, household_head_1, 1, self.batch)
        self.investigator.member_answered(self.question_1, household_head_2, 2, self.batch)

        self.investigator.member_answered(general_question_1, household_head_1, 4, self.batch)
        self.investigator.member_answered(general_question_1, household_head_2, 1, self.batch)

        self.investigator.member_answered(general_question_2, household_head_1, 4, self.batch)
        self.investigator.member_answered(general_question_2, household_head_2, 3, self.batch)

        self.investigator.member_answered(self.question_2, household_head_1, self.no_option.order, self.batch)
        self.investigator.member_answered(self.question_2, household_head_2, self.yes_option.order, self.batch)

        self.investigator.member_answered(self.question_3, household_head_1, 1, self.batch)
        self.investigator.member_answered(self.question_3, household_head_2, 2, self.batch)

        result_down_load_service = ResultsDownloadService(batch=self.batch)
        age = '24'
        age_14 = '15'
        expected_csv_data = [
            ['Kampala', household_head_1.household.household_code, household_head_1.surname, age, '2', '1990',
             'Male' if household_head_1.male else 'Female', 1, self.no_option.order, self.no_option.text, 1, 4, 4],
            ['Kampala', household_head_2.household.household_code, member_1.surname, age_14, '2', '1999',
             'Male' if member_1.male else 'Female', '', '', '', 4, 4],
            ['Kampala', household_head_2.household.household_code, household_head_2.surname, age, '2', '1990',
             'Male' if household_head_2.male else 'Female', 2, self.yes_option.order, self.yes_option.text, 2, 1, 3],
            ['Kampala', household_head_2.household.household_code, member_2.surname, age_14, '2', '1999',
             'Male' if member_2.male else 'Female', '', '', '', 1, 3]]

        actual_csv_data = result_down_load_service.get_summarised_answers()
        self.assertEqual(4, len(actual_csv_data))
        for i in range(4):
            self.assertIn(expected_csv_data[i], actual_csv_data)
Пример #3
0
def survey_completion_summary(request, household_id, batch_id):
    household = get_object_or_404(Household, pk=household_id)
    batch = get_object_or_404(Batch, pk=batch_id)
    survey = batch.survey
    ea = household.listing.ea
    allocations = SurveyAllocation.objects.filter(allocation_ea=ea, survey=batch.survey)
    context = {}
    if allocations.exists():
        completion_rates = BatchLocationCompletionRates(batch, ea=ea, specific_households=[household_id, ])
        result_service = ResultsDownloadService(batch=batch, specific_households=[household_id, ])
        reports = result_service.generate_report()
        reports_headers = reports.pop(0)
        context.update({
        'household' : household,
        'batch': batch,
        'reports_headers': reports_headers,
        'reports': reports,
        'completion_rates': completion_rates,
        'interviewer': allocations[0].interviewer
        })
    request.breadcrumbs([
        ('Completion Rates', reverse('survey_completion_rates', )),
        ('EA Completion', reverse('ea_completion_summary', args=(ea.pk, batch.pk))),
    ])
    return render(request, 'aggregates/household_completion_report.html', context)
Пример #4
0
    def test_should_repeat_questions_in_general_for_all_members(self):
        AGE = '24'
        general_group = HouseholdMemberGroup.objects.create(name="GENERAL", order=2)

        general_condition = GroupCondition.objects.create(attribute="GENERAL", value="HEAD", condition='EQUALS')
        general_group.conditions.add(general_condition)

        general_question_1 = Question.objects.create(group=general_group, text="General Question 1",
                                                     answer_type=Question.NUMBER,
                                                     order=4, identifier='Q31')
        general_question_2 = Question.objects.create(group=general_group, text="General Question 2",
                                                     answer_type=Question.NUMBER,
                                                     order=5, identifier='Q41')

        general_question_1.batches.add(self.batch)
        general_question_2.batches.add(self.batch)

        BatchQuestionOrder.objects.create(question=general_question_1, batch=self.batch, order=4)
        BatchQuestionOrder.objects.create(question=general_question_2, batch=self.batch, order=5)

        household_head_1 = self.create_household_head(0, self.investigator, self.batch.survey)
        household_head_2 = self.create_household_head(1, self.investigator, self.batch.survey)

        member_1 = HouseholdMember.objects.create(surname="Member 1", date_of_birth=date(1999, 2, 9),
                                                  household=household_head_1.household)
        member_2 = HouseholdMember.objects.create(surname="Member 2", date_of_birth=date(1999, 2, 9),
                                                  household=household_head_2.household)

        self.investigator.member_answered(self.question_1, household_head_1, 1, self.batch)
        self.investigator.member_answered(self.question_1, household_head_2, 2, self.batch)

        self.investigator.member_answered(general_question_1, household_head_1, 4, self.batch)
        self.investigator.member_answered(general_question_1, household_head_2, 1, self.batch)

        self.investigator.member_answered(general_question_2, household_head_1, 4, self.batch)
        self.investigator.member_answered(general_question_2, household_head_2, 3, self.batch)

        self.investigator.member_answered(self.question_2, household_head_1, self.no_option.order, self.batch)
        self.investigator.member_answered(self.question_2, household_head_2, self.yes_option.order, self.batch)

        self.investigator.member_answered(self.question_3, household_head_1, 1, self.batch)
        self.investigator.member_answered(self.question_3, household_head_2, 2, self.batch)

        result_down_load_service = ResultsDownloadService(batch=self.batch)
        age = '24'
        age_14 = '15'
        expected_csv_data = [
            ['Kampala', household_head_1.household.household_code, household_head_1.surname, age, '2', '1990',
             'Male' if household_head_1.male else 'Female', 1, self.no_option.order, self.no_option.text, 1, 4, 4],
            ['Kampala', household_head_2.household.household_code, member_1.surname, age_14, '2', '1999',
             'Male' if member_1.male else 'Female', '', '', '', 4, 4],
            ['Kampala', household_head_2.household.household_code, household_head_2.surname, age, '2', '1990',
             'Male' if household_head_2.male else 'Female', 2, self.yes_option.order, self.yes_option.text, 2, 1, 3],
            ['Kampala', household_head_2.household.household_code, member_2.surname, age_14, '2', '1999',
             'Male' if member_2.male else 'Female', '', '', '', 1, 3]]

        actual_csv_data = result_down_load_service.get_summarised_answers()
        self.assertEqual(4, len(actual_csv_data))
        for i in range(4):
            self.assertIn(expected_csv_data[i], actual_csv_data)
Пример #5
0
def _view_qset_data(request,
                    model_class,
                    interviews,
                    title,
                    disabled_fields=[]):
    params = request.GET if request.method == 'GET' else request.POST
    survey_filter = SurveyResultsFilterForm(model_class,
                                            disabled_fields=disabled_fields,
                                            data=params)
    locations_filter = LocationsFilterForm(data=request.GET, include_ea=True)
    selected_qset = None
    survey = None
    items_per_page = int(params.get('max_display_per_page', 50))
    try:
        page_index = int(params.get('page', 1)) - 1
    except BaseException:
        page_index = 0
    if survey_filter.is_valid():
        interviews = survey_filter.get_interviews(interviews=interviews)
        selected_qset = survey_filter.cleaned_data['question_set']
        survey = survey_filter.cleaned_data['survey']
    if locations_filter.is_valid():
        interviews = interviews.filter(
            ea__in=locations_filter.get_enumerations())
    search_fields = [
        'ea__name',
        'survey__name',
        'question_set__name',
        'answer__as_text',
    ]
    if 'q' in request.GET:
        interviews = get_filterset(interviews, request.GET['q'], search_fields)
    context = {
        'survey_filter': survey_filter,
        'interviews': interviews,
        'locations_filter': locations_filter,
        'location_filter_types': LocationType.in_between(),
        'placeholder': 'Response, EA, Survey, %s' % model_class.verbose_name(),
        'selected_qset': selected_qset,
        'model_class': model_class,
        'items_per_page': items_per_page,
        'max_display_per_page': items_per_page,
        'title': title
    }
    if selected_qset and survey:
        # page_start = page_index * items_per_page
        # interviews = interviews[page_start: page_start + items_per_page]()
        download_service = ResultsDownloadService(
            selected_qset,
            survey=survey,
            interviews=interviews,
            page_index=page_index,
            items_per_page=items_per_page)
        df = download_service.get_interview_answers()
        context['report'] = mark_safe(
            df.to_html(classes='table table-striped\
                    dataTable table-bordered table-hover table-sort',
                       max_rows=items_per_page))
    return render(request, 'question_set/view_all_data.html', context)
Пример #6
0
 def test_formats_headers_for_csv_leaving_out_country(self):
     result_down_load_service = ResultsDownloadService(batch=self.batch)
     header_structure = [unicode(self.district.name), unicode(self.county.name), unicode(self.subcounty.name), unicode(self.parish.name),
                         unicode(self.village.name),unicode(self.ea.name),
                         'Household Number', 'Family Name', 'First Name', 'Age', 'Date of Birth', 'Gender'
                         ]
     headers = result_down_load_service.set_report_headers()
     self.assertEqual(header_structure, headers)
Пример #7
0
def download(request):
    survey_batch_filter_form = SurveyBatchFilterForm(data=request.GET)
    locations_filter = LocationsFilterForm(data=request.GET)
    last_selected_loc = locations_filter.last_location_selected
    if request.GET and request.GET.get('action'):
        survey_batch_filter_form = SurveyBatchFilterForm(data=request.GET)
        if survey_batch_filter_form.is_valid():
            batch = survey_batch_filter_form.cleaned_data['batch']
            survey = survey_batch_filter_form.cleaned_data['survey']
            multi_option = survey_batch_filter_form.cleaned_data[
                'multi_option']
            restricted_to = None
            if last_selected_loc:
                restricted_to = [
                    last_selected_loc,
                ]
            if request.GET.get('action') == 'Email Spreadsheet':
                composer = ResultComposer(
                    request.user,
                    ResultsDownloadService(batch=batch,
                                           survey=survey,
                                           restrict_to=restricted_to,
                                           multi_display=multi_option))
                send_mail.delay(composer)
                messages.warning(
                    request,
                    "Email would be sent to you shortly. This could take a while."
                )
            else:
                download_service = ResultsDownloadService(
                    batch=batch,
                    survey=survey,
                    restrict_to=restricted_to,
                    multi_display=multi_option)
                file_name = '%s%s' % (
                    '%s-%s-' %
                    (last_selected_loc.type.name, last_selected_loc.name)
                    if last_selected_loc else '',
                    batch.name if batch else survey.name)
                generate_result_link.delay(request.user, download_service,
                                           file_name)
                messages.warning(
                    request,
                    "Download is in progress. Download link would be available to you shortly"
                )
    loc_types = LocationType.in_between()
    return render(
        request, 'aggregates/download_excel.html', {
            'survey_batch_filter_form':
            survey_batch_filter_form,
            'locations_filter':
            locations_filter,
            'export_url':
            '%s?%s' % (reverse('excel_report'), request.META['QUERY_STRING']),
            'location_filter_types':
            loc_types
        })
    def test_formats_headers_for_csv_leaving_out_country(self):
        result_down_load_service = ResultsDownloadService(batch=self.batch)
        header_structure = [self.district.name, self.county.name, self.subcounty.name, self.parish.name,
                            self.village.name,
                            'Household ID', 'Name', 'Age', 'Month of Birth', 'Year of Birth', 'Gender',
                            self.question_1.identifier,
                            self.question_2.identifier, '', self.question_3.identifier]

        headers = result_down_load_service.set_report_headers()
        self.assertEqual(header_structure, headers)
Пример #9
0
    def test_formats_headers_for_csv_leaving_out_country(self):
        result_down_load_service = ResultsDownloadService(batch=self.batch)
        header_structure = [self.district.name, self.county.name, self.subcounty.name, self.parish.name,
                            self.village.name,
                            'Household ID', 'Name', 'Age', 'Month of Birth', 'Year of Birth', 'Gender',
                            self.question_1.identifier,
                            self.question_2.identifier, '', self.question_3.identifier]

        headers = result_down_load_service.set_report_headers()
        self.assertEqual(header_structure, headers)
Пример #10
0
def _view_qset_data(request, model_class, interviews,title, disabled_fields=[]):
    params = request.GET if request.method == 'GET' else request.POST
    survey_filter = SurveyResultsFilterForm(
        model_class, disabled_fields=disabled_fields, data=params)
    locations_filter = LocationsFilterForm(data=request.GET, include_ea=True)
    selected_qset = None
    survey = None
    items_per_page = int(params.get('max_display_per_page', 50))
    try:
        page_index = int(params.get('page', 1)) - 1
    except BaseException:
        page_index = 0
    if survey_filter.is_valid():
        interviews = survey_filter.get_interviews(interviews=interviews)
        selected_qset = survey_filter.cleaned_data['question_set']
        survey = survey_filter.cleaned_data['survey']
    if locations_filter.is_valid():
        interviews = interviews.filter(ea__in=locations_filter.get_enumerations())
    search_fields = [
        'ea__name',
        'survey__name',
        'question_set__name',
        'answer__as_text',
    ]
    if 'q' in request.GET:
        interviews = get_filterset(interviews, request.GET['q'], search_fields)
    context = {
        'survey_filter': survey_filter,
        'interviews': interviews,
        'locations_filter': locations_filter,
        'location_filter_types': LocationType.in_between(),
        'placeholder': 'Response, EA, Survey, %s' % model_class.verbose_name(),
        'selected_qset': selected_qset,
        'model_class': model_class,
        'items_per_page': items_per_page,
        'max_display_per_page': items_per_page,
        'title':title}
    if selected_qset and survey:
        # page_start = page_index * items_per_page
        # interviews = interviews[page_start: page_start + items_per_page]()
        download_service = ResultsDownloadService(
            selected_qset,
            survey=survey,
            interviews=interviews,
            page_index=page_index,
            items_per_page=items_per_page)
        df = download_service.get_interview_answers()
        context['report'] = mark_safe(
            df.to_html(
                classes='table table-striped\
                    dataTable table-bordered table-hover table-sort',
                max_rows=items_per_page))
    return render(request, 'question_set/view_all_data.html', context)
Пример #11
0
    def test_gets_summarised_response_for_all_batches_under_survey(self):
        household_listing = HouseholdListing.objects.create(ea=self.ea,list_registrar=self.investigator,initial_survey=self.survey)
        survey_householdlisting = SurveyHouseholdListing.objects.create(listing=household_listing,survey=self.survey)
        HouseholdMemberGroup.objects.create(name="GENERAL", order=2)
        household_head_1 = create_household_head(0, self.investigator,household_listing,survey_householdlisting)
        household_head_2 = create_household_head(1, self.investigator,household_listing,survey_householdlisting)
        household_head_3 = create_household_head(2, self.investigator,household_listing,survey_householdlisting)
        household_head_4 = create_household_head(3, self.investigator,household_listing,survey_householdlisting)
        household_head_5 = create_household_head(4, self.investigator,household_listing,survey_householdlisting)

        batchB = Batch.objects.create(order=2, name="different batch", survey=self.survey)
        module = QuestionModule.objects.create(name="Education in a different batch")
        question_1B = Question.objects.create(identifier='1.21',text="This is a question21", answer_type='Numerical Answer',
                                           group=self.group,batch=self.batch,module=module)
        question_2B = Question.objects.create(identifier='1.22',text="This is a question22", answer_type='Numerical Answer',
                                           group=self.group,batch=self.batch,module=module)
        question_3B = Question.objects.create(identifier='1.23',text="This is a question23", answer_type='Numerical Answer',
                                           group=self.group,batch=self.batch,module=module)

        yes_option = QuestionOption.objects.create(question=question_2B, text="Yes", order=1)
        no_option = QuestionOption.objects.create(question=question_2B, text="No", order=2)

        result_down_load_service = ResultsDownloadService(survey=self.survey)

        header_structure = [unicode(self.district.name), unicode(self.county.name), unicode(self.subcounty.name), unicode(self.parish.name),
                            unicode(self.village.name), unicode(self.ea.name),
                            'Household Number', 'Family Name', 'First Name','Age', 'Date of Birth', 'Gender']

        headers = result_down_load_service.set_report_headers()
        self.assertEqual(header_structure, headers)

        AGE = '28'
        household1=household_head_1.surname+'-'+household_head_1.first_name
        household2=household_head_2.surname+'-'+household_head_2.first_name
        household3=household_head_3.surname+'-'+household_head_3.first_name
        household4=household_head_4.surname+'-'+household_head_4.first_name
        household5=household_head_5.surname+'-'+household_head_5.first_name
        expected_csv_data = [

            [u'Kampala', unicode(self.ea.name),household_head_2.household.house_number, unicode(household2), AGE, '01-01-1988',
             'Male' if household_head_2.household.head_sex else 'Female'],
            [u'Kampala', unicode(self.ea.name),household_head_3.household.house_number, unicode(household3), AGE, '01-01-1988',
             'Male' if household_head_3.household.head_sex else 'Female'],
            [u'Kampala', unicode(self.ea.name),household_head_4.household.house_number, unicode(household4),AGE, '01-01-1988',
             'Male' if household_head_4.household.head_sex else 'Female'],
            [u'Kampala', unicode(self.ea.name),household_head_5.household.house_number, unicode(household5),AGE, '01-01-1988',
             'Male' if household_head_5.household.head_sex else 'Female']]

        actual_csv_data = result_down_load_service.get_summarised_answers()
        self.assertEqual(5, len(actual_csv_data))
        for i in range(4):
            self.assertIn(expected_csv_data[i], actual_csv_data)
    def test_gets_summarised_response_for_a_given_batch(self):
        HouseholdMemberGroup.objects.create(name="GENERAL", order=2)
        household_head_1 = self.create_household_head(0, self.investigator, self.batch.survey)
        household_head_2 = self.create_household_head(1, self.investigator, self.batch.survey)
        household_head_3 = self.create_household_head(2, self.investigator, self.batch.survey)
        household_head_4 = self.create_household_head(3, self.investigator, self.batch.survey)
        household_head_5 = self.create_household_head(4, self.investigator, self.batch.survey)

        self.investigator.member_answered(self.question_1, household_head_1, 1, self.batch)
        self.investigator.member_answered(self.question_1, household_head_2, 2, self.batch)
        self.investigator.member_answered(self.question_1, household_head_3, 1, self.batch)
        self.investigator.member_answered(self.question_1, household_head_4, 2, self.batch)
        self.investigator.member_answered(self.question_1, household_head_5, 3, self.batch)

        self.investigator.member_answered(self.question_2, household_head_1, self.no_option.order, self.batch)
        self.investigator.member_answered(self.question_2, household_head_2, self.yes_option.order, self.batch)
        self.investigator.member_answered(self.question_2, household_head_3, self.no_option.order, self.batch)
        self.investigator.member_answered(self.question_2, household_head_4, self.yes_option.order, self.batch)
        self.investigator.member_answered(self.question_2, household_head_5, self.yes_option.order, self.batch)

        self.investigator.member_answered(self.question_3, household_head_1, 1, self.batch)
        self.investigator.member_answered(self.question_3, household_head_2, 2, self.batch)
        self.investigator.member_answered(self.question_3, household_head_3, 1, self.batch)
        self.investigator.member_answered(self.question_3, household_head_4, 2, self.batch)
        self.investigator.member_answered(self.question_3, household_head_5, 3, self.batch)

        result_down_load_service = ResultsDownloadService(batch=self.batch)
        AGE = '24'
        expected_csv_data = [
            ['Kampala', household_head_1.household.household_code, household_head_1.surname, AGE, '2', '1990',
             'Male' if household_head_1.male else 'Female', 1, self.no_option.order, self.no_option.text, 1],
            ['Kampala', household_head_2.household.household_code, household_head_2.surname, AGE, '2', '1990',
             'Male' if household_head_2.male else 'Female', 2, self.yes_option.order, self.yes_option.text, 2],
            ['Kampala', household_head_3.household.household_code, household_head_3.surname, AGE, '2', '1990',
             'Male' if household_head_3.male else 'Female', 1, self.no_option.order, self.no_option.text, 1],
            ['Kampala', household_head_4.household.household_code, household_head_4.surname, AGE, '2', '1990',
             'Male' if household_head_4.male else 'Female', 2, self.yes_option.order, self.yes_option.text, 2],
            ['Kampala', household_head_5.household.household_code, household_head_5.surname, AGE, '2', '1990',
             'Male' if household_head_5.male else 'Female', 3, self.yes_option.order, self.yes_option.text, 3]]

        actual_csv_data = result_down_load_service.get_summarised_answers()
        self.assertEqual(5, len(actual_csv_data))
        for i in range(5):
            self.assertIn(expected_csv_data[i], actual_csv_data)
Пример #13
0
    def test_gets_summarised_response_for_a_given_batch(self):
        HouseholdMemberGroup.objects.create(name="GENERAL", order=2)
        household_head_1 = self.create_household_head(0, self.investigator, self.batch.survey)
        household_head_2 = self.create_household_head(1, self.investigator, self.batch.survey)
        household_head_3 = self.create_household_head(2, self.investigator, self.batch.survey)
        household_head_4 = self.create_household_head(3, self.investigator, self.batch.survey)
        household_head_5 = self.create_household_head(4, self.investigator, self.batch.survey)

        self.investigator.member_answered(self.question_1, household_head_1, 1, self.batch)
        self.investigator.member_answered(self.question_1, household_head_2, 2, self.batch)
        self.investigator.member_answered(self.question_1, household_head_3, 1, self.batch)
        self.investigator.member_answered(self.question_1, household_head_4, 2, self.batch)
        self.investigator.member_answered(self.question_1, household_head_5, 3, self.batch)

        self.investigator.member_answered(self.question_2, household_head_1, self.no_option.order, self.batch)
        self.investigator.member_answered(self.question_2, household_head_2, self.yes_option.order, self.batch)
        self.investigator.member_answered(self.question_2, household_head_3, self.no_option.order, self.batch)
        self.investigator.member_answered(self.question_2, household_head_4, self.yes_option.order, self.batch)
        self.investigator.member_answered(self.question_2, household_head_5, self.yes_option.order, self.batch)

        self.investigator.member_answered(self.question_3, household_head_1, 1, self.batch)
        self.investigator.member_answered(self.question_3, household_head_2, 2, self.batch)
        self.investigator.member_answered(self.question_3, household_head_3, 1, self.batch)
        self.investigator.member_answered(self.question_3, household_head_4, 2, self.batch)
        self.investigator.member_answered(self.question_3, household_head_5, 3, self.batch)

        result_down_load_service = ResultsDownloadService(batch=self.batch)
        AGE = '24'
        expected_csv_data = [
            ['Kampala', household_head_1.household.household_code, household_head_1.surname, AGE, '2', '1990',
             'Male' if household_head_1.male else 'Female', 1, self.no_option.order, self.no_option.text, 1],
            ['Kampala', household_head_2.household.household_code, household_head_2.surname, AGE, '2', '1990',
             'Male' if household_head_2.male else 'Female', 2, self.yes_option.order, self.yes_option.text, 2],
            ['Kampala', household_head_3.household.household_code, household_head_3.surname, AGE, '2', '1990',
             'Male' if household_head_3.male else 'Female', 1, self.no_option.order, self.no_option.text, 1],
            ['Kampala', household_head_4.household.household_code, household_head_4.surname, AGE, '2', '1990',
             'Male' if household_head_4.male else 'Female', 2, self.yes_option.order, self.yes_option.text, 2],
            ['Kampala', household_head_5.household.household_code, household_head_5.surname, AGE, '2', '1990',
             'Male' if household_head_5.male else 'Female', 3, self.yes_option.order, self.yes_option.text, 3]]

        actual_csv_data = result_down_load_service.get_summarised_answers()
        self.assertEqual(5, len(actual_csv_data))
        for i in range(5):
            self.assertIn(expected_csv_data[i], actual_csv_data)
Пример #14
0
    def test_should_repeat_questions_in_general_for_all_members(self):
        household_listing1 = HouseholdListing.objects.create(ea=self.ea,list_registrar=self.investigator,initial_survey=self.survey)
        survey_householdlisting1 = SurveyHouseholdListing.objects.create(listing=household_listing1,survey=self.survey)
        AGE = '24'
        general_group = HouseholdMemberGroup.objects.create(name="GENERAL", order=2)

        general_condition = GroupCondition.objects.create(attribute="GENERAL", value="HEAD", condition='EQUALS')
        general_group.conditions.add(general_condition)
        module1 = QuestionModule.objects.create(name="Education123")
        general_question_1 = Question.objects.create(identifier='1.111',text="This is a question111", answer_type='Numerical Answer',
                                           group=self.group,batch=self.batch,module=module1)
        general_question_2 = Question.objects.create(identifier='1.112',text="This is a question112", answer_type='Numerical Answer',
                                           group=self.group,batch=self.batch,module=module1)
        ea = EnumerationArea.objects.create(name="EA")
        ea.locations.add(self.kampala)
        household_head_1 = create_household_head(0, self.investigator,household_listing1,survey_householdlisting1)
        household_head_2 = create_household_head(1, self.investigator,household_listing1,survey_householdlisting1)
        household_listing = HouseholdListing.objects.create(ea=ea,list_registrar=self.investigator,initial_survey=self.survey)
        household = Household.objects.create(house_number=123456,listing=household_listing,physical_address='Test address',
                                             last_registrar=self.investigator,registration_channel="ODK Access",head_desc="Head",head_sex='MALE')
        survey_householdlisting = SurveyHouseholdListing.objects.create(listing=household_listing,survey=self.survey)
        member_1 = HouseholdMember.objects.create(surname="sur", first_name='fir', gender='MALE', date_of_birth="1988-01-01",
                                                          household=household_head_1.household,survey_listing=survey_householdlisting,
                                                          registrar=self.investigator,registration_channel="ODK Access")
        member_2 = HouseholdMember.objects.create(surname="sur", first_name='fir', gender='MALE', date_of_birth="1988-01-01",
                                                          household=household_head_2.household,survey_listing=survey_householdlisting,
                                                          registrar=self.investigator,registration_channel="ODK Access")
        result_down_load_service = ResultsDownloadService(batch=self.batch)
        age = '28'
        age_14 = '15'
        household1=household_head_1.surname+'-'+household_head_1.first_name
        member1=member_1.surname+'-'+member_1.first_name
        household2=household_head_2.surname+'-'+household_head_2.first_name
        expected_csv_data = [
            [u'Kampala',unicode(ea.name), household_head_1.household.house_number, household1, age,  '01-01-1988',
             'Male' if household_head_1.household.head_sex else 'Female'],
            [u'Kampala' ,unicode(ea.name), household_head_2.household.house_number, household2, age, '01-01-1988',
             'Male' if household_head_2.household.head_sex else 'Female']]

        actual_csv_data = result_down_load_service.get_summarised_answers()
        self.assertEqual(4, len(actual_csv_data))
        for i in range(2):
            self.assertIn(expected_csv_data[i], actual_csv_data)
Пример #15
0
def _process_export(survey_batch_filter_form):
    batch = survey_batch_filter_form.cleaned_data['batch']
    survey = survey_batch_filter_form.cleaned_data['survey']
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="%s.csv"' % (
        batch.name if batch else survey.name)
    data = ResultsDownloadService(batch=batch, survey=survey).generate_report()
    writer = csv.writer(response)
    for row in data:
        writer.writerow(row)
    return response
Пример #16
0
def download_data(request, qset_id):
    qset = QuestionSet.get(pk=qset_id)
    params = request.GET if request.method == 'GET' else request.POST
    survey_filter = QuestionSetResultsFilterForm(qset, data=params)
    locations_filter = LocationsFilterForm(data=request.GET, include_ea=True)
    interviews = survey_filter.get_interviews()
    if locations_filter.is_valid():
        interviews = interviews.filter(
            ea__in=locations_filter.get_enumerations()).order_by('created')
    last_selected_loc = locations_filter.last_location_selected
    download_service = ResultsDownloadService(qset, interviews=interviews)
    file_name = '%s%s' % ('%s-%s-' %
                          (last_selected_loc.type.name, last_selected_loc.name)
                          if last_selected_loc else '', qset.name)
    reports_df = download_service.generate_interview_reports()
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment;\
        filename="%s.csv"' % file_name
    reports_df.to_csv(response,
                      date_format='%Y-%m-%d %H:%M:%S',
                      encoding='utf-8')  # exclude interview id
    return response
Пример #17
0
 def test_gets_summarised_response_for_a_given_batch(self):
     household_listing = HouseholdListing.objects.create(ea=self.ea,list_registrar=self.investigator,initial_survey=self.survey)
     survey_householdlisting = SurveyHouseholdListing.objects.create(listing=household_listing,survey=self.survey)
     HouseholdMemberGroup.objects.create(name="GENERAL", order=2)
     household_head_1 = create_household_head(0, self.investigator,household_listing,survey_householdlisting)
     household_head_2 = create_household_head(1, self.investigator,household_listing,survey_householdlisting)
     household_head_3 = create_household_head(2, self.investigator,household_listing,survey_householdlisting)
     household_head_4 = create_household_head(3, self.investigator,household_listing,survey_householdlisting)
     household_head_5 = create_household_head(4, self.investigator,household_listing,survey_householdlisting)
     result_down_load_service = ResultsDownloadService(batch=self.batch)
     AGE = '28'
     household1=household_head_1.surname+'-'+household_head_1.first_name
     household2=household_head_2.surname+'-'+household_head_2.first_name
     household3=household_head_3.surname+'-'+household_head_3.first_name
     household4=household_head_4.surname+'-'+household_head_4.first_name
     household5=household_head_5.surname+'-'+household_head_5.first_name
     expected_csv_data = [
         [u'Kampala', unicode(self.ea.name), household_head_1.household.house_number,unicode(household1),AGE, '01-01-1988',
          'Male' if household_head_1.household.head_sex else 'Female'],
         [u'Kampala', unicode(self.ea.name),household_head_2.household.house_number, unicode(household2), AGE, '01-01-1988',
          'Male' if household_head_2.household.head_sex else 'Female'],
         [u'Kampala', unicode(self.ea.name),household_head_3.household.house_number, unicode(household3), AGE, '01-01-1988',
          'Male' if household_head_3.household.head_sex else 'Female'],
         [u'Kampala', unicode(self.ea.name),household_head_4.household.house_number, unicode(household4),AGE, '01-01-1988',
          'Male' if household_head_4.household.head_sex else 'Female'],
         [u'Kampala', unicode(self.ea.name),household_head_5.household.house_number, unicode(household5),AGE, '01-01-1988',
          'Male' if household_head_5.household.head_sex else 'Female']]
     batch = Batch.objects.create(name="Batch name", description='description')
     group_1 = HouseholdMemberGroup.objects.create(name="Group 11", order=10)
     group_2 = HouseholdMemberGroup.objects.create(name="Group 12", order=11)
     group_3 = HouseholdMemberGroup.objects.create(name="Group 13", order=12)
     household_member_group = HouseholdMemberGroup.objects.create(name="Greater than 65 years", order=19)
     question_mod = QuestionModule.objects.create(name="Test question name",description="test desc")
     question_1 = Question.objects.create(identifier='1.1',text="This is a question1", answer_type='Numerical Answer',
                                         group=group_3,batch=batch,module=question_mod)
     actual_csv_data = result_down_load_service.get_summarised_answers()
     self.assertEqual(5, len(actual_csv_data))
     for i in range(5):
         self.assertIn(expected_csv_data[i], actual_csv_data)
Пример #18
0
def download_data(request, qset_id):
    qset = QuestionSet.get(pk=qset_id)
    params = request.GET if request.method == 'GET' else request.POST
    survey_filter = QuestionSetResultsFilterForm(qset, data=params)
    locations_filter = LocationsFilterForm(data=request.GET, include_ea=True)
    interviews = survey_filter.get_interviews()
    if locations_filter.is_valid():
        interviews = interviews.filter(
            ea__in=locations_filter.get_enumerations()).order_by('created')
    last_selected_loc = locations_filter.last_location_selected
    download_service = ResultsDownloadService(qset, interviews=interviews)
    file_name = '%s%s' % ('%s-%s-' % (
        last_selected_loc.type.name,
        last_selected_loc.name) if last_selected_loc else '',
        qset.name)
    reports_df = download_service.generate_interview_reports()
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment;\
        filename="%s.csv"' % file_name
    reports_df.to_csv(
        response,
        date_format='%Y-%m-%d %H:%M:%S',
        encoding='utf-8')  # exclude interview id
    return response
    def test_gets_summarised_response_for_all_batches_under_survey(self):
        HouseholdMemberGroup.objects.create(name="GENERAL", order=2)
        household_head_1 = self.create_household_head(0, self.investigator, self.batch.survey)
        household_head_2 = self.create_household_head(1, self.investigator, self.batch.survey)
        household_head_3 = self.create_household_head(2, self.investigator, self.batch.survey)
        household_head_4 = self.create_household_head(3, self.investigator, self.batch.survey)
        household_head_5 = self.create_household_head(4, self.investigator, self.batch.survey)

        self.investigator.member_answered(self.question_1, household_head_1, 1, self.batch)
        self.investigator.member_answered(self.question_1, household_head_2, 2, self.batch)
        self.investigator.member_answered(self.question_1, household_head_3, 1, self.batch)
        self.investigator.member_answered(self.question_1, household_head_4, 2, self.batch)
        self.investigator.member_answered(self.question_1, household_head_5, 3, self.batch)

        self.investigator.member_answered(self.question_2, household_head_1, self.no_option.order, self.batch)
        self.investigator.member_answered(self.question_2, household_head_2, self.yes_option.order, self.batch)
        self.investigator.member_answered(self.question_2, household_head_3, self.no_option.order, self.batch)
        self.investigator.member_answered(self.question_2, household_head_4, self.yes_option.order, self.batch)
        self.investigator.member_answered(self.question_2, household_head_5, self.yes_option.order, self.batch)

        self.investigator.member_answered(self.question_3, household_head_1, 1, self.batch)
        self.investigator.member_answered(self.question_3, household_head_2, 2, self.batch)
        self.investigator.member_answered(self.question_3, household_head_3, 1, self.batch)
        self.investigator.member_answered(self.question_3, household_head_4, 2, self.batch)
        self.investigator.member_answered(self.question_3, household_head_5, 3, self.batch)

        batchB = Batch.objects.create(order=2, name="different batch", survey=self.survey)
        module = QuestionModule.objects.create(name="Education in a different batch")
        question_1B = Question.objects.create(group=self.group, text="Question 1 B", module=module,
                                                  answer_type=Question.NUMBER,
                                                  order=1, identifier='Q1B')
        question_2B = Question.objects.create(group=self.group, text="Question 2B", module=module,
                                                  answer_type=Question.MULTICHOICE,
                                                  order=2, identifier='Q2B')
        question_3B = Question.objects.create(group=self.group, text="Question 3B", module=module,
                                                  answer_type=Question.NUMBER,
                                                  order=3, identifier='Q3B')

        yes_option = QuestionOption.objects.create(question=question_2B, text="Yes", order=1)
        no_option = QuestionOption.objects.create(question=question_2B, text="No", order=2)

        question_1B.batches.add(batchB)
        question_2B.batches.add(batchB)
        question_3B.batches.add(batchB)

        BatchQuestionOrder.objects.create(question=question_1B, batch=batchB, order=1)
        BatchQuestionOrder.objects.create(question=question_2B, batch=batchB, order=2)
        BatchQuestionOrder.objects.create(question=question_3B, batch=batchB, order=3)

        self.investigator.member_answered(question_1B, household_head_1, 1, batchB)
        self.investigator.member_answered(question_1B, household_head_2, 2, batchB)
        self.investigator.member_answered(question_1B, household_head_3, 1, batchB)
        self.investigator.member_answered(question_1B, household_head_4, 2, batchB)
        self.investigator.member_answered(question_1B, household_head_5, 3, batchB)

        self.investigator.member_answered(question_2B, household_head_1, no_option.order, batchB)
        self.investigator.member_answered(question_2B, household_head_2, yes_option.order, batchB)
        self.investigator.member_answered(question_2B, household_head_3, no_option.order, batchB)
        self.investigator.member_answered(question_2B, household_head_4, yes_option.order, batchB)
        self.investigator.member_answered(question_2B, household_head_5, yes_option.order, batchB)

        self.investigator.member_answered(question_3B, household_head_1, 1, batchB)
        self.investigator.member_answered(question_3B, household_head_2, 2, batchB)
        self.investigator.member_answered(question_3B, household_head_3, 1, batchB)
        self.investigator.member_answered(question_3B, household_head_4, 2, batchB)
        self.investigator.member_answered(question_3B, household_head_5, 3, batchB)

        result_down_load_service = ResultsDownloadService(survey=self.survey)

        header_structure = [self.district.name, self.county.name, self.subcounty.name, self.parish.name,
                            self.village.name,
                            'Household ID', 'Name', 'Age', 'Month of Birth', 'Year of Birth', 'Gender',
                            self.question_1.identifier, self.question_2.identifier, '', self.question_3.identifier,
                            question_1B.identifier, question_2B.identifier, '', question_3B.identifier]

        headers = result_down_load_service.set_report_headers()
        self.assertEqual(header_structure, headers)

        age = '24'
        expected_csv_data = [
            ['Kampala', household_head_1.household.household_code, household_head_1.surname, age, '2', '1990',
             'Male' if household_head_1.male else 'Female', 1, self.no_option.order, self.no_option.text, 1,
            1, no_option.order, no_option.text, 1],
            ['Kampala', household_head_2.household.household_code, household_head_2.surname, age, '2', '1990',
             'Male' if household_head_2.male else 'Female', 2, self.yes_option.order, self.yes_option.text, 2,
             2, yes_option.order, yes_option.text, 2],
            ['Kampala', household_head_3.household.household_code, household_head_3.surname, age, '2', '1990',
             'Male' if household_head_3.male else 'Female', 1, self.no_option.order, self.no_option.text, 1,
             1, no_option.order, no_option.text, 1],
            ['Kampala', household_head_4.household.household_code, household_head_4.surname, age, '2', '1990',
             'Male' if household_head_4.male else 'Female', 2, self.yes_option.order, self.yes_option.text, 2,
             2, yes_option.order, yes_option.text, 2],
            ['Kampala', household_head_5.household.household_code, household_head_5.surname, age, '2', '1990',
             'Male' if household_head_5.male else 'Female', 3, self.yes_option.order, self.yes_option.text, 3,
             3, yes_option.order, yes_option.text, 3]]

        actual_csv_data = result_down_load_service.get_summarised_answers()
        self.assertEqual(5, len(actual_csv_data))
        for i in range(5):
            self.assertIn(expected_csv_data[i], actual_csv_data)
 def test_reference_interview_report(self):
     listing_form = mommy.make(ListingTemplate)
     mommy.make(QuestionSetChannel,
                qset=listing_form,
                channel=self.access_channel.choice_name())
     self.survey.has_sampling = True
     self.survey.listing_form = listing_form
     self.survey.save()
     interviews = self._prep_answers(listing_form)
     rs = ResultsDownloadService(listing_form,
                                 survey=self.survey,
                                 follow_ref=True)
     reports_df = rs.generate_interview_reports()
     for idx, interview in enumerate(interviews):
         for answer in interview.answer.all():
             # since this ref_interview only captured one row of information, so this is valid
             self.assertEquals(answer.as_text,
                               reports_df[answer.question.identifier][idx])
     self.assertEquals(reports_df['EA'][0], self.ea.name)
     for location in self.ea.locations.first().get_ancestors().exclude(
             id=Location.country().id):
         self.assertEquals(reports_df[location.type.name][0], location.name)
     ref_interview = Interview.objects.last()
     self._create_ussd_non_group_questions(self.qset)
     n_quest = Question.objects.filter(
         answer_type=NumericalAnswer.choice_name(), qset=self.qset).last()
     t_quest = Question.objects.filter(answer_type=TextAnswer.choice_name(),
                                       qset=self.qset).last()
     m_quest = Question.objects.filter(
         answer_type=MultiChoiceAnswer.choice_name(),
         qset=self.qset).last()
     answers = [
         {
             n_quest.id: 27,
             t_quest.id: 'Test Ref',
             m_quest.id: 'N'
         },
     ]
     question_map = {
         n_quest.id: n_quest,
         t_quest.id: t_quest,
         m_quest.id: m_quest
     }
     Interview.objects.filter(question_set=self.qset).delete()
     interviews = Interview.save_answers(self.qset,
                                         self.survey,
                                         self.ea,
                                         self.access_channel,
                                         question_map,
                                         answers,
                                         reference_interview=ref_interview)
     rs = ResultsDownloadService(self.qset,
                                 survey=self.survey,
                                 follow_ref=True)
     reports_df = rs.generate_interview_reports()
     for answer in ref_interview.answer.all():
         # since this ref_interview only captured one row of information, so this is valid
         self.assertEquals(answer.as_text,
                           reports_df[answer.question.identifier][0])
     for answer in interviews[0].answer.all():
         # since this ref_interview only captured one row of information, so this is valid
         self.assertEquals(answer.as_text,
                           reports_df[answer.question.identifier][0])
     self.assertEquals(reports_df['EA'][0], self.ea.name)
     for location in self.ea.locations.first().get_ancestors().exclude(
             id=Location.country().id):
         self.assertEquals(reports_df[location.type.name][0], location.name)
Пример #21
0
def download(request):
    request_data = request.GET if request.method == 'GET' else request.POST
    survey_batch_filter_form = SurveyBatchFilterForm(data=request_data)
    locations_filter = LocationsFilterForm(data=request_data)
    last_selected_loc = locations_filter.last_location_selected
    if request_data and request_data.get('action'):
        survey_batch_filter_form = SurveyBatchFilterForm(data=request_data)
        if survey_batch_filter_form.is_valid():
            batch = survey_batch_filter_form.cleaned_data['batch']
            survey = survey_batch_filter_form.cleaned_data['survey']
            multi_option = \
                survey_batch_filter_form.cleaned_data['multi_option']
            restricted_to = None
            if last_selected_loc:
                restricted_to = [
                    last_selected_loc,
                ]
            if request_data.get('action') == 'Email Spreadsheet':
                composer = ResultComposer(
                    request.user,
                    ResultsDownloadService(batch,
                                           survey=survey,
                                           restrict_to=restricted_to,
                                           multi_display=multi_option))
                send_mail.delay(composer)
                messages.warning(
                    request, "Email would be sent to\
                        you shortly. This could take a while.")
            else:
                download_service = ResultsDownloadService(
                    batch,
                    survey=survey,
                    restrict_to=restricted_to,
                    multi_display=multi_option)
                file_name = '%s%s' % (
                    '%s-%s-' %
                    (last_selected_loc.type.name, last_selected_loc.name)
                    if last_selected_loc else '',
                    batch.name if batch else survey.name)
                reports_df = download_service.generate_interview_reports()
                response = HttpResponse(content_type='application/zip')
                string_buf = StringIO()
                reports_df.to_csv(string_buf, columns=reports_df.columns[1:])
                string_buf.seek(0)
                file_contents = string_buf.read()
                string_buf.close()
                zip_file = InMemoryZip()
                zip_file = zip_file.append("%s.csv" % file_name, file_contents)
                response['Content-Disposition'] = 'attachment;\
                    filename=%s.zip' % file_name
                response.write(zip_file.read())
                # exclude interview id
                if not request.is_ajax():
                    messages.info(request, "Download successfully downloaded")
                return response
    loc_types = LocationType.in_between()
    return render(
        request, 'aggregates/download_excel.html', {
            'survey_batch_filter_form':
            survey_batch_filter_form,
            'locations_filter':
            locations_filter,
            'export_url':
            '%s?%s' % (reverse('excel_report'), request.META['QUERY_STRING']),
            'location_filter_types':
            loc_types
        })
Пример #22
0
    def test_gets_summarised_response_for_all_batches_under_survey(self):
        HouseholdMemberGroup.objects.create(name="GENERAL", order=2)
        household_head_1 = self.create_household_head(0, self.investigator, self.batch.survey)
        household_head_2 = self.create_household_head(1, self.investigator, self.batch.survey)
        household_head_3 = self.create_household_head(2, self.investigator, self.batch.survey)
        household_head_4 = self.create_household_head(3, self.investigator, self.batch.survey)
        household_head_5 = self.create_household_head(4, self.investigator, self.batch.survey)

        self.investigator.member_answered(self.question_1, household_head_1, 1, self.batch)
        self.investigator.member_answered(self.question_1, household_head_2, 2, self.batch)
        self.investigator.member_answered(self.question_1, household_head_3, 1, self.batch)
        self.investigator.member_answered(self.question_1, household_head_4, 2, self.batch)
        self.investigator.member_answered(self.question_1, household_head_5, 3, self.batch)

        self.investigator.member_answered(self.question_2, household_head_1, self.no_option.order, self.batch)
        self.investigator.member_answered(self.question_2, household_head_2, self.yes_option.order, self.batch)
        self.investigator.member_answered(self.question_2, household_head_3, self.no_option.order, self.batch)
        self.investigator.member_answered(self.question_2, household_head_4, self.yes_option.order, self.batch)
        self.investigator.member_answered(self.question_2, household_head_5, self.yes_option.order, self.batch)

        self.investigator.member_answered(self.question_3, household_head_1, 1, self.batch)
        self.investigator.member_answered(self.question_3, household_head_2, 2, self.batch)
        self.investigator.member_answered(self.question_3, household_head_3, 1, self.batch)
        self.investigator.member_answered(self.question_3, household_head_4, 2, self.batch)
        self.investigator.member_answered(self.question_3, household_head_5, 3, self.batch)

        batchB = Batch.objects.create(order=2, name="different batch", survey=self.survey)
        module = QuestionModule.objects.create(name="Education in a different batch")
        question_1B = Question.objects.create(group=self.group, text="Question 1 B", module=module,
                                                  answer_type=Question.NUMBER,
                                                  order=1, identifier='Q1B')
        question_2B = Question.objects.create(group=self.group, text="Question 2B", module=module,
                                                  answer_type=Question.MULTICHOICE,
                                                  order=2, identifier='Q2B')
        question_3B = Question.objects.create(group=self.group, text="Question 3B", module=module,
                                                  answer_type=Question.NUMBER,
                                                  order=3, identifier='Q3B')

        yes_option = QuestionOption.objects.create(question=question_2B, text="Yes", order=1)
        no_option = QuestionOption.objects.create(question=question_2B, text="No", order=2)

        question_1B.batches.add(batchB)
        question_2B.batches.add(batchB)
        question_3B.batches.add(batchB)

        BatchQuestionOrder.objects.create(question=question_1B, batch=batchB, order=1)
        BatchQuestionOrder.objects.create(question=question_2B, batch=batchB, order=2)
        BatchQuestionOrder.objects.create(question=question_3B, batch=batchB, order=3)

        self.investigator.member_answered(question_1B, household_head_1, 1, batchB)
        self.investigator.member_answered(question_1B, household_head_2, 2, batchB)
        self.investigator.member_answered(question_1B, household_head_3, 1, batchB)
        self.investigator.member_answered(question_1B, household_head_4, 2, batchB)
        self.investigator.member_answered(question_1B, household_head_5, 3, batchB)

        self.investigator.member_answered(question_2B, household_head_1, no_option.order, batchB)
        self.investigator.member_answered(question_2B, household_head_2, yes_option.order, batchB)
        self.investigator.member_answered(question_2B, household_head_3, no_option.order, batchB)
        self.investigator.member_answered(question_2B, household_head_4, yes_option.order, batchB)
        self.investigator.member_answered(question_2B, household_head_5, yes_option.order, batchB)

        self.investigator.member_answered(question_3B, household_head_1, 1, batchB)
        self.investigator.member_answered(question_3B, household_head_2, 2, batchB)
        self.investigator.member_answered(question_3B, household_head_3, 1, batchB)
        self.investigator.member_answered(question_3B, household_head_4, 2, batchB)
        self.investigator.member_answered(question_3B, household_head_5, 3, batchB)

        result_down_load_service = ResultsDownloadService(survey=self.survey)

        header_structure = [self.district.name, self.county.name, self.subcounty.name, self.parish.name,
                            self.village.name,
                            'Household ID', 'Name', 'Age', 'Month of Birth', 'Year of Birth', 'Gender',
                            self.question_1.identifier, self.question_2.identifier, '', self.question_3.identifier,
                            question_1B.identifier, question_2B.identifier, '', question_3B.identifier]

        headers = result_down_load_service.set_report_headers()
        self.assertEqual(header_structure, headers)

        age = '24'
        expected_csv_data = [
            ['Kampala', household_head_1.household.household_code, household_head_1.surname, age, '2', '1990',
             'Male' if household_head_1.male else 'Female', 1, self.no_option.order, self.no_option.text, 1,
            1, no_option.order, no_option.text, 1],
            ['Kampala', household_head_2.household.household_code, household_head_2.surname, age, '2', '1990',
             'Male' if household_head_2.male else 'Female', 2, self.yes_option.order, self.yes_option.text, 2,
             2, yes_option.order, yes_option.text, 2],
            ['Kampala', household_head_3.household.household_code, household_head_3.surname, age, '2', '1990',
             'Male' if household_head_3.male else 'Female', 1, self.no_option.order, self.no_option.text, 1,
             1, no_option.order, no_option.text, 1],
            ['Kampala', household_head_4.household.household_code, household_head_4.surname, age, '2', '1990',
             'Male' if household_head_4.male else 'Female', 2, self.yes_option.order, self.yes_option.text, 2,
             2, yes_option.order, yes_option.text, 2],
            ['Kampala', household_head_5.household.household_code, household_head_5.surname, age, '2', '1990',
             'Male' if household_head_5.male else 'Female', 3, self.yes_option.order, self.yes_option.text, 3,
             3, yes_option.order, yes_option.text, 3]]

        actual_csv_data = result_down_load_service.get_summarised_answers()
        self.assertEqual(5, len(actual_csv_data))
        for i in range(5):
            self.assertIn(expected_csv_data[i], actual_csv_data)
Пример #23
0
def download(request):
    request_data = request.GET if request.method == 'GET' else request.POST
    survey_batch_filter_form = SurveyBatchFilterForm(data=request_data)
    locations_filter = LocationsFilterForm(data=request_data)
    last_selected_loc = locations_filter.last_location_selected
    if request_data and request_data.get('action'):
        survey_batch_filter_form = SurveyBatchFilterForm(data=request_data)
        if survey_batch_filter_form.is_valid():
            batch = survey_batch_filter_form.cleaned_data['batch']
            survey = survey_batch_filter_form.cleaned_data['survey']
            multi_option = \
                survey_batch_filter_form.cleaned_data['multi_option']
            restricted_to = None
            if last_selected_loc:
                restricted_to = [last_selected_loc, ]
            if request_data.get('action') == 'Email Spreadsheet':
                composer = ResultComposer(
                    request.user,
                    ResultsDownloadService(
                        batch,
                        survey=survey,
                        restrict_to=restricted_to,
                        multi_display=multi_option))
                send_mail.delay(composer)
                messages.warning(
                    request, "Email would be sent to\
                        you shortly. This could take a while.")
            else:
                download_service = ResultsDownloadService(
                    batch,
                    survey=survey,
                    restrict_to=restricted_to,
                    multi_display=multi_option)
                file_name = '%s%s' % ('%s-%s-' % (
                    last_selected_loc.type.name,
                    last_selected_loc.name) if last_selected_loc else '',
                    batch.name if batch else survey.name)
                reports_df = download_service.generate_interview_reports()
                response = HttpResponse(content_type='application/zip')
                string_buf = StringIO()
                reports_df.to_csv(string_buf, columns=reports_df.columns[1:])
                string_buf.seek(0)
                file_contents = string_buf.read()
                string_buf.close()
                zip_file = InMemoryZip()
                zip_file = zip_file.append("%s.csv" % file_name, file_contents)
                response['Content-Disposition'] = 'attachment;\
                    filename=%s.zip' % file_name
                response.write(zip_file.read())
                # exclude interview id
                if not request.is_ajax():
                    messages.info(request, "Download successfully downloaded")
                return response
    loc_types = LocationType.in_between()
    return render(request,
                  'aggregates/download_excel.html',
                  {'survey_batch_filter_form': survey_batch_filter_form,
                   'locations_filter': locations_filter,
                   'export_url': '%s?%s' % (reverse('excel_report'),
                                            request.META['QUERY_STRING']),
                   'location_filter_types': loc_types})