Exemplo n.º 1
0
    def GET(self):
        params = web.input(page=1, ed="", d_id="")
        edit_val = params.ed
        session = get_session()
        if session.role == 'District User':
            districts_SQL = (
                "SELECT id, name FROM locations WHERE type_id = "
                "(SELECT id FROM locationtype WHERE name = 'district') "
                "AND name = '%s'" % session.username.capitalize())
        else:
            districts_SQL = (
                "SELECT id, name FROM locations WHERE type_id = "
                "(SELECT id FROM locationtype WHERE name = 'district') ORDER by name"
            )

        districts = db.query(districts_SQL)
        rweek = get_reporting_week(datetime.datetime.now())
        year, week = rweek.split('W')
        reporting_weeks = []
        for i in range(1, int(week) + 1):
            reporting_weeks.append("%sW%s" % (year, i))
        hmis_033b_dataset = HMIS_033B_DATASET

        l = locals()
        del l['self']
        return render.dataentry(**l)
Exemplo n.º 2
0
 def GET(self):
     web.header('Content-Type', 'application/json')
     return json.dumps(
         {"period": get_reporting_week(datetime.datetime.now())})
Exemplo n.º 3
0
    def POST(self):
        params = web.input(facilitycode="",
                           form="",
                           district="",
                           msisdn="",
                           raw_msg="",
                           report_type="",
                           facility="",
                           reporter_type="",
                           reporter_name="")
        extras = {'reporter_type': params.reporter_type}

        if PREFERED_DHIS2_CONTENT_TYPE == 'json':
            dataValues = []
        else:
            dataValues = ""
        # print("FACILITYCODE:", params.facilitycode, "==>", params.facility)
        if params.facilitycode:
            if not USE_OLD_WEBHOOKS:
                values = json.loads(web.data())
                results = values.get('results', {})
                thresholds_list = []
                for key, v in results.iteritems():
                    val = v.get('value')
                    try:
                        val = int(float(val))
                    except:
                        pass
                    label = v.get('name')
                    slug = "%s_%s" % (params.form, label)
                    # print(slug)
                    if val.__str__().isdigit() or slug in TEXT_INDICATORS:
                        if not (val) and params.form in getattr(
                                settings, 'REPORTS_WITH_COMMANDS',
                            ['cases', 'death', 'epc', 'epd'
                             ]):  # XXX irregular forms
                            if label not in params.raw_msg.lower():
                                continue  # skip zero values for cases and death
                        if slug not in IndicatorMapping:
                            # print("Indicator Not Supported.::.", slug)
                            continue
                        # XXX check thresholds here
                        if IndicatorMapping[slug]['threshold']:
                            try:
                                threshold = int(
                                    float(IndicatorMapping[slug]['threshold']))
                                if val >= threshold:
                                    thresholds_list.append('{0} {1}'.format(
                                        val, IndicatorMapping[slug]['descr']))
                            except:
                                # print("Threshold.::.Failed to Add threshold Message")
                                pass
                        # print("%s=>%s" % (slug, val), IndicatorMapping[slug])
                        if PREFERED_DHIS2_CONTENT_TYPE == 'json':
                            dataValues.append({
                                'dataElement':
                                IndicatorMapping[slug]['dhis2_id'],
                                'categoryOptionCombo':
                                IndicatorMapping[slug]['dhis2_combo_id'],
                                'value':
                                val
                            })
                        else:
                            dataValues += (
                                "<dataValue dataElement='%s' categoryOptionCombo="
                                "'%s' value='%s' />\n" %
                                (IndicatorMapping[slug]['dhis2_id'],
                                 IndicatorMapping[slug]['dhis2_combo_id'],
                                 val))

                # Build alert message and send it
                # print("Thresholds List.::.", thresholds_list)
                if thresholds_list:
                    alert_message = "Thresholds alert: {0} ({1}) of {2} - {3} district reported:\n".format(
                        params.reporter_name, params.msisdn, params.facility,
                        params.district)
                    alert_message += '\n'.join(thresholds_list)
                    alert_message += '\n' + params.raw_msg
                    if len(params.facility) > 11:
                        send_threshold_alert(alert_message, params.district)
                        # print(alert_message)

            else:
                values = json.loads(
                    params['values']
                )  # only way we can get out Rapidpro values in webpy
                thresholds_list = []
                for v in values:
                    val = v.get('value')
                    try:
                        val = int(float(val))
                    except:
                        pass
                    label = v.get('label')
                    slug = "%s_%s" % (params.form, label)
                    if val.__str__().isdigit() or slug in TEXT_INDICATORS:
                        if not (val) and params.form in getattr(
                                settings, 'REPORTS_WITH_COMMANDS',
                            ['cases', 'death', 'epc', 'epd']):
                            if label not in params.raw_msg.lower():
                                continue  # skip zero values for cases and death
                        if slug not in IndicatorMapping:
                            print("Indicator Not Supported.::.", slug)
                            continue
                        # XXX check thresholds here
                        if IndicatorMapping[slug]['threshold']:
                            try:
                                threshold = int(
                                    float(IndicatorMapping[slug]['threshold']))
                                print("++++++++++ val:", val,
                                      "+++++ threshold", threshold)
                                if val > threshold:
                                    thresholds_list.append('{0} {1}'.format(
                                        val, IndicatorMapping[slug]['descr']))
                            except Exception as e:
                                print(
                                    "Threshold.::.Failed to Add threshold Message=>",
                                    str(e))
                                pass
                        print("%s=>%s" % (slug, val), IndicatorMapping[slug])
                        if PREFERED_DHIS2_CONTENT_TYPE == 'json':
                            dataValues.append({
                                'dataElement':
                                IndicatorMapping[slug]['dhis2_id'],
                                'categoryOptionCombo':
                                IndicatorMapping[slug]['dhis2_combo_id'],
                                'value':
                                val
                            })
                        else:
                            dataValues += (
                                "<dataValue dataElement='%s' categoryOptionCombo="
                                "'%s' value='%s' />\n" %
                                (IndicatorMapping[slug]['dhis2_id'],
                                 IndicatorMapping[slug]['dhis2_combo_id'],
                                 val))

                # Build alert message and send it
                print("Thresholds List.::.", thresholds_list)
                if thresholds_list:
                    alert_message = "Thresholds alert: {0} ({1}) of {2} - {3} district reported:\n".format(
                        params.reporter_name, params.msisdn, params.facility,
                        params.district)
                    alert_message += '\n'.join(thresholds_list)
                    alert_message += '\n' + params.raw_msg
                    if len(params.facility) > 11:
                        send_threshold_alert(alert_message, params.district)
                        print(alert_message)

            if not dataValues and params.form in ('cases', 'death'):
                if PREFERED_DHIS2_CONTENT_TYPE == 'json':
                    dataValues = []
                else:
                    dataValues = DEFAULT_DATA_VALUES[params.form]

            if dataValues:
                args_dict = {
                    'completeDate':
                    datetime.datetime.now().strftime("%Y-%m-%d"),
                    'period': get_reporting_week(datetime.datetime.now()),
                    'orgUnit': params.facilitycode,
                    'dataValues': dataValues
                }
                if PREFERED_DHIS2_CONTENT_TYPE == 'json':
                    args_dict['dataSet'] = IndicatorsDataSet.get(
                        params.form, HMIS_033B_DATASET)
                    args_dict[
                        'attributeOptionCombo'] = HMIS_033B_DATASET_ATTR_OPT_COMBO
                    payload = json.dumps(args_dict)
                else:
                    payload = XML_TEMPLATE % args_dict
                year, week = tuple(args_dict['period'].split('W'))
                print(payload)
                destination_name = KEYWORD_SERVER_MAPPINGS.get(
                    params.form, config['dispatcher2_destination'])
                extra_params = {
                    'week': week,
                    'year': year,
                    'msisdn': params.msisdn,
                    'facility': params.facilitycode,
                    'raw_msg': params.raw_msg,
                    'district': params.district,
                    'report_type': params.report_type,
                    # 'source': config['dispatcher2_source'],
                    # 'destination': config['dispatcher2_destination'],
                    'source': serversByName[config['dispatcher2_source']],
                    'destination': serversByName[destination_name],
                    'extras': json.dumps(extras),
                    'status': config.get('default-queue-status', 'pending')
                }
                # now ready to queue to DB for pushing to DHIS2
                # resp = queue_submission(serverid, post_xml, year, week)
                print(extra_params)
                if PREFERED_DHIS2_CONTENT_TYPE == 'json':
                    extra_params['ctype'] = 'json'
                    # resp = post_request_to_dispatcher2(
                    #    payload, params=extra_params, ctype='json')
                    extra_params['body'] = payload
                    report_id = queue_request(db, extra_params)
                else:
                    extra_params['ctype'] = 'xml'
                    # resp = post_request_to_dispatcher2(payload, params=extra_params)
                    extra_params['body'] = payload
                    report_id = queue_request(db, extra_params)
                # print "Resp:", resp
                # Invalidate the older similar reports
                yr, wk = get_current_week()
                invalidate_older_similar_reports.delay(params.msisdn,
                                                       params.report_type, yr,
                                                       wk, report_id)

        return json.dumps({"status": "success"})
Exemplo n.º 4
0
    def POST(self):
        params = web.input(facilitycode="",
                           form="",
                           district="",
                           msisdn="",
                           raw_msg="",
                           report_type="",
                           facility="",
                           reporter_type="",
                           uuid="",
                           reporter_name="")
        extras = {'reporter_type': params.reporter_type}
        # values = json.loads(params['values'])  # only way we can get out Rapidpro values in webpy
        if PREFERED_DHIS2_CONTENT_TYPE == 'json':
            dataValues = []
        else:
            dataValues = ""
        print("FACILITYCODE:", params.facilitycode, "==>", params.facility,
              "UUID:", params.uuid)
        if params.facilitycode:
            if not USE_OLD_WEBHOOKS:
                values = json.loads(web.data())
                results = values.get('results', {})
                thresholds_list = []
                for key, v in results.iteritems():
                    val = v.get('value')
                    try:
                        val = int(float(val))
                    except:
                        pass
                    label = v.get('name')
                    slug = "%s_%s" % (params.form, label)
                    if val.__str__().isdigit() or slug in TEXT_INDICATORS:
                        if not (val) and params.form in [
                                'cases', 'death', 'epc', 'epd'
                        ]:
                            if label not in params.raw_msg.lower():
                                continue  # skip zero values for cases, death, epc and epd
                        if slug not in IndicatorMapping:
                            continue
                        # XXX check thresholds here
                        if IndicatorMapping[slug]['threshold']:
                            try:
                                threshold = int(
                                    float(IndicatorMapping[slug]['threshold']))
                                if val > threshold:
                                    thresholds_list.append('{} {}'.format(
                                        val, IndicatorMapping[slug]['descr']))
                            except:
                                pass
                        print("%s=>%s" % (slug, val), IndicatorMapping[slug])
                        if PREFERED_DHIS2_CONTENT_TYPE == 'json':
                            dataValues.append({
                                'dataElement':
                                IndicatorMapping[slug]['dhis2_id'],
                                'categoryOptionCombo':
                                IndicatorMapping[slug]['dhis2_combo_id'],
                                'value':
                                val
                            })
                        else:
                            dataValues += (
                                "<dataValue dataElement='%s' categoryOptionCombo="
                                "'%s' value='%s' />\n" %
                                (IndicatorMapping[slug]['dhis2_id'],
                                 IndicatorMapping[slug]['dhis2_combo_id'],
                                 val))

                # Build alert message and send it
                alert_message = "Thresholds alert: {0} ({1}) of {2} - {3} district reported:\n".format(
                    params.reporter_name, params.msisdn, params.facility,
                    params.district)
                alert_message += '\n'.join(thresholds_list)
                send_threshold_alert(alert_message, params.district)
                print(alert_message)

            else:
                values = json.loads(
                    params['values']
                )  # only way we can get out Rapidpro values in webpy
                thresholds_list = []
                for v in values:
                    val = v.get('value')
                    try:
                        val = int(float(val))
                    except:
                        pass
                    label = v.get('label')
                    slug = "%s_%s" % (params.form, label)
                    if val.__str__().isdigit() or slug in TEXT_INDICATORS:
                        if not (val) and params.form in ['cases', 'death']:
                            if label not in params.raw_msg.lower():
                                continue  # skip zero values for cases and death
                        if slug not in IndicatorMapping:
                            continue
                        # XXX check thresholds here
                        if IndicatorMapping[slug]['threshold']:
                            try:
                                threshold = int(
                                    float(IndicatorMapping[slug]['threshold']))
                                if val > threshold:
                                    thresholds_list.append('{} {}'.format(
                                        val, IndicatorMapping[slug]['descr']))
                            except:
                                pass
                        print("%s=>%s" % (slug, val), IndicatorMapping[slug])
                        if PREFERED_DHIS2_CONTENT_TYPE == 'json':
                            dataValues.append({
                                'dataElement':
                                IndicatorMapping[slug]['dhis2_id'],
                                'categoryOptionCombo':
                                IndicatorMapping[slug]['dhis2_combo_id'],
                                'value':
                                val
                            })
                        else:
                            dataValues += (
                                "<dataValue dataElement='%s' categoryOptionCombo="
                                "'%s' value='%s' />\n" %
                                (IndicatorMapping[slug]['dhis2_id'],
                                 IndicatorMapping[slug]['dhis2_combo_id'],
                                 val))

                # Build alert message and send it
                alert_message = "Thresholds alert: {0} ({1}) of {2} - {3} district reported:\n".format(
                    params.reporter_name, params.msisdn, params.facility,
                    params.district)
                alert_message += '\n'.join(thresholds_list)
                send_threshold_alert(alert_message, params.district)
                print(alert_message)

            if not dataValues and params.form in ('cases', 'death'):
                if PREFERED_DHIS2_CONTENT_TYPE == 'json':
                    dataValues = []
                else:
                    dataValues = DEFAULT_DATA_VALUES[params.form]

            if dataValues:
                args_dict = {
                    'completeDate':
                    datetime.datetime.now().strftime("%Y-%m-%d"),
                    'period': get_reporting_week(datetime.datetime.now()),
                    'orgUnit': params.facilitycode,
                    'dataValues': dataValues
                }
                if PREFERED_DHIS2_CONTENT_TYPE == 'json':
                    args_dict['dataSet'] = HMIS_033B_DATASET
                    args_dict[
                        'attributeOptionCombo'] = HMIS_033B_DATASET_ATTR_OPT_COMBO
                    payload = json.dumps(args_dict)
                else:
                    payload = XML_TEMPLATE % args_dict
                year, week = tuple(args_dict['period'].split('W'))
                print(payload)
                extra_params = {
                    'week': week,
                    'year': year,
                    'msisdn': params.msisdn,
                    'facility': params.facilitycode,
                    'raw_msg': params.raw_msg,
                    'district': params.district,
                    'report_type': params.report_type,
                    # 'source': config['dispatcher2_source'],
                    # 'destination': config['dispatcher2_destination'],
                    'source': serversByName[config['dispatcher2_source']],
                    'destination':
                    serversByName[config['dispatcher2_destination']],
                    'extras': json.dumps(extras),
                    'response': self.get_last_response_message(params.uuid),
                    'status': config.get('default-queue-status', 'pending')
                }
                # now ready to queue to DB for pushing to DHIS2
                # resp = queue_submission(serverid, post_xml, year, week)
                print(extra_params)
                if PREFERED_DHIS2_CONTENT_TYPE == 'json':
                    extra_params['ctype'] = 'json'
                    # resp = post_request_to_dispatcher2(
                    #    payload, params=extra_params, ctype='json')
                    extra_params['body'] = payload
                    queue_rejected_reports(db, extra_params)
                else:
                    extra_params['ctype'] = 'xml'
                    # resp = post_request_to_dispatcher2(payload, params=extra_params)
                    extra_params['body'] = payload
                    queue_rejected_reports(db, extra_params)
                # print "Resp:", resp

        return json.dumps({"status": "success"})
Exemplo n.º 5
0
    def POST(self):
        params = web.input(facilitycode="",
                           form="",
                           district="",
                           msisdn="",
                           raw_msg="",
                           report_type="",
                           facility="",
                           reporter_type="")
        extras = {'reporter_type': params.reporter_type}
        # values = json.loads(params['values'])  # only way we can get out Rapidpro values in webpy
        if PREFERED_DHIS2_CONTENT_TYPE == 'json':
            dataValues = []
        else:
            dataValues = ""
        print "FACILITYCODE:", params.facilitycode, "==>", params.facility
        if params.facilitycode:
            if not USE_OLD_WEBHOOKS:
                values = json.loads(web.data())
                results = values.get('results', {})
                for key, v in results.iteritems():
                    val = v.get('value')
                    try:
                        val = int(float(val))
                    except:
                        pass
                    label = v.get('name')
                    slug = "%s_%s" % (params.form, label)
                    if val.__str__().isdigit() or slug in TEXT_INDICATORS:
                        if not (val) and params.form in getattr(
                                settings, 'IRREGULAR_FORMS',
                            ['cases', 'death', 'epc', 'epd'
                             ]):  # XXX irregular forms
                            if label not in params.raw_msg.lower():
                                continue  # skip zero values for cases and death
                        print "%s=>%s" % (slug, val), MAPPING[slug]
                        if PREFERED_DHIS2_CONTENT_TYPE == 'json':
                            dataValues.append({
                                'dataElement':
                                MAPPING[slug]['dhis2_id'],
                                'categoryOptionCombo':
                                MAPPING[slug]['dhis2_combo_id'],
                                'value':
                                val
                            })
                        else:
                            dataValues += (
                                "<dataValue dataElement='%s' categoryOptionCombo="
                                "'%s' value='%s' />\n" %
                                (MAPPING[slug]['dhis2_id'],
                                 MAPPING[slug]['dhis2_combo_id'], val))
            else:
                values = json.loads(
                    params['values']
                )  # only way we can get out Rapidpro values in webpy
                for v in values:
                    val = v.get('value')
                    try:
                        val = int(float(val))
                    except:
                        pass
                    label = v.get('label')
                    slug = "%s_%s" % (params.form, label)
                    if val.__str__().isdigit() or slug in TEXT_INDICATORS:
                        if not (val) and params.form in [
                                'cases', 'death', 'epc', 'death'
                        ]:
                            if label not in params.raw_msg.lower():
                                continue  # skip zero values for cases and death
                        print "%s=>%s" % (slug, val), MAPPING[slug]
                        if PREFERED_DHIS2_CONTENT_TYPE == 'json':
                            dataValues.append({
                                'dataElement':
                                MAPPING[slug]['dhis2_id'],
                                'categoryOptionCombo':
                                MAPPING[slug]['dhis2_combo_id'],
                                'value':
                                val
                            })
                        else:
                            dataValues += (
                                "<dataValue dataElement='%s' categoryOptionCombo="
                                "'%s' value='%s' />\n" %
                                (MAPPING[slug]['dhis2_id'],
                                 MAPPING[slug]['dhis2_combo_id'], val))

            if not dataValues and params.form in ('cases', 'death'):
                if PREFERED_DHIS2_CONTENT_TYPE == 'json':
                    dataValues = []
                else:
                    dataValues = DEFAULT_DATA_VALUES[params.form]

            if dataValues:
                args_dict = {
                    'completeDate':
                    datetime.datetime.now().strftime("%Y-%m-%d"),
                    'period': get_reporting_week(datetime.datetime.now()),
                    'orgUnit': params.facilitycode,
                    'dataValues': dataValues
                }
                if PREFERED_DHIS2_CONTENT_TYPE == 'json':
                    args_dict['dataSet'] = HMIS_033B_DATASET
                    args_dict[
                        'attributeOptionCombo'] = HMIS_033B_DATASET_ATTR_OPT_COMBO
                    payload = json.dumps(args_dict)
                else:
                    payload = XML_TEMPLATE % args_dict
                year, week = tuple(args_dict['period'].split('W'))
                print payload
                extra_params = {
                    'week': week,
                    'year': year,
                    'msisdn': params.msisdn,
                    'facility': params.facilitycode,
                    'raw_msg': params.raw_msg,
                    'district': params.district,
                    'report_type': params.report_type,
                    # 'source': config['dispatcher2_source'],
                    # 'destination': config['dispatcher2_destination'],
                    'source': serversByName[config['dispatcher2_source']],
                    'destination':
                    serversByName[config['dispatcher2_destination']],
                    'extras': json.dumps(extras),
                    'status': config.get('default-queue-status', 'pending')
                }
                # now ready to queue to DB for pushing to DHIS2
                # resp = queue_submission(serverid, post_xml, year, week)
                print extra_params
                if PREFERED_DHIS2_CONTENT_TYPE == 'json':
                    extra_params['ctype'] = 'json'
                    # resp = post_request_to_dispatcher2(
                    #    payload, params=extra_params, ctype='json')
                    extra_params['body'] = payload
                    queue_request(db, extra_params)
                else:
                    extra_params['ctype'] = 'xml'
                    # resp = post_request_to_dispatcher2(payload, params=extra_params)
                    extra_params['body'] = payload
                    queue_request(db, extra_params)
                # print "Resp:", resp

        return json.dumps({"status": "success"})