Example #1
0
    def POST(self):
        session = get_session()
        params = web.input(username="", password="")
        username = params.username
        password = params.password
        r = auth_user(db, username, password)
        if r[0]:
            session.loggedin = True
            info = r[1]
            session.name = info.firstname + " " + info.lastname
            session.username = username
            session.sesid = info.id
            session.role = info.role
            session.criteria = ""
            put_session(session)
            log_dict = {
                'logtype': 'Web',
                'action': 'Login',
                'actor': username,
                'ip': web.ctx['ip'],
                'descr': 'User %s logged in' % username,
                'user': info.id
            }
            audit_log(db, log_dict)

            l = locals()
            del l['self']
            return web.seeother("/requests")
        else:
            session.loggedin = False
            session.logon_err = r[1]
        l = locals()
        del l['self']
        return render.login(**l)
Example #2
0
    def POST(self):
        session = get_session()
        params = web.input(username="", password="")
        username = params.username
        password = params.password
        r = auth_user(db, username, password)
        if r[0]:
            session.loggedin = True
            info = r[1]
            session.name = info.firstname + " " + info.lastname
            session.username = username
            session.sesid = info.id
            session.role = info.role
            session.perms = role_permissions(db, info.user_role)
            # get system permissions at log in time
            session.can_view_reports = has_perm(session.perms, 'Reports', 'r')
            session.can_view_warehouse = has_perm(session.perms, 'Warehouse',
                                                  'r')
            session.can_manage_warehouse = has_perm(session.perms, 'Warehouse',
                                                    'w')
            session.can_view_reporters = has_perm(session.perms, 'Reporters',
                                                  'r')
            session.can_manage_reporters = has_perm(session.perms, 'Reporters',
                                                    'w')
            session.can_view_dpoints = has_perm(session.perms,
                                                'Distribution Points', 'r')
            session.can_manage_dpoints = has_perm(session.perms,
                                                  'Distribution Points', 'w')
            session.can_view_adminunits = has_perm(session.perms,
                                                   'Admin Units', 'r')
            session.can_manage_adminunits = has_perm(session.perms,
                                                     'Admin Units', 'w')
            put_session(session)
            log_dict = {
                'logtype': 'Web',
                'action': 'Login',
                'actor': username,
                'ip': web.ctx['ip'],
                'descr': 'User %s logged in' % username,
                'user': info.id
            }
            audit_log(db, log_dict)

            l = locals()
            del l['self']
            if info.role == 'Warehouse Manager':
                return web.seeother("/warehousedata")
            elif info.role == 'Micro Planning':
                return web.seeother("/reporters")
            elif info.role == 'Data Manager':
                return web.seeother("/adminunits")
            else:
                return web.seeother("/dashboard")
        else:
            session.loggedin = False
            session.logon_err = r[1]
        l = locals()
        del l['self']
        return render.login(**l)
Example #3
0
 def GET(self):
     session = get_session()
     log_dict = {
         'logtype': 'Web', 'action': 'Logout', 'actor': session.username,
         'ip': web.ctx['ip'], 'descr': 'User %s logged out' % session.username,
         'user': session.sesid
     }
     audit_log(db, log_dict)
     session.kill()
     return web.seeother("/")
Example #4
0
    def POST(self):
        session = get_session()
        username = session.username
        params = web.input(page=1, reqid=[])
        try:
            page = int(params.page)
        except:
            page = 1
        limit = PAGE_LIMIT
        start = (page - 1) * limit if page > 0 else 0

        with db.transaction():
            if params.abtn == 'Cancel Selected':
                if params.reqid:
                    for val in params.reqid:
                        db.update('requests',
                                  where="id = %s" % val,
                                  status='canceled',
                                  updated='NOW()')
                    log_dict = {
                        'logtype':
                        'Web',
                        'action':
                        'Cancel Requests',
                        'actor':
                        username,
                        'ip':
                        web.ctx['ip'],
                        'descr':
                        'User %s canceled %s request(s)' %
                        (username, len(params.reqid)),
                        'user':
                        session.sesid
                    }
                    audit_log(db, log_dict)
                db.transaction().commit()
                return web.seeother("/ready")
        dic = lit(relations='requests',
                  fields="*",
                  criteria="status='ready'",
                  order="id desc",
                  limit=limit,
                  offset=start)
        res = doquery(db, dic)
        count = countquery(db, dic)
        pagination_str = getPaginationString(default(page, 0), count, limit, 2,
                                             "ready", "?page=")

        l = locals()
        del l['self']
        return render.ready(**l)
Example #5
0
    def POST(self):
        session = get_session()
        params = web.input(username="", password="")
        username = params.username
        password = params.password
        r = auth_user(db, username, password)
        if r[0]:
            session.loggedin = True
            info = r[1]
            session.name = info.firstname + " " + info.lastname
            session.username = username
            session.sesid = info.id
            session.role = info.role
            session.districts = info.districts
            # districts_string to be used in a SIMILAR TO statment while getting reports from requests table
            session.districts_string = '|'.join(['%s' % allDistricts[d] for d in info.districts])
            print(session.districts_string)
            session.districts_array = str([int(x) for x in info.districts]).replace(
                '[', '{').replace(']', '}').replace('\'', '\"')
            session.criteria = ""
            user_perms = []
            perms = db.query(
                "SELECT codename FROM permissions WHERE id IN "
                " (SELECT permission_id FROM user_permissions WHERE user_id = $user_id)", {'user_id': info.id})
            for p in perms:
                user_perms.append(p['codename'])
            session.permissions = user_perms
            put_session(session)
            log_dict = {
                'logtype': 'Web', 'action': 'Login', 'actor': username,
                'ip': web.ctx['ip'], 'descr': 'User %s logged in' % username,
                'user': info.id
            }
            audit_log(db, log_dict)

            l = locals()
            del l['self']
            if info.role == 'District User':
                return web.seeother("/approve")
            else:
                return web.seeother("/approve")
        else:
            session.loggedin = False
            session.logon_err = r[1]
        l = locals()
        del l['self']
        return render.login(**l)
Example #6
0
    def POST(self):
        session = get_session()
        params = web.input(ed="", d_id="", store_name="", location="", district="")
        allow_edit = False
        try:
            edit_val = int(params.ed)
            allow_edit = True
        except:
            pass

        with db.transaction():
            if params.ed and allow_edit:
                r = db.query(
                    "UPDATE stores SET name = $name, location = $loc, district_id = $district "
                    "WHERE id = $id", {
                        'name': params.store_name, 'id': edit_val,
                        'loc': params.location, 'district': params.district})
                if r:
                    log_dict = {
                        'logtype': 'Web', 'action': 'Edit', 'actor': session.username,
                        'ip': web.ctx['ip'],
                        'descr': 'Edit Store Name (id:%s)=>%s' % (
                            params.location, params.store_name),
                        'user': session.sesid
                    }
                    audit_log(db, log_dict)
                return web.seeother("/stores")
            else:  # adding village
                parent = params.location if params.location else 0
                store_name = params.store_name
                r = db.query(
                    "INSERT INTO stores(name, location, district_id, created_by) "
                    "VALUES ($name, $loc, $district, $user);", {
                        'name': store_name, 'loc': parent,
                        'user': session.sesid, 'district': params.district})
                if r:
                    log_dict = {
                        'logtype': 'Web', 'action': 'Create', 'actor': session.username,
                        'ip': web.ctx['ip'],
                        'descr': 'Created Store (parent:%s)=>%s' % (
                            parent, store_name),
                        'user': session.sesid
                    }
                    audit_log(db, log_dict)
                return web.seeother("/stores")
Example #7
0
    def POST(self):
        session = get_session()
        params = web.input(ed="",
                           d_id="",
                           location_name="",
                           subcounty="",
                           location="",
                           district=0)
        allow_edit = False
        try:
            edit_val = int(params.ed)
            allow_edit = True
        except:
            pass

        with db.transaction():
            if params.ed and allow_edit:
                r = db.query(
                    "UPDATE locations SET name = $name WHERE id = $id", {
                        'name': params.location_name,
                        'id': edit_val
                    })
                if r:
                    log_dict = {
                        'logtype':
                        'Web',
                        'action':
                        'Edit',
                        'actor':
                        session.username,
                        'ip':
                        web.ctx['ip'],
                        'descr':
                        'Edit Subcounty Name (id:%s)=>%s' %
                        (params.location, params.location_name),
                        'user':
                        session.sesid
                    }
                    audit_log(db, log_dict)
                return web.seeother("/parishes")
            else:  # adding subcounty
                parent = params.subcounty if params.subcounty else 0
                location_name = params.location_name
                r = db.query("SELECT add_node(1, $location_name, $parent)", {
                    'location_name': location_name,
                    'parent': parent
                })
                if r:
                    log_dict = {
                        'logtype':
                        'Web',
                        'action':
                        'Create',
                        'actor':
                        session.username,
                        'ip':
                        web.ctx['ip'],
                        'descr':
                        'Created Parish(parent:%s)=>%s' %
                        (parent, location_name),
                        'user':
                        session.sesid
                    }
                    audit_log(db, log_dict)
                return web.seeother("/parishes")
Example #8
0
    def POST(self):
        session = get_session()
        params = web.input(firstname="",
                           lastname="",
                           telephone="",
                           email="",
                           location="",
                           role=[],
                           alt_telephone="",
                           page="1",
                           ed="",
                           d_id="",
                           district="",
                           facility="")

        allow_edit = False
        try:
            edit_val = int(params.ed)
            allow_edit = True
        except:
            pass

        with db.transaction():
            if params.ed and allow_edit:
                location = params.location if params.location else None
                r = db.query(
                    "UPDATE reporters SET firstname=$firstname, lastname=$lastname, "
                    "telephone=$telephone, email=$email, reporting_location=$location, "
                    "alternate_tel=$alt_tel, district_id = $district_id "
                    "WHERE id=$id RETURNING id", {
                        'firstname': params.firstname,
                        'lastname': params.lastname,
                        'telephone': params.telephone,
                        'email': params.email,
                        'location': location,
                        'id': params.ed,
                        'alt_tel': params.alt_telephone,
                        'district_id': params.district
                    })
                if r:
                    print params.role
                    db.query(
                        "UPDATE reporters SET groups = $groups::INTEGER[], "
                        " jparents = $ancestors WHERE id = $id", {
                            'id':
                            params.ed,
                            'groups':
                            str([int(x) for x in params.role]).replace(
                                '[', '{').replace(']', '}').replace(
                                    '\'', '\"'),
                            'ancestors':
                            psycopg2.extras.Json(
                                {
                                    'd': params.district,
                                    's': params.subcounty
                                },
                                dumps=simplejson.dumps)
                        })

                    log_dict = {
                        'logtype':
                        'Web',
                        'action':
                        'Update',
                        'actor':
                        session.username,
                        'ip':
                        web.ctx['ip'],
                        'descr':
                        'Updated reporter %s:%s (%s)' %
                        (params.ed, params.firstname + ' ' + params.lastname,
                         params.telephone),
                        'user':
                        session.sesid
                    }
                    audit_log(db, log_dict)
                return web.seeother("/reporters")
            else:
                location = params.location if params.location else None
                has_reporter = db.query(
                    "SELECT id FROM reporters WHERE telephone = $tel",
                    {'tel': params.telephone})
                if has_reporter:
                    session.rdata_err = (
                        "Reporter with Telephone:%s already registered" %
                        params.telephone)
                    return web.seeother("/reporters")
                session.rdata_err = ""
                r = db.query(
                    "INSERT INTO reporters (firstname, lastname, telephone, email, "
                    " reporting_location, alternate_tel, "
                    " district_id, facilityid) VALUES "
                    " ($firstname, $lastname, $telephone, $email, $location, "
                    " $alt_tel, $district_id, $facilityid) RETURNING id", {
                        'firstname': params.firstname,
                        'lastname': params.lastname,
                        'telephone': params.telephone,
                        'email': params.email,
                        'location': location,
                        'alt_tel': params.alt_telephone,
                        'district_id': params.district,
                        'facilityid': params.facility
                    })
                if r:
                    reporter_id = r[0]['id']

                    db.query(
                        "UPDATE reporters SET groups = $groups::INTEGER[], "
                        " jparents = $ancestors WHERE id = $id", {
                            'id':
                            reporter_id,
                            'groups':
                            str([int(x) for x in params.role]).replace(
                                '[', '{').replace(']', '}').replace(
                                    '\'', '\"'),
                            'ancestors':
                            psycopg2.extras.Json(
                                {
                                    'd': params.district,
                                    's': params.subcounty
                                },
                                dumps=simplejson.dumps)
                        })

                    log_dict = {
                        'logtype':
                        'Web',
                        'action':
                        'Create',
                        'actor':
                        session.username,
                        'ip':
                        web.ctx['ip'],
                        'descr':
                        'Created reporter %s:%s (%s)' %
                        (reporter_id, params.firstname + ' ' + params.lastname,
                         params.telephone),
                        'user':
                        session.sesid
                    }
                    audit_log(db, log_dict)
                return web.seeother("/reporters")

        l = locals()
        del l['self']
        return render.reporters(**l)
Example #9
0
    def GET(self):
        params = web.input(page=1,
                           ed="",
                           d_id="",
                           caller="web",
                           search="",
                           show="")
        edit_val = params.ed
        search_field = params.search
        show = params.show
        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)
        district = {}
        roles = db.query("SELECT id, name from reporter_groups order by name")
        allow_edit = False

        try:
            edit_val = int(params.ed)
            allow_edit = True
        except ValueError:
            pass
        try:
            page = int(params.page)
        except:
            page = 1
        limit = PAGE_LIMIT
        start = (page - 1) * limit if page > 0 else 0

        if params.ed and allow_edit:
            res = db.query(
                "SELECT id, firstname, lastname, gender, telephone, "
                "reporting_location, role, alternate_tel, facilityid, facility, code, date_of_birth, "
                "national_id, created, loc_name FROM reporters_view1 "
                " WHERE id = $id", {'id': edit_val})
            if res:
                r = res[0]
                reporter_id = edit_val
                firstname = r.firstname
                lastname = r.lastname
                gender = r.gender
                telephone = r.telephone
                national_id = r.national_id
                role = r.role.split(',')
                alt_telephone = r.alternate_tel
                location = r.reporting_location
                parish = ""
                subcounty = ""
                facilityid = r.facilityid
                facility = r.facility
                facilityname = r.facility
                code = r.code
                date_of_birth = r.date_of_birth
                district = ""
                village = ""
                villagename = r.loc_name
                subcounties = []
                ancestors = db.query(
                    "SELECT id, name, level FROM get_ancestors($loc) "
                    "WHERE level > 1 ORDER BY level DESC;", {'loc': location})
                if ancestors:
                    for loc in ancestors:
                        if loc['level'] == 4:
                            parish = loc
                            parishname = loc['name']
                            villages = db.query(
                                "SELECT id, name FROM get_children($id)",
                                {'id': loc['id']})
                        if loc['level'] == 3:
                            subcounty = loc
                            subcountyname = loc['name']
                            parishes = db.query(
                                "SELECT id, name FROM get_children($id)",
                                {'id': loc['id']})
                        elif loc['level'] == 2:
                            district = loc
                            districtname = loc['name']
                            subcounties = db.query(
                                "SELECT id, name FROM get_children($id)",
                                {'id': loc['id']})
                else:
                    district = location
                location_for_facilities = subcounty.id if subcounty else district.id

                if location_for_facilities:
                    facilities = db.query(
                        "SELECT id, name FROM healthfacilities WHERE location=$loc",
                        {'loc': location_for_facilities})
                if facilityid:
                    facility = r.facility

        allow_del = False
        try:
            del_val = int(params.d_id)
            allow_del = True
        except ValueError:
            pass
        if params.d_id and allow_del:
            if session.role in ('District User', 'Administrator'):
                reporter = db.query(
                    "SELECT firstname || ' ' || lastname as name, telephone "
                    "FROM reporters WHERE id = $id", {'id': params.d_id})
                if reporter:
                    rx = reporter[0]
                    log_dict = {
                        'logtype':
                        'Web',
                        'action':
                        'Delete',
                        'actor':
                        session.username,
                        'ip':
                        web.ctx['ip'],
                        'descr':
                        'Deleted reporter %s:%s (%s)' %
                        (params.d_id, rx['name'], rx['telephone']),
                        'user':
                        session.sesid
                    }
                    # db.query("DELETE FROM reporter_groups_reporters WHERE reporter_id=$id", {'id': params.d_id})
                    # db.query("DELETE FROM reporter_healthfacility WHERE reporter_id=$id", {'id': params.d_id})
                    db.query("DELETE FROM schedules WHERE reporter_id=$id",
                             {'id': params.d_id})
                    db.query("DELETE FROM reporters WHERE id=$id",
                             {'id': params.d_id})
                    audit_log(db, log_dict)
                    if params.caller == "api":  # return json if API call
                        web.header("Content-Type",
                                   "application/json; charset=utf-8")
                        return json.dumps({'message': "success"})

        if session.role == 'District User':
            district_id = allDistrictsByName['%s' %
                                             session.username.capitalize()]
            criteria = "district_id=%s" % district_id
            if params.search:
                criteria += (
                    " AND (telephone ilike '%%%%%s%%%%' OR alternate_tel ilike '%%%%%s%%%%' OR "
                    "name ilike '%%%%%s%%%%')")
                criteria = criteria % (params.search, params.search,
                                       params.search)
                dic = lit(
                    relations='reporters_view1',
                    fields=
                    ("id, name, gender, telephone, district_id, alternate_tel, "
                     "facility, role, uuid, created "),
                    criteria=criteria,
                    order="facility, name",
                    limit=limit,
                    offset=start)
            else:
                dic = lit(
                    relations='reporters_view1',
                    fields=
                    ("id, name, gender, telephone, district_id, alternate_tel, "
                     "facility, role,  uuid, created "),
                    criteria=criteria,
                    order="id desc",
                    limit=limit,
                    offset=start)
        else:
            criteria = "TRUE "
            if params.search:
                criteria += (
                    " AND (telephone ilike '%%%%%s%%%%' OR alternate_tel ilike '%%%%%s%%%%' OR "
                    "name ilike '%%%%%s%%%%')")
                criteria = criteria % (params.search, params.search,
                                       params.search)
                dic = lit(
                    relations='reporters_view1',
                    fields=
                    ("id, name, gender, telephone, district_id, alternate_tel, "
                     "facility, role, uuid, created "),
                    criteria=criteria,
                    order="facility, name",
                    limit=limit,
                    offset=start)
            else:
                criteria = "id >  (SELECT max(id) - 250 FROM reporters)"
                dic = lit(
                    relations='reporters_view1',
                    fields=
                    ("id, name, gender, telephone, district_id, alternate_tel, "
                     "facility, role, uuid, created "),
                    criteria=criteria,
                    order="facility, name",
                    limit=limit,
                    offset=start)

        try:
            reporters = doquery(db, dic)
            count = countquery(db, dic)
        except:
            reporters = []
            count = 0
        pagination_str = getPaginationString(default(page, 0), count, limit, 2,
                                             "reporters", "?page=")
        l = locals()
        del l['self']
        return render.reporters(**l)
Example #10
0
    def POST(self):
        params = web.input(firstname="",
                           lastname="",
                           gender="",
                           telephone="",
                           email="",
                           location="",
                           role="",
                           alt_telephone="",
                           page="1",
                           ed="",
                           d_id="",
                           district="",
                           facility="",
                           code="",
                           date_of_birth="",
                           national_id="",
                           caller="",
                           user="******",
                           districtname="",
                           subcounty="",
                           parish="",
                           subcountyname="",
                           parishname="",
                           villagename="",
                           facilityname="")
        if params.caller != 'api':
            session = get_session()
            username = session.username
            userid = session.sesid
        else:
            rs = db.query(
                "SELECT id, username FROM users WHERE username = '******';" %
                params.user)
            if rs:
                xuser = rs[0]
                userid = xuser['id']
                username = xuser['username']

        allow_edit = False
        try:
            edit_val = int(params.ed)
            allow_edit = True
        except:
            pass
        facilityuid = ""
        rs = db.query("SELECT code FROM healthfacilities WHERE id = %s;" %
                      params.facility)
        if rs:
            facilityuid = rs[0]['code']

        current_time = datetime.datetime.now()
        # Set params to schedule a push_contact to Push reporter to RapidPro
        urns = []
        if params.alt_telephone:
            try:
                alt_telephone = format_msisdn(params.alt_telephone)
                urns.append("tel:" + alt_telephone)
            except:
                alt_telephone = ''
        if params.telephone:
            try:
                telephone = format_msisdn(params.telephone)
                urns.append("tel:" + telephone)
            except:
                telephone = ''
        contact_params = {
            'urns': urns,
            'name': params.firstname + ' ' + params.lastname,
            # 'groups': ['%s' % rolesById[int(params.role)]],
            'fields': {
                # 'email': params.email,
                'gender': params.gender,
                'facility': params.facilityname,
                'village': params.villagename,
                'district': params.districtname,
                'sub_county': params.subcountyname,
                'parish': params.parishname,
                'facilityuid': facilityuid,
                'type': '%s' % rolesById[int(params.role)]
            }
        }

        with db.transaction():
            if params.ed and allow_edit:
                location = params.location if params.location else None
                date_of_birth = params.date_of_birth if params.date_of_birth else None
                r = db.query(
                    "UPDATE reporters SET firstname=$firstname, lastname=$lastname, gender=$gender, "
                    "telephone=$telephone, reporting_location=$location, "
                    "alternate_tel=$alt_tel, district_id = $district_id, facilityid=$facility, "
                    "code=$code, date_of_birth=$date_of_birth, national_id=$national_id "
                    "WHERE id=$id RETURNING id", {
                        'firstname': params.firstname,
                        'lastname': params.lastname,
                        'gender': params.gender,
                        'telephone': params.telephone,
                        'location': location,
                        'id': params.ed,
                        'alt_tel': params.alt_telephone,
                        'district_id': params.district,
                        'code': params.code,
                        'date_of_birth': date_of_birth,
                        'national_id': params.national_id,
                        'facility': params.facility
                    })
                if r:
                    db.query(
                        "UPDATE reporters SET groups = $groups::INTEGER[], "
                        " jparents = $ancestors WHERE id = $id", {
                            'id':
                            params.ed,
                            'groups':
                            str([int(params.role)]).replace('[', '{').replace(
                                ']', '}').replace('\'', '\"'),
                            'ancestors':
                            psycopg2.extras.Json(
                                {
                                    'd': params.district,
                                    's': params.subcounty,
                                    'p': params.parish
                                },
                                dumps=simplejson.dumps)
                        })

                    log_dict = {
                        'logtype':
                        'Web',
                        'action':
                        'Update',
                        'actor':
                        username,
                        'ip':
                        web.ctx['ip'],
                        'descr':
                        'Updated reporter %s:%s (%s)' %
                        (params.ed, params.firstname + ' ' + params.lastname,
                         params.telephone),
                        'user':
                        userid
                    }
                    audit_log(db, log_dict)

                    sync_time = current_time + datetime.timedelta(seconds=60)
                    queue_schedule(db, contact_params, sync_time, userid,
                                   'push_contact', params.ed)
                if params.caller == 'api':
                    web.header("Content-Type",
                               "application/json; charset=utf-8")
                    return json.dumps(
                        {'message': 'Reporter edited successfully.'})

                else:
                    return web.seeother("/reporters")
            else:
                location = params.location if params.location else None
                has_reporter = db.query(
                    "SELECT id FROM reporters WHERE telephone = $tel",
                    {'tel': params.telephone})
                if has_reporter:
                    if params.caller == 'api':
                        web.header("Content-Type",
                                   "application/json; charset=utf-8")
                        return json.dumps({
                            'message':
                            "Reporter with Telephone:%s already registered" %
                            params.telephone
                        })
                    else:
                        session.rdata_err = (
                            "Reporter with Telephone:%s already registered" %
                            params.telephone)
                        return web.seeother("/reporters")
                if params.caller != 'api':
                    session.rdata_err = ""
                r = db.query(
                    "INSERT INTO reporters (firstname, lastname, gender, telephone, "
                    " reporting_location, alternate_tel, "
                    " district_id, code, date_of_birth, national_id, facilityid) VALUES "
                    " ($firstname, $lastname, $gender, $telephone, $location, "
                    " $alt_tel, $district_id, $code, $date_of_birth, $national_id, $facilityid) RETURNING id",
                    {
                        'firstname':
                        params.firstname,
                        'lastname':
                        params.lastname,
                        'gender':
                        params.gender,
                        'telephone':
                        params.telephone,
                        'location':
                        location,
                        'alt_tel':
                        params.alt_telephone,
                        'district_id':
                        params.district,
                        'code':
                        params.code,
                        'date_of_birth':
                        params.date_of_birth if params.date_of_birth else None,
                        'national_id':
                        params.national_id,
                        'facilityid':
                        params.facility
                    })
                if r:
                    reporter_id = r[0]['id']

                    db.query(
                        "UPDATE reporters SET groups = $groups::INTEGER[], "
                        " jparents = $ancestors WHERE id = $id", {
                            'id':
                            reporter_id,
                            'groups':
                            str([int(params.role)]).replace('[', '{').replace(
                                ']', '}').replace('\'', '\"'),
                            'ancestors':
                            psycopg2.extras.Json(
                                {
                                    'd': params.district,
                                    's': params.subcounty,
                                    'p': params.parish
                                },
                                dumps=simplejson.dumps)
                        })

                    log_dict = {
                        'logtype':
                        'Web',
                        'action':
                        'Create',
                        'actor':
                        username,
                        'ip':
                        web.ctx['ip'],
                        'descr':
                        'Created reporter %s:%s (%s)' %
                        (reporter_id, params.firstname + ' ' + params.lastname,
                         params.telephone),
                        'user':
                        userid
                    }

                    audit_log(db, log_dict)

                    sync_time = current_time + datetime.timedelta(seconds=60)
                    queue_schedule(db, contact_params, sync_time, userid,
                                   'push_contact', reporter_id)
                if params.caller == 'api':
                    web.header("Content-Type",
                               "application/json; charset=utf-8")
                    return json.dumps({'message': 'success'})
                else:
                    return web.seeother("/reporters?show=true")

        l = locals()
        del l['self']
        if params.caller == 'api':
            pass
        else:
            return render.reporters(**l)
Example #11
0
    def POST(self):
        session = get_session()
        params = web.input(ed="",
                           d_id="",
                           location_name="",
                           parish="",
                           location="")
        allow_edit = False
        try:
            edit_val = int(params.ed)
            allow_edit = True
        except:
            pass

        with db.transaction():
            if params.ed and allow_edit:
                r = db.query(
                    "UPDATE locations SET name = $name WHERE id = $id", {
                        'name': params.location_name,
                        'id': params.location
                    })
                if r:
                    log_dict = {
                        'logtype':
                        'Web',
                        'action':
                        'Edit',
                        'actor':
                        session.username,
                        'ip':
                        web.ctx['ip'],
                        'descr':
                        'Edit Village Name (id:%s)=>%s' %
                        (params.location, params.location_name),
                        'user':
                        session.sesid
                    }
                    audit_log(db, log_dict)
                return web.seeother("/adminunits")
            else:  # adding village
                parent = params.parish if params.parish else 0
                village_name = params.location_name
                r = db.query("SELECT add_node(1, $village_name, $parent)", {
                    'village_name': village_name,
                    'parent': parent
                })
                if r:
                    log_dict = {
                        'logtype':
                        'Web',
                        'action':
                        'Create',
                        'actor':
                        session.username,
                        'ip':
                        web.ctx['ip'],
                        'descr':
                        'Created Village(parent:%s)=>%s' %
                        (parent, village_name),
                        'user':
                        session.sesid
                    }
                    audit_log(db, log_dict)
                return web.seeother("/adminunits")
    def POST(self):
        params = web.input(name="",
                           form="",
                           form_order="",
                           slug="",
                           cmd="",
                           dataset="",
                           dataelement="",
                           category_combo="",
                           threshold="",
                           page="1",
                           ed="",
                           d_id="")

        session = get_session()
        allow_edit = False
        try:
            edit_val = int(params.ed)
            allow_edit = True
        except:
            pass

        with db.transaction():
            if params.ed and allow_edit:
                r = db.query(
                    "UPDATE dhis2_mtrack_indicators_mapping SET "
                    "(description, form, form_order, slug, cmd, dataset, dataelement, category_combo, threshold) "
                    "= ($descr, $form, $form_order, $slug, $cmd, $dataset, $dataelement, $category_combo, $threshold) "
                    "WHERE id = $id", {
                        'descr': params.name,
                        'form': params.form,
                        'form_order': params.form_order,
                        'slug': params.slug,
                        'cmd': params.cmd,
                        'dataset': params.dataset,
                        'threshold': params.threshold,
                        'dataelement': params.dataelement,
                        'category_combo': params.category_combo,
                        'id': params.ed
                    })
                log_dict = {
                    'logtype':
                    'Web',
                    'action':
                    'Update',
                    'actor':
                    session.username,
                    'ip':
                    web.ctx['ip'],
                    'descr':
                    'Updated Indicator Mapping. id:%s =>  Dataset %s: Form:%s Cmd:%s)'
                    % (params.ed, params.dataset, params.form, params.cmd),
                    'user':
                    session.sesid
                }
                audit_log(db, log_dict)
                return web.seeother("/indicators")
            else:
                has_indicator = db.query(
                    "SELECT id FROM dhis2_mtrack_indicators_mapping "
                    "WHERE form=$form AND cmd=$cmd AND dataset=$dataset", {
                        'form': params.form,
                        'cmd': params.cmd,
                        'dataset': params.dataset
                    })
                if has_indicator:
                    session.idata_err = (
                        "Indicator with Dataset:%s, From:%s, Command:%s "
                        "already registered" %
                        (params.dataset, params.form, params.cmd))
                session.idata_err = ""
                r = db.query(
                    "INSERT INTO dhis2_mtrack_indicators_mapping (description, form, form_order, "
                    "slug, cmd, dataset, dataelement, category_combo, threshold) VALUES "
                    "($descr, $form, $form_order, $slug, $cmd, $dataset, $dataelement, "
                    "$category_combo, $threshold) RETURNING id", {
                        'descr': params.name,
                        'form': params.form,
                        'form_order': params.form_order,
                        'slug': params.slug,
                        'cmd': params.cmd,
                        'dataset': params.dataset,
                        'threshold': params.threshold,
                        'dataelement': params.dataelement,
                        'category_combo': params.category_combo
                    })

                log_dict = {
                    'logtype':
                    'Web',
                    'action':
                    'Create',
                    'actor':
                    session.username,
                    'ip':
                    web.ctx['ip'],
                    'descr':
                    'Created Indicator Mapping. Dataset %s: Form:%s Cmd:%s)' %
                    (params.dataset, params.form, params.cmd),
                    'user':
                    session.sesid
                }
                audit_log(db, log_dict)
                return web.seeother("/indicators")

        l = locals()
        del l['self']
        return render.indicators(**l)
Example #13
0
    def POST(self):
        session = get_session()
        params = web.input(firstname="",
                           lastname="",
                           telephone="",
                           email="",
                           location="",
                           dpoint="",
                           national_id="",
                           role="",
                           alt_telephone="",
                           page="1",
                           ed="",
                           d_id="",
                           district="")

        allow_edit = False
        try:
            edit_val = int(params.ed)
            allow_edit = True
        except:
            pass

        with db.transaction():
            if params.ed and allow_edit:
                location = params.location if params.location else None
                dpoint = params.dpoint if params.dpoint else None
                r = db.query(
                    "UPDATE reporters SET firstname=$firstname, lastname=$lastname, "
                    "telephone=$telephone, email=$email, reporting_location=$location, "
                    "distribution_point=$dpoint, national_id=$nid, alternate_tel=$alt_tel, "
                    "district_id = $district_id "
                    "WHERE id=$id RETURNING id", {
                        'firstname': params.firstname,
                        'lastname': params.lastname,
                        'telephone': params.telephone,
                        'email': params.email,
                        'location': location,
                        'dpoint': dpoint,
                        'nid': params.national_id,
                        'id': params.ed,
                        'alt_tel': params.alt_telephone,
                        'district_id': params.district
                    })
                if r:
                    db.query(
                        "UPDATE reporter_groups_reporters SET group_id = $gid "
                        " WHERE reporter_id = $id ", {
                            'gid': params.role,
                            'id': params.ed
                        })
                    log_dict = {
                        'logtype':
                        'Web',
                        'action':
                        'Update',
                        'actor':
                        session.username,
                        'ip':
                        web.ctx['ip'],
                        'descr':
                        'Updated reporter %s:%s (%s)' %
                        (params.ed, params.firstname + ' ' + params.lastname,
                         params.telephone),
                        'user':
                        session.sesid
                    }
                    audit_log(db, log_dict)
                return web.seeother("/reporters")
            else:
                location = params.location if params.location else None
                dpoint = params.dpoint if params.dpoint else None
                has_reporter = db.query(
                    "SELECT id FROM reporters WHERE telephone = $tel",
                    {'tel': params.telephone})
                if has_reporter:
                    session.rdata_err = (
                        "Reporter with Telephone:%s already registered" %
                        params.telephone)
                    return web.seeother("/reporters")
                session.rdata_err = ""
                r = db.query(
                    "INSERT INTO reporters (firstname, lastname, telephone, email, "
                    " reporting_location, distribution_point, national_id, alternate_tel, uuid, "
                    " created_by, district_id) VALUES "
                    " ($firstname, $lastname, $telephone, $email, $location, $dpoint,"
                    " $nid, $alt_tel, uuid_generate_v4(), $user, $district_id) RETURNING id",
                    {
                        'firstname': params.firstname,
                        'lastname': params.lastname,
                        'telephone': params.telephone,
                        'email': params.email,
                        'location': location,
                        'dpoint': dpoint,
                        'nid': params.national_id,
                        'alt_tel': params.alt_telephone,
                        'user': session.sesid,
                        'district_id': params.district
                    })
                if r:
                    reporter_id = r[0]['id']
                    db.query(
                        "INSERT INTO reporter_groups_reporters (group_id, reporter_id) "
                        " VALUES ($role, $reporter_id)", {
                            'role': params.role,
                            'reporter_id': reporter_id
                        })
                    log_dict = {
                        'logtype':
                        'Web',
                        'action':
                        'Create',
                        'actor':
                        session.username,
                        'ip':
                        web.ctx['ip'],
                        'descr':
                        'Created reporter %s:%s (%s)' %
                        (reporter_id, params.firstname + ' ' + params.lastname,
                         params.telephone),
                        'user':
                        session.sesid
                    }
                    audit_log(db, log_dict)
                return web.seeother("/reporters")

        l = locals()
        del l['self']
        return render.reporters(**l)
Example #14
0
    def GET(self):
        params = web.input(page=1, ed="", d_id="")
        session = get_session()
        countries = db.query("SELECT id, name FROM countries ORDER BY name")
        warehouses = db.query("SELECT id, name FROM warehouses ORDER BY name")
        manufacturers = db.query(
            "SELECT id, name FROM manufacturers ORDER by name")
        funding_sources = db.query(
            "SELECT id, name FROM funding_sources ORDER by name")
        nda_samples = 0
        unbs_samples = 0
        allow_edit = False
        net_types = NET_TYPES
        try:
            edit_val = int(params.ed)
            allow_edit = True
        except ValueError:
            pass
        if params.ed and allow_edit:
            res = db.query(
                "SELECT * FROM national_delivery_log WHERE id = $id",
                {'id': params.ed})
            if res:
                r = res[0]
                po_number, funding_source, manufacturer = (r.po_number,
                                                           r.funding_source,
                                                           r.manufacturer)
                made_in, batch_number, nets_type = (r.made_in, r.batch_number,
                                                    r.nets_type)
                nets_color, nets_size, quantity = (r.nets_color, r.nets_size,
                                                   r.quantity_bales)
                entry_date, waybill, warehouse_branch = (r.entry_date,
                                                         r.waybill,
                                                         r.warehouse_branch)
                sub_warehouse, nda_samples, unbs_samples = (r.sub_warehouse,
                                                            r.nda_samples,
                                                            r.unbs_samples)
                nda_sampling_date, nda_testing_result_date = (
                    r.nda_sampling_date, r.nda_testing_result_date)
                nda_conditional_release_date = r.nda_conditional_release_date
                unbs_samples, unbs_sampling_date = (r.unbs_samples,
                                                    r.unbs_sampling_date)
                remarks = r.remarks
                goods_received_note = r.goods_received_note
                # block a None from being put in date fields
                entry_date = entry_date or ''
                nda_sampling_date = nda_sampling_date or ''
                nda_testing_result_date = nda_testing_result_date or ''
                nda_conditional_release_date = nda_conditional_release_date or ''
                unbs_sampling_date = unbs_sampling_date or ''
                wx = db.query(
                    "SELECT id FROM warehouses WHERE id = "
                    "(SELECT warehouse_id FROM warehouse_branches "
                    " WHERE id = $branch) ", {'branch': warehouse_branch})
                warehouse = wx[0]['id']
                branches = []
                if warehouse:
                    branches = db.query(
                        "SELECT id, name FROM warehouse_branches WHERE warehouse_id = "
                        "$wid", {'wid': warehouse})

        allow_del = False
        try:
            del_val = int(params.d_id)
            allow_del = True
        except ValueError:
            pass
        if params.d_id and allow_del:
            if session.role in ('Warehouse Manager', 'Administrator'):
                res = db.query(
                    "SELECT id, waybill, quantity_bales FROM national_delivery_log "
                    " WHERE id = $id", {'id': params.d_id})
                if res:
                    data = res[0]
                    log_dict = {
                        'logtype':
                        'Web',
                        'action':
                        'Delete',
                        'actor':
                        session.username,
                        'ip':
                        web.ctx['ip'],
                        'descr':
                        'Delete warehouse data id:%s, Waybill:%s, Qty (bales):%s'
                        %
                        (data['id'], data['waybill'], data['quantity_bales']),
                        'user':
                        session.sesid
                    }
                    db.query(
                        "DELETE FROM national_delivery_log WHERE id = $id",
                        {'id': params.d_id})
                    audit_log(db, log_dict)
                    if params.caller == "api":  # return json if API call
                        web.header("Content-Type",
                                   "application/json; charset=utf-8")
                        return json.dumps({'message': "success"})

        warehousedata = db.query(
            "SELECT * FROM national_delivery_log_view ORDER BY id DESC")

        l = locals()
        del l['self']
        return render.warehousedata(**l)
Example #15
0
    def POST(self):
        session = get_session()
        params = web.input(page=1,
                           ed="",
                           d_id="",
                           po_number="",
                           funding_source="",
                           manufacturer="",
                           made_in="",
                           batch_number="",
                           nets_type="",
                           nets_color="",
                           nets_size="",
                           quantity="",
                           waybill="",
                           warehouse_branch="",
                           sub_warehouse="",
                           entry_date="",
                           nda_samples="",
                           nda_sampling_date="",
                           nda_conditional_release_date="",
                           nda_testing_result_date="",
                           unbs_samples="",
                           unbs_sampling_date="",
                           remarks="",
                           goods_received_note="")
        allow_edit = False
        try:
            edit_val = int(params.ed)
            allow_edit = True
        except ValueError:
            pass

        with db.transaction():
            nda_samples = 0
            unbs_samples = 0
            try:
                nda_samples = int(params.nda_samples)
                unbs_samples = int(params.unbs_samples)
                quantity = int(params.quantity)
            except:
                pass
            total_nets = (quantity * QUANTITY_PER_BALE) - (nda_samples +
                                                           unbs_samples)
            if params.ed and allow_edit:
                r = db.query(
                    "UPDATE national_delivery_log SET po_number=$po_number, funding_source=$funding_source, "
                    "manufacturer=$manufacturer, made_in=$made_in, batch_number=$batch_number, "
                    "nets_type=$nets_type, nets_size=$nets_size, nets_color=$nets_color, "
                    "quantity_bales=$quantity, entry_date=$entry_date, waybill=$waybill, "
                    "warehouse_branch=$branch, sub_warehouse=$sub_warehouse, nda_samples=$nda_samples, "
                    "nda_sampling_date=$nda_sampling_date, "
                    "nda_conditional_release_date=$nda_crdate, nda_testing_result_date=$nda_trdate, "
                    "unbs_samples=$unbs_samples, unbs_sampling_date=$unbs_sdate, remarks = $remarks, "
                    "goods_received_note=$grn, created_by=$user, quantity=$total "
                    " WHERE id = $id RETURNING id", {
                        'po_number':
                        params.po_number,
                        'funding_source':
                        params.funding_source,
                        'manufacturer':
                        params.manufacturer,
                        'made_in':
                        params.made_in,
                        'batch_number':
                        params.batch_number,
                        'nets_type':
                        params.nets_type,
                        'nets_color':
                        params.nets_color,
                        'nets_size':
                        params.nets_size,
                        'quantity':
                        params.quantity,
                        'entry_date':
                        params.entry_date,
                        'waybill':
                        params.waybill,
                        'branch':
                        params.warehouse_branch,
                        'sub_warehouse':
                        params.sub_warehouse,
                        'nda_samples':
                        params.nda_samples,
                        'nda_sampling_date':
                        None if not params.nda_sampling_date else
                        params.nda_sampling_date,
                        'nda_crdate':
                        None if not params.nda_conditional_release_date else
                        params.nda_conditional_release_date,
                        'nda_trdate':
                        None if not params.nda_testing_result_date else
                        params.nda_testing_result_date,
                        'unbs_samples':
                        params.unbs_samples,
                        'unbs_sdate':
                        None if not params.unbs_sampling_date else
                        params.unbs_sampling_date,
                        'remarks':
                        params.remarks,
                        'grn':
                        params.goods_received_note,
                        'user':
                        session.sesid,
                        'total':
                        total_nets,
                        'id':
                        params.ed
                    })

                if r:
                    data_id = r[0]['id']
                    log_dict = {
                        'logtype':
                        'Warehouse',
                        'action':
                        'Update',
                        'actor':
                        session.username,
                        'ip':
                        web.ctx['ip'],
                        'descr':
                        'Updated warehouse data id:%s, Waybill:%s, Qty (bales):%s'
                        % (data_id, params.waybill, params.quantity),
                        'user':
                        session.sesid
                    }
                    audit_log(db, log_dict)
                return web.seeother("/warehousedata")
            else:
                has_entry = db.query(
                    "SELECT id FROM national_delivery_log WHERE waybill=$waybill "
                    "AND goods_received_note = $grn", {
                        'waybill': params.waybill,
                        'grn': params.goods_received_note
                    })
                if has_entry:
                    session.wdata_err = (
                        "Entry with Waybill:%s AND Goods Received Note:%s "
                        "already entered" %
                        (params.waybill, params.goods_received_note))
                    return web.seeother("/warehousedata")
                session.wdata_err = ""
                r = db.query(
                    "INSERT INTO national_delivery_log (po_number, funding_source, manufacturer, "
                    "made_in, batch_number, nets_type, nets_size, nets_color, quantity_bales, "
                    "entry_date, waybill, warehouse_branch, sub_warehouse, nda_samples, nda_sampling_date, "
                    "nda_conditional_release_date, nda_testing_result_date, unbs_samples, "
                    "unbs_sampling_date, remarks, goods_received_note, created_by, quantity) "
                    "VALUES ($po_number, $funding_source, $manufacturer, "
                    "$made_in, $batch_number, $nets_type, $nets_size, $nets_color, $quantity, "
                    "$entry_date, $waybill, $branch, $sub_warehouse, $nda_samples, "
                    "$nda_sampling_date, $nda_crdate, $nda_trdate, $unbs_samples, "
                    "$unbs_sdate, $remarks, $grn, $user, $total) RETURNING id",
                    {
                        'po_number':
                        params.po_number,
                        'funding_source':
                        params.funding_source,
                        'manufacturer':
                        params.manufacturer,
                        'made_in':
                        params.made_in,
                        'batch_number':
                        params.batch_number,
                        'nets_type':
                        params.nets_type,
                        'nets_color':
                        params.nets_color,
                        'nets_size':
                        params.nets_size,
                        'quantity':
                        params.quantity,
                        'entry_date':
                        params.entry_date,
                        'waybill':
                        params.waybill,
                        'branch':
                        params.warehouse_branch,
                        'sub_warehouse':
                        params.sub_warehouse,
                        'nda_samples':
                        params.nda_samples,
                        'nda_sampling_date':
                        None if not params.nda_sampling_date else
                        params.nda_sampling_date,
                        'nda_crdate':
                        None if not params.nda_conditional_release_date else
                        params.nda_conditional_release_date,
                        'nda_trdate':
                        None if not params.nda_testing_result_date else
                        params.nda_testing_result_date,
                        'unbs_samples':
                        params.unbs_samples,
                        'unbs_sdate':
                        None if not params.unbs_sampling_date else
                        params.unbs_sampling_date,
                        'remarks':
                        params.remarks,
                        'grn':
                        params.goods_received_note,
                        'user':
                        session.sesid,
                        'total':
                        total_nets
                    })

                if r:
                    data_id = r[0]['id']
                    log_dict = {
                        'logtype':
                        'Warehouse',
                        'action':
                        'Create',
                        'actor':
                        session.username,
                        'ip':
                        web.ctx['ip'],
                        'descr':
                        'Added warehouse data entry id:%s, Waybill:%s, GRN:%s, Qty (bales):%s'
                        % (data_id, params.waybill, params.goods_received_note,
                           params.quantity),
                        'user':
                        session.sesid
                    }
                    audit_log(db, log_dict)
                return web.seeother("/warehousedata")
        l = locals()
        del l['self']
        return render.warehousedata(**l)
Example #16
0
    def POST(self):
        params = web.input(ed="",
                           d_id="",
                           district="",
                           subcounty="",
                           release_order="",
                           waybill="",
                           quantity_bales="",
                           warehouse="",
                           warehouse_branch="",
                           departure_date="",
                           departure_time="",
                           driver="",
                           driver_tel="",
                           remarks="",
                           track_no_plate="",
                           quantity_bales_old=0,
                           parish="")
        session = get_session()
        current_time = datetime.datetime.now()
        allow_edit = False
        try:
            edit_val = int(params.ed)
            allow_edit = True
        except ValueError:
            pass

        with db.transaction():
            if params.ed and allow_edit:
                q = db.query(
                    "SELECT id FROM reporters WHERE "
                    "replace(telephone, '+', '') = $tel OR "
                    "replace(alternate_tel, '+', '') = $tel",
                    {'tel': params.driver_tel.replace('+', '')})
                if q:
                    driver_id = q[0]['id']
                else:
                    q = db.query(
                        "INSERT INTO reporters (firstname, telephone, reporting_location) "
                        " VALUES ($name, $tel, 1) RETURNING id", {
                            'name': params.driver,
                            'tel': params.driver_tel
                        })
                    driver_id = q[0]['id']
                    db.query(
                        "INSERT INTO reporter_groups_reporters (group_id, reporter_id) "
                        "VALUES ((SELECT id FROM reporter_groups WHERE name = 'Driver'), $reporter_id)",
                        {'reporter_id': driver_id})

                    # Schedule a push_contact to Push driver to RapidPro
                    contact_params = {
                        'phone': params.driver_tel,
                        'name': params.driver,
                        'groups': ['Driver']
                    }

                    sync_time = current_time + datetime.timedelta(
                        seconds=5
                    )  # XXX consider making the seconds configurable
                    queue_schedule(db, contact_params, sync_time,
                                   session.sesid, 'push_contact')

                # check if new quantities leave us in a consistent state
                old_quantity = int(params.quantity_bales_old)
                quantity_bales = int(params.quantity_bales)
                if not can_still_distribute(db, quantity_bales, old_quantity):
                    session.ddata_err = (
                        "You cannot distribute more than is available for distribution!"
                    )
                    return web.seeother("/dispatch")
                session.ddata_err = ""
                r = db.query(
                    "UPDATE distribution_log SET release_order=$release_order, "
                    "destination=$destination, waybill=$waybill, warehouse_branch = $branch, "
                    "departure_date=$ddate, departure_time=$dtime, remarks=$remarks, "
                    "quantity_bales=$quantity_bales, quantity_nets=$quantity_nets, "
                    " district_id=$district, "
                    "delivered_by=$delivered_by WHERE id = $id RETURNING id", {
                        'release_order':
                        params.release_order,
                        'destination':
                        params.subcounty,
                        'waybill':
                        params.waybill,
                        'branch':
                        params.warehouse_branch,
                        'ddate':
                        params.departure_date,
                        'dtime':
                        params.departure_time,
                        'remarks':
                        params.remarks,
                        'quantity_bales':
                        params.quantity_bales,
                        'quantity_nets':
                        (QUANTITY_PER_BALE * int(params.quantity_bales)),
                        'delivered_by':
                        driver_id,
                        'district':
                        params.district,
                        'id':
                        params.ed
                    })

                if r:
                    data_id = r[0]['id']
                    subcounty = ""
                    district = ""
                    parish = ""
                    # get subcounty name to use in SMS
                    sc = db.query(
                        "SELECT get_location_name($subcounty) as name;",
                        {'subcounty': params.subcounty})
                    if sc:
                        subcounty = sc[0]['name']

                    # get parish name if available
                    par = db.query(
                        "SELECT get_location_name($parish) as name;",
                        {'parish': params.parish})
                    if par:
                        parish = par[0]['name']
                        db.query(
                            "UPDATE distribution_log SET dest_parish = $parish "
                            "WHERE id = $id", {
                                'parish': params.parish,
                                'id': data_id
                            })

                    # get district name to use in SMS
                    dist = db.query(
                        "SELECT get_location_name($district) as name;",
                        {'district': params.district})
                    if dist:
                        district = dist[0]['name']

                    # sched_time = time to send SMS
                    sched_time = current_time + datetime.timedelta(
                        minutes=SMS_OFFSET_TIME)

                    # appropriately edit scheduled messages
                    sms_args = {
                        'parish': parish,
                        'subcounty': subcounty,
                        'district': district,
                        'waybill': params.waybill,
                        'quantity': quantity_bales,
                        'shortcode': config.get('shortcode', '6400')
                    }
                    national_reporters = get_location_role_reporters(
                        db, 1, config['national_reporters'])
                    district_reporters = get_location_role_reporters(
                        db, params.district, config['district_reporters'])
                    district_reporters += get_location_role_reporters(
                        db, params.subcounty, ['Subcounty Supervisor'])
                    subcounty_reporters = get_location_role_reporters(
                        db, params.subcounty, config['subcounty_reporters'])
                    parish_reporters = get_location_role_reporters(
                        db, params.parish, config['parish_reporters'])

                    scheduled_msgs = db.query(
                        "SELECT a.schedule_id, a.level, a.triggered_by FROM distribution_log_schedules a, "
                        " schedules b WHERE a.distribution_log_id = $log_id AND "
                        " b.id = a.schedule_id AND b.status = 'ready' "
                        " AND a.triggered_by = 1",
                        {'log_id': data_id})  # XXX 'ready'
                    if scheduled_msgs:  # we still have ready schedules
                        for s in scheduled_msgs:
                            sched = db.query(
                                "SELECT id FROM schedules WHERE id = $sched_id "
                                "FOR UPDATE NOWAIT",
                                {'sched_id': s['schedule_id']})

                            # build SMS to send to notifying parties
                            sms_text = ""
                            if parish:
                                sms_text = config[
                                    'parish_nets_sms_prefix_template'] % sms_args
                            sms_text += config[
                                'national_sms_template'] % sms_args
                            if s['level'] == 'national':
                                sms_params = {
                                    'text': sms_text,
                                    'to': ' '.join(national_reporters)
                                }
                                update_queued_sms(db, s['schedule_id'],
                                                  sms_params, sched_time,
                                                  session.sesid)

                            elif s['level'] == 'district':
                                sms_params = {
                                    'text': sms_text,
                                    'to': ' '.join(district_reporters)
                                }
                                update_queued_sms(db, s['schedule_id'],
                                                  sms_params, sched_time,
                                                  session.sesid)

                            elif s['level'] == 'subcounty':
                                if subcounty_reporters and not parish:
                                    sms_text += (
                                        '\n Once received / offloaded, please send '
                                        '"REC %(waybill)s %(quantity)s" to %(shortcode)s'
                                        % sms_args)
                                sms_params = {
                                    'text': sms_text,
                                    'to': ' '.join(subcounty_reporters)
                                }
                                update_queued_sms(db, s['schedule_id'],
                                                  sms_params, sched_time,
                                                  session.sesid)
                            elif s['level'] == 'parish':
                                if parish_reporters:
                                    sms_text += (
                                        '\n Once received / offloaded, please send '
                                        '"REC %(waybill)s %(quantity)s" to %(shortcode)s'
                                        % sms_args)
                                    sms_params = {
                                        'text': sms_text,
                                        'to': ' '.join(parish_reporters)
                                    }
                                    update_queued_sms(db, s['schedule_id'],
                                                      sms_params, sched_time,
                                                      session.sesid)

                            elif s['level'] == 'driver':
                                if parish:
                                    driver_sms_text = config[
                                        'driver_parish_sms_template'] % sms_args
                                else:
                                    driver_sms_text = config[
                                        'driver_sms_template'] % sms_args
                                sms_params = {
                                    'text': driver_sms_text,
                                    'to': params.driver_tel
                                }
                                update_queued_sms(db, s['schedule_id'],
                                                  sms_params, sched_time,
                                                  session.sesid)
                    else:  # no ready schedules were found
                        sms_text = config['national_sms_template'] % sms_args
                        sms_params = {
                            'text': sms_text,
                            'to': ' '.join(district_reporters)
                        }
                        sched_id = queue_schedule(db, sms_params, sched_time,
                                                  session.sesid)
                        log_schedule(db, data_id, sched_id, 'district')
                        # print "+=======+=======+===>", district_reporters

                        sms_params = {
                            'text': sms_text,
                            'to': ' '.join(national_reporters)
                        }
                        sched_id = queue_schedule(db, sms_params, sched_time,
                                                  session.sesid)
                        log_schedule(db, data_id, sched_id, 'national')
                        # print "*=======*=======*===>", national_reporters
                        if subcounty_reporters and not parish:
                            sms_text += (
                                '\n Once received / offloaded, please send '
                                '"REC %(waybill)s %(quantity)s" to %(shortcode)s'
                                % sms_args)
                        sms_params = {
                            'text': sms_text,
                            'to': ' '.join(subcounty_reporters)
                        }
                        sched_id = queue_schedule(db, sms_params, sched_time,
                                                  session.sesid)
                        log_schedule(db, data_id, sched_id, 'subcounty')
                        # print "@=======@=======@===>", subcounty_reporters

                        if parish_reporters:
                            sms_text += (
                                '\n Once received / offloaded, please send '
                                '"REC %(waybill)s %(quantity)s" to %(shortcode)s'
                                % sms_args)
                            sms_params = {
                                'text': sms_text,
                                'to': ' '.join(parish_reporters)
                            }
                            sched_id = queue_schedule(db, sms_params,
                                                      sched_time,
                                                      session.sesid)
                            log_schedule(db, data_id, sched_id, 'parish')
                        # print "@=======@=======@===>", parish_reporters

                        # for the driver
                        if parish:
                            driver_sms_text = config[
                                'driver_parish_sms_template'] % sms_args
                        else:
                            driver_sms_text = config[
                                'driver_sms_template'] % sms_args

                        sms_params = {
                            'text': driver_sms_text,
                            'to': params.driver_tel
                        }
                        sched_id = queue_schedule(db, sms_params, sched_time,
                                                  session.sesid)
                        log_schedule(db, data_id, sched_id, 'driver')

                    log_dict = {
                        'logtype':
                        'Distribution',
                        'action':
                        'Update',
                        'actor':
                        session.username,
                        'ip':
                        web.ctx['ip'],
                        'descr':
                        'Updated distribution data id:%s, Waybill:%s, Qty (bales):%s'
                        % (data_id, params.waybill, params.quantity_bales),
                        'user':
                        session.sesid
                    }
                    audit_log(db, log_dict)
                return web.seeother("/dispatch")
            else:
                # check whether what we want to distribute is available in stock
                quantity_bales = int(params.quantity_bales)
                if not can_still_distribute(db, quantity_bales):
                    session.ddata_err = (
                        "You cannot distribute more than is available for distribution!"
                    )
                    return web.seeother("/dispatch")
                session.ddata_err = ""

                has_entry = db.query(
                    "SELECT id FROM distribution_log WHERE waybill=$waybill",
                    {'waybill': params.waybill})
                if has_entry:
                    session.ddata_err = (
                        "Entry with Waybill: %s already entered!" %
                        params.waybill)
                    return web.seeother("/dispatch")
                session.ddata_err = ""
                q = db.query("SELECT id FROM reporters WHERE telephone = $tel",
                             {'tel': params.driver_tel})
                if q:
                    driver_id = q[0]['id']
                else:
                    q = db.query(
                        "INSERT INTO reporters (firstname, telephone, reporting_location) "
                        " VALUES ($name, $tel, 1) RETURNING id", {
                            'name': params.driver,
                            'tel': params.driver_tel
                        })
                    driver_id = q[0]['id']
                    db.query(
                        "INSERT INTO reporter_groups_reporters (group_id, reporter_id) "
                        "VALUES ((SELECT id FROM reporter_groups WHERE name = 'Driver'), $reporter_id)",
                        {'reporter_id': driver_id})
                    # Schedule a push_contact to Push driver to RapidPro
                    contact_params = {
                        'phone': params.driver_tel,
                        'name': params.driver,
                        'groups': ['Driver'],
                    }

                    sync_time = current_time + datetime.timedelta(
                        seconds=10
                    )  # XXX consider making the seconds configurable
                    queue_schedule(db, contact_params, sync_time,
                                   session.sesid, 'push_contact')

                r = db.query(
                    "INSERT INTO distribution_log (source, dest, release_order, waybill, "
                    " quantity_bales, quantity_nets, remarks, warehouse_branch, "
                    " departure_date, departure_time, destination, delivered_by, created_by, "
                    " district_id, track_no_plate) "
                    "VALUES('national', 'subcounty', $release_order, $waybill, $quantity_bales, "
                    "$quantity_nets, $remarks, $branch, $ddate, $dtime, $destination, "
                    "$delivered_by, $user, $district, $noplate) "
                    "RETURNING id", {
                        'release_order':
                        params.release_order,
                        'waybill':
                        params.waybill,
                        'quantity_bales':
                        params.quantity_bales,
                        'quantity_nets':
                        (QUANTITY_PER_BALE * int(params.quantity_bales)),
                        'remarks':
                        params.remarks,
                        'branch':
                        params.warehouse_branch,
                        'ddate':
                        params.departure_date,
                        'dtime':
                        params.departure_time,
                        'destination':
                        params.subcounty,
                        'delivered_by':
                        driver_id,
                        'user':
                        session.sesid,
                        'noplate':
                        params.track_no_plate,
                        'district':
                        params.district
                    })
                if r:
                    log_id = r[0]['id']
                    subcounty = ""
                    district = ""
                    parish = ""
                    # get subcounty name to use in SMS
                    sc = db.query(
                        "SELECT get_location_name($subcounty) as name;",
                        {'subcounty': params.subcounty})
                    if sc:
                        subcounty = sc[0]['name']
                    # get parish name if available
                    par = db.query(
                        "SELECT get_location_name($parish) as name;",
                        {'parish': params.parish})
                    if par:
                        parish = par[0]['name']
                        db.query(
                            "UPDATE distribution_log SET dest_parish = $parish "
                            "WHERE id = $id", {
                                'parish': params.parish,
                                'id': log_id
                            })

                    # get district name to use in SMS
                    dist = db.query(
                        "SELECT get_location_name($district) as name;",
                        {'district': params.district})
                    if dist:
                        district = dist[0]['name']

                    # sched_time allows to give distribution_log edits sometime #SMS_OFFSET_TIME
                    sched_time = current_time + datetime.timedelta(
                        minutes=SMS_OFFSET_TIME)

                    # build SMS to send to notifying parties
                    sms_args = {
                        'parish': parish,
                        'subcounty': subcounty,
                        'district': district,
                        'waybill': params.waybill,
                        'quantity': quantity_bales,
                        'shortcode': config.get('shortcode', '6400')
                    }
                    sms_text = ""
                    if parish:
                        sms_text = config[
                            'parish_nets_sms_prefix_template'] % sms_args

                    sms_text += config['national_sms_template'] % sms_args

                    district_reporters = get_location_role_reporters(
                        db, params.district, config['district_reporters'])
                    district_reporters += get_location_role_reporters(
                        db, params.subcounty, ['Subcounty Supervisor'])
                    sms_params = {
                        'text': sms_text,
                        'to': ' '.join(district_reporters)
                    }
                    sched_id = queue_schedule(db, sms_params, sched_time,
                                              session.sesid)
                    log_schedule(db, log_id, sched_id, 'district')
                    # print "+=======+=======+===>", district_reporters

                    national_reporters = get_location_role_reporters(
                        db, 1, config['national_reporters'])
                    sms_params = {
                        'text': sms_text,
                        'to': ' '.join(national_reporters)
                    }
                    sched_id = queue_schedule(db, sms_params, sched_time,
                                              session.sesid)
                    log_schedule(db, log_id, sched_id, 'national')
                    # print "*=======*=======*===>", national_reporters

                    subcounty_reporters = get_location_role_reporters(
                        db, params.subcounty, config['subcounty_reporters'])
                    parish_reporters = get_location_role_reporters(
                        db, params.parish, config['parish_reporters'])

                    if subcounty_reporters and not parish:
                        sms_text += (
                            '\n Once received / offloaded, please send '
                            '"REC %(waybill)s %(quantity)s" to %(shortcode)s' %
                            sms_args)
                    sms_params = {
                        'text': sms_text,
                        'to': ' '.join(subcounty_reporters)
                    }
                    sched_id = queue_schedule(db, sms_params, sched_time,
                                              session.sesid)
                    log_schedule(db, log_id, sched_id, 'subcounty')
                    # print "@=======@=======@===>", subcounty_reporters

                    if parish_reporters:
                        sms_text += (
                            '\n Once received / offloaded, please send '
                            '"REC %(waybill)s %(quantity)s" to %(shortcode)s' %
                            sms_args)
                        sms_params = {
                            'text': sms_text,
                            'to': ' '.join(parish_reporters)
                        }
                        sched_id = queue_schedule(db, sms_params, sched_time,
                                                  session.sesid)
                        log_schedule(db, log_id, sched_id, 'parish')
                    # print "@=======@=======@===>", parish_reporters

                    # for the driver
                    if parish:
                        driver_sms_text = config[
                            'driver_parish_sms_template'] % sms_args
                    else:
                        driver_sms_text = config[
                            'driver_sms_template'] % sms_args
                    sms_params = {
                        'text': driver_sms_text,
                        'to': params.driver_tel
                    }
                    sched_id = queue_schedule(db, sms_params, sched_time,
                                              session.sesid)
                    log_schedule(db, log_id, sched_id, 'driver')

                    log_dict = {
                        'logtype':
                        'Distribution',
                        'action':
                        'Create',
                        'actor':
                        session.username,
                        'ip':
                        web.ctx['ip'],
                        'descr':
                        'Added distribution entry id:%s, Waybill:%s, Qty (bales):%s'
                        % (log_id, params.waybill, params.quantity_bales),
                        'user':
                        session.sesid
                    }
                    audit_log(db, log_dict)

                return web.seeother("/dispatch")

        l = locals()
        del l['self']
        return render.dispatch(**l)
Example #17
0
    def POST(self):
        params = web.input(
            page=1, ed="", d_id="", po_number="", funding_source="", manufacturer="",
            made_in="", batch_number="", nets_type="", nets_color="", nets_size="",
            quantity="0", waybill="", warehouse_branch="", sub_warehouse="", entry_date="",
            nda_samples="0", nda_sampling_date="", nda_conditional_release_date="",
            nda_testing_result_date="", unbs_samples="0", unbs_sampling_date="",
            remarks="", goods_received_note="", caller='web', user=''
        )
        print web.data()
        userid = 0
        user = db.query("SELECT id FROM users WHERE username = $user", {'user': params.user})
        if user:
            userid = user[0]['id']

        with db.transaction():
            nda_samples = 0
            unbs_samples = 0
            try:
                nda_samples = int(params.nda_samples)
                unbs_samples = int(params.unbs_samples)
                quantity = int(params.quantity)
            except:
                pass
            total_nets = (quantity * QUANTITY_PER_BALE) - (nda_samples + unbs_samples)

            has_entry = db.query(
                "SELECT id FROM national_delivery_log WHERE waybill=$waybill "
                "AND goods_received_note = $grn",
                {'waybill': params.waybill, 'grn': params.goods_received_note})
            if has_entry:
                return json.dumps({
                    'status': 'FAILED', 'messsage':
                    'Waybill or GRN Already Exists [%s: %s]' % (params.waybill, params.goods_received_note)})
            r = db.query(
                "INSERT INTO national_delivery_log (po_number, funding_source, manufacturer, "
                "made_in, batch_number, nets_type, nets_size, nets_color, quantity_bales, "
                "entry_date, waybill, warehouse_branch, sub_warehouse, nda_samples, nda_sampling_date, "
                "nda_conditional_release_date, nda_testing_result_date, unbs_samples, "
                "unbs_sampling_date, remarks, goods_received_note, created_by, quantity) "
                "VALUES ($po_number, $funding_source, $manufacturer, "
                "$made_in, $batch_number, $nets_type, $nets_size, $nets_color, $quantity, "
                "$entry_date, $waybill, $branch, $sub_warehouse, $nda_samples, "
                "$nda_sampling_date, $nda_crdate, $nda_trdate, $unbs_samples, "
                "$unbs_sdate, $remarks, $grn, $user, $total) RETURNING id", {
                    'po_number': params.po_number, 'funding_source': params.funding_source,
                    'manufacturer': params.manufacturer, 'made_in': params.made_in,
                    'batch_number': params.batch_number, 'nets_type': params.nets_type,
                    'nets_color': params.nets_color, 'nets_size': params.nets_size,
                    'quantity': params.quantity, 'entry_date': params.entry_date,
                    'waybill': params.waybill, 'branch': params.warehouse_branch,
                    'sub_warehouse': params.sub_warehouse, 'nda_samples': params.nda_samples,
                    'nda_sampling_date': None if not params.nda_sampling_date else params.nda_sampling_date,
                    'nda_crdate': None if not params.nda_conditional_release_date else params.nda_conditional_release_date,
                    'nda_trdate': None if not params.nda_testing_result_date else params.nda_testing_result_date,
                    'unbs_samples': params.unbs_samples,
                    'unbs_sdate': None if not params.unbs_sampling_date else params.unbs_sampling_date,
                    'remarks': params.remarks, 'grn': params.goods_received_note,
                    'user': userid if userid else 1, 'total': total_nets
                })

            if r:
                data_id = r[0]['id']
                log_dict = {
                    'logtype': 'Warehouse', 'action': 'Create', 'actor': params.user,
                    'ip': web.ctx['ip'],
                    'descr': 'Added warehouse data entry id:%s, Waybill:%s, GRN:%s, Qty (bales):%s' % (
                        data_id, params.waybill, params.goods_received_note, params.quantity),
                    'user': userid if userid else 1
                }
                audit_log(db, log_dict)
                return json.dumps({'status': 'SUCCESS', 'message': 'successfully added!'})
        return render.warehousedata({
            'status': 'FAILED', 'message': 'Not Added [%s: %s]' % (params.waybill, params.goods_received_note)})
Example #18
0
    def POST(self):
        params = web.input(firstname="",
                           lastname="",
                           gender="",
                           telephone="",
                           email="",
                           location="",
                           role=[],
                           alt_telephone="",
                           page="1",
                           ed="",
                           d_id="",
                           district="",
                           facility="",
                           code="",
                           date_of_birth="",
                           caller="",
                           user="******")
        if params.caller != 'api':
            session = get_session()
            username = session.username
            userid = session.sesid
        else:
            rs = db.query(
                "SELECT id, username FROM users WHERE username = '******';" %
                params.user)
            if rs:
                xuser = rs[0]
                userid = xuser['id']
                username = xuser['username']

        allow_edit = False
        try:
            edit_val = int(params.ed)
            allow_edit = True
        except:
            pass
        current_time = datetime.datetime.now()
        # Set params to schedule a push_contact to Push reporter to RapidPro
        urns = []
        if params.alt_telephone:
            try:
                alt_telephone = format_msisdn(params.alt_telephone)
                urns.append("tel:" + alt_telephone)
            except:
                alt_telephone = ''
        if params.telephone:
            try:
                telephone = format_msisdn(params.telephone)
                urns.append("tel:" + telephone)
            except:
                telephone = ''
        groups = ['%s' % rolesById[int(i)] for i in params.role]
        contact_params = {
            'urns': urns,
            'name': params.firstname + ' ' + params.lastname,
            'groups': groups,
            'fields': {
                # 'email': params.email,
                'type': 'VHT' if 'VHT' in groups else 'HC'
            }
        }

        with db.transaction():
            if params.ed and allow_edit:
                location = params.location if params.location else None
                r = db.query(
                    "UPDATE reporters SET firstname=$firstname, lastname=$lastname, "
                    "telephone=$telephone, reporting_location=$location, "
                    "alternate_tel=$alt_tel, district_id = $district_id "
                    "WHERE id=$id RETURNING id", {
                        'firstname': params.firstname,
                        'lastname': params.lastname,
                        'gender': params.gender,
                        'telephone': params.telephone,
                        'location': location,
                        'id': params.ed,
                        'alt_tel': params.alt_telephone,
                        'district_id': params.district
                    })
                if r:
                    for group_id in params.role:
                        rx = db.query(
                            "SELECT id FROM reporter_groups_reporters "
                            "WHERE reporter_id = $id AND group_id =$gid ", {
                                'gid': group_id,
                                'id': params.ed
                            })
                        if not rx:
                            db.query(
                                "INSERT INTO reporter_groups_reporters (group_id, reporter_id) "
                                " VALUES ($group_id, $reporter_id)", {
                                    'group_id': group_id,
                                    'reporter_id': params.ed
                                })
                    # delete other groups
                    db.query(
                        "DELETE FROM reporter_groups_reporters WHERE "
                        "reporter_id=$id AND group_id NOT IN $roles", {
                            'id': params.ed,
                            'roles': params.role
                        })

                    log_dict = {
                        'logtype':
                        'Web',
                        'action':
                        'Update',
                        'actor':
                        username,
                        'ip':
                        web.ctx['ip'],
                        'descr':
                        'Updated reporter %s:%s (%s)' %
                        (params.ed, params.firstname + ' ' + params.lastname,
                         params.telephone),
                        'user':
                        userid
                    }
                    audit_log(db, log_dict)

                    sync_time = current_time + datetime.timedelta(seconds=60)
                    if urns:  # only queue if we have numbers
                        queue_schedule(db, contact_params, sync_time, userid,
                                       'contact_push')
                return web.seeother("/reporters")
            else:
                location = params.location if params.location else None
                has_reporter = db.query(
                    "SELECT id FROM reporters WHERE telephone = $tel",
                    {'tel': params.telephone})
                if has_reporter:
                    reporterid = has_reporter[0]["id"]
                    rx = db.query(
                        "UPDATE reporters SET firstname=$firstname, lastname=$lastname, "
                        "telephone=$telephone, reporting_location=$location, "
                        "alternate_tel=$alt_tel, district_id = $district_id "
                        "WHERE id=$id RETURNING id", {
                            'firstname': params.firstname,
                            'lastname': params.lastname,
                            'gender': params.gender,
                            'telephone': params.telephone,
                            'location': location,
                            'id': reporterid,
                            'alt_tel': params.alt_telephone,
                            'district_id': params.district
                        })
                    if params.caller == 'api':
                        return json.dumps({
                            'message':
                            "Reporter with Telephone:%s already registered" %
                            params.telephone
                        })
                    else:
                        session.rdata_err = (
                            "Reporter with Telephone:%s already registered" %
                            params.telephone)
                        return web.seeother("/reporters")
                if params.caller != 'api':
                    session.rdata_err = ""
                r = db.query(
                    "INSERT INTO reporters (firstname, lastname, telephone, "
                    " reporting_location, alternate_tel, "
                    " district_id) VALUES "
                    " ($firstname, $lastname, $telephone, $location, "
                    " $alt_tel, $district_id) RETURNING id", {
                        'firstname': params.firstname,
                        'lastname': params.lastname,
                        'telephone': params.telephone,
                        'location': location,
                        'alt_tel': params.alt_telephone,
                        'district_id': params.district,
                    })
                if r:
                    reporter_id = r[0]['id']
                    db.query(
                        "INSERT INTO reporter_healthfacility (reporter_id, facility_id) "
                        "VALUES($reporter_id, $facility_id)", {
                            'reporter_id': reporter_id,
                            'facility_id': params.facility
                        })
                    for group_id in params.role:
                        db.query(
                            "INSERT INTO reporter_groups_reporters (group_id, reporter_id) "
                            " VALUES ($role, $reporter_id)", {
                                'role': group_id,
                                'reporter_id': reporter_id
                            })
                    log_dict = {
                        'logtype':
                        'Web',
                        'action':
                        'Create',
                        'actor':
                        username,
                        'ip':
                        web.ctx['ip'],
                        'descr':
                        'Created reporter %s:%s (%s)' %
                        (reporter_id, params.firstname + ' ' + params.lastname,
                         params.telephone),
                        'user':
                        userid
                    }
                    audit_log(db, log_dict)

                    sync_time = current_time + datetime.timedelta(seconds=60)
                    if contact_params['urns']:
                        queue_schedule(db, contact_params, sync_time, userid,
                                       'contact_push')
                if params.caller == 'api':
                    return json.dumps({'message': 'success'})
                else:
                    return web.seeother("/reporters?show=true")

        l = locals()
        del l['self']
        if params.caller == 'api':
            pass
        else:
            return render.reporters(**l)
Example #19
0
    def GET(self):
        params = web.input(page=1, ed="", d_id="", caller="web", search="")
        edit_val = params.ed
        session = get_session()
        districts = db.query(
            "SELECT id, name FROM locations WHERE type_id = "
            "(SELECT id FROM locationtype WHERE name = 'district') ORDER by name"
        )
        roles = db.query("SELECT id, name from reporter_groups order by name")
        district = {}
        allow_edit = False
        try:
            edit_val = int(params.ed)
            allow_edit = True
        except ValueError:
            pass
        if params.ed and allow_edit:
            res = db.query(
                "SELECT id, firstname, lastname, telephone, email, national_id, "
                "reporting_location, distribution_point, role, dpoint,alternate_tel "
                "FROM reporters_view "
                " WHERE id = $id", {'id': edit_val})
            if res:
                r = res[0]
                firstname = r.firstname
                lastname = r.lastname
                telephone = r.telephone
                email = r.email
                role = r.role
                national_id = r.national_id
                alt_telephone = r.alternate_tel
                dpoint_id = r.distribution_point
                dpoint = r.dpoint
                location = r.reporting_location
                subcounty = ""
                district = ""
                parish = ""
                village = location
                villages = []
                parishes = []
                subcounties = []
                ancestors = db.query(
                    "SELECT id, name, level FROM get_ancestors($loc) "
                    "WHERE level > 1 ORDER BY level DESC;", {'loc': location})
                if ancestors:
                    for loc in ancestors:
                        if loc['level'] == 5:
                            village = loc
                        elif loc['level'] == 4:
                            parish = loc
                            villages = db.query(
                                "SELECT id, name FROM get_children($id)",
                                {'id': loc['id']})
                        elif loc['level'] == 3:
                            subcounty = loc
                            parishes = db.query(
                                "SELECT id, name FROM get_children($id)",
                                {'id': loc['id']})
                        elif loc['level'] == 2:
                            district = loc
                            subcounties = db.query(
                                "SELECT id, name FROM get_children($id)",
                                {'id': loc['id']})
                else:
                    district = location
        allow_del = False
        try:
            del_val = int(params.d_id)
            allow_del = True
        except ValueError:
            pass
        if params.d_id and allow_del:
            if session.role in ('Micro Planning', 'Administrator'):
                reporter = db.query(
                    "SELECT firstname || ' ' || lastname as name , telephone "
                    "FROM reporters WHERE id = $id", {'id': params.d_id})
                if reporter:
                    rx = reporter[0]
                    log_dict = {
                        'logtype':
                        'Web',
                        'action':
                        'Delete',
                        'actor':
                        session.username,
                        'ip':
                        web.ctx['ip'],
                        'descr':
                        'Deleted reporter %s:%s (%s)' %
                        (params.d_id, rx['name'], rx['telephone']),
                        'user':
                        session.sesid
                    }
                    db.query(
                        "DELETE FROM reporter_groups_reporters WHERE reporter_id=$id",
                        {'id': params.d_id})
                    db.query("DELETE FROM reporters WHERE id=$id",
                             {'id': params.d_id})
                    audit_log(db, log_dict)
                    if params.caller == "api":  # return json if API call
                        web.header("Content-Type",
                                   "application/json; charset=utf-8")
                        return json.dumps({'message': "success"})
        if session.role == 'Administrator':
            if params.search:
                REPORTER_SQL = (
                    "SELECT * FROM reporters_view4 WHERE  telephone ilike $search OR "
                    " firstname ilike $search OR lastname ilike $search")
            else:
                REPORTER_SQL = "SELECT * FROM reporters_view4 WHERE id >  (SELECT max(id) - 8 FROM reporters);"
        else:
            if params.search:
                REPORTER_SQL = (
                    "SELECT * FROM reporters_view4 WHERE created_by = $user AND "
                    " (firstname ilike $search OR lastname ilike $search OR telephone ilike $search)"
                )
            else:
                REPORTER_SQL = "SELECT * FROM reporters_view4 WHERE created_by = $user ORDER BY id DESC LIMIT 50"

        reporters = db.query(REPORTER_SQL, {
            'user': session.sesid,
            'search': '%%%s%%' % params.search
        })
        l = locals()
        del l['self']
        return render.reporters(**l)