本文整理汇总了Python中snisi_core.models.Periods.MonthPeriod.current方法的典型用法代码示例。如果您正苦于以下问题:Python MonthPeriod.current方法的具体用法?Python MonthPeriod.current怎么用?Python MonthPeriod.current使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类snisi_core.models.Periods.MonthPeriod
的用法示例。
在下文中一共展示了MonthPeriod.current方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: handle
# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import current [as 别名]
def handle(self, *args, **options):
period = MonthPeriod.current().previous()
cluster = Cluster.get_or_none("nutrition_routine")
districts = [e.casted() for e in cluster.members()
if e.type.slug == 'health_district']
print("DISTRICT,ATTENDUS,ARRIVÉS,COMPLÉTUDE")
tot_nb_exp = 0
tot_nb_arr = 0
for district in districts:
exps = ExpectedReporting.objects.filter(
period=period, entity__parent__parent=district,
report_class__slug='nutrition_monthly_routine')
nb_exp = exps.count()
nb_arr = exps.filter(
completion_status=ExpectedReporting.COMPLETION_COMPLETE) \
.count()
tot_nb_exp += nb_exp
tot_nb_arr += nb_arr
pc = nb_arr / float(nb_exp)
print("{ds},{exp},{arr},{pc}".format(
ds=district.name, exp=nb_exp, arr=nb_arr, pc=pc))
tot_pc = tot_nb_arr / float(tot_nb_exp)
print("TOTAL,{exp},{arr},{pc}".format(exp=tot_nb_exp,
arr=tot_nb_arr, pc=tot_pc))
示例2: handle
# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import current [as 别名]
def handle(self, *args, **options):
logger.info("snisi_cataract daily-checkups")
day = timezone.now().day
period = MonthPeriod.current().previous()
category_matrix = {
'end_of_cataract_mission_period': generate_aggregated_reports,
}
def handle_category(category):
slug = "{domain}_{period}_{category}".format(
domain=DOMAIN_SLUG, period=period.strid(), category=category)
task, created = PeriodicTask.get_or_create(slug, category)
if task.can_trigger():
try:
category_matrix.get(category)(period)
except Exception as e:
logger.exception(e)
else:
task.trigger()
if day >= ROUTINE_REGION_AGG_DAY:
# validate all district reports
# create aggregated for region
# create aggregated for country
# send notification to central/national
handle_category("end_of_cataract_mission_period")
示例3: dashboard
# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import current [as 别名]
def dashboard(request, **kwargs):
now = timezone.now()
last_period = MonthPeriod.current().previous() if now.day < 26 else None
periods = MonthPeriod.all_from(
MonthPeriod.from_url_str("11-2014"), last_period)
entity = request.user.location.casted()
context = {
'periods': periods,
'entity': entity,
}
if entity.has_ureni or entity.has_urenas:
context.update({
'sam_performance': SAMPerformanceTable(entity=entity,
periods=periods)
})
if entity.has_urenam:
context.update({
'mam_performance': MAMPerformanceTable(entity=entity,
periods=periods)
})
return render(request, kwargs.get('template_name',
'nutrition/dashboard.html'), context)
示例4: handle
# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import current [as 别名]
def handle(self, *args, **options):
period = MonthPeriod.current().previous()
category = 'end_of_district_period'
for pt in PeriodicTask.objects.filter(category=category):
regexp = r'_{p}_{cat}'.format(p=period.strid(), cat=category)
if not pt.slug.endswith(regexp):
continue
logger.info("Untriggering {}".format(pt))
pt.untrigger()
示例5: routine_month_period_complete
# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import current [as 别名]
def routine_month_period_complete(period, domain, entity):
region_eord = domain.import_from('ROUTINE_REGION_AGG_DAY')
district_eord = domain.import_from('ROUTINE_DISTRICT_AGG_DAY')
current = MonthPeriod.current()
if period >= current:
return False
if period < current.previous():
return True
if entity.type.slug in ('country', 'region', 'health_district'):
eord = region_eord
else:
eord = district_eord
return timezone.now().day >= eord
示例6: handle
# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import current [as 别名]
def handle(self, *args, **options):
period = MonthPeriod.current()
now = timezone.now()
if not period.end_on < now:
logger.error("Can not close mission before end of period")
return
for mission in CATMissionR.objects.filter(strategy=FIXED,
period=period):
logger.info("Closing {}".format(mission))
mission.close(period.end_on.date())
logger.info("All Done")
示例7: display_weekly
# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import current [as 别名]
def display_weekly(request,
entity_slug=None,
perioda_str=None,
periodb_str=None,
**kwargs):
context = {}
root = request.user.location
cluster = Cluster.get_or_none('nutrition_routine')
entity = Entity.get_or_none(entity_slug) or root
# report_cls depends on entity
try:
report_cls = WeeklyNutritionR \
if entity.type.slug == 'health_center' else AggWeeklyNutritionR
except:
report_cls = None
# default is show periods since begining of this year.
if perioda_str is None and periodb_str is None:
nb_mp_ty = MonthPeriod.current().start_on.month - 1
else:
nb_mp_ty = 2
context.update(entity_periods_context(
request=request,
root=root,
cluster=cluster,
view_name='nutrition_weekly',
entity_slug=entity_slug,
report_cls=report_cls,
perioda_str=perioda_str,
periodb_str=periodb_str,
period_cls=MonthPeriod,
assume_previous=False,
must_be_in_cluster=True,
backlog_periods=nb_mp_ty,
))
extended_end, district_agg, region_agg = important_weekly_day_names()
context.update({
'day_ext_end': extended_end,
'day_agg_ds': district_agg,
'day_agg_rs': region_agg
})
if report_cls:
weekly_data = []
for week_period in nutperiods_for(context['periods']):
d = {'week_period': week_period}
try:
report = report_cls.objects.get(
entity=entity, period=week_period)
except report_cls.DoesNotExist:
report = None
d.update({'report': report})
weekly_data.append(d)
context.update({'weekly_data': weekly_data})
return render(request,
kwargs.get('template_name', 'nutrition/weekly.html'),
context)
示例8: cataract_mission_browser
# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import current [as 别名]
def cataract_mission_browser(request,
entity_slug=None,
period_str=None,
**kwargs):
context = {}
root = request.user.location
cluster = Cluster.get_or_none('cataract')
entity = Entity.get_or_none(entity_slug)
if entity is None:
entity = root
if entity is None:
raise Http404("Aucune entité pour le code {}".format(entity_slug))
# make sure requested entity is in cluster
ensure_entity_in_cluster(cluster, entity)
# check permissions on this entity and raise 403
provider_allowed_or_denied(request.user, 'access_cataract', entity)
# mission browser is reserved to district-level and above
ensure_entity_at_least(entity, 'health_district')
def period_from_strid(period_str, reportcls=None):
period = None
if period_str:
try:
period = Period.from_url_str(period_str).casted()
except:
pass
return period
period = period_from_strid(period_str)
if period is None:
period = MonthPeriod.current()
try:
first_period = MonthPeriod.find_create_by_date(
CATMissionR.objects.all()
.order_by('period__start_on')[0].period.middle())
except IndexError:
first_period = MonthPeriod.current()
all_periods = MonthPeriod.all_from(first_period)
context.update({
'all_periods': [(p.strid(), p) for p in reversed(all_periods)],
'period': period,
'base_url': get_base_url_for_period(
view_name='cataract_missions', entity=entity,
period_str=period_str or period.strid())
})
context.update(entity_browser_context(
root=root, selected_entity=entity,
full_lineage=['country', 'health_region', 'health_district'],
cluster=cluster))
# retrieve list of missions for that period
missions = CATMissionR.objects.filter(
period=period,
entity__slug__in=[e.slug for e in entity.get_health_districts()])
context.update({'missions': missions})
return render(request,
kwargs.get('template_name', 'cataract/missions_list.html'),
context)
示例9: cataract_dashboard
# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import current [as 别名]
def cataract_dashboard(request,
entity_slug=None,
perioda_str=None,
periodb_str=None,
**kwargs):
context = {}
root = request.user.location
cluster = Cluster.get_or_none('cataract')
entity = Entity.get_or_none(entity_slug)
if entity is None:
entity = root
if entity is None:
raise Http404("Aucune entité pour le code {}".format(entity_slug))
# make sure requested entity is in cluster
ensure_entity_in_cluster(cluster, entity)
# check permissions on this entity and raise 403
provider_allowed_or_denied(request.user, 'access_cataract', entity)
# mission browser is reserved to district-level and above
ensure_entity_at_least(entity, 'health_district')
def period_from_strid(period_str, reportcls=None):
period = None
if period_str:
try:
period = Period.from_url_str(period_str).casted()
except:
pass
return period
perioda = period_from_strid(perioda_str)
periodb = period_from_strid(periodb_str)
if periodb is None:
periodb = MonthPeriod.current()
if perioda is None:
perioda = periodb
if perioda is None or periodb is None:
raise Http404("Période incorrecte.")
if perioda > periodb:
t = perioda
perioda = periodb
periodb = t
del(t)
try:
first_period = MonthPeriod.find_create_by_date(
CATMissionR.objects.all().order_by(
'period__start_on')[0].period.middle())
except IndexError:
first_period = MonthPeriod.current()
all_periods = MonthPeriod.all_from(first_period)
periods = MonthPeriod.all_from(perioda, periodb)
context.update({
'all_periods': [(p.strid(), p) for p in reversed(all_periods)],
'periods': periods,
'perioda': perioda,
'periodb': periodb,
'base_url': get_base_url_for_periods(
view_name='cataract_dashboard',
entity=entity,
perioda_str=perioda_str or perioda.strid(),
periodb_str=periodb_str or periodb.strid())
})
context.update(entity_browser_context(
root=root, selected_entity=entity,
full_lineage=['country', 'health_region', 'health_district'],
cluster=cluster))
# retrieve Indicator Table
from snisi_cataract.indicators import (MissionDataSummary,
CumulativeSurgeryData)
missions_followup = MissionDataSummary(entity=entity,
periods=periods)
cumulative_surgeries = CumulativeSurgeryData(entity=entity,
periods=periods)
context.update({
'missions_followup': missions_followup,
'cumulative_surgeries': cumulative_surgeries,
})
return render(request,
kwargs.get('template_name', 'cataract/dashboard.html'),
context)
示例10: handle
# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import current [as 别名]
def handle(self, *args, **options):
logger.info("snisi_nutrition daily-checkups")
now = timezone.now()
today = now.date()
day = now.day
period = MonthPeriod.current().previous()
category_matrix = {
'end_of_reporting_period':
end_of_reporting_period_notifications,
'end_of_extended_reporting_period':
end_of_extended_reporting_period_notifications,
'performance_indicators':
performance_indicators_notifications,
'inputs_stockouts':
inputs_stockouts_notifications,
'end_of_district_period': generate_district_reports,
'end_of_region_period': generate_region_country_reports,
'end_of_weekly_district_period': generate_weekly_district_reports,
'end_of_weekly_region_period':
generate_weekly_region_country_reports,
}
def handle_category(category, custom_period=None):
if custom_period is None:
custom_period = period
slug = "{domain}_{period}_{category}".format(
domain=DOMAIN_SLUG,
period=custom_period.strid(),
category=category)
task, created = PeriodicTask.get_or_create(slug, category)
if task.can_trigger():
try:
if category_matrix.get(category)(custom_period) \
is not False:
task.trigger()
except Exception as e:
logger.error("Exception raised during aggregation.")
logger.exception(e)
else:
logger.debug("{} already triggered".format(task))
# Monthly reports
# On 6th
if day >= ROUTINE_REPORTING_END_DAY:
# send warning notice to non-satisfied HC person
handle_category("end_of_reporting_period")
pass
# On 11th
if day >= ROUTINE_EXTENDED_REPORTING_END_DAY:
# send summary notification and validation invitatin to districts
handle_category("end_of_extended_reporting_period")
pass
# On 16th
if day >= ROUTINE_DISTRICT_AGG_DAY:
# validate all HC reports
# create aggregated for district
# create expected-validation for district
# send notification to regions
handle_category("end_of_district_period")
handle_category("performance_indicators")
handle_category("inputs_stockouts")
# On 26th
if day >= ROUTINE_REGION_AGG_DAY:
# validate all district reports
# create aggregated for region
# create aggregated for country
# send notification to central/national
handle_category("end_of_region_period")
# WEEKLY REPORTS
# number and position of weeks across month is inconsistent.
# loop through potential past weeks and process if possible
pf = NutWeekPeriod.find_create_by_date(period.start_on)
pl = NutWeekPeriod.current()
wperiods = [p for p in NutWeekPeriod.all_from(pf, pl)
if p.end_on < now]
for wperiod in wperiods:
# validate all HC reports
# create aggregated for district
# create expected-validation for district
# send notification to regions
if (wperiod.end_on + datetime.timedelta(
days=ROUTINE_DISTRICT_AGG_DAYS_DELTA)).date() <= today:
handle_category("end_of_weekly_district_period", wperiod)
# validate all district reports
# create aggregated for region
# create aggregated for country
# send notification to central/national
if (wperiod.end_on + datetime.timedelta(
#.........这里部分代码省略.........
示例11: monthly_report
# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import current [as 别名]
#.........这里部分代码省略.........
'vita_100_injectable_received',
'vita_100_injectable_used',
'vita_100_injectable_lost',
'vita_200_injectable_initial',
'vita_200_injectable_received',
'vita_200_injectable_used',
'vita_200_injectable_lost',
'iron_folic_acid_initial',
'iron_folic_acid_received',
'iron_folic_acid_used',
'iron_folic_acid_lost',
]
# harmonized meta-data
try:
hc = Entity.get_or_none(provider.location.slug)
except:
hc = None
for rslug in ('urenam', 'urenas', 'ureni', 'stocks'):
if (getattr(hc, 'has_{}'.format(rslug), False) or rslug == 'stocks') \
and len(arguments.get('{}_data'.format(rslug))) < 2:
return reply.error("Données manquantes pour {}"
.format(rslug.upper()))
# now we have well formed and authenticated data.
# let's check for business-logic errors.
checker = NutritionRIntegrityChecker()
# feed data holder with sms provided data
for key, value in arguments.items():
checker.set(key, value)
period = MonthPeriod.current().previous()
checker.set('entity', hc)
checker.set('hc', getattr(hc, 'slug', None))
checker.set('month', period.middle().month)
checker.set('year', period.middle().year)
today = datetime.date.today()
checker.set('fillin_day', today.day)
checker.set('fillin_month', today.month)
checker.set('fillin_year', today.year)
checker.set('submit_time', message.event_on)
checker.set('author', provider.name())
checker.set('submitter', provider)
# ensure we have a expecteds and all
checker.check()
if not checker.is_valid():
return reply.error(checker.errors.pop().render(short=True))
# build requirements for report
entity = Entity.get_or_none(checker.get('hc'))
# expected reporting defines if report is expeted or not
expected_reporting = ExpectedReporting.get_or_none(
report_class=reportcls_nut,
period=period,
within_period=False,
entity=entity,
within_entity=False,
amount_expected=ExpectedReporting.EXPECTED_SINGLE)
# should have already been checked in checker.
if expected_reporting is None:
示例12: dashboard
# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import current [as 别名]
def dashboard(request, **kwargs):
now = timezone.now()
last_period = MonthPeriod.current().previous() if now.day < 26 else None
if now.day < 10:
last_period = last_period.previous()
periods = MonthPeriod.all_from(
MonthPeriod.from_url_str("11-2014"), last_period)
entity = request.user.location.casted()
fwp = NutWeekPeriod.find_create_by_date(datetime.datetime(2014, 12, 1))
lwp = NutWeekPeriod.find_create_by_date(datetime.datetime(2015, 6, 26))
wperiods = NutWeekPeriod.all_from(fwp, lwp)
imatrix = OrderedDict([
('promptitude', TableauPromptitudeRapportage),
('promptitude_graph', FigurePromptitudeRapportage),
('w_promptitude', WeekTableauPromptitudeRapportage),
('w_promptitude_graph', WeekFigurePromptitudeRapportage),
])
gp = lambda s: wperiods if s.startswith('w_') else periods
sm_indics = {slug: icls(entity=entity, periods=gp(slug))
for slug, icls in imatrix.items()}
def pc(a, b):
try:
return b / a
except ZeroDivisionError:
return 0
mopti = Entity.get_or_none("SSH3")
nb_hc = len(mopti.get_health_centers())
nb_months = len(periods)
nb_exp = nb_hc * nb_months
nb_received = NutritionR.objects.all().count()
nb_received_it = NutritionR.objects.filter(
arrival_status=NutritionR.ON_TIME).count()
# nb_stock = len([1 for r in NutritionStocksR.objects.all()
# if r.has_stockout()])
nb_stock_thera = len([1 for r in NutritionStocksR.objects.all()
if r.has_therapeutic_stockout()])
nb_stock_drug = len([1 for r in NutritionStocksR.objects.all()
if r.has_drug_stockout()])
nb_weeks = len(wperiods)
nb_expw = nb_hc * nb_weeks
nb_receivedw = WeeklyNutritionR.objects.all().count()
nb_received_itw = WeeklyNutritionR.objects.filter(
arrival_status=WeeklyNutritionR.ON_TIME).count()
ds_received = [(ds.name,
pc(len(ds.get_health_centers()) * nb_months,
NutritionR.objects.filter(
entity__slug__in=[hc.slug
for hc in ds.get_health_centers()])
.count()))
for ds in mopti.get_health_districts()]
ds_auto_val = [(ds.name,
pc(len(ds.get_health_centers()) * nb_months,
NutritionR.objects.filter(
entity__slug__in=[hc.slug
for hc in ds.get_health_centers()],
auto_validated=False)
.count()))
for ds in mopti.get_health_districts()]
nb_hc_100 = len([hc for hc in mopti.get_health_centers()
if NutritionR.objects.filter(entity__slug=hc.slug)
.count() == nb_months])
overall_table = OrderedDict([
("Nombre de centres", nb_hc),
("Nombre de mois", nb_months),
("Nombre de rapports attendus", nb_exp),
("Nombre de rapports reçus", nb_received),
("Taux de complétude moyen", pc(nb_exp, nb_received)),
("Nombre de rapports reçus à temps", nb_received_it),
("Taux de promptitude moyen", pc(nb_exp, nb_received_it)),
("Nombre de semaines", nb_weeks),
("Nombre de rapports hebdo attendus", nb_expw),
("Nombre de rapports hebdo reçus", nb_receivedw),
("Taux de complétude hebdo moyen", pc(nb_expw, nb_receivedw)),
("Nombre de rapports hebdo reçus à temps", nb_received_itw),
("Taux de promptitude hebdo moyen", pc(nb_expw, nb_received_itw)),
("Nombre de rapports avec de mauvais indicateurs de performances", 0),
("Pourcentage de mauvais indicateurs de performances", 0),
("Classement du rapportage (complétude) par DS", "-"),
])
for idx, dsdd in enumerate(sorted(ds_received,
key=lambda x: x[1], reverse=True)):
overall_table.update({
"nº {} – DS de {}".format(idx + 1, dsdd[0]): dsdd[1]})
overall_table.update({"Taux de rapports validés par les districts": "-"})
for idx, dsdd in enumerate(sorted(ds_auto_val,
#.........这里部分代码省略.........
示例13: handle
# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import current [as 别名]
def handle(self, *args, **options):
logger.info("snisi_malaria daily-checkups")
day = timezone.now().day
period = MonthPeriod.current().previous()
this_month = period.following()
# period_str = period.strid()
wperiod = FixedMonthWeek.previous_week(FixedMonthWeek.current())
# wperiod_str = MonthPeriod.current().strid()
logger.debug("{} -- {}".format(period, wperiod))
category_matrix = {
'end_of_reporting_period': end_of_reporting_period_notifications,
'end_of_extended_reporting_period':
end_of_extended_reporting_period_notifications,
'end_of_district_period': generate_district_reports,
'end_of_region_period': generate_region_country_reports,
'end_of_first_week_period_reporting': generate_weekly_reports,
'end_of_second_week_period_reporting': generate_weekly_reports,
'end_of_third_week_period_reporting': generate_weekly_reports,
'end_of_fourth_week_period_reporting': generate_weekly_reports,
'end_of_fifth_week_period_reporting': generate_weekly_reports,
}
def handle_category(category, nperiod=None, wperiod=None):
if nperiod is None:
nperiod = period
slug = "{domain}_{period}_{category}".format(
domain=DOMAIN_SLUG, period=nperiod.strid(), category=category)
task, created = PeriodicTask.get_or_create(slug, category)
if task.can_trigger():
logger.debug("triggering {}".format(task))
try:
category_matrix.get(category)(period=nperiod,
wperiod=wperiod)
except Exception as e:
logger.exception(e)
else:
task.trigger()
else:
logger.info("{} already triggered".format(task))
# On 1st
if day >= 1:
# in case we had only 28 days last month
wperiod = FixedMonthFourthWeek.find_create_from(
period.middle().year, period.middle().month)
handle_category("end_of_fourth_week_period_reporting",
period, wperiod)
wperiod = FixedMonthFifthWeek.find_create_from(
period.middle().year, period.middle().month)
handle_category("end_of_fifth_week_period_reporting",
period, wperiod)
# On 6th
if day >= ROUTINE_REPORTING_END_DAY:
# send warning notice to non-satisfied HC person
handle_category("end_of_reporting_period")
# On 11th
if day >= ROUTINE_EXTENDED_REPORTING_END_DAY:
# send summary notification and validation invitatin to districts
handle_category("end_of_extended_reporting_period")
# On 13th
if day >= 13:
wperiod = FixedMonthFirstWeek.find_create_from(
period.following().middle().year,
period.following().middle().month)
handle_category("end_of_first_week_period_reporting",
this_month, wperiod)
# On 16th
if day >= ROUTINE_DISTRICT_AGG_DAY:
# validate all HC reports
# create aggregated for district
# create expected-validation for district
# send notification to regions
handle_category("end_of_district_period")
# On 20th
if day >= 20:
wperiod = FixedMonthSecondWeek.find_create_from(
period.following().middle().year,
period.following().middle().month)
handle_category("end_of_second_week_period_reporting",
this_month, wperiod)
# On 26th
if day >= ROUTINE_REGION_AGG_DAY:
# validate all district reports
# create aggregated for region
# create aggregated for country
# send notification to central/national
handle_category("end_of_region_period")
# On 27th
if day >= 27:
#.........这里部分代码省略.........
示例14: base_malaria_report
# 需要导入模块: from snisi_core.models.Periods import MonthPeriod [as 别名]
# 或者: from snisi_core.models.Periods.MonthPeriod import current [as 别名]
def base_malaria_report(message, arguments):
reply = SMSReply(message, PROJECT_BRAND)
# 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] = MalariaR.YES if bool(int(value)) \
else MalariaR.NO
except:
logger.warning("Unable to convert SMS data to int: {}"
.format(message.content))
# failure to convert means non-numeric value which we can't process.
return reply.error("Les données sont malformées.")
# check credentials
try:
provider = Provider.active.get(username=arguments['username'])
except Provider.DoesNotExist:
return reply.error("Ce nom d'utilisateur "
"({}) n'existe pas.".format(arguments['username']))
if not provider.check_password(arguments['password']):
return reply.error("Votre mot de passe est incorrect.")
# now we have well formed and authenticated data.
# let's check for business-logic errors.
checker = MalariaRSourceReportChecker()
# feed data holder with sms provided data
for key, value in arguments.items():
if key.split('_')[0] in ('u5', 'o5', 'pw',
'stockout', 'year', 'month'):
checker.set(key, value)
# harmonized meta-data
try:
hc = provider.location
except:
hc = None
checker.set('entity', hc)
checker.set('hc', getattr(hc, 'slug', None))
today = datetime.date.today()
checker.set('fillin_day', today.day)
checker.set('fillin_month', today.month)
checker.set('fillin_year', today.year)
period = MonthPeriod.current().previous()
checker.set('month', period.middle().month)
checker.set('year', period.middle().year)
checker.set('submit_time', message.event_on)
checker.set('author', provider.name())
checker.set('submitter', provider)
# test the data
checker.check()
if not checker.is_valid():
return reply.error(checker.errors.pop().render(short=True))
# build requirements for report
period = MonthPeriod.find_create_from(year=checker.get('year'),
month=checker.get('month'))
entity = HealthEntity.objects.get(slug=checker.get('hc'),
type__slug='health_center')
# expected reporting defines if report is expeted or not
expected_reporting = ExpectedReporting.get_or_none(
report_class=reportcls,
period=period,
within_period=False,
entity=entity,
within_entity=False,
amount_expected=ExpectedReporting.EXPECTED_SINGLE)
# should have already been checked in checker.
if expected_reporting is None:
logger.error("Expected reporting not found: "
"cls:{cls} - period:{period} - entity:{entity}"
.format(cls=reportcls, period=period, entity=entity))
return reply.error("Aucun rapport de routine attendu à "
"{entity} pour {period}"
.format(entity=entity, period=period))
report, text_message = create_report(provider=provider,
expected_reporting=expected_reporting,
completed_on=timezone.now(),
integrity_checker=checker,
data_source=message.content,)
if report:
return reply.success(text_message)
else:
return reply.error(text_message)