Exemplo n.º 1
0
    def previous_months_summary(self, months=6):
        now = datetime.datetime.utcnow()
        six_month_summary = []
        last_month_summary = None
        performance_threshold = get_performance_threshold(self.domain)
        filtered_users = self.get_users_by_filter()
        active_not_deleted_users = UserES().domain(self.domain).values_list("_id", flat=True)
        for i in range(-months, 1):
            year, month = add_months(now.year, now.month, i)
            month_as_date = datetime.date(year, month, 1)
            this_month_summary = MonthlyPerformanceSummary(
                domain=self.domain,
                performance_threshold=performance_threshold,
                month=month_as_date,
                previous_summary=last_month_summary,
                selected_users=filtered_users,
                active_not_deleted_users=active_not_deleted_users,
            )
            six_month_summary.append(this_month_summary)
            if last_month_summary is not None:
                last_month_summary.set_next_month_summary(this_month_summary)
            last_month_summary = this_month_summary

        # these steps have to be done in a second outer loop so that 'next month summary' is available
        # whenever it is needed
        for summary in six_month_summary:
            summary.finalize()
            summary.set_percent_active()

        return six_month_summary[1:]
Exemplo n.º 2
0
    def _apply_datespan_shifts(self, datespan):
        if datespan and not isinstance(datespan, DateSpan):
            raise ValueError("datespan must be an instance of DateSpan")

        if datespan:
            datespan = copy.copy(datespan)
            now = datetime.datetime.utcnow()

            # make sure we don't go over the current day
            # remember, there is no timezone support for this yet
            if datespan.enddate > now:
                datespan.enddate = now

            datespan.enddate = datespan.enddate.replace(hour=23, minute=59, second=59, microsecond=999999)
            if self.fixed_datespan_days:
                datespan.startdate = datespan.enddate - datetime.timedelta(days=self.fixed_datespan_days,
                                                                           microseconds=-1)
            if self.fixed_datespan_months:
                # By making the assumption that the end date is always the end of the month
                # the first months adjustment is accomplished by moving the start date to
                # the beginning of the month. Any additional months are subtracted in the usual way
                start = self.get_first_day_of_month(datespan.enddate.year, datespan.enddate.month)
                start_year, start_month = add_months(start.year, start.month, -(self.fixed_datespan_months - 1))
                datespan.startdate = start.replace(year=start_year, month=start_month)

            if self.startdate_shift:
                datespan.startdate = datespan.startdate + datetime.timedelta(days=self.startdate_shift)
            if self.enddate_shift:
                datespan.enddate = datespan.enddate + datetime.timedelta(days=self.enddate_shift)
            
        return datespan
Exemplo n.º 3
0
 def previous_six_months(self):
     now = datetime.datetime.utcnow()
     six_month_summary = []
     last_month_summary = None
     performance_threshold = get_performance_threshold(self.domain)
     filtered_users = self.get_users_by_filter()
     active_not_deleted_users = UserES().domain(self.domain).values_list(
         "_id", flat=True)
     for i in range(-6, 1):
         year, month = add_months(now.year, now.month, i)
         month_as_date = datetime.date(year, month, 1)
         this_month_summary = MonthlyPerformanceSummary(
             domain=self.domain,
             performance_threshold=performance_threshold,
             month=month_as_date,
             previous_summary=last_month_summary,
             selected_users=filtered_users,
             active_not_deleted_users=active_not_deleted_users,
         )
         six_month_summary.append(this_month_summary)
         if last_month_summary is not None:
             last_month_summary.set_next_month_summary(this_month_summary)
             this_month_summary.set_num_inactive_users(
                 len(this_month_summary.get_dropouts()))
         this_month_summary.set_percent_active()
         last_month_summary = this_month_summary
     return six_month_summary[1:]
Exemplo n.º 4
0
    def __init__(self, case, report, child_index=1, is_secondary=False, explicit_month=None, explicit_year=None):
        self.child_index = child_index
        self.case = case
        self.report = report
        self.data_provider = report.data_provider
        self.block = report.block.lower()
        self.month = explicit_month or report.month
        self.year = explicit_year or report.year
        self.is_secondary = is_secondary
        self.case_is_out_of_range = False

        if not report.is_rendered_as_email:
            self.img_elem = '<div style="width:160px !important;"><img src="/static/opm/img/%s">' \
                            '<text class="image-descriptor" style="display:none">%s</text></div>'
        else:
            self.img_elem = '<div><img src="/static/opm/img/%s"><text class="image-descriptor" ' \
                            'style="display:none">%s</text></div>'

        self.set_case_properties()
        self.last_month_row = None
        if not is_secondary:
            self.add_extra_children()
            # if we were called directly, set the last month's row on this
            last_year, last_month = add_months(self.year, self.month, -1)
            try:
                self.last_month_row = OPMCaseRow(case, report, 1, is_secondary=True,
                                                 explicit_month=last_month, explicit_year=last_year)
            except InvalidRow:
                pass
Exemplo n.º 5
0
    def previous_months_summary(self, months=6):
        now = datetime.datetime.utcnow()
        six_month_summary = []
        last_month_summary = None
        performance_threshold = get_performance_threshold(self.domain)
        filtered_users = self.get_users_by_filter()
        active_not_deleted_users = UserES().domain(self.domain).values_list(
            "_id", flat=True)
        for i in range(-months, 1):
            year, month = add_months(now.year, now.month, i)
            month_as_date = datetime.date(year, month, 1)
            this_month_summary = MonthlyPerformanceSummary(
                domain=self.domain,
                performance_threshold=performance_threshold,
                month=month_as_date,
                previous_summary=last_month_summary,
                selected_users=filtered_users,
                active_not_deleted_users=active_not_deleted_users,
            )
            six_month_summary.append(this_month_summary)
            if last_month_summary is not None:
                last_month_summary.set_next_month_summary(this_month_summary)
            last_month_summary = this_month_summary

        # these steps have to be done in a second outer loop so that 'next month summary' is available
        # whenever it is needed
        for summary in six_month_summary:
            summary.finalize()
            summary.set_percent_active()

        return six_month_summary[1:]
Exemplo n.º 6
0
    def _apply_datespan_shifts(self, datespan):
        if datespan and not isinstance(datespan, DateSpan):
            raise ValueError("datespan must be an instance of DateSpan")

        if datespan:
            datespan = copy.copy(datespan)
            now = datetime.datetime.utcnow()

            # make sure we don't go over the current day
            # remember, there is no timezone support for this yet
            if datespan.enddate > now:
                datespan.enddate = now

            datespan.enddate = datespan.enddate.replace(hour=23, minute=59, second=59, microsecond=999999)
            if self.fixed_datespan_days:
                datespan.startdate = datespan.enddate - datetime.timedelta(days=self.fixed_datespan_days,
                                                                           microseconds=-1)
            if self.fixed_datespan_months:
                start_year, start_month = add_months(datespan.enddate.year, datespan.enddate.month,
                    -self.fixed_datespan_months)
                try:
                    datespan.startdate = datetime.datetime(start_year, start_month, datespan.enddate.day,
                        datespan.enddate.hour, datespan.enddate.minute, datespan.enddate.second,
                        datespan.enddate.microsecond) + datetime.timedelta(microseconds=1)
                except ValueError:
                    # day is out of range for month
                    datespan.startdate = self.get_last_day_of_month(start_year, start_month)

            if self.startdate_shift:
                datespan.startdate = datespan.startdate + datetime.timedelta(days=self.startdate_shift)
            if self.enddate_shift:
                datespan.enddate = datespan.enddate + datetime.timedelta(days=self.enddate_shift)
            
        return datespan
Exemplo n.º 7
0
 def datespan(self):
     now = datetime.datetime.utcnow()
     year, month = add_months(now.year, now.month, -1)
     last_month = DateSpan.from_month(month, year)
     self.request.datespan = last_month
     self.context.update(dict(datespan=last_month))
     return last_month
Exemplo n.º 8
0
    def _apply_datespan_shifts(self, datespan):
        if datespan and not isinstance(datespan, DateSpan):
            raise ValueError("datespan must be an instance of DateSpan")

        if datespan:
            datespan = copy.copy(datespan)
            datespan.enddate = datespan.enddate.replace(hour=23, minute=59, second=59, microsecond=999999)
            if self.fixed_datespan_days:
                datespan.startdate = datespan.enddate - datetime.timedelta(days=self.fixed_datespan_days,
                                                                           microseconds=-1)
            if self.fixed_datespan_months:
                start_year, start_month = add_months(datespan.enddate.year, datespan.enddate.month,
                    -self.fixed_datespan_months)
                try:
                    datespan.startdate = datetime.datetime(start_year, start_month, datespan.enddate.day,
                        datespan.enddate.hour, datespan.enddate.minute, datespan.enddate.second,
                        datespan.enddate.microsecond) + datetime.timedelta(microseconds=1)
                except ValueError:
                    # day is out of range for month
                    datespan.startdate = self.get_last_day_of_month(start_year, start_month)

            datespan.startdate = datespan.startdate + datetime.timedelta(days=self.startdate_shift)
            datespan.enddate = datespan.enddate + datetime.timedelta(days=self.enddate_shift)
            
        return datespan
Exemplo n.º 9
0
    def _apply_datespan_shifts(self, datespan):
        if datespan and not isinstance(datespan, DateSpan):
            raise ValueError("datespan must be an instance of DateSpan")

        if datespan:
            datespan = copy.copy(datespan)
            now = datetime.datetime.utcnow()

            # make sure we don't go over the current day
            # remember, there is no timezone support for this yet
            if datespan.enddate > now:
                datespan.enddate = now

            datespan.enddate = datespan.enddate.replace(hour=23, minute=59, second=59, microsecond=999999)
            if self.fixed_datespan_days:
                datespan.startdate = datespan.enddate - datetime.timedelta(days=self.fixed_datespan_days,
                                                                           microseconds=-1)
            if self.fixed_datespan_months:
                # By making the assumption that the end date is always the end of the month
                # the first months adjustment is accomplished by moving the start date to
                # the beginning of the month. Any additional months are subtracted in the usual way
                start = self.get_first_day_of_month(datespan.enddate.year, datespan.enddate.month)
                start_year, start_month = add_months(start.year, start.month, -(self.fixed_datespan_months - 1))
                datespan.startdate = start.replace(year=start_year, month=start_month)

            if self.startdate_shift:
                datespan.startdate = datespan.startdate + datetime.timedelta(days=self.startdate_shift)
            if self.enddate_shift:
                datespan.enddate = datespan.enddate + datetime.timedelta(days=self.enddate_shift)
            
        return datespan
Exemplo n.º 10
0
def generate_domain_subscription_from_date(date_start, billing_account, domain,
                                           min_num_months=None, is_immediately_active=False,
                                           delay_invoicing_until=None, save=True):
    # make sure the first month is never a full month (for testing)
    date_start = date_start.replace(day=max(2, date_start.day))

    subscription_length = random.randint(min_num_months or 3, 25)
    date_end_year, date_end_month = add_months(date_start.year, date_start.month, subscription_length)
    date_end_last_day = calendar.monthrange(date_end_year, date_end_month)[1]

    # make sure that the last month is never a full month (for testing)
    date_end = datetime.date(date_end_year, date_end_month, min(date_end_last_day - 1, date_start.day + 1))

    subscriber, _ = Subscriber.objects.get_or_create(domain=domain, organization=None)
    subscription = Subscription(
        account=billing_account,
        plan_version=arbitrary_subscribable_plan(),
        subscriber=subscriber,
        salesforce_contract_id=data_gen.arbitrary_unique_name("SFC")[:80],
        date_start=date_start,
        date_end=date_end,
        is_active=is_immediately_active,
        date_delay_invoicing=delay_invoicing_until,
    )
    if save:
        subscription.save()
    return subscription, subscription_length
Exemplo n.º 11
0
    def _apply_datespan_shifts(self, datespan):
        if datespan and not isinstance(datespan, DateSpan):
            raise ValueError("datespan must be an instance of DateSpan")

        if datespan:
            datespan = copy.copy(datespan)
            now = datetime.datetime.utcnow()

            # make sure we don't go over the current day
            # remember, there is no timezone support for this yet
            if datespan.enddate > now:
                datespan.enddate = now

            datespan.enddate = datespan.enddate.replace(hour=23, minute=59, second=59, microsecond=999999)
            if self.fixed_datespan_days:
                datespan.startdate = datespan.enddate - datetime.timedelta(days=self.fixed_datespan_days,
                                                                           microseconds=-1)
            if self.fixed_datespan_months:
                start_year, start_month = add_months(datespan.enddate.year, datespan.enddate.month,
                    -self.fixed_datespan_months)
                try:
                    datespan.startdate = datetime.datetime(start_year, start_month, datespan.enddate.day,
                        datespan.enddate.hour, datespan.enddate.minute, datespan.enddate.second,
                        datespan.enddate.microsecond) + datetime.timedelta(microseconds=1)
                except ValueError:
                    # day is out of range for month
                    datespan.startdate = self.get_last_day_of_month(start_year, start_month)

            if self.startdate_shift:
                datespan.startdate = datespan.startdate + datetime.timedelta(days=self.startdate_shift)
            if self.enddate_shift:
                datespan.enddate = datespan.enddate + datetime.timedelta(days=self.enddate_shift)
            
        return datespan
Exemplo n.º 12
0
    def template_context(self):
        now = datetime.datetime.utcnow()
        rows = []
        last_month_summary = None
        performance_threshold = get_performance_threshold(self.domain)
        for i in range(-5, 1):
            year, month = add_months(now.year, now.month, i)
            month_as_date = datetime.date(year, month, 1)
            this_month_summary = MonthlyPerformanceSummary(
                domain=self.domain,
                performance_threshold=performance_threshold,
                month=month_as_date,
                previous_summary=last_month_summary,
            )
            rows.append(this_month_summary)
            if last_month_summary is not None:
                last_month_summary.set_next_month_summary(this_month_summary)
            last_month_summary = this_month_summary

        return {
            'rows': rows,
            'this_month': rows[-1],
            'last_month': rows[-2],
            'threshold': performance_threshold,
        }
Exemplo n.º 13
0
def generate_domain_subscription_from_date(date_start,
                                           billing_account,
                                           domain,
                                           min_num_months=None,
                                           is_immediately_active=False,
                                           delay_invoicing_until=None,
                                           save=True):
    # make sure the first month is never a full month (for testing)
    date_start = date_start.replace(day=max(2, date_start.day))

    subscription_length = random.randint(min_num_months or 3, 25)
    date_end_year, date_end_month = add_months(date_start.year,
                                               date_start.month,
                                               subscription_length)
    date_end_last_day = calendar.monthrange(date_end_year, date_end_month)[1]

    # make sure that the last month is never a full month (for testing)
    date_end = datetime.date(date_end_year, date_end_month,
                             min(date_end_last_day - 1, date_start.day + 1))

    subscriber, _ = Subscriber.objects.get_or_create(domain=domain,
                                                     organization=None)
    subscription = Subscription(
        account=billing_account,
        plan_version=arbitrary_subscribable_plan(),
        subscriber=subscriber,
        salesforce_contract_id=data_gen.arbitrary_unique_name("SFC")[:80],
        date_start=date_start,
        date_end=date_end,
        is_active=is_immediately_active,
        date_delay_invoicing=delay_invoicing_until,
    )
    if save:
        subscription.save()
    return subscription, subscription_length
Exemplo n.º 14
0
 def datespan(self):
     now = datetime.datetime.utcnow()
     year, month = add_months(now.year, now.month, -1)
     last_month = DateSpan.from_month(month, year)
     self.request.datespan = last_month
     self.context.update(dict(datespan=last_month))
     return last_month
Exemplo n.º 15
0
def get_previous_month_date_range(reference_date=None):
    reference_date = reference_date or datetime.date.today()

    last_month_year, last_month = add_months(reference_date.year, reference_date.month, -1)
    _, last_day = calendar.monthrange(last_month_year, last_month)
    date_start = datetime.date(last_month_year, last_month, 1)
    date_end = datetime.date(last_month_year, last_month, last_day)

    return date_start, date_end
Exemplo n.º 16
0
 def get_default_start_end(cls):
     # Last month's date range
     today = datetime.datetime.utcnow()
     (last_month_year, last_month) = add_months(today.year, today.month, -1)
     (_, last_day) = calendar.monthrange(last_month_year, last_month)
     start_date = datetime.datetime(today.year, last_month, 1, hour=0, minute=0, second=0, microsecond=0)
     end_date = datetime.datetime(today.year, last_month, last_day,
                                  hour=23, minute=59, second=59, microsecond=999999)
     return start_date, end_date
Exemplo n.º 17
0
def _get_window_date(status_type, date):
    # we need this method because the soh and super reports actually
    # are sometimes treated as reports for _next_ month
    if status_type == SupplyPointStatusTypes.SOH_FACILITY or status_type == SupplyPointStatusTypes.SUPERVISION_FACILITY:
        # if the date is after the last business day of the month
        # count it for the next month
        if date.date() >= get_business_day_of_month(date.year, date.month, -1):
            year, month = add_months(date.year, date.month, 1)
            return datetime(year, month, 1)
    return datetime(date.year, date.month, 1)
Exemplo n.º 18
0
def _get_window_date(status_type, date):
    # we need this method because the soh and super reports actually
    # are sometimes treated as reports for _next_ month
    if status_type == SupplyPointStatusTypes.SOH_FACILITY or \
       status_type == SupplyPointStatusTypes.SUPERVISION_FACILITY:
        # if the date is after the last business day of the month
        # count it for the next month
        if date.date() >= get_business_day_of_month(date.year, date.month, -1):
            year, month = add_months(date.year, date.month, 1)
            return datetime(year, month, 1)
    return datetime(date.year, date.month, 1)
Exemplo n.º 19
0
def _gir_csv_response(month, year):
    query_month = "{year}-{month}-01".format(year=year, month=month)
    prev_month_year, prev_month = add_months(year, month, -1)
    prev_month_string = "{year}-{month}-01".format(year=prev_month_year, month=prev_month)
    two_ago_year, two_ago_month = add_months(year, month, -2)
    two_ago_string = "{year}-{month}-01".format(year=two_ago_year, month=two_ago_month)
    if not GIRRow.objects.filter(month=query_month).exists():
        return HttpResponse('Sorry, that month is not yet available')
    queryset = GIRRow.objects.filter(month__in=[query_month, prev_month_string, two_ago_string]).order_by('-month')
    domain_months = defaultdict(list)
    for item in queryset:
        domain_months[item.domain_name].append(item)
    field_names = GIR_FIELDS
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=gir.csv'
    writer = csv.writer(response)
    writer.writerow(list(field_names))
    for months in domain_months.values():
        writer.writerow(months[0].export_row(months[1:]))
    return response
Exemplo n.º 20
0
def _gir_csv_response(month, year):
    query_month = "{year}-{month}-01".format(year=year, month=month)
    prev_month_year, prev_month = add_months(year, month, -1)
    prev_month_string = "{year}-{month}-01".format(year=prev_month_year, month=prev_month)
    two_ago_year, two_ago_month = add_months(year, month, -2)
    two_ago_string = "{year}-{month}-01".format(year=two_ago_year, month=two_ago_month)
    if not GIRRow.objects.filter(month=query_month).exists():
        return HttpResponse('Sorry, that month is not yet available')
    queryset = GIRRow.objects.filter(month__in=[query_month, prev_month_string, two_ago_string]).order_by('-month')
    domain_months = defaultdict(list)
    for item in queryset:
        domain_months[item.domain_name].append(item)
    field_names = GIR_FIELDS
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename=gir.csv'
    writer = UnicodeWriter(response)
    writer.writerow(list(field_names))
    for months in domain_months.values():
        writer.writerow(months[0].export_row(months[1:]))
    return response
Exemplo n.º 21
0
 def get_active_recent(domain, monthspan):
     months = (domain.internal.experienced_threshold
               or DEFAULT_EXPERIENCED_THRESHOLD) - 1
     threshold_month = add_months(monthspan.startdate.year,
                                  monthspan.startdate.month, -months)
     first_month = datetime.date(day=1,
                                 year=threshold_month[0],
                                 month=threshold_month[1])
     all_users, users_dict, sms = active_mobile_users(
         domain, first_month, monthspan.computed_enddate)
     return set(users_dict.keys()) | sms
Exemplo n.º 22
0
def create_alert(location_id, date, alert_type, details):
    text = ''
    # url = ''
    date = datetime(date.year, date.month, 1)
    expyear, expmonth = add_months(date.year, date.month, 1)
    expires = datetime(expyear, expmonth, 1)

    number = 0 if 'number' not in details else details['number']

    if alert_type in [const.PRODUCT_STOCKOUT, const.NO_PRIMARY_CONTACT]:
        if alert_type == const.PRODUCT_STOCKOUT:
            text = '%s is stocked out of %s.' % (details['org'].name,
                                                 details['product'].name)
        elif alert_type == const.NO_PRIMARY_CONTACT:
            text = '%s has no primary contact.' % details['org'].name

        alert = Alert.objects.filter(location_id=location_id,
                                     date=date,
                                     type=alert_type,
                                     text=text)
        if not alert:
            Alert(location_id=location_id,
                  date=date,
                  type=alert_type,
                  expires=expires,
                  text=text).save()

    else:
        if alert_type == const.RR_NOT_SUBMITTED:
            text = '%s have reported not submitting their R&R form as of today.' % \
                   ((str(number) + ' facility') if number == 1 else (str(number) + ' facilities'))
        elif alert_type == const.RR_NOT_RESPONDED:
            text = '%s did not respond to the SMS asking if they had submitted their R&R form.' % \
                   ((str(number) + ' facility') if number == 1 else (str(number) + ' facilities'))
        elif alert_type == const.DELIVERY_NOT_RECEIVED:
            text = '%s have reported not receiving their deliveries as of today.' % \
                   ((str(number) + ' facility') if number == 1 else (str(number) + ' facilities'))
        elif alert_type == const.DELIVERY_NOT_RESPONDING:
            text = '%s did not respond to the SMS asking if they had received their delivery.' % \
                   ((str(number) + ' facility') if number == 1 else (str(number) + ' facilities'))
        elif alert_type == const.SOH_NOT_RESPONDING:
            text = '%s have not reported their stock levels for last month.' % \
                   ((str(number) + ' facility') if number == 1 else (str(number) + ' facilities'))

        alert, created = Alert.objects.get_or_create(location_id=location_id,
                                                     date=date,
                                                     type=alert_type,
                                                     expires=expires)
        alert.number = number
        alert.text = text
        alert.save()
Exemplo n.º 23
0
def get_possibly_experienced(domain, start):

    user_ids = get_mobile_users(domain.name)
    threshold = domain.internal.experienced_threshold or DEFAULT_EXPERIENCED_THRESHOLD
    months = threshold - 2
    threshold_month = add_months(start.startdate.year, start.startdate.month,
                                 -months)
    end_month = datetime.date(day=1,
                              year=threshold_month[0],
                              month=threshold_month[1])

    form_users = set(FormES().domain(domain.name).user_aggregation().submitted(
        lt=end_month).user_id(user_ids).size(0).run().aggregations.user.keys)

    return set(form_users)
Exemplo n.º 24
0
 def check_condition(self, forms=None, child_age=None):
     child_age = child_age or 5
     report_year, report_month = 2014, 6
     dod_year, dod_month = add_months(report_year, report_month, -child_age)
     report = Report(
         month=report_month,
         year=report_year,
         block=getattr(self, 'block', 'Atri'),
     )
     case = OPMCase(
         forms=forms or [],
         dod=date(dod_year, dod_month, 10),
     )
     row = MockCaseRow(case, report, child_index=self.child_index)
     self.assertEqual(row.child_age, child_age)
     return getattr(row, self.row_property)
 def check_condition(self, forms=None, child_age=None):
     child_age = child_age or 5
     report_year, report_month = 2014, 6
     dod_year, dod_month = add_months(report_year, report_month, -child_age)
     report = Report(
         month=report_month,
         year=report_year,
         block=getattr(self, 'block', 'Atri'),
     )
     case = OPMCase(
         forms=forms or [],
         dod=date(dod_year, dod_month, 10),
     )
     row = MockCaseRow(case, report, child_index=self.child_index)
     self.assertEqual(row.child_age, child_age)
     return getattr(row, self.row_property)
Exemplo n.º 26
0
def single_chw_summary(request):
    """Report for a single CHW""" 
    chw_id = request.GET.get("chw", None)
    chws = CommunityHealthWorker.view("chw/by_clinic", include_docs=True)
    main_chw = CommunityHealthWorker.get(chw_id) if chw_id else None
    
    punchcard_url = ""
    if main_chw:
        punchcard_url = get_punchcard_url(get_data(main_chw.current_clinic_id, chw_id), width=910)
        # patch on extra data for display
        main_chw.last_submission = get_last_submission_date(main_chw.get_id)    
        main_chw.first_submission = get_first_submission_date(main_chw.get_id)    
        main_chw.forms_submitted = get_forms_submitted(main_chw.get_id)    
        forms_breakdown = get_submission_breakdown(main_chw.get_id)
        main_chw.hh_surveys = forms_breakdown[config.CHW_HOUSEHOLD_SURVEY_NAMESPACE]
        main_chw.fus = forms_breakdown[config.CHW_FOLLOWUP_NAMESPACE]
        main_chw.refs = forms_breakdown[config.CHW_REFERRAL_NAMESPACE]
        main_chw.monthly_surveys = forms_breakdown[config.CHW_MONTHLY_SURVEY_NAMESPACE]
        
        # recent monthly surveys
        main_chw.recent_surveys = get_recent_forms(main_chw.get_id, config.CHW_MONTHLY_SURVEY_NAMESPACE)
        
        if not request.datespan.is_valid():
            messages.error(request, request.datespan.get_validation_reason())
            messages.warning(request, "Performance Indicators are not displayed. Please fix the other errors")
            report = {"name": "Partial CHW Summary for %s" % main_chw.formatted_name}
        else:
            report = get_chw_pi_report(main_chw, request.datespan.startdate, request.datespan.enddate)
    else:        
        report = {"name": "CHW Summary"}
    fake_hh_data = []
    now = datetime.now()
    for i in range(3):
        year, month = add_months(now.year, now.month, -i)
        fake_hh_data.append(["%s %s" % (year, month), 100, 200, "25%", "13%"])
        
    return render_to_response(request, "reports/chw_summary.html", 
                              {"report": report,
                               "chw_id": chw_id,
                               "main_chw":    main_chw,
                               "chws":   chws,
                               "punchcard_url":    punchcard_url,
                               "show_dates": False,
                               "hh_data": fake_hh_data, # TODO
                               "fu_data": fake_hh_data, # TODO
                               "ref_data": fake_hh_data # TODO
                               })
Exemplo n.º 27
0
    def get_first_days(self, current_month, num_previous_months, as_datespans=False):
        enddate = current_month or datetime.datetime.utcnow()
        enddate = self.get_first_day_of_month(enddate.year, enddate.month)
        (start_year, start_month) = add_months(enddate.year, enddate.month, -num_previous_months)
        startdate = self.get_last_day_of_month(start_year, start_month)

        months = months_between(startdate, enddate)

        month_dates = list()
        for year, month in months:
            if as_datespans:
                month_dates.append(self.get_month_datespan((year, month)))
            else:
                month_dates.append(self.get_first_day_of_month(year, month))

        datespan = self.get_month_datespan((startdate.year, startdate.month), (enddate.year, enddate.month))
        return month_dates, datespan
Exemplo n.º 28
0
def create_alert(location_id, date, alert_type, details):
    text = ''
    # url = ''
    date = datetime(date.year, date.month, 1)
    expyear, expmonth = add_months(date.year, date.month, 1)
    expires = datetime(expyear, expmonth, 1)

    number = 0 if 'number' not in details else details['number']

    if alert_type in [const.PRODUCT_STOCKOUT, const.NO_PRIMARY_CONTACT]:
        if alert_type == const.PRODUCT_STOCKOUT:
            text = '%s is stocked out of %s.' % (details['org'].name, details['product'].name)
        elif alert_type == const.NO_PRIMARY_CONTACT:
            text = '%s has no primary contact.' % details['org'].name

        alert = Alert.objects.filter(location_id=location_id, date=date, type=alert_type, text=text)
        if not alert:
            Alert(location_id=location_id, date=date, type=alert_type, expires=expires, text=text).save()

    else:
        if alert_type == const.RR_NOT_SUBMITTED:
            text = '%s have reported not submitting their R&R form as of today.' % \
                   ((str(number) + ' facility') if number == 1 else (str(number) + ' facilities'))
        elif alert_type == const.RR_NOT_RESPONDED:
            text = '%s did not respond to the SMS asking if they had submitted their R&R form.' % \
                   ((str(number) + ' facility') if number == 1 else (str(number) + ' facilities'))
        elif alert_type == const.DELIVERY_NOT_RECEIVED:
            text = '%s have reported not receiving their deliveries as of today.' % \
                   ((str(number) + ' facility') if number == 1 else (str(number) + ' facilities'))
        elif alert_type == const.DELIVERY_NOT_RESPONDING:
            text = '%s did not respond to the SMS asking if they had received their delivery.' % \
                   ((str(number) + ' facility') if number == 1 else (str(number) + ' facilities'))
        elif alert_type == const.SOH_NOT_RESPONDING:
            text = '%s have not reported their stock levels for last month.' % \
                   ((str(number) + ' facility') if number == 1 else (str(number) + ' facilities'))

        alert, created = Alert.objects.get_or_create(
            location_id=location_id,
            date=date,
            type=alert_type,
            expires=expires
        )
        alert.number = number
        alert.text = text
        alert.save()
Exemplo n.º 29
0
    def template_context(self):
        now = datetime.datetime.utcnow()
        rows = []
        last_month_summary = None
        for i in range(-6, 0):
            year, month = add_months(now.year, now.month, i)
            month_as_date = datetime.date(year, month, 1)
            this_month_summary = MonthlyPerformanceSummary(
                domain=self.domain,
                month=month_as_date,
                previous_summary=last_month_summary,
            )
            rows.append(this_month_summary)
            last_month_summary = this_month_summary

        return {
            'rows': rows,
            'last_month': rows[-1]
        }
Exemplo n.º 30
0
def get_possibly_experienced(domain, start):

    user_ids = get_mobile_users(domain.name)
    threshold = domain.internal.experienced_threshold or DEFAULT_EXPERIENCED_THRESHOLD
    months = threshold - 2
    threshold_month = add_months(start.startdate.year, start.startdate.month, -months)
    end_month = datetime.date(day=1, year=threshold_month[0], month=threshold_month[1])

    form_users = set(
        FormES()
        .domain(domain.name)
        .user_aggregation()
        .submitted(lt=end_month)
        .user_id(user_ids)
        .size(0)
        .run()
        .aggregations.user.keys
    )

    return set(form_users)
Exemplo n.º 31
0
    def get_first_days(self, current_month, num_previous_months, as_datespans=False):
        enddate = current_month or datetime.datetime.utcnow()
        enddate = self.get_first_day_of_month(enddate.year, enddate.month)
        (start_year, start_month) = add_months(enddate.year, enddate.month, -num_previous_months)
        startdate = self.get_last_day_of_month(start_year, start_month)

        months = months_between(startdate, enddate)

        month_dates = list()
        for year, month in months:
            if as_datespans:
                month_dates.append(self.get_month_datespan((year, month)))
            else:
                month_dates.append(self.get_first_day_of_month(year, month))

        datespan = self.get_month_datespan(
            (startdate.year, startdate.month),
            (enddate.year, enddate.month)
        )
        return month_dates, datespan
Exemplo n.º 32
0
def make_case_row(form_props=None, vhnd_props=None, block='Atri', child_age=6):
    """
    Accepts lists of properties available in form and at the vhnd
    and returns a corresponding case row
    """
    report_year = 2014
    report_month = 6
    date_in_month = datetime(2014, 6, 10)
    child_age = child_age
    owner_id = 'mock_owner_id'

    forms = [XFormInstance(
        form={'child_1': {prop: '1' for prop in form_props or []}},
        received_on=date_in_month,
        xmlns=constants.CFU1_XMLNS,
    )]

    dod_year, dod_month = add_months(report_year, report_month, -child_age)
    case = OPMCase(
        forms=forms or [],
        dod=date(dod_year, dod_month, 10),
        owner_id=owner_id,
    )

    data_provider = MockDataProvider(explicit_map={
        owner_id: {
            prop: {date_in_month.date()}
            for prop in vhnd_props or []
        }
    })

    report = Report(
        month=report_month,
        year=report_year,
        block=block,
    )

    row = MockCaseRow(case, report, data_provider=data_provider)
    assert row.child_age == child_age
    return row
Exemplo n.º 33
0
def create_alert(org, date, type, details):
    text = ''
    # url = ''
    date = datetime(date.year, date.month, 1)
    expyear, expmonth = add_months(date.year, date.month, 1)
    expires = datetime(expyear, expmonth, 1)

    number = 0 if 'number' not in details else details['number']

    if type in ['product_stockout', 'no_primary_contact']:
        if type == 'product_stockout':
            text = '%s is stocked out of %s.' % (details['org'].name, details['product'].name)
        elif type == 'no_primary_contact':
            text = '%s has no primary contact.' % details['org'].name

        alert = Alert.objects.filter(supply_point=org, date=date, type=type, text=text)
        if not alert:
            Alert(supply_point=org, date=date, type=type, expires=expires, text=text).save()

    else:
        if type == 'rr_not_submitted':
            text = '%s have reported not submitting their R&R form as of today.' % \
                   ((str(number) + ' facility') if number == 1 else (str(number) + ' facilities'))
        elif type == 'rr_not_responded':
            text = '%s did not respond to the SMS asking if they had submitted their R&R form.' % \
                   ((str(number) + ' facility') if number == 1 else (str(number) + ' facilities'))
        elif type == 'delivery_not_received':
            text = '%s have reported not receiving their deliveries as of today.' % \
                   ((str(number) + ' facility') if number == 1 else (str(number) + ' facilities'))
        elif type == 'delivery_not_responding':
            text = '%s did not respond to the SMS asking if they had received their delivery.' % \
                   ((str(number) + ' facility') if number == 1 else (str(number) + ' facilities'))
        elif type == 'soh_not_responding':
            text = '%s have not reported their stock levels for last month.' % \
                   ((str(number) + ' facility') if number == 1 else (str(number) + ' facilities'))

        alert, created = Alert.objects.get_or_create(supply_point=org, date=date, type=type, expires=expires)
        alert.number = number
        alert.text = text
        alert.save()
Exemplo n.º 34
0
def make_case_row(form_props=None, vhnd_props=None, block='Atri', child_age=6):
    """
    Accepts lists of properties available in form and at the vhnd
    and returns a corresponding case row
    """
    report_year = 2014
    report_month = 6
    date_in_month = datetime(2014, 6, 10)
    child_age = child_age
    owner_id = 'mock_owner_id'

    forms = [XFormInstance(
        form={'child_1': {prop: '1' for prop in form_props or []}},
        received_on=date_in_month,
        xmlns=constants.CFU1_XMLNS,
    )]

    dod_year, dod_month = add_months(report_year, report_month, -child_age)
    case = OPMCase(
        forms=forms or [],
        dod=date(dod_year, dod_month, 10),
        owner_id=owner_id,
    )

    data_provider = MockDataProvider(explicit_map={
        owner_id: {
            prop: {date_in_month.date()}
            for prop in vhnd_props or []
        }
    })

    report = Report(
        month=report_month,
        year=report_year,
        block=block,
    )

    row = MockCaseRow(case, report, data_provider=data_provider)
    assert row.child_age == child_age
    return row
Exemplo n.º 35
0
        self.is_secondary = is_secondary
        self.case_is_out_of_range = False

        if not report.is_rendered_as_email:
            self.img_elem = '<div style="width:160px !important;"><img src="/static/opm/img/%s">' \
                            '<text class="image-descriptor" style="display:none">%s</text></div>'
        else:
            self.img_elem = '<div><img src="/static/opm/img/%s"><text class="image-descriptor" ' \
                            'style="display:none">%s</text></div>'

        self.set_case_properties()
        self.last_month_row = None
        if not is_secondary:
            self.add_extra_children()
            # if we were called directly, set the last month's row on this
            last_year, last_month = add_months(self.year, self.month, -1)
            try:
                self.last_month_row = OPMCaseRow(case, report, 1, is_secondary=True,
                                                 explicit_month=last_month, explicit_year=last_year)
            except InvalidRow:
                pass

    @property
    def readable_status(self):
        if self.report.is_rendered_as_email:
            with localize('hin'):
                return _(self.status)
        return self.status

    def child_xpath(self, template):
        return template.format(num=self.child_index)
Exemplo n.º 36
0
 def get_months_before(self, months_before=None):
     new_year, new_month = add_months(self.year, self.month, -months_before)
     return first_of_next_month(datetime.datetime(new_year, new_month, 1))
Exemplo n.º 37
0
 def get_months_after(self, months_after=None):
     new_year, new_month = add_months(self.year, self.month, months_after)
     return first_of_next_month(datetime.datetime(new_year, new_month, 1))
Exemplo n.º 38
0
 def get_months_before(self, months_before=None):
     new_year, new_month = add_months(self.year, self.month, -months_before)
     return first_of_next_month(datetime.datetime(new_year, new_month, 1))
Exemplo n.º 39
0
 def get_months_after(self, months_after=None):
     new_year, new_month = add_months(self.year, self.month, months_after)
     return first_of_next_month(datetime.datetime(new_year, new_month, 1))
Exemplo n.º 40
0
def get_previous_month_date_range(reference_date=None):
    reference_date = reference_date or datetime.date.today()

    last_month_year, last_month = add_months(reference_date.year,
                                             reference_date.month, -1)
    return get_first_last_days(last_month_year, last_month)
Exemplo n.º 41
0
def get_relative_edd_from_preg_month(report_date, month):
    months_until_edd = 9 - month
    new_year, new_month = add_months(report_date.year, report_date.month, months_until_edd)
    return type(report_date)(new_year, new_month, 1)
Exemplo n.º 42
0
 def previous_month(self):
     prev_year, prev_month = add_months(self.month.year, self.month.month,
                                        -1)
     return datetime.datetime(prev_year, prev_month, 1)
Exemplo n.º 43
0
def get_previous_month_date_range(reference_date=None):
    reference_date = reference_date or datetime.date.today()

    last_month_year, last_month = add_months(reference_date.year, reference_date.month, -1)
    return get_first_last_days(last_month_year, last_month)
Exemplo n.º 44
0
def offset_date(reference_date, offset):
    new_year, new_month = add_months(reference_date.year, reference_date.month, offset)
    return type(reference_date)(new_year, new_month, 1)
Exemplo n.º 45
0
 def get_active_recent(domain, monthspan):
     months = (domain.internal.experienced_threshold or DEFAULT_EXPERIENCED_THRESHOLD) - 1
     threshold_month = add_months(monthspan.startdate.year, monthspan.startdate.month, -months)
     first_month = datetime.date(day=1, year=threshold_month[0], month=threshold_month[1])
     all_users, users_dict, sms = active_mobile_users(domain, first_month, monthspan.computed_enddate)
     return set(users_dict.keys()) | sms
Exemplo n.º 46
0
def months_from_date(reference_date, months_from_date):
    year, month = add_months(reference_date.year, reference_date.month, months_from_date)
    return datetime.date(year, month, 1)
Exemplo n.º 47
0
def get_relative_edd_from_preg_month(report_date, month):
    months_until_edd = 9 - month
    new_year, new_month = add_months(report_date.year, report_date.month, months_until_edd)
    return type(report_date)(new_year, new_month, 1)
Exemplo n.º 48
0
 def previous_month(self):
     prev_year, prev_month = add_months(self.month.year, self.month.month, -1)
     return datetime.datetime(prev_year, prev_month, 1)
Exemplo n.º 49
0
def months_from_date(reference_date, months_from_date):
    year, month = add_months(reference_date.year, reference_date.month,
                             months_from_date)
    return datetime.date(year, month, 1)
Exemplo n.º 50
0
def offset_date(reference_date, offset):
    new_year, new_month = add_months(reference_date.year, reference_date.month, offset)
    return type(reference_date)(new_year, new_month, 1)
Exemplo n.º 51
0
class SetupProjectPerformanceMixin(object):
    DOMAIN_NAME = "test_domain"
    USERNAME = "******"
    USERNAME1 = "testuser1"
    USERNAME2 = "testuser2"
    WEB_USER = "******"
    USER_TYPE = "CommCareUser"
    now = datetime.datetime.utcnow()
    year, month = add_months(now.year, now.month, 1)
    month_as_date = datetime.date(year, month, 1)
    prev_month_as_date = datetime.date(now.year, now.month, 1)

    @classmethod
    def class_setup(cls):
        cls._setup_domain()
        cls._setup_users()
        cls._setup_malt_tables()

    @classmethod
    def class_teardown(cls):
        UserESFake.reset_docs()
        cls.domain.delete()

    @classmethod
    def make_mobile_worker(cls, username, domain=None):
        domain = domain or cls.domain
        user = CommCareUser.create(domain, username, '123', None, None)
        doc = user._doc
        doc['username.exact'] = doc['username']
        UserESFake.save_doc(doc)
        return user

    @classmethod
    def _setup_users(cls):
        cls.user = cls.make_mobile_worker(cls.USERNAME, cls.DOMAIN_NAME)
        cls.user1 = cls.make_mobile_worker(cls.USERNAME1, cls.DOMAIN_NAME)
        cls.user2 = cls.make_mobile_worker(cls.USERNAME2, cls.DOMAIN_NAME)

    @classmethod
    def _setup_domain(cls):
        cls.domain = Domain(name=cls.DOMAIN_NAME)
        cls.domain.save()

    @classmethod
    def _setup_malt_tables(cls):
        malt_user = MALTRow.objects.create(
            month=cls.month_as_date,
            user_id=cls.user._id,
            username=cls.USERNAME,
            domain_name=cls.DOMAIN_NAME,
            user_type=cls.USER_TYPE,
            num_of_forms=16,
            app_id=MISSING_APP_ID,
        )
        malt_user.save()
        malt_user1 = MALTRow.objects.create(
            month=cls.month_as_date,
            user_id=cls.user1._id,
            username=cls.USERNAME1,
            domain_name=cls.DOMAIN_NAME,
            user_type=cls.USER_TYPE,
            num_of_forms=16,
            app_id=MISSING_APP_ID,
        )
        malt_user1.save()
        malt_user_prev = MALTRow.objects.create(
            month=cls.prev_month_as_date,
            user_id=cls.user._id,
            username=cls.USERNAME,
            domain_name=cls.DOMAIN_NAME,
            user_type=cls.USER_TYPE,
            num_of_forms=15,
            app_id=MISSING_APP_ID,
        )
        malt_user_prev.save()