def palu(message): # common start of error message error_start = u"Impossible d'enregistrer le rapport. " # create variables from text messages. try: args_names = ['kw1', 'username', 'password', 'month', 'year', \ 'u5_total_consultation_all_causes', \ 'u5_total_suspected_malaria_cases', \ 'u5_total_simple_malaria_cases', \ 'u5_total_severe_malaria_cases', \ 'u5_total_tested_malaria_cases', \ 'u5_total_confirmed_malaria_cases', \ 'u5_total_treated_malaria_cases', \ 'u5_total_inpatient_all_causes', \ 'u5_total_malaria_inpatient', \ 'u5_total_death_all_causes', \ 'u5_total_malaria_death', \ 'u5_total_distributed_bednets', \ 'o5_total_consultation_all_causes', \ 'o5_total_suspected_malaria_cases', \ 'o5_total_simple_malaria_cases', \ 'o5_total_severe_malaria_cases', \ 'o5_total_tested_malaria_cases', \ 'o5_total_confirmed_malaria_cases', \ 'o5_total_treated_malaria_cases', \ 'o5_total_inpatient_all_causes', \ 'o5_total_malaria_inpatient', \ 'o5_total_death_all_causes', \ 'o5_total_malaria_death', \ 'pw_total_consultation_all_causes', \ 'pw_total_suspected_malaria_cases', \ 'pw_total_severe_malaria_cases', \ 'pw_total_tested_malaria_cases', \ 'pw_total_confirmed_malaria_cases', \ 'pw_total_treated_malaria_cases', \ 'pw_total_inpatient_all_causes', \ 'pw_total_malaria_inpatient', \ 'pw_total_death_all_causes', \ 'pw_total_malaria_death', \ 'pw_total_distributed_bednets', \ 'pw_total_anc1', \ 'pw_total_sp1', \ 'pw_total_sp2', \ 'stockout_act_children', 'stockout_act_youth', 'stockout_act_adult', \ 'stockout_artemether', 'stockout_quinine', 'stockout_serum', \ 'stockout_bednet', 'stockout_rdt', 'stockout_sp'] args_values = message.content.strip().lower().split() arguments = dict(zip(args_names, args_values)) except ValueError: # failure to split means we proabably lack a data or more # we can't process it. message.respond(error_start + u" Le format du SMS est incorrect.") return True # convert form-data to int or bool respectively try: for key, value in arguments.items(): if key.split('_')[0] in ('u5', 'o5', 'pw', 'month', 'year'): arguments[key] = int(value) if key.split('_')[0] == 'stockout': arguments[key] = MalariaReport.YES if bool(int(value)) \ else MalariaReport.NO except: raise # failure to convert means non-numeric value which we can't process. message.respond(error_start + u" Les données sont malformées.") return True # check credentials try: provider = Provider.active.get(user__username=arguments['username']) except Provider.DoesNotExist: message.respond(error_start + u"Ce nom d'utilisateur " + u"(%s) n'existe pas." % \ arguments['username']) return True if not provider.check_password(arguments['password']): message.respond(error_start + u"Votre mot de passe est incorrect.") return True # now we have well formed and authenticated data. # let's check for business-logic errors. # create a data holder for validator data_browser = MalariaDataHolder() # feed data holder with sms provided data for key, value in arguments.items(): if key.split('_')[0] in ('u5', 'o5', 'pw', \ 'stockout', 'year', 'month'): data_browser.set(key, value) # feed data holder with guessable data try: hc = entity_for(provider).slug except: hc = None data_browser.set('hc', hc) today = datetime.date.today() data_browser.set('fillin_day', today.day) data_browser.set('fillin_month', today.month) data_browser.set('fillin_year', today.year) data_browser.set('author', provider.name()) # create validator and fire validator = MalariaReportValidator(data_browser) validator.errors.reset() try: validator.validate() except AttributeError as e: message.respond(error_start + e.__str__()) return True errors = validator.errors # return first error to user if errors.count() > 0: message.respond(error_start + errors.all()[0]) return True # create the report try: period = MonthPeriod.find_create_from(year=data_browser.get('year'), \ month=data_browser.get('month')) entity = Entity.objects.get(slug=data_browser.get('hc'), \ type__slug='cscom') report = MalariaReport.start(period, entity, provider, \ type=MalariaReport.TYPE_SOURCE) report.add_underfive_data(*data_browser.data_for_cat('u5')) report.add_overfive_data(*data_browser.data_for_cat('o5')) report.add_pregnantwomen_data(*data_browser.data_for_cat('pw')) report.add_stockout_data(*data_browser.data_for_cat('so')) #report.save() with reversion.create_revision(): report.save() reversion.set_user(provider.user) except Exception as e: message.respond(error_start + u"Une erreur technique s'est " \ u"produite. Reessayez plus tard et " \ u"contactez ANTIM si le probleme persiste.") logger.error(u"Unable to save report to DB. Message: %s | Exp: %r" \ % (message.content, e)) return True message.respond(u"[SUCCES] Le rapport de %(cscom)s pour %(period)s " u"a ete enregistre. " \ u"Le No de recu est #%(receipt)s." \ % {'cscom': report.entity.display_full_name(), \ 'period': report.period, \ 'receipt': report.receipt}) try: to = contact_for(report.entity.parent).phone_number except: to = None if not to: return True send_sms(to, u"[ALERTE] Le CSCom %(cscom)s vient d'envoyer le " \ u"rapport #%(receipt)s pour %(period)s." \ % {'cscom': report.entity.display_full_name(), \ 'period': report.period, \ 'receipt': report.receipt}) return True
def validate(self): """ runs MalariaReportValidator """ from pnlp_core.validators import MalariaReportValidator validator = MalariaReportValidator(self) validator.validate() return validator.errors
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 validate(self): """ Triggers malaria routine Validator """ validator = MalariaReportValidator(self) validator.errors.reset() validator.validate() self.errors.fusion(validator.errors)