def validation_list(request): context = {'category': 'validation'} web_provider = request.user.get_profile() entity = provider_entity(web_provider) period = current_reporting_period() # check permission or raise 403 # should never raise as already checked by decorator provider_can_or_403('can_validate_report', web_provider, entity) not_sent = [(ent, contact_for(ent)) \ for ent in get_not_received_reports(entity, period)] context.update({'not_validated': get_reports_to_validate(entity, period), 'validated': get_validated_reports(entity, period), 'not_sent': not_sent}) context.update({'is_complete': context['validated'].__len__() == \ entity.get_children().__len__(), 'is_idle': context['not_validated'].__len__() == 0 \ and context['not_sent'].__len__() > 0}) context.update({'time_cscom_over': time_cscom_over(), \ 'time_district_over': time_district_over(), \ 'time_region_over': time_region_over()}) context.update({'validation_over': not time_can_validate(entity)}) context.update({'current_period': current_period(), \ 'current_reporting_period': period}) return render(request, 'validation_list.html', context)
def validation_list(request): context = {'category': 'validation'} web_provider = request.user.get_profile() entity = provider_entity(web_provider) period = current_reporting_period() # check permission or raise 403 # should never raise as already checked by decorator provider_can_or_403('can_validate_report', web_provider, entity) not_sent = [(ent, contact_for(ent)) \ for ent in get_not_received_reports(entity, period)] context.update({ 'not_validated': get_reports_to_validate(entity, period), 'validated': get_validated_reports(entity, period), 'not_sent': not_sent }) context.update({'is_complete': context['validated'].__len__() == \ entity.get_children().__len__(), 'is_idle': context['not_validated'].__len__() == 0 \ and context['not_sent'].__len__() > 0}) context.update({'time_cscom_over': time_cscom_over(), \ 'time_district_over': time_district_over(), \ 'time_region_over': time_region_over()}) context.update({'validation_over': not time_can_validate(entity)}) context.update({'current_period': current_period(), \ 'current_reporting_period': period}) return render(request, 'validation_list.html', context)
def report_do_validation(request, report_receipt): context = {'category': 'validation'} web_provider = request.user.get_profile() report = get_object_or_404(MalariaReport, receipt=report_receipt) # check permission or raise 403 provider_can_or_403('can_validate_report', web_provider, report.entity) report._status = MalariaReport.STATUS_VALIDATED report.modified_by = web_provider report.modified_on = datetime.now() with reversion.create_revision(): report.save() reversion.set_user(web_provider.user) context.update({'report': report}) messages.info(request, u"Le rapport %(receipt)s de %(entity)s " \ u"a été validé." % {'receipt': report.receipt, \ 'entity': report.entity}) return redirect('validation')
def excel_export(request, report_receipt): context = {'category': 'raw_data'} web_provider = request.user.get_profile() report = get_object_or_404(MalariaReport, receipt=report_receipt) context.update({'report': report}) # check permission or raise 403 provider_can_or_403('can_view_raw_data', web_provider, report.entity) file_name = 'PNLP_%(entity)s.%(month)s.%(year)s.xls' \ % {'entity': report.entity.slug, \ 'month': report.period.middle().month, \ 'year': report.period.middle().year} file_content = report_as_excel(report).getvalue() response = HttpResponse(file_content, \ content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="%s"' % file_name response['Content-Length'] = len(file_content) return response
def report_validation(request, report_receipt): context = {'category': 'validation'} web_provider = request.user.get_profile() report = get_object_or_404(MalariaReport, receipt=report_receipt) context.update({'report': report}) # check permission or raise 403 provider_can_or_403('can_validate_report', web_provider, report.entity) if request.method == 'POST': form = MalariaReportForm(request.POST, instance=report) if form.is_valid(): data_browser = MalariaDataHolder() # feed data holder with sms provided data for key in form.cleaned_data: if key.split('_')[0] in ('u5', 'o5', 'pw', 'stockout'): data_browser.set(key, form.cleaned_data.get(key)) # feed data holder with guessable data data_browser.set('month', report.period.middle().month) data_browser.set('year', report.period.middle().year) data_browser.set('hc', report.entity.slug) data_browser.set('fillin_day', report.created_on.day) data_browser.set('fillin_month', report.created_on.month) data_browser.set('fillin_year', report.created_on.year) data_browser.set('author', report.created_by.name()) # create validator and fire validator = MalariaReportValidator(data_browser, data_only=True, is_editing=True, level=web_provider.first_role().slug) validator.errors.reset() try: validator.validate() except Exception as e: print(u"Exception on form validation. " u"Report %(id)d with %(e)r" % {'id': report.id, 'e': e}) raise if validator.errors.count() > 0: # validation errors context.update({'all_errors': validator.errors.all(True)}) else: # no validation error neither # save report new_report = form.save(commit=False) new_report.modified_by = web_provider new_report.modified_on = datetime.now() with reversion.create_revision(): new_report.save() reversion.set_user(web_provider.user) #new_report.save() context.update({'saved': True, 'report': new_report}) else: # django form validation errors pass else: form = MalariaReportForm(instance=report) context.update({'form': form}) return render(request, 'report_validation.html', context)
def report_validation(request, report_receipt): context = {'category': 'validation'} web_provider = request.user.get_profile() report = get_object_or_404(MalariaReport, receipt=report_receipt) context.update({'report': report}) # check permission or raise 403 provider_can_or_403('can_validate_report', web_provider, report.entity) if request.method == 'POST': form = MalariaReportForm(request.POST, instance=report) if form.is_valid(): data_browser = MalariaDataHolder() # feed data holder with sms provided data for key in form.cleaned_data: if key.split('_')[0] in ('u5', 'o5', 'pw', 'stockout'): data_browser.set(key, form.cleaned_data.get(key)) # feed data holder with guessable data data_browser.set('month', report.period.middle().month) data_browser.set('year', report.period.middle().year) data_browser.set('hc', report.entity.slug) data_browser.set('fillin_day', report.created_on.day) data_browser.set('fillin_month', report.created_on.month) data_browser.set('fillin_year', report.created_on.year) data_browser.set('author', report.created_by.name()) # create validator and fire validator = MalariaReportValidator( data_browser, data_only=True, is_editing=True, level=web_provider.first_role().slug) validator.errors.reset() try: validator.validate() except Exception as e: print(u"Exception on form validation. " u"Report %(id)d with %(e)r" % { 'id': report.id, 'e': e }) raise if validator.errors.count() > 0: # validation errors context.update({'all_errors': validator.errors.all(True)}) else: # no validation error neither # save report new_report = form.save(commit=False) new_report.modified_by = web_provider new_report.modified_on = datetime.now() with reversion.create_revision(): new_report.save() reversion.set_user(web_provider.user) #new_report.save() context.update({'saved': True, 'report': new_report}) else: # django form validation errors pass else: form = MalariaReportForm(instance=report) context.update({'form': form}) return render(request, 'report_validation.html', context)
def indicator_browser(request, entity_code=None, period_str=None, \ section_index='1', sub_section=None): context = {'category': 'indicator_data'} web_provider = request.user.get_profile() root = web_provider.first_target() periods = [] speriod = eperiod = None entity = None #section_index = int(section_index) - 1 # find entity or default to provider target # raise 404 on wrong provided entity code if entity_code: entity = get_object_or_404(Entity, slug=entity_code) if not entity: entity = web_provider.first_target() context.update({'entity': entity}) # define a list of all possible periods. # this is the list of all existing MonthPeriod anterior to current def all_anterior_periods(period): return MonthPeriod.objects\ .filter(start_on__lte=period.start_on)\ .order_by('start_on') all_periods = list(all_anterior_periods(current_reporting_period()).all()) if not MalariaReport.validated.filter(entity=entity, period=current_reporting_period()) \ .count(): all_periods.remove(current_reporting_period()) # retrieve Periods from string # if period_string include innexistant periods -> 404. if period_str: speriod_str, eperiod_str = period_str.split('-') try: speriod = MonthPeriod.find_create_from(\ year=int(speriod_str[-4:]), \ month=int(speriod_str[:2]), \ dont_create=True) eperiod = MonthPeriod.find_create_from(\ year=int(eperiod_str[-4:]), \ month=int(eperiod_str[:2]), \ dont_create=True) # loop on Period.next() from start one to end one. period = speriod while period.middle() <= eperiod.middle(): periods.append(period) period = period.next() except: raise Http404(_(u"Requested period interval (%(period_str)s) " \ u"includes inexistant periods.") \ % {'period': period_str}) # in case user did not request a specific interval # default to current_reporting_period if not speriod or not eperiod: speriod = eperiod = current_reporting_period() periods = [speriod] # if end period is before start period, redirect to opposite if eperiod.middle() < speriod.middle(): return redirect('indicator_data', \ entity_code=entity.slug, \ period_str='%s-%s' % (eperiod.pid, speriod.pid)) # periods variables context.update({'period_str': '%s-%s' % (speriod.pid, eperiod.pid), \ 'speriod': speriod, 'eperiod': eperiod}) context.update({'periods': [(p.pid, p.middle()) for p in periods], \ 'all_periods': [(p.pid, p.middle()) for p in all_periods]}) # check permissions on this entity and raise 403 provider_can_or_403('can_view_indicator_data', web_provider, entity) # build entities browser context.update({'root': root, \ 'paths': entities_path(root, entity)}) from pnlp_core.indicators import INDICATOR_SECTIONS context.update({'sections': \ sorted(INDICATOR_SECTIONS.values(), \ cmp=lambda a, b: int(a['id'].strip('a').strip('b')) \ - int(b['id'].strip('a').strip('b')))}) try: section = INDICATOR_SECTIONS[section_index] if not sub_section: if len(section['sections']): sub_section = section['sections'].keys()[0] sname = 'pnlp_core.indicators.section%s' % section_index.__str__() if sub_section: sname = '%s_%s' % (sname, sub_section.__str__()) sm = import_path(sname) except: raise raise Http404(_(u"This section does not exist.")) # section 1 specifics if section_index == '1': context.update({'contact': contact_for(entity)}) context.update({'section': section, 'sub_section': sub_section}) context.update({'widgets': [widget(entity=entity, periods=periods) \ for widget in sm.WIDGETS]}) return render(request, 'indicator_data.html', context)
def data_browser(request, entity_code=None, period_str=None): context = {'category': 'raw_data'} web_provider = request.user.get_profile() root = web_provider.first_target() period = None entity = None # find period from string or default to current reporting if period_str: try: period = MonthPeriod.find_create_from(year=int(period_str[-4:]), \ month=int(period_str[:2]), \ dont_create=True) except: pass if not period: period = current_reporting_period() # find entity or default to provider target # raise 404 on wrong provided entity code if entity_code: entity = get_object_or_404(Entity, slug=entity_code) if not entity: entity = web_provider.first_target() context.update({'entity': entity}) # check permissions on this entity and raise 403 provider_can_or_403('can_view_raw_data', web_provider, entity) # build entities browser context.update({'root': root, \ 'paths': entities_path(root, entity)}) # build periods list all_periods = raw_data_periods_for(entity) if period_str and not period in all_periods: raise Http404(_(u"No report for that period")) try: # get validated report for that period and location report = MalariaReport.validated.get(entity=entity, period=period) except MalariaReport.DoesNotExist: # district users need to be able to see the generated report # which have been created based on their validations/data. # if a district is looking at its root district and report exist # but not validated, we show it (with period) and no valid flag if web_provider.first_role().slug == 'district' and root == entity: try: report = MalariaReport.unvalidated.get(entity=entity, \ period=period) if not period in all_periods: all_periods.insert(0, period) except: report = None else: report = None # send period variables to template context.update({'periods': [(p.middle().strftime('%m%Y'), p.middle()) \ for p in all_periods], \ 'period': period}) if report: context.update({'report': report}) form = MalariaReportForm(instance=report) context.update({'form': form}) else: context.update({'no_report': True}) return render(request, 'raw_data.html', context)