def rendered_content(self):
        from corehq.apps.users.views.mobile.users import EditCommCareUserView
        users = get_users_by_location_id(self.config['domain'],
                                         self.config['location_id'])
        in_charges = FacilityInCharge.objects.filter(
            location=self.location
        ).values_list('user_id', flat=True)
        if self.location.parent.location_type.name == 'district':
            children = self.location.parent.get_descendants()
            availaible_in_charges = list(chain.from_iterable([
                filter(
                    lambda u: 'In Charge' in u.user_data.get('role', []),
                    get_users_by_location_id(self.config['domain'], child.location_id)
                )
                for child in children
            ]))
        else:
            availaible_in_charges = filter(
                lambda u: 'In Charge' in u.user_data.get('role', []),
                get_users_by_location_id(self.domain, self.location_id)
            )
        user_to_dict = lambda sms_user: {
            'id': sms_user.get_id,
            'full_name': sms_user.full_name,
            'phone_numbers': sms_user.phone_numbers,
            'in_charge': sms_user.get_id in in_charges,
            'location_name': sms_user.location.sql_location.name,
            'url': reverse(EditCommCareUserView.urlname, args=[self.config['domain'], sms_user.get_id])
        }

        web_users_from_extension = list(iter_docs(
            WebUser.get_db(),
            EWSExtension.objects.filter(domain=self.domain,
                                        location_id=self.location_id).values_list('user_id', flat=True)
        ))

        WebUserInfo = collections.namedtuple('WebUserInfo', 'id first_name last_name email')

        web_users = {
            WebUserInfo(
                id=web_user['_id'],
                first_name=web_user['first_name'],
                last_name=web_user['last_name'],
                email=web_user['email']
            )
            for web_user in (UserES().web_users().domain(self.config['domain']).term(
                "domain_memberships.location_id", self.location_id
            ).run().hits + web_users_from_extension)
        }

        return render_to_string('ewsghana/partials/users_tables.html', {
            'users': [user_to_dict(user) for user in users],
            'domain': self.domain,
            'location_id': self.location_id,
            'web_users': web_users,
            'district_in_charges': [user_to_dict(user) for user in availaible_in_charges]
        })
Example #2
0
    def rendered_content(self):
        from corehq.apps.users.views.mobile.users import EditCommCareUserView
        users = get_users_by_location_id(self.config['domain'],
                                         self.config['location_id'])
        in_charges = FacilityInCharge.objects.filter(
            location=self.location).values_list('user_id', flat=True)
        if self.location.parent.location_type.name == 'district':
            children = self.location.parent.get_descendants()
            availaible_in_charges = list(
                chain.from_iterable([
                    filter(
                        lambda u: 'In Charge' in u.user_data.get('role', []),
                        get_users_by_location_id(self.config['domain'],
                                                 child.location_id))
                    for child in children
                ]))
        else:
            availaible_in_charges = filter(
                lambda u: 'In Charge' in u.user_data.get('role', []),
                get_users_by_location_id(self.domain, self.location_id))
        user_to_dict = lambda sms_user: {
            'id':
            sms_user.get_id,
            'full_name':
            sms_user.full_name,
            'phone_numbers':
            sms_user.phone_numbers,
            'in_charge':
            sms_user.get_id in in_charges,
            'location_name':
            sms_user.location.sql_location.name,
            'url':
            reverse(EditCommCareUserView.urlname,
                    args=[self.config['domain'], sms_user.get_id])
        }

        web_users = [{
            'id': web_user['_id'],
            'first_name': web_user['first_name'],
            'last_name': web_user['last_name'],
            'email': web_user['email']
        } for web_user in UserES().web_users().domain(
            self.config['domain']).term("domain_memberships.location_id",
                                        self.config['location_id']).run().hits]
        return render_to_string(
            'ewsghana/partials/users_tables.html', {
                'users': [user_to_dict(user) for user in users],
                'domain':
                self.domain,
                'location_id':
                self.location_id,
                'web_users':
                web_users,
                'district_in_charges':
                [user_to_dict(user) for user in availaible_in_charges]
            })
    def rendered_content(self):
        from corehq.apps.users.views.mobile.users import EditCommCareUserView
        users = get_users_by_location_id(self.config['location_id'])

        user_to_dict = lambda sms_user: {
            'id': sms_user.get_id,
            'full_name': sms_user.full_name,
            'phone_numbers': sms_user.phone_numbers,
            'in_charge': user.user_data.get('role') == 'In Charge',
            'url': reverse(EditCommCareUserView.urlname, args=[self.config['domain'], sms_user.get_id])
        }

        web_users = [
            {
                'id': web_user['_id'],
                'first_name': web_user['first_name'],
                'last_name': web_user['last_name'],
                'email': web_user['email']
            }
            for web_user in UserES().web_users().domain(self.config['domain']).term(
                "domain_memberships.location_id", self.config['location_id']
            ).run().hits
        ]
        return render_to_string('ewsghana/partials/users_tables.html', {
            'users': [user_to_dict(user) for user in users],
            'domain': self.domain,
            'location_id': self.location_id,
            'web_users': web_users
        })
Example #4
0
def populate_no_primary_alerts(location, date):
    # First of all we have to delete all existing alert for this date.
    alert = Alert.objects.filter(location_id=location.get_id, date=date, type=const.NO_PRIMARY_CONTACT)
    alert.delete()
    # create no primary contact alerts
    if not get_users_by_location_id(location.domain, location.get_id):
        create_alert(location, date, NO_PRIMARY_CONTACT, {'org': location})
Example #5
0
    def _send_delivery_alert_to_facilities(self, location):
        locs = [c.get_id for c in location.get_children()]
        users = []
        for location_id in locs:
            users.extend(get_users_by_location_id(self.domain, location_id))

        for user in users:
            send_translated_message(user, DELIVERY_CONFIRM_CHILDREN, district_name=location.name)
Example #6
0
 def send_message(self, sql_location, message, **kwargs):
     for user in get_users_by_location_id(self.domain,
                                          sql_location.location_id):
         verified_number = user.get_verified_number()
         if verified_number:
             with localize(user.get_language_code()):
                 send_sms_to_verified_number(verified_number,
                                             message % kwargs)
Example #7
0
def populate_no_primary_alerts(location, date):
    # First of all we have to delete all existing alert for this date.
    alert = Alert.objects.filter(location_id=location.get_id,
                                 date=date,
                                 type=const.NO_PRIMARY_CONTACT)
    alert.delete()
    # create no primary contact alerts
    if not get_users_by_location_id(location.domain, location.get_id):
        create_alert(location, date, NO_PRIMARY_CONTACT, {'org': location})
Example #8
0
def configure_in_charge(request, domain):
    in_charge_ids = request.POST.getlist('users[]')
    location_id = request.POST.get('location_id')
    all_users = get_users_by_location_id(location_id)

    for u in all_users:
        if (u.user_data.get('role') == 'In Charge') != (u._id in in_charge_ids):
            u.user_data['role'] = 'In Charge' if u._id in in_charge_ids else 'Other'
            u.save()
    return HttpResponse('OK')
Example #9
0
    def supervisor(self):
        """
        Returns None if there is a misconfiguration (i.e., if the AWW's location
        has no parent location, or if there are no users at the parent location).
        """
        supervisor_location = self.user.sql_location.parent
        if supervisor_location is None:
            return None

        return get_users_by_location_id(self.domain, supervisor_location.location_id).first()
Example #10
0
    def _send_delivery_alert_to_facilities(self, location):
        locs = [c.get_id for c in location.children]
        users = []
        for location_id in locs:
            users.extend(get_users_by_location_id(self.domain, location_id))

        for user in users:
            if user.get_verified_number():
                send_sms_to_verified_number(user.get_verified_number(), DELIVERY_CONFIRM_CHILDREN %
                                            {"district_name": location.name})
Example #11
0
    def supervisor(self):
        """
        Returns None if there is a misconfiguration (i.e., if the AWW's location
        has no parent location, or if there are no users at the parent location).
        """
        supervisor_location = self.user.sql_location.parent
        if supervisor_location is None:
            return None

        return get_users_by_location_id(self.domain, supervisor_location.location_id).first()
Example #12
0
def send_message_to_admins(user, message):
    users = get_users_by_location_id(user.domain, user.location.get_id)
    in_charge_users = [
        u for u in users if u.get_verified_number()
        and "In Charge" in u.user_data.get('role', [])
    ]
    for in_charge_user in in_charge_users:
        send_sms_to_verified_number(
            in_charge_user.get_verified_number(),
            message % (in_charge_user.full_name, in_charge_user.location.name))
Example #13
0
    def _send_delivery_alert_to_facilities(self, location):
        locs = [c.get_id for c in location.get_children()]
        users = []
        for location_id in locs:
            users.extend(get_users_by_location_id(self.domain, location_id))

        for user in users:
            send_translated_message(user,
                                    DELIVERY_CONFIRM_CHILDREN,
                                    district_name=location.name)
Example #14
0
def send_message_to_admins(user, message):
    users = get_users_by_location_id(user.domain, user.location.get_id)
    in_charge_users = [
        u
        for u in users
        if get_verified_number_for_recipient(u) and "In Charge" in u.user_data.get('role', [])
    ]
    for in_charge_user in in_charge_users:
        send_sms_to_verified_number(get_verified_number_for_recipient(in_charge_user),
                                    message % (in_charge_user.full_name, in_charge_user.location.name))
Example #15
0
    def _send_delivery_alert_to_facilities(self, location):
        locs = [c.get_id for c in location.children]
        users = []
        for location_id in locs:
            users.extend(get_users_by_location_id(self.domain, location_id))

        for user in users:
            if user.get_verified_number():
                send_sms_to_verified_number(
                    user.get_verified_number(), DELIVERY_CONFIRM_CHILDREN %
                    {"district_name": location.name})
Example #16
0
 def send_message(self, sql_location, message, **kwargs):
     for user in get_users_by_location_id(self.domain, sql_location.location_id):
         send_translated_message(user, message, **kwargs)
Example #17
0
 def supervisor(self):
     supervisor_location = self.user.sql_location.parent
     return get_users_by_location_id(
         self.domain, supervisor_location.location_id).first()
 def send_message(self, sql_location, message, **kwargs):
     for user in get_users_by_location_id(sql_location.location_id):
         send_sms_to_verified_number(user.get_verified_number(), message % kwargs)
Example #19
0
 def get_location_users(self, sql_location):
     return get_users_by_location_id(self.domain, sql_location.location_id)
Example #20
0
def process_facility_warehouse_data(facility, start_date, end_date, runner=None):
    """
    process all the facility-level warehouse tables
    """
    logging.info("processing facility %s (%s)" % (facility.name, str(facility._id)))

    sql_location = facility.sql_location
    if runner:
        runner.location = sql_location
        runner.save()

    for alert_type in [const.SOH_NOT_RESPONDING, const.RR_NOT_RESPONDED, const.DELIVERY_NOT_RESPONDING]:
        alert = Alert.objects.filter(location_id=facility._id, date__gte=start_date, date__lt=end_date,
                                     type=alert_type)
        alert.delete()

    supply_point_id = sql_location.supply_point_id
    location_id = facility._id
    new_statuses = SupplyPointStatus.objects.filter(
        location_id=facility._id,
        status_date__gte=start_date,
        status_date__lt=end_date
    ).order_by('status_date').iterator()
    process_facility_statuses(location_id, new_statuses)

    new_reports = StockReport.objects.filter(
        stocktransaction__case_id=supply_point_id,
        date__gte=start_date,
        date__lt=end_date,
        stocktransaction__type='stockonhand'
    ).distinct().order_by('date').iterator()
    process_facility_product_reports(location_id, new_reports)

    new_trans = get_latest_transaction_from_each_month(supply_point_id, start_date, end_date)
    process_facility_transactions(location_id, new_trans, start_date, end_date)

    products = SQLProduct.objects.filter(domain=facility.domain, is_archived=False)
    users = get_users_by_location_id(facility.domain, facility.get_id)

    # go through all the possible values in the date ranges
    # # and make sure there are warehouse tables there
    for year, month in months_between(start_date, end_date):
        window_date = datetime(year, month, 1)
        # create org_summary for every fac/date combo
        org_summary, created = OrganizationSummary.objects.get_or_create(
            location_id=facility._id,
            date=window_date
        )

        org_summary.total_orgs = 1
        alt = average_lead_time(facility._id, window_date)
        if alt:
            alt = alt.days
        org_summary.average_lead_time_in_days = alt or 0
        org_summary.save()

        # create group_summary for every org_summary title combo
        for title in const.NEEDED_STATUS_TYPES:
            GroupSummary.objects.get_or_create(org_summary=org_summary,
                                               title=title)
        # update all the non-response data
        not_responding_facility(org_summary)
        # alerts
        with transaction.atomic():
            populate_no_primary_alerts(facility, window_date, users)
            populate_facility_stockout_alerts(facility, window_date)

    update_product_availability_facility_data(facility, products, start_date, end_date)
    update_historical_data_for_location(facility)
Example #21
0
    def rendered_content(self):
        from corehq.apps.users.views.mobile.users import EditCommCareUserView
        users = get_users_by_location_id(self.config['domain'],
                                         self.config['location_id'])
        in_charges = FacilityInCharge.objects.filter(
            location=self.location).values_list('user_id', flat=True)
        if self.location.parent.location_type.name == 'district':
            children = self.location.parent.get_descendants()
            availaible_in_charges = list(
                chain.from_iterable([[
                    u for u in get_users_by_location_id(
                        self.config['domain'], child.location_id)
                    if 'In Charge' in u.user_data.get('role', [])
                ] for child in children]))
        else:
            availaible_in_charges = [
                u for u in get_users_by_location_id(self.domain,
                                                    self.location_id)
                if 'In Charge' in u.user_data.get('role', [])
            ]
        user_to_dict = lambda sms_user: {
            'id':
            sms_user.get_id,
            'full_name':
            sms_user.full_name,
            'phone_numbers':
            sms_user.phone_numbers,
            'in_charge':
            sms_user.get_id in in_charges,
            'location_name':
            sms_user.location.sql_location.name,
            'url':
            reverse(EditCommCareUserView.urlname,
                    args=[self.config['domain'], sms_user.get_id])
        }

        web_users_from_extension = list(
            iter_docs(
                WebUser.get_db(),
                EWSExtension.objects.filter(
                    domain=self.domain,
                    location_id=self.location_id).values_list('user_id',
                                                              flat=True)))

        WebUserInfo = collections.namedtuple('WebUserInfo',
                                             'id first_name last_name email')

        web_users = {
            WebUserInfo(id=web_user['_id'],
                        first_name=web_user['first_name'],
                        last_name=web_user['last_name'],
                        email=web_user['email'])
            for web_user in (UserES().web_users().domain(
                self.config['domain']).term("domain_memberships.location_id",
                                            self.location_id).run().hits +
                             web_users_from_extension)
        }

        return render_to_string(
            'ewsghana/partials/users_tables.html', {
                'users': [user_to_dict(user) for user in users],
                'domain':
                self.domain,
                'location_id':
                self.location_id,
                'web_users':
                web_users,
                'district_in_charges':
                [user_to_dict(user) for user in availaible_in_charges]
            })
Example #22
0
 def get_location_users(self, sql_location):
     return get_users_by_location_id(self.domain, sql_location.location_id)
Example #23
0
 def send_message(self, sql_location, message, **kwargs):
     for user in get_users_by_location_id(self.domain,
                                          sql_location.location_id):
         send_translated_message(user, message, **kwargs)
Example #24
0
def process_facility_warehouse_data(facility,
                                    start_date,
                                    end_date,
                                    runner=None):
    """
    process all the facility-level warehouse tables
    """
    logging.info("processing facility %s (%s)" %
                 (facility.name, str(facility.location_id)))

    sql_location = facility.sql_location
    if runner:
        runner.location = sql_location
        runner.save()

    for alert_type in [
            const.SOH_NOT_RESPONDING, const.RR_NOT_RESPONDED,
            const.DELIVERY_NOT_RESPONDING
    ]:
        alert = Alert.objects.filter(location_id=facility.location_id,
                                     date__gte=start_date,
                                     date__lt=end_date,
                                     type=alert_type)
        alert.delete()

    supply_point_id = sql_location.supply_point_id
    location_id = facility.location_id
    new_statuses = SupplyPointStatus.objects.filter(
        location_id=facility.location_id,
        status_date__gte=start_date,
        status_date__lt=end_date).order_by('status_date').iterator()
    process_facility_statuses(location_id, new_statuses)

    new_reports = StockReport.objects.filter(
        stocktransaction__case_id=supply_point_id,
        date__gte=start_date,
        date__lt=end_date,
        stocktransaction__type='stockonhand').distinct().order_by(
            'date').iterator()
    process_facility_product_reports(location_id, new_reports)

    new_trans = get_latest_transaction_from_each_month(supply_point_id,
                                                       start_date, end_date)
    process_facility_transactions(location_id, new_trans, start_date, end_date)

    products = SQLProduct.objects.filter(domain=facility.domain,
                                         is_archived=False)
    users = get_users_by_location_id(facility.domain, facility.get_id)

    # go through all the possible values in the date ranges
    # # and make sure there are warehouse tables there
    for year, month in months_between(start_date, end_date):
        window_date = datetime(year, month, 1)
        # create org_summary for every fac/date combo
        org_summary, created = OrganizationSummary.objects.get_or_create(
            location_id=facility.location_id, date=window_date)

        org_summary.total_orgs = 1
        alt = average_lead_time(facility.location_id, window_date)
        if alt:
            alt = alt.days
        org_summary.average_lead_time_in_days = alt or 0
        org_summary.save()

        # create group_summary for every org_summary title combo
        for title in const.NEEDED_STATUS_TYPES:
            GroupSummary.objects.get_or_create(org_summary=org_summary,
                                               title=title)
        # update all the non-response data
        not_responding_facility(org_summary)
        # alerts
        with transaction.atomic():
            populate_no_primary_alerts(facility, window_date, users)
            populate_facility_stockout_alerts(facility, window_date)

    update_product_availability_facility_data(facility, products, start_date,
                                              end_date)
    update_historical_data_for_location(facility)
 def send_message(self, sql_location, message, **kwargs):
     for user in get_users_by_location_id(self.domain, sql_location.location_id):
         verified_number = user.get_verified_number()
         if verified_number:
             with localize(user.get_language_code()):
                 send_sms_to_verified_number(verified_number, message % kwargs)