Esempio n. 1
0
    def POST(self, place):
        data = json.loads(web.data())['data']

        for row in data:
            code = place.key + "/" + row['code']
            pb = Place.find(code)

            if row['ward'] and row['ward'].strip():
                # Extract te group code from its name
                key = place.key + "/" + row['ward'].split("-")[0].strip()
                ward = Place.find(key)
                if pb.ward_id != ward.id:
                    pb.set_ward(ward)
            else:
                pb.set_ward(None)

            if row['px'] and row['px'].strip():
                # Extract te group code from its name
                key = place.key + "/" + row['px'].split("-")[0].strip()
                px = Place.find(key)
                if pb.px_id != px.id:
                    pb.set_px(px)
            else:
                pb.set_px(None)

        web.header("content-type", "application/json")
        return '{"result": "ok"}'
Esempio n. 2
0
def add_polling_centers(state, filename):
    d = {}
    with db.transaction():
        for ac_code, px_code, pb_code, name in read_csv(filename):
            print "adding polling center", state.id, ac_code, px_code
            if (ac_code, px_code) not in d:
                key = "{0}/{1}/{2}".format(state.key, ac_code, px_code)                    
                if not db.select("places", where="type='PX' AND key=$key", vars=locals()):
                    pb_key = "{0}/{1}/{2}".format(state.key, ac_code, pb_code)
                    pb = Place.find(pb_key)
                    lazy_insert("places", key=key, name=name, type="PX", 
                        code=key.split("/")[-1],
                        state_id=state.id,
                        region_id=pb.region_id,
                        pc_id=pb.pc_id,
                        ac_id=pb.ac_id,
                        ward_id=pb.ward_id)
                d[ac_code, px_code] = 1
        commit_lazy_inserts()

    with db.transaction():
        for ac_code, px_code, pb_code, name in read_csv(filename):
            key = "{0}/{1}/{2}".format(state.key, ac_code, px_code)                    
            px = Place.find(key)
            pb_key = "{0}/{1}/{2}".format(state.key, ac_code, pb_code)
            db.update("places", px_id=px.id, where="key=$pb_key", vars=locals())
Esempio n. 3
0
    def POST_update_pcs(self, place, data):
        for row in data:
            key = place.key + "/" + row['code']
            pc = Place.find(key)

            if row['region'] and row['region'].strip():
                # Extract te group code from its name
                key = place.key + "/" + row['region'].split("-")[0].strip()
                region = Place.find(key)
                if pc.region_id != region.id:
                    pc.set_parent("REGION", region)
            else:
                pc.set_parent("REGION", None)
        web.header("content-type", "application/json")
        return '{"result": "ok"}'
Esempio n. 4
0
    def GET(self, key):
        place = Place.find(key)
        if not place:
            raise web.notfound()

        booths = place.get_all_polling_booths()
        from collections import defaultdict
        d = defaultdict(list)
        pxd = {}
        for booth in booths:
            px = booth.get_parent("PX")
            px_code = px.key.split("/")[-1]
            d[px_code].append(booth)
            pxd[px_code] = px

        def get_row(px_code):
            booths = d[px_code]
            px = pxd[px_code]
            ward = px.get_parent("WARD")
            ward_name = ward and ward.name or "-"
            return [place.code, place.name, px_code, ",".join(b.code for b in booths), px.name, ward_name]

        data = [get_row(px_code) for px_code in sorted(d)]
        web.header("content-type", "text/plain")
        return "\n".join("\t".join(row) for row in data)
Esempio n. 5
0
    def POST(self):
        i = web.input()
        token = i.get('token')
        place_key = i.get('place')
        #client_key = i['client_key']
        #client_secret = i['client_secret']

        user = account.token2user(token)
        place = Place.find(key=place_key)

        if not user:
            return jsonify(
                    status='failed',
                    code='error_token_invalid',
                    message='Token is either invalid or expired.')

        if not place:
            return jsonify(
                    status='failed',
                    code='error_invalid_input',
                    message='Invalid Place')

        if not place.writable_by(user):
            return jsonify(
                    status='failed',
                    code='error_permission_denied',
                    message="User doesn't have permission to modify data at this place.")
        else:
            return jsonify(
                    status='ok',
                    code='authorized',
                    message='The user is authorized to modify data at this place.')
Esempio n. 6
0
 def POST(self, code):
     place = Place.find(key=code)
     if not place:
         raise web.notfound()
     i = web.input(info="")
     place.update_info(i.info)
     raise web.seeother(place.url + "/info")
Esempio n. 7
0
def main():
    import sys
    import webapp
    webapp.check_config()

    global db 
    db = get_db()

    if "--add-admin" in sys.argv:
        index = sys.argv.index("--add-admin")
        email = sys.argv[index+1]
        state = Place.find(key=webapp.get_state())

        # Hack to fix the error at account.get_current_user() when adding volunteer
        web.ctx.current_user = None

        state.add_volunteer("Fix Your Name", email, "0000000000", role="admin")
        return
    if "--polling-centers" in sys.argv:
        index = sys.argv.index("--polling-centers")
        state_code = sys.argv[index+1]
        filename = sys.argv[index+2]
        state = Place.find(state_code)
        print "add_polling_centers", state, filename
        add_polling_centers(state, filename)
        return
    if "--wards" in sys.argv:
        index = sys.argv.index("--wards")
        state_code = sys.argv[index+1]
        filename = sys.argv[index+2]
        state = Place.find(state_code)
        print "add_wards", state, filename
        add_wards(state, filename)
        return


    
    dir = sys.argv[1]
    code = sys.argv[2]
    name = sys.argv[3]

    state = add_state(code, name)

    add_pcs(state, dir)
    add_acs(state, dir)
    #add_wards(state, dir)
    add_polling_booths(state, dir)
Esempio n. 8
0
def autoadd_pb_agents(place_key):
    """Finds all volunteers in the place and adds a new role as polling booth agent.
    """
    place = Place.find(place_key)
    if not place:
        raise ValueError("Invalid place {0}".format(place_key))

    _add_pb_agents(place, place.get_all_volunteers())
Esempio n. 9
0
 def GET(self, code):
     place = Place.find(key=code)
     if not place:
         raise web.notfound()
     user = account.get_current_user()
     if not place.writable_by(user, roles=['coordinator', 'admin']):
         raise web.seeother(place.url)
     return render.ward_report(place)
Esempio n. 10
0
def debug(place_key):
    place = Place.find(place_key)
    if not place:
        raise ValueError("Invalid place {0}".format(place_key))    

    agents = [a for a in place.get_pb_agents() if a.voterid if a.email]
    a = agents[0]
    utils.sendmail_voterid_added(a)
Esempio n. 11
0
def main():
    if not db.select("places", where="type='STATE' AND code='karnataka'"):
        db.insert("places", name="Karnataka", type="STATE", code="karnataka", parent_id=None)
    state = Place.find("karnataka")
    #add_places(state)
    add_pcs(state)
    add_acs(state)
    add_wards(state)
    add_polling_booths(state)
Esempio n. 12
0
 def GET(self, code):
     place = Place.find(key=code)
     if not place:
         raise web.notfound()
     i = web.input(m=None)
     if i.m == "edit":
         return render.edit_info(place)
     else:
         return render.place_info(place)
Esempio n. 13
0
 def POST(self, code):
     place = Place.find(key=code)
     if not place:
         raise web.notfound()
     elif not place.writable_by(account.get_current_user(), roles=['admin']):
         # only admins can edit places
         raise web.seeother(place.url + "/users")
     i = web.input(places="")
     place.add_places(i.places)
     raise web.seeother(place.url)
Esempio n. 14
0
def email_voterid_added(place_key):
    """Email all volunteers that their voter ID registration is complete.
    """
    place = Place.find(place_key)
    if not place:
        raise ValueError("Invalid place {0}".format(place_key))

    agents = [a for a in place.get_pb_agents() if a.email and a.get_voterid_info()]    
    conn = utils.get_smtp_conn()    
    for a in agents:
        utils.sendmail_voterid_added(a, conn=conn)
Esempio n. 15
0
def update_voterinfo(place_key):
    """Updtes voter info of all volunteers with voterids whos voter info is not updated yet.
    """
    place = Place.find(place_key)
    if not place:
        raise ValueError("Invalid place {0}".format(place_key))    
    for a in place.get_all_volunteers("pb_agent"):
        a.populate_voterid_info()
        info = a.get_voterid_info()
        if info and info.pb_id != a.place_id:
            a.update(place_id=info.pb_id)
Esempio n. 16
0
    def POST(self, code):
        place = Place.find(key=code)
        if not place:
            raise web.notfound()
        user = account.get_current_user()
        if not place.writable_by(user, roles=['coordinator', 'admin']):
            raise web.seeother(place.url)

        links = json.loads(web.data())['data']
        links = [link for link in links if link.get('url')]
        place.save_links(links)
        return '{"result": "ok"}'
Esempio n. 17
0
    def GET(self, key):
        place = Place.find(key=key)
        self.check_write_access(place)

        i = web.input(action="")
        if i.action == "add":
            form = self.make_form()
            return render.add_people(place, form, add_users=True)
        else:
            roles = ['admin', 'user']
            users = place.get_people(roles)
            return render.users(place, users)
Esempio n. 18
0
def add_pb_agents(place_key, tsv_file):
    """Takes a tsv file containing name, phone, email fields and adds them as PB agents.
    """
    place = Place.find(place_key)
    if not place:
        raise ValueError("Invalid place {0}".format(place_key))

    def parse_line(line):
        name, phone, email = line.strip("\n").split("\t")
        return web.storage(name=name, phone=phone, email=email, voterid=None)

    agents = [parse_line(line) for line in open(tsv_file) if line.strip()]
    _add_pb_agents(place, agents)
Esempio n. 19
0
    def GET(self, code):
        if not is_coordinator():
            raise web.notfound()

        place = Place.find(key=code)
        if not place:
            raise web.notfound()
        user = account.get_current_user()
        if not place.writable_by(user, roles=['coordinator', 'admin']):
            raise web.seeother(place.url)
        dataset = place.get_all_coordinators_as_dataset()
        web.header("Content-disposition", "attachment; filename=%s-coordinators.xls" % place.code)
        web.header("Content-Type", "application/vnd.ms-excel")
        return dataset.xls
Esempio n. 20
0
    def POST(self, code):
        place = Place.find(key=code)
        if not place:
            raise web.notfound()
        elif not place.writable_by(account.get_current_user(), roles=['admin']):
            # only admins can delete places
            raise web.seeother(place.url)

        i = web.input(action=None)
        if i.action == "cancel":
            raise web.seeother(place.url)
        else:
            parent = place.parent
            place.delete()
            raise web.seeother(parent.url)
Esempio n. 21
0
    def POST(self, place, id):
        person = Person.find(place_id=place.id, id=id)
        if not person:
            raise web.notfound()

        user = account.get_current_user()
        if user.role not in ['admin', 'coordinator'] and person.id != int(id):
            return render.access_restricted()

        i = web.input()
        if i.action == "save":
            d = dict(name=i.name, email=i.email, phone=i.phone, voterid=i.voterid)
            if self.can_change_role(user):
                d['role'] = i.role
            person.update(d)
            if person.role == 'pb_agent':
                person.populate_voterid_info()
                if person.get_voterid_info():
                    utils.sendmail_voterid_added(person)
                else:
                    utils.sendmail_voterid_pending(person)
            flash.add_flash_message("success", "Thanks for updating!")            
        elif i.action == "delete" and self.can_change_role(user): # don't allow self deletes
            person.delete()
            flash.add_flash_message("success", "Delete the volunteer successfully.")            
        elif i.action == "update-place":
            next = i.get("next")
            new_place = Place.find(i.place)
            if not new_place:
                flash.add_flash_message("warning", "Unable to update the location of the volunteer.")
                raise web.seeother(next or place.url)
            elif not new_place.writable_by(user):
                return render.access_restricted()
            else:
                person.update(place_id=new_place.id)
                flash.add_flash_message("success", "Assigned {0} to {1}".format(person.name, new_place.name))
                raise web.seeother(next or new_place.url)
        elif i.action in ("make-ward-coordinator", 'make-ac-coordinator', 'make-pc-coordinator'):
            type = i.action.split("-")[1]
            parent = place.get_parent(type)
            if not parent or not parent.writable_by(user):
                return render.access_restricted()
            parent.add_volunteer(name=person.name, email=person.email, phone=person.phone, role='coordinator')
            raise web.seeother(parent.url)
        raise web.seeother(place.url)


        raise web.seeother(place.url)
Esempio n. 22
0
    def POST(self, key):
        place = Place.find(key=key)
        self.check_write_access(place)

        if not place:
            raise web.notfound()
        elif not place.writable_by(account.get_current_user()):
            raise web.seeother(place.url + "/users")

        i = web.input()
        form = self.make_form(i)
        if form.validate():
            place.add_volunteer(i.name.strip(), i.email.strip(), i.phone.strip(), i.voterid.strip(), i.role.strip())
            raise web.redirect(place.url + "/users")
        else:
            return render.add_people(place, form, add_users=True)
Esempio n. 23
0
def email_fill_voterid(place_key):
    """Reminds all PB volunteers who have not filled their voter ID
    in the specified place to fill it.

    place can be a PC/AC or a WARD.
    """
    place = Place.find(place_key)
    if not place:
        raise ValueError("Invalid place {0}".format(place_key))

    agents = [a for a in place.get_pb_agents() if a.email and not a.voterid]

    pool = ThreadPool(20)
    def sendmail(a):
        utils.sendmail_voterid_pending(a)
    pool.map(sendmail, agents)
Esempio n. 24
0
    def g(self, code, *args):
        place = Place.find(key=code)
        if not place:
            raise web.notfound()

        if types is not None and place.type not in types:
            raise web.notfound()

        user = account.get_current_user()

        if not user or not place.viewable_by(user):
            raise web.ok(render.access_restricted())

        if roles:
            if not user or not place.writable_by(user, roles=roles):
                return render.permission_denied(user=user)
        return f(self, place, *args)
Esempio n. 25
0
    def POST(self, code, date):
        place = Place.find(key=code)
        if not place:
            raise web.notfound()

        user = account.get_current_user()
        if not place.writable_by(user, roles=['coordinator', 'volunteer', 'admin']):
            raise web.seeother(place.url)

        data = json.loads(web.data())['data']

        # skip empty rows
        data = [row for row in data if any(row)]

        place.add_coverage(date, data, account.get_current_user())
        web.header("content-type", "application/json")
        return '{"result": "ok"}'
Esempio n. 26
0
def add_invites(place_key, filename, batch):
    from webapp import import_people

    place = Place.find(place_key)
    if not place:
        raise ValueError("Invalid place {0}".format(place_key))

    rows = [line.strip("\n").split("\t") for line in open(filename) if line.strip()]
    re_badchars = re.compile("[^A-Za-z0-9 \.-]+")
    count = 0
    with get_db().transaction():
        for row in rows:
            name, phone, email = row
            name = re_badchars.sub("", name).strip()
            d = web.storage(name=name, phone=phone, email=email, place=None, role=None)
            if import_people().add_volunteer(d, place, batch=batch, as_invite=True):
                count += 1
    logger.info("imported %s people", count)
Esempio n. 27
0
    def add_volunteer(self, row, ac, batch, as_invite):
        if not row.name:
            return

        if row.place:
            key = ac.key + "/" + row.place.split("-")[0].strip()
            place = Place.find(key)
            if not place:
                return
        else:
            place = ac
        if row.email and place.find_volunteer(email=row.email, phone=None, role=row.role):
            logger.warn("Already found a vol with same email and role. Ignoring this %s", row)
            return
        if row.phone and place.find_volunteer(email=None, phone=row.phone, role=row.role):
            logger.warn("Already found a vol with same phone number and role. Ignoring this %s", row)
            return
        if not row.email and not row.phone:
            logger.warn("No email/phone number specified. Ignoring this %s", row)
            return

        if as_invite:
            if not row.email:
                logger.warn("Can't add invite as no email provided. Ignoring this %s", row)
                return
            if Invite.find_by_email(row.email):
                logger.warn("Already found an invite with the same email. Ignoring this %s", row)
                return

            place.add_invite(       
                name=row.name, 
                phone=row.phone, 
                email=row.email, 
                batch=batch)
        else:
            place.add_volunteer(
                name=row.name, 
                phone=row.phone, 
                email=row.email, 
                voterid=row.voterid, 
                role=row.role,
                notes=batch)
        return True
Esempio n. 28
0
 def POST(self, source):
     i = web.input()
     form = SignupForm(i)
     if form.validate():
         notes = "signup"
         if source:
             notes = notes + " " + source
         place = Place.find(i.ward)
         agent = place.add_volunteer(
             name=i.name, 
             phone=i.phone,
             email=i.email,
             voterid=i.voterid,
             role='pb_agent',
             notes=notes)
         agent.populate_voterid_info()
         if agent.get_voterid_info():
             utils.sendmail_voterid_added(agent)
         else:
             utils.sendmail_voterid_pending(agent)
         return render.thankyou(place, agent)
     else:
         return render.signup(form)
Esempio n. 29
0
def place_list():
    object_list = (p for p in Place.find() if not p._data.get('placeref'))
    return render_template('place_list.html', object_list=object_list)
Esempio n. 30
0
def map_places():
    places = [p for p in Place.find()]
    print('places gathered, rendering template...')
    return render_template('map_places.html', places=places)
Esempio n. 31
0
def map_circles_integrated():
    places = [p for p in Place.find() if list(p.events)]
    return render_template('map_circles_integrated.html', places=places)
Esempio n. 32
0
def map_circles_integrated():
    places = [p for p in Place.find() if list(p.events)]
    return render_template('map_circles_integrated.html', places=places)
Esempio n. 33
0
def map_places():
    places = [p for p in Place.find()]
    print('places gathered, rendering template...')
    return render_template('map_places.html', places=places)