예제 #1
0
 def test_get_by_block(self):
     election_codes = ['102000638','102000648','102000665','31000053']
     block = {
         'precinct_id': 3703,
         'street_name': 'BRUCE',
         'street_type': 'ST',
         'low_addr': '',
         'high_addr': '',
         'odd_even': ''
     }
     voters = Voter.get_by_block(block, election_codes)
     block = {
         'precinct_id': 3703,
         'street_name': 'BRUCE',
         'street_type': 'ST',
         'low_addr': '1001',
         'high_addr': '1033',
         'odd_even': ''
     }
     voters = Voter.get_by_block(block, election_codes)
     block = {
         'precinct_id': 3703,
         'street_name': 'BRUCE',
         'street_type': 'ST',
         'low_addr': '1001',
         'high_addr': '1033',
         'odd_even': 'O',
     }
     voters = Voter.get_by_block(block, election_codes)
     pass
예제 #2
0
def analyze():
    from models.contact import Contact
    from models.voter import Voter

    contacts = Contact.get_all(dao)

    probs = {
        'reg': [], 'name': [], 'vrec': [],
        'addr': [], 'pct': []
    }

    for contact in contacts:
        if not contact.voter_id:
            probs['reg'].append(bld_row(contact))
            continue
        voter = Voter.get_one(dao, contact.voter_id)
        if not voter:
            matches = Voter.get_by_name(dao, contact.name)
            if len(matches) == 1:
                show('No voter registration:', contact, matches[0])
                reply = input('Copy voter?').upper()
                if reply == 'Y':
                    repair(contact, matches[0])
                else:
                    probs['vrec'].append(bld_row(contact))
                    for match in matches:
                        probs['vrec'].append(bld_row(match))
            continue
        if str(contact.name) != str(voter.name):
            show('Name mismatch:', contact, voter)
            reply = input('Copy voter?').upper()
            if reply == 'Y':
                repair(contact, voter)
            else:
                probs['name'].append((bld_row(contact), bld_row(voter)))
            continue
        if str(contact.address) != str(voter.address):
            show('Address mismatch:', contact, voter)
            reply = input('Copy voter?').upper()
            if reply == 'Y':
                repair(contact, voter)
            else:
                probs['addr'].append((bld_row(contact), bld_row(voter)))
            continue
        if contact.address.precinct_id != voter.address.precinct_id:
            show('Precinct mismatch:', contact, voter)
            reply = input('Copy voter?').upper()
            if reply == 'Y':
                repair(contact, voter)
            else:
                probs['pct'].append((bld_row(contact), bld_row(voter)))
    return probs
예제 #3
0
    def synchronize(dao):
        # from models.dao import Dao
        from models.voter import Voter

        # dao = Dao(stateful=True)
        contacts = Contact.get_all(dao)
        problems = {'reg': [], 'name': [], 'vrec': [], 'addr': [], 'pct': []}
        for contact in contacts:
            if not contact.voter_id:
                problems['reg'].append(contact)
                continue
            voter = Voter.get_one(dao, contact.voter_id)
            if not voter:
                problems['vrec'].append([
                    contact.id,
                    str(contact.name),
                    str(contact.address), contact.address.city,
                    contact.address.zipcode, contact.address.precinct_id, None
                ])
                continue
            if str(contact.name) != str(voter.name):
                problems['name'].append((str(contact.name), str(voter.name)))
                continue
            if str(contact.address) != str(voter.address):
                problems['addr'].append(contact)
                continue
            if contact.address.precinct_id != voter.address.precinct_id:
                problems['pct'].append(contact)
            # contact.copy_voter(voter)
            # contact.update(dao)
        return problems
예제 #4
0
    def get_best_voter_rec(dao, contact):
        from models.voter import Voter

        candidates = Voter.voters_by_name_and_address(dao, contact.address,
                                                      contact.name)
        if not candidates:
            return None
        streets = set(
            [candidate.address.street_name for candidate in candidates])
        best_street = MatchLib.get_best_match(contact.address.street_name,
                                              streets, 85)
        if not best_street:
            return None
        candidates = [
            candidate for candidate in candidates
            if candidate.address.street_name == best_street
        ]
        best_name = MatchLib.get_best_match(
            str(contact), [str(candidate.name) for candidate in candidates],
            85)
        if not best_name:
            return None
        return [
            candidate for candidate in candidates
            if str(candidate.name) == best_name
        ][0]
예제 #5
0
def assign_precinct():
    from models.precinct import Precinct

    if request.method == 'GET':
        precincts = Precinct.get_all()
        contacts = Contact.get_with_missing_precinct()
        return render_template('contacts/con_precinct.html',
                               title='Unassigned Precinct',
                               precincts=precincts,
                               contacts=contacts)

    params = json.loads(request.form['params'])
    contact = Contact(params)
    dao = Dao(stateful=True)
    if 'voter_id' in params and params['voter_id']:
        voter = Voter.get_one(dao, params['voter_id'])
        nickname = contact.name.first
        contact.name = voter.name
        contact.name.nickname = nickname
        contact.address = voter.address
        contact.reg_date = voter.reg_date
    try:
        contact.update(dao)
        return jsonify(msg="Update successful!")
    except Exception as ex:
        return jsonify(error=str(ex))
    finally:
        dao.close()
예제 #6
0
def csv_import():
    from models.turf import Turf
    from models.submission import Submission

    if request.method == 'GET':
        return render_template('voters/voter_import.html',
                               title='Voter Import')

    data = json.loads(request.form['params'])['data']
    cities = Turf.get_cities()
    submissions = [
        Submission.from_web(rec, cities) for rec in data if rec['data0']
    ]
    Voter.batch_lookup(submissions)
    return jsonify(
        lookups=[submission.serialize() for submission in submissions])
예제 #7
0
def voter_lookup():
    from models.voter import Voter

    contact = json.loads(request.form['params'])
    try:
        voters = Voter.fuzzy_lookup(contact)
        candidates = [voter.serialize() for voter in voters]
        return jsonify(candidates=candidates)
    except Exception as ex:
        return jsonify(error=str(ex))
def run_test():
    cities = Address.get_cities()
    f = open('voter_test.csv', 'r')
    rdr = csv.reader(f)
    submissions = [Submission.from_csv(row, cities, with_contact=False) for row in rdr]
    lookups = Voter.lookup(submissions)
    for lookup in lookups:
        print(str(lookup.name), str(lookup.address))
        for match in lookup.matches:
            print(str(match), str(match.address))
        print('\n')
예제 #9
0
def run_test():
    cities = Address.get_cities()
    f = open('voter_test.csv', 'r')
    rdr = csv.reader(f)
    submissions = [
        Submission.from_csv(row, cities, with_contact=False) for row in rdr
    ]
    lookups = Voter.lookup(submissions)
    for lookup in lookups:
        print(str(lookup.name), str(lookup.address))
        for match in lookup.matches:
            print(str(match), str(match.address))
        print('\n')
예제 #10
0
def lookup():
    dao = Dao()
    matches = Voter.lookup(dao, request.args)
    result = [{
        'name': str(match.name),
        'address': str(match.address),
        'city': match.address.city,
        'zipcode': match.address.zipcode,
        'gender': match.gender,
        'birth_year': match.birth_year,
        'voter_id': match.id
    } for match in matches]
    return jsonify(matches=result)
예제 #11
0
def get_vrex(d):
    from models.voter import Voter

    flds = name_flds + ', ' + addr_flds + ', ' + pct_flds + ', ' + rec_flds
    sql = ("SELECT %s "
           "FROM voters "
           "WHERE last_name=? "
           "AND first_name=? "
           "AND middle_name=? "
           "ORDER BY reg_date;") % (flds, )
    vals = (d['last_name'], d['first_name'], d['middle_name'])
    rex = dao.execute(sql, vals)
    return [Voter(rec) for rec in rex]
예제 #12
0
def worksheet():
    from models.address import Address
    from models.election import Election

    if request.method == 'GET':
        dao = Dao()
        jurisdictions = Turf.get_jurisdictions(dao)
        return render_template('voters/worksheet.html',
                               title='Voter Worksheet',
                               jurisdictions=jurisdictions)

    blocks = json.loads(request.form['params'])['blocks']
    dao = Dao(stateful=True)
    elections = Election.get(dao)

    data = []

    for block in blocks:
        data += Voter.get_by_block(dao, block, elections)
    voters = []

    dao.close()

    for voter in data:
        v = [
            voter['last_name'], voter['first_name'], voter['middle_name'],
            voter['name_suffix'],
            str(Address(voter)), voter['city'], voter['zipcode'],
            voter['gender'],
            str(voter['birth_year']),
            voter['party'] if voter['party'] else 'N', voter['voter_id'],
            voter['reg_date'], voter['permanent_absentee']
            if voter['permanent_absentee'] else 'N', voter['status'],
            voter['uocava']
        ]
        for election in elections:
            v.append(voter[election['date']])
        voters.append(v)

    return jsonify(elections=[
        election['date'] + ":" + election['description']
        for election in elections
    ],
                   voters=voters)
예제 #13
0
def voter_lookup():
    from models.voter import Voter

    contact = json.loads(request.form['params'])
    dao = Dao(stateful=True)
    try:
        voters = Voter.lookup(dao, contact)
        candidates = [{
            'name': {
                'last': voter.name.last,
                'first': voter.name.first,
                'middle': voter.name.middle,
                'suffix': voter.name.suffix
            },
            'address': {
                'house_number': voter.address.house_number,
                'pre_direction': voter.address.pre_direction,
                'street_name': voter.address.street_name,
                'street_type': voter.address.street_type,
                'suf_direction': voter.address.suf_direction,
                'unit': voter.address.unit,
                'city': voter.address.city,
                'zipcode': voter.address.zipcode
            },
            'voter_info': {
                'voter_id': voter.voter_id,
                'precinct_id': voter.precinct_id,
                'birth_year': voter.birth_year,
                'gender': voter.gender,
                'reg_date': voter.reg_date
            }
        } for voter in voters]
        return jsonify(candidates=candidates)
    except Exception as ex:
        return jsonify(error=str(ex))
    finally:
        dao.close()
예제 #14
0
def to_local_format(voters):
    for voter in voters:
        vtr_obj = Voter(voter)
        voter['name'] = str(vtr_obj.name)
        voter['address'] = str(vtr_obj.address)
    return voters
예제 #15
0
def create_eligible_list():

    if request.method == 'POST':

        print(request.form)

        success = False
        curr_session = db.session

        sendList = []

        try:
            data = (request.form.to_dict())["data"]
            data = json.loads(data)
            electionId = int(data["electionId"])
            electionName = db.engine.execute(
                "SELECT electionName FROM Elections where electionId = " +
                str(electionId)).fetchone()
            electionName = electionName[0]
            hostId = data["hostId"]
            print(electionId)
            print(hostId)
            lst = json.loads(data["id"])
            for voterId in lst:
                listMember = {}
                print("VoterId Recieved ==> " + str(voterId))
                otp = gen_otp()

                electionId = int(electionId)

                voter = Voter(electionId=electionId, id=voterId, otp=otp)

                print("Printing == > ")
                print("==> making Object")

                listMember["voterId"] = voterId
                listMember["electionId"] = electionId
                listMember["otp"] = otp

                curr_session.add(voter)

                print("==> Current session added")
                sendList.append(listMember)

        except Exception as e:
            return render_template(
                "/frontpage.html",
                display=getDisplay(),
                alert="Error in creating the List of eligible voters.")

        try:
            curr_session.commit()
            success = True

            for eligibleVoter in sendList:
                send_email(electionId=eligibleVoter["electionId"],
                           voterId=eligibleVoter["voterId"],
                           otp=eligibleVoter["otp"])

        except Exception as err:
            print(err)
            curr_session.roll_back()
            curr_session.flush()

        if success:
            return render_template("/frontpage.html",
                                   display=getDisplay(),
                                   alert="Successfully Hosted the election")
        return render_template("/frontpage.html",
                               display=getDisplay(),
                               alert="Error in hosting the election")
    return render_template("/frontpage.html",
                           display=getDisplay(),
                           alert="Method Not allowed.")
예제 #16
0
def get_voter():
    dao = Dao(stateful=True)
    voter = Voter.get_voter(dao, request.args['voter_id'])
    dao.close()
    return jsonify(voter=voter)
예제 #17
0
def get_voter(voter_id):
    sql = "SELECT * FROM voters WHERE voter_id=?;"
    rex = dao.execute(sql, (voter_id, ))
    return Voter(rex[0]) if rex else None
예제 #18
0
def add_many(dao, data):
    voters = [Voter(d) for d in data]
    values = [voter.get_values() for voter in voters]
    dao.add_many('voters', db_cols, values)