def retrieve_and_store_ballot_for_voter(voter_id, text_for_map_search=''):
    google_civic_election_id = 0
    if not positive_value_exists(text_for_map_search):
        # Retrieve it from voter address
        voter_address_manager = VoterAddressManager()
        text_for_map_search = voter_address_manager.retrieve_ballot_map_text_from_voter_id(voter_id)

    if positive_value_exists(text_for_map_search):
        one_ballot_results = retrieve_one_ballot_from_google_civic_api(text_for_map_search)
        if one_ballot_results['success']:
            one_ballot_json = one_ballot_results['structured_json']

            # We update VoterAddress with normalized address data in store_one_ballot_from_google_civic_api

            store_one_ballot_results = store_one_ballot_from_google_civic_api(one_ballot_json, voter_id)
            if store_one_ballot_results['success']:
                status = 'RETRIEVED_AND_STORED_BALLOT_FOR_VOTER'
                success = True
                google_civic_election_id = store_one_ballot_results['google_civic_election_id']
            else:
                status = 'UNABLE_TO-store_one_ballot_from_google_civic_api'
                success = False
        else:
            status = 'UNABLE_TO-retrieve_one_ballot_from_google_civic_api'
            success = False
    else:
        status = 'MISSING_ADDRESS_TEXT_FOR_BALLOT_SEARCH'
        success = False

    results = {
        'google_civic_election_id': google_civic_election_id,
        'success': success,
        'status': status,
    }
    return results
Example #2
0
def voter_address_save(voter_device_id, address_raw_text,
                       address_variable_exists):
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        return HttpResponse(json.dumps(results['json_data']),
                            content_type='application/json')

    if not address_variable_exists:
        json_data = {
            'status': "MISSING_POST_VARIABLE-ADDRESS",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if voter_id < 0:
        json_data = {
            'status': "VOTER_NOT_FOUND_FROM_DEVICE_ID",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    # At this point, we have a valid voter

    voter_address_manager = VoterAddressManager()
    address_type = BALLOT_ADDRESS

    # We wrap get_or_create because we want to centralize error handling
    results = voter_address_manager.update_or_create_voter_address(
        voter_id, address_type, address_raw_text.strip())
    if results['success']:
        json_data = {
            'status': "VOTER_ADDRESS_SAVED",
            'success': True,
            'voter_device_id': voter_device_id,
            'address': address_raw_text,
        }
    # elif results['status'] == 'MULTIPLE_MATCHING_ADDRESSES_FOUND':
    # delete all currently matching addresses and save again
    else:
        json_data = {
            'status': results['status'],
            'success': False,
            'voter_device_id': voter_device_id,
        }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Example #3
0
def voter_address_save(voter_device_id, address_raw_text, address_variable_exists):
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        return HttpResponse(json.dumps(results['json_data']), content_type='application/json')

    if not address_variable_exists:
        json_data = {
                'status': "MISSING_POST_VARIABLE-ADDRESS",
                'success': False,
                'voter_device_id': voter_device_id,
            }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if voter_id < 0:
        json_data = {
            'status': "VOTER_NOT_FOUND_FROM_DEVICE_ID",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    # At this point, we have a valid voter

    voter_address_manager = VoterAddressManager()
    address_type = BALLOT_ADDRESS

    # We wrap get_or_create because we want to centralize error handling
    results = voter_address_manager.update_or_create_voter_address(voter_id, address_type, address_raw_text.strip())
    if results['success']:
        json_data = {
                'status': "VOTER_ADDRESS_SAVED",
                'success': True,
                'voter_device_id': voter_device_id,
                'address': address_raw_text,
            }
    # elif results['status'] == 'MULTIPLE_MATCHING_ADDRESSES_FOUND':
        # delete all currently matching addresses and save again
    else:
        json_data = {
                'status': results['status'],
                'success': False,
                'voter_device_id': voter_device_id,
            }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Example #4
0
def voter_address_retrieve(voter_device_id):
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        return HttpResponse(json.dumps(results['json_data']), content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if voter_id < 0:
        json_data = {
            'status': "VOTER_NOT_FOUND_FROM_VOTER_DEVICE_ID",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    voter_address_manager = VoterAddressManager()
    results = voter_address_manager.retrieve_ballot_address_from_voter_id(voter_id)

    if results['voter_address_found']:
        voter_address = results['voter_address']
        json_data = {
            'voter_device_id': voter_device_id,
            'address_type': voter_address.address_type if voter_address.address_type else '',
            'address': voter_address.address if voter_address.address else '',
            'latitude': voter_address.latitude if voter_address.latitude else '',
            'longitude': voter_address.longitude if voter_address.longitude else '',
            'normalized_line1': voter_address.normalized_line1 if voter_address.normalized_line1 else '',
            'normalized_line2': voter_address.normalized_line2 if voter_address.normalized_line2 else '',
            'normalized_city': voter_address.normalized_city if voter_address.normalized_city else '',
            'normalized_state': voter_address.normalized_state if voter_address.normalized_state else '',
            'normalized_zip': voter_address.normalized_zip if voter_address.normalized_zip else '',
            'success': True,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
    else:
        json_data = {
            'status': "VOTER_ADDRESS_NOT_RETRIEVED",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
Example #5
0
def voter_ballot_items_retrieve_for_api(voter_device_id,
                                        google_civic_election_id):
    status = ''

    # We retrieve voter_device_link
    voter_device_link_manager = VoterDeviceLinkManager()
    voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(
        voter_device_id)
    if not voter_device_link_results['voter_device_link_found']:
        status += "VALID_VOTER_DEVICE_ID_MISSING "
        error_json_data = {
            'status': status,
            'success': False,
            'voter_device_id': voter_device_id,
            'ballot_found': False,
            'ballot_item_list': [],
            'google_civic_election_id': google_civic_election_id,
            'text_for_map_search': '',
            'substituted_address_nearby': '',
            'ballot_caveat': '',
            'is_from_substituted_address': False,
            'is_from_test_ballot': False,
        }
        return error_json_data

    voter_device_link = voter_device_link_results['voter_device_link']
    voter_id = voter_device_link.voter_id

    if not positive_value_exists(voter_id):
        status += " " + "VALID_VOTER_ID_MISSING"
        error_json_data = {
            'status': status,
            'success': False,
            'voter_device_id': voter_device_id,
            'ballot_found': False,
            'ballot_item_list': [],
            'google_civic_election_id': google_civic_election_id,
            'text_for_map_search': '',
            'substituted_address_nearby': '',
            'ballot_caveat': '',
            'is_from_substituted_address': False,
            'is_from_test_ballot': False,
        }
        return error_json_data

    voter_address_manager = VoterAddressManager()
    voter_address_id = 0
    address_type = BALLOT_ADDRESS
    voter_address_results = voter_address_manager.retrieve_address(
        voter_address_id, voter_id, address_type)
    status += " " + voter_address_results['status']
    if not positive_value_exists(
            voter_address_results['voter_address_has_value']):
        error_json_data = {
            'status': status,
            'success': voter_address_results['success'],
            'voter_device_id': voter_device_id,
            'ballot_found': False,
            'ballot_item_list': [],
            'google_civic_election_id': 0,
            'text_for_map_search': '',
            'substituted_address_nearby': '',
            'ballot_caveat': '',
            'is_from_substituted_address': False,
            'is_from_test_ballot': False,
        }
        return error_json_data

    voter_address = voter_address_results['voter_address']

    results = choose_election_and_prepare_ballot_data(
        voter_device_link, google_civic_election_id, voter_address)
    status += " " + results['status']
    if not results['voter_ballot_saved_found']:
        if positive_value_exists(voter_address.text_for_map_search):
            ballot_caveat = "We could not find a ballot near '{text_for_map_search}'.".format(
                text_for_map_search=voter_address.text_for_map_search)
        else:
            ballot_caveat = "Please save your address so we can find your ballot."

        error_json_data = {
            'status': status,
            'success': True,
            'voter_device_id': voter_device_id,
            'ballot_found': False,
            'ballot_item_list': [],
            'google_civic_election_id': 0,
            'text_for_map_search': voter_address.text_for_map_search,
            'substituted_address_nearby': '',
            'ballot_caveat': ballot_caveat,
            'is_from_substituted_address': False,
            'is_from_test_ballot': False,
        }
        return error_json_data

    google_civic_election_id = results['google_civic_election_id']
    voter_ballot_saved = results['voter_ballot_saved']

    # Update voter_device_link
    if voter_device_link.google_civic_election_id != google_civic_election_id:
        voter_device_link_manager.update_voter_device_link_with_election_id(
            voter_device_link, google_civic_election_id)

    # Update voter_address to include matching google_civic_election_id and voter_ballot_saved entry
    if positive_value_exists(google_civic_election_id):
        voter_address.google_civic_election_id = google_civic_election_id
        voter_address_manager.update_existing_voter_address_object(
            voter_address)

        # Get and return the ballot_item_list
        results = voter_ballot_items_retrieve_for_one_election_for_api(
            voter_device_id, voter_id, google_civic_election_id)

        if not positive_value_exists(voter_ballot_saved.election_description_text) \
                or not positive_value_exists(voter_ballot_saved.election_date_text()):
            try:
                election_manager = ElectionManager()
                election_results = election_manager.retrieve_election(
                    google_civic_election_id)
                if election_results['election_found']:
                    election = election_results['election']
                    if not positive_value_exists(
                            voter_ballot_saved.election_description_text):
                        voter_ballot_saved.election_description_text = election.election_name
                    if not positive_value_exists(
                            voter_ballot_saved.election_date_text()):
                        voter_ballot_saved.election_date = \
                            datetime.strptime(election.election_day_text, "%Y-%m-%d").date()
                    voter_ballot_saved.save()
            except Exception as e:
                status += "Failed to update election_name"

        status += " " + results['status']
        json_data = {
            'status': status,
            'success': True,
            'voter_device_id': voter_device_id,
            'ballot_found': True,
            'ballot_item_list': results['ballot_item_list'],
            'google_civic_election_id': google_civic_election_id,
            'election_name': voter_ballot_saved.election_description_text,
            'election_date': voter_ballot_saved.election_date_text(),
            'text_for_map_search':
            voter_ballot_saved.original_text_for_map_search,
            'substituted_address_nearby':
            voter_ballot_saved.substituted_address_nearby,
            'ballot_caveat': voter_ballot_saved.ballot_caveat(),
            'is_from_substituted_address':
            voter_ballot_saved.is_from_substituted_address,
            'is_from_test_ballot': voter_ballot_saved.is_from_test_ballot,
        }
        return json_data

    status += " " + "NO_VOTER_BALLOT_SAVED_FOUND"
    error_json_data = {
        'status': status,
        'success': True,
        'voter_device_id': voter_device_id,
        'ballot_found': False,
        'ballot_item_list': [],
        'google_civic_election_id': 0,
        'text_for_map_search': '',
        'substituted_address_nearby': '',
        'ballot_caveat': '',
        'is_from_substituted_address': False,
        'is_from_test_ballot': False,
    }
    return error_json_data
Example #6
0
def figure_out_google_civic_election_id_voter_is_watching(voter_device_id):
    status = ''

    # We zero out this value  since we will never have this coming in for this function
    google_civic_election_id = 0

    # We retrieve voter_device_link
    voter_device_link_manager = VoterDeviceLinkManager()
    voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(
        voter_device_id)
    if not voter_device_link_results['voter_device_link_found']:
        status += "VALID_VOTER_DEVICE_ID_MISSING: " + voter_device_link_results[
            'status']
        results = {
            'status': status,
            'success': False,
            'voter_device_id': voter_device_id,
            'voter_device_link_found': False,
            'voter_address_object_found': False,
            'voter_ballot_saved_found': False,
            'google_civic_election_id': 0,
        }
        return results

    voter_device_link = voter_device_link_results['voter_device_link']
    voter_id = voter_device_link.voter_id

    if not positive_value_exists(voter_id):
        status += " " + "VALID_VOTER_ID_MISSING"
        results = {
            'status': status,
            'success': False,
            'voter_device_id': voter_device_id,
            'voter_device_link_found': False,
            'voter_address_object_found': False,
            'voter_ballot_saved_found': False,
            'google_civic_election_id': 0,
        }
        return results

    voter_address_manager = VoterAddressManager()
    voter_address_id = 0
    address_type = BALLOT_ADDRESS
    voter_address_results = voter_address_manager.retrieve_address(
        voter_address_id, voter_id, address_type)
    status += " " + voter_address_results['status']
    if not positive_value_exists(
            voter_address_results['voter_address_has_value']):
        # If there isn't an address with a value, then there won't be a voter_ballot_saved_found
        results = {
            'status':
            status,
            'success':
            True,
            'voter_device_id':
            voter_device_id,
            'voter_device_link_found':
            False,
            'voter_address_object_found':
            voter_address_results['voter_address_found'],
            'voter_ballot_saved_found':
            False,
            'google_civic_election_id':
            0,
        }
        return results

    voter_address = voter_address_results['voter_address']

    # This routine finds a ballot saved for this voter
    choose_election_results = choose_election_from_existing_data(
        voter_device_link, google_civic_election_id, voter_address)
    status += " " + choose_election_results['status']
    results = {
        'status':
        status,
        'success':
        choose_election_results['success'],
        'voter_device_id':
        voter_device_id,
        'voter_device_link_found':
        True,
        'voter_address_object_found':
        voter_address_results['voter_address_found'],
        'voter_ballot_saved_found':
        choose_election_results['voter_ballot_saved_found'],
        'google_civic_election_id':
        choose_election_results['google_civic_election_id'],
    }
    return results
Example #7
0
def voter_ballot_items_retrieve_from_google_civic_for_api(
        voter_device_id, text_for_map_search='', use_test_election=False):
    """
    We are telling the server to explicitly reach out to the Google Civic API and retrieve the ballot items
    for this voter.
    """
    # Confirm that we have a Google Civic API Key (GOOGLE_CIVIC_API_KEY)
    if not positive_value_exists(GOOGLE_CIVIC_API_KEY):
        results = {
            'status': 'NO_GOOGLE_CIVIC_API_KEY',
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    # Confirm that we have the URL where we retrieve voter ballots (VOTER_INFO_URL)
    if not positive_value_exists(VOTER_INFO_URL):
        results = {
            'status': 'MISSING VOTER_INFO_URL in config/environment_variables.json',
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    # Get voter_id from the voter_device_id so we can figure out which ballot_items to offer
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        results = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        results = {
            'status': "VALID_VOTER_ID_MISSING",
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    google_civic_election_id = 0
    status = ''
    success = False
    election_date_text = ''
    election_description_text = ''
    election_data_retrieved = False
    polling_location_retrieved = False
    contests_retrieved = False
    if not positive_value_exists(text_for_map_search):
        # Retrieve it from voter address
        voter_address_manager = VoterAddressManager()
        text_for_map_search = voter_address_manager.retrieve_ballot_map_text_from_voter_id(voter_id)

    if positive_value_exists(text_for_map_search):
        one_ballot_results = retrieve_one_ballot_from_google_civic_api(
            text_for_map_search, google_civic_election_id, use_test_election)

        if one_ballot_results['success']:
            one_ballot_json = one_ballot_results['structured_json']
            election_date_text = one_ballot_json['election']['electionDay']
            election_description_text = one_ballot_json['election']['name']

            # We may receive some election data, but not all of the data we need
            if one_ballot_results['election_data_retrieved']:
                election_data_retrieved = True
                success = True

            if one_ballot_results['polling_location_retrieved']:
                polling_location_retrieved = True
                success = True

            if one_ballot_results['contests_retrieved']:
                contests_retrieved = True

                # Now that we know we have new ballot data, we need to delete prior ballot data for this election
                # because when we change voterAddress, we usually get different ballot items
                ballot_item_list_manager = BallotItemListManager()
                # We include a google_civic_election_id, so only the ballot info for this election is removed
                google_civic_election_id_to_delete = one_ballot_json['election']['id']  # '0' would mean "delete all"
                if positive_value_exists(google_civic_election_id_to_delete):
                    ballot_item_list_manager.delete_all_ballot_items_for_voter(
                        voter_id, google_civic_election_id_to_delete)

                # store_on_ballot... adds an entry to the BallotReturned table
                # We update VoterAddress with normalized address data in store_one_ballot_from_google_civic_api
                store_one_ballot_results = store_one_ballot_from_google_civic_api(one_ballot_json, voter_id)
                if store_one_ballot_results['success']:
                    status += 'RETRIEVED_FROM_GOOGLE_CIVIC_AND_STORED_BALLOT_FOR_VOTER '
                    success = True
                    google_civic_election_id = store_one_ballot_results['google_civic_election_id']
                else:
                    status += 'UNABLE_TO-store_one_ballot_from_google_civic_api'
        elif 'error' in one_ballot_results['structured_json']:
            if one_ballot_results['structured_json']['error']['message'] == 'Election unknown':
                success = False  # It is only successful if new ballot data is retrieved.
            else:
                success = False
            status += "GOOGLE_CIVIC_API_ERROR: " + one_ballot_results['structured_json']['error']['message']

        else:
            status += 'UNABLE_TO-retrieve_one_ballot_from_google_civic_api'
            success = False
    else:
        status += 'MISSING_ADDRESS_TEXT_FOR_BALLOT_SEARCH'
        success = False

    # If a google_civic_election_id was not returned, outside of this function we search again using a test election,
    # so that during our initial user testing, ballot data is returned in areas where elections don't currently exist

    results = {
        'success': success,
        'status': status,
        'voter_device_id': voter_device_id,
        'google_civic_election_id': google_civic_election_id,
        'text_for_map_search': text_for_map_search,
        'election_date_text': election_date_text,
        'election_description_text': election_description_text,
        'election_data_retrieved': election_data_retrieved,
        'polling_location_retrieved': polling_location_retrieved,
        'contests_retrieved': contests_retrieved,
    }
    return results
Example #8
0
def store_one_ballot_from_google_civic_api(one_ballot_json, voter_id=0, polling_location_we_vote_id=''):
    """
    When we pass in a voter_id, we want to save this ballot related to the voter.
    When we pass in polling_location_we_vote_id, we want to save a ballot for that area, which is useful for
    getting new voters started by showing them a ballot roughly near them.
    """
    #     "election": {
    #     "electionDay": "2015-11-03",
    #     "id": "4162",
    #     "name": "Virginia General Election",
    #     "ocdDivisionId": "ocd-division/country:us/state:va"
    # },
    if 'election' not in one_ballot_json:
        results = {
            'status': 'BALLOT_JSON_MISSING_ELECTION',
            'success': False,
            'google_civic_election_id': 0,
        }
        return results

    election_date_text = ''
    election_description_text = ''
    if 'electionDay' in one_ballot_json['election']:
        election_date_text = one_ballot_json['election']['electionDay']
    if 'name' in one_ballot_json['election']:
        election_description_text = one_ballot_json['election']['name']

    if 'id' not in one_ballot_json['election']:
        results = {
            'status': 'BALLOT_JSON_MISSING_ELECTION_ID',
            'success': False,
            'google_civic_election_id': 0,
        }
        return results

    voter_address_dict = one_ballot_json['normalizedInput'] if 'normalizedInput' in one_ballot_json else {}
    if positive_value_exists(voter_id):
        if positive_value_exists(voter_address_dict):
            # When saving a ballot for an individual voter, use this data to update voter address with the
            #  normalized address information returned from Google Civic
            # "normalizedInput": {
            #   "line1": "254 hartford st",
            #   "city": "san francisco",
            #   "state": "CA",
            #   "zip": "94114"
            #  },
            voter_address_manager = VoterAddressManager()
            voter_address_manager.update_voter_address_with_normalized_values(
                voter_id, voter_address_dict)
            # Note that neither 'success' nor 'status' are set here because updating the voter_address with normalized
            # values isn't critical to the success of storing the ballot for a voter
    # We don't store the normalized address information when we capture a ballot for a polling location

    google_civic_election_id = one_ballot_json['election']['id']
    ocd_division_id = one_ballot_json['election']['ocdDivisionId']
    state_code = extract_state_from_ocd_division_id(ocd_division_id)
    if not positive_value_exists(state_code):
        # We have a backup method of looking up state from one_ballot_json['state']['name']
        # in case the ocd state fails
        state_name = ''
        if 'state' in one_ballot_json:
            if 'name' in one_ballot_json['state']:
                state_name = one_ballot_json['state']['name']
            elif len(one_ballot_json['state']) > 0:
                # In some cases, like test elections 2000 a list is returned in one_ballot_json['state']
                for one_state_entry in one_ballot_json['state']:
                    if 'name' in one_state_entry:
                        state_name = one_state_entry['name']
        state_code = convert_state_text_to_state_code(state_name)

    # Loop through all contests and store in local db cache
    if 'contests' in one_ballot_json:
        results = process_contests_from_structured_json(one_ballot_json['contests'], google_civic_election_id,
                                                        ocd_division_id, state_code, voter_id,
                                                        polling_location_we_vote_id)

        status = results['status']
        success = results['success']
    else:
        status = "STORE_ONE_BALLOT_NO_CONTESTS_FOUND"
        success = False

    # When saving a ballot for individual voter, loop through all pollingLocations and store in local db
    # process_polling_locations_from_structured_json(one_ballot_json['pollingLocations'])

    # If we successfully save a ballot, create/update a BallotReturned entry
    is_test_election = True if positive_value_exists(google_civic_election_id) \
        and convert_to_int(google_civic_election_id) == 2000 else False
    if success and positive_value_exists(voter_address_dict) and not is_test_election:
        ballot_returned_manager = BallotReturnedManager()
        if positive_value_exists(voter_id) and positive_value_exists(google_civic_election_id):
            results = ballot_returned_manager.retrieve_ballot_returned_from_voter_id(voter_id, google_civic_election_id)
            if results['ballot_returned_found']:
                update_results = ballot_returned_manager.update_ballot_returned_with_normalized_values(
                    voter_address_dict, results['ballot_returned'])
            else:
                create_results = ballot_returned_manager.create_ballot_returned_with_normalized_values(
                    voter_address_dict,
                    election_date_text, election_description_text,
                    google_civic_election_id, voter_id, '')
        if positive_value_exists(polling_location_we_vote_id) and positive_value_exists(google_civic_election_id):
            results = ballot_returned_manager.retrieve_ballot_returned_from_polling_location_we_vote_id(
                polling_location_we_vote_id, google_civic_election_id)
            if results['ballot_returned_found']:
                update_results = ballot_returned_manager.update_ballot_returned_with_normalized_values(
                    voter_address_dict, results['ballot_returned'])
            else:
                create_results = ballot_returned_manager.create_ballot_returned_with_normalized_values(
                    voter_address_dict,
                    election_date_text, election_description_text,
                    google_civic_election_id, 0, polling_location_we_vote_id)
        # Currently we don't report the success or failure of storing ballot_returned

    results = {
        'status': status,
        'success': success,
        'google_civic_election_id': google_civic_election_id,
    }
    return results
Example #9
0
def figure_out_google_civic_election_id_voter_is_watching(voter_device_id):
    status = ''

    # We zero out this value  since we will never have this coming in for this function
    google_civic_election_id = 0

    # We retrieve voter_device_link
    voter_device_link_manager = VoterDeviceLinkManager()
    voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(voter_device_id)
    if not voter_device_link_results['voter_device_link_found']:
        status += "VALID_VOTER_DEVICE_ID_MISSING: " + voter_device_link_results['status']
        results = {
            'status':                       status,
            'success':                      False,
            'voter_device_id':              voter_device_id,
            'voter_device_link_found':      False,
            'voter_address_object_found':   False,
            'voter_ballot_saved_found':     False,
            'google_civic_election_id':     0,
        }
        return results

    voter_device_link = voter_device_link_results['voter_device_link']
    voter_id = voter_device_link.voter_id

    if not positive_value_exists(voter_id):
        status += " " + "VALID_VOTER_ID_MISSING"
        results = {
            'status':                       status,
            'success':                      False,
            'voter_device_id':              voter_device_id,
            'voter_device_link_found':      False,
            'voter_address_object_found':   False,
            'voter_ballot_saved_found':     False,
            'google_civic_election_id':     0,
        }
        return results

    voter_address_manager = VoterAddressManager()
    voter_address_id = 0
    address_type = BALLOT_ADDRESS
    voter_address_results = voter_address_manager.retrieve_address(voter_address_id, voter_id, address_type)
    status += " " + voter_address_results['status']
    if not positive_value_exists(voter_address_results['voter_address_has_value']):
        # If there isn't an address with a value, then there won't be a voter_ballot_saved_found
        results = {
            'status':                       status,
            'success':                      True,
            'voter_device_id':              voter_device_id,
            'voter_device_link_found':      False,
            'voter_address_object_found':   voter_address_results['voter_address_found'],
            'voter_ballot_saved_found':     False,
            'google_civic_election_id':     0,
        }
        return results

    voter_address = voter_address_results['voter_address']

    # This routine finds a ballot saved for this voter
    choose_election_results = choose_election_from_existing_data(voter_device_link, google_civic_election_id,
                                                                 voter_address)
    status += " " + choose_election_results['status']
    results = {
        'status': status,
        'success': choose_election_results['success'],
        'voter_device_id': voter_device_id,
        'voter_device_link_found': True,
        'voter_address_object_found': voter_address_results['voter_address_found'],
        'voter_ballot_saved_found': choose_election_results['voter_ballot_saved_found'],
        'google_civic_election_id': choose_election_results['google_civic_election_id'],
    }
    return results
Example #10
0
def positions_count_for_all_ballot_items_for_api(voter_device_id, google_civic_election_id=0,
                                                 show_positions_this_voter_follows=True):
    """
    We want to return a JSON file with the a list of the support and oppose counts from the orgs, friends and
    public figures the voter follows
    """
    # Get voter_id from the voter_device_id so we can know whose stars to retrieve
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status':                   "VALID_VOTER_DEVICE_ID_MISSING-COUNT_FOR_ALL_BALLOT_ITEMS",
            'success':                  False,
            'google_civic_election_id': google_civic_election_id,
            'ballot_item_list':         [],
        }
        return json_data

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status':                   "VALID_VOTER_ID_MISSING-COUNT_FOR_ALL_BALLOT_ITEMS",
            'success':                  False,
            'google_civic_election_id': google_civic_election_id,
            'ballot_item_list':         [],
        }
        return json_data

    if not positive_value_exists(google_civic_election_id):
        # We must have an election id to proceed -- otherwise we don't know what ballot items to work with
        voter_device_link_manager = VoterDeviceLinkManager()
        voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(voter_device_id)
        if voter_device_link_results['voter_device_link_found']:
            voter_device_link = voter_device_link_results['voter_device_link']
            if positive_value_exists(voter_device_link.google_civic_election_id):
                google_civic_election_id = voter_device_link.google_civic_election_id
        if not positive_value_exists(google_civic_election_id):
            voter_address_manager = VoterAddressManager()
            voter_address_results = voter_address_manager.retrieve_address(0, voter_id)
            if voter_address_results['voter_address_found']:
                voter_address = voter_address_results['voter_address']
                if positive_value_exists(voter_address.google_civic_election_id):
                    google_civic_election_id = voter_address.google_civic_election_id
        google_civic_election_id = convert_to_int(google_civic_election_id)

    if not positive_value_exists(google_civic_election_id):
        json_data = {
            'status':                   "GOOGLE_CIVIC_ELECTION_ID_MISSING-COUNT_FOR_ALL_BALLOT_ITEMS",
            'success':                  False,
            'google_civic_election_id': google_civic_election_id,
            'ballot_item_list':         [],
        }
        return json_data

    position_list_manager = PositionListManager()
    candidate_list_object = CandidateCampaignList()

    follow_organization_list_manager = FollowOrganizationList()
    organizations_followed_by_voter = \
        follow_organization_list_manager.retrieve_follow_organization_by_voter_id_simple_id_array(voter_id)

    # Get a list of all candidates and measures from this election (in the active election)
    ballot_item_results = voter_ballot_items_retrieve_for_one_election_for_api(voter_device_id, voter_id,
                                                                               google_civic_election_id)
    ballot_item_list = ballot_item_results['ballot_item_list']

    # The list where we capture results
    ballot_item_list_results = []

    # ballot_item_list is populated with contest_office and contest_measure entries
    for one_ballot_item in ballot_item_list:
        # Retrieve all positions for each ballot item
        if one_ballot_item['kind_of_ballot_item'] == OFFICE:
            results = candidate_list_object.retrieve_all_candidates_for_office(0, one_ballot_item['we_vote_id'])
            success = results['success']
            candidate_list = results['candidate_list']

            if success:
                for candidate in candidate_list:
                    # Loop through all candidates under this office
                    support_positions_list_for_one_ballot_item = \
                        position_list_manager.retrieve_all_positions_for_candidate_campaign(
                            0, candidate.we_vote_id, SUPPORT)
                    oppose_positions_list_for_one_ballot_item = \
                        position_list_manager.retrieve_all_positions_for_candidate_campaign(
                            0, candidate.we_vote_id, OPPOSE)
                    finalize_results = finalize_support_and_oppose_positions_count(
                        voter_id, show_positions_this_voter_follows,
                        organizations_followed_by_voter,
                        support_positions_list_for_one_ballot_item,
                        oppose_positions_list_for_one_ballot_item)
                    one_ballot_item_results = {
                        'ballot_item_we_vote_id': candidate.we_vote_id,
                        'support_count': finalize_results['support_positions_count'],
                        'oppose_count': finalize_results['oppose_positions_count'],
                    }
                    ballot_item_list_results.append(one_ballot_item_results)
        elif one_ballot_item['kind_of_ballot_item'] == MEASURE:
            support_positions_list_for_one_ballot_item = \
                position_list_manager.retrieve_all_positions_for_contest_measure(0, one_ballot_item['we_vote_id'],
                                                                                 SUPPORT)
            oppose_positions_list_for_one_ballot_item = \
                position_list_manager.retrieve_all_positions_for_contest_measure(0, one_ballot_item['we_vote_id'],
                                                                                 OPPOSE)
            finalize_results = finalize_support_and_oppose_positions_count(
                voter_id, show_positions_this_voter_follows,
                organizations_followed_by_voter,
                support_positions_list_for_one_ballot_item,
                oppose_positions_list_for_one_ballot_item)
            one_ballot_item_results = {
                'ballot_item_we_vote_id': one_ballot_item['we_vote_id'],
                'support_count': finalize_results['support_positions_count'],
                'oppose_count': finalize_results['oppose_positions_count'],
            }
            ballot_item_list_results.append(one_ballot_item_results)
        else:
            # Skip the rest of this loop
            continue

    json_data = {
        'success':                  True,
        'status':                   "POSITIONS_COUNT_FOR_ALL_BALLOT_ITEMS",
        'google_civic_election_id': google_civic_election_id,
        'ballot_item_list':         ballot_item_list_results,
    }
    return json_data
Example #11
0
def voter_address_retrieve(voter_device_id):
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        return HttpResponse(json.dumps(results['json_data']),
                            content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if voter_id < 0:
        json_data = {
            'status': "VOTER_NOT_FOUND_FROM_VOTER_DEVICE_ID",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    voter_address_manager = VoterAddressManager()
    results = voter_address_manager.retrieve_ballot_address_from_voter_id(
        voter_id)

    if results['voter_address_found']:
        voter_address = results['voter_address']
        json_data = {
            'voter_device_id':
            voter_device_id,
            'address_type':
            voter_address.address_type if voter_address.address_type else '',
            'address':
            voter_address.address if voter_address.address else '',
            'latitude':
            voter_address.latitude if voter_address.latitude else '',
            'longitude':
            voter_address.longitude if voter_address.longitude else '',
            'normalized_line1':
            voter_address.normalized_line1
            if voter_address.normalized_line1 else '',
            'normalized_line2':
            voter_address.normalized_line2
            if voter_address.normalized_line2 else '',
            'normalized_city':
            voter_address.normalized_city
            if voter_address.normalized_city else '',
            'normalized_state':
            voter_address.normalized_state
            if voter_address.normalized_state else '',
            'normalized_zip':
            voter_address.normalized_zip
            if voter_address.normalized_zip else '',
            'success':
            True,
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')
    else:
        json_data = {
            'status': "VOTER_ADDRESS_NOT_RETRIEVED",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')
Example #12
0
def voter_ballot_items_retrieve_from_google_civic_for_api(
        voter_device_id, text_for_map_search='', use_test_election=False):
    """
    We are telling the server to explicitly reach out to the Google Civic API and retrieve the ballot items
    for this voter.
    """
    # Confirm that we have a Google Civic API Key (GOOGLE_CIVIC_API_KEY)
    if not positive_value_exists(GOOGLE_CIVIC_API_KEY):
        results = {
            'status': 'NO_GOOGLE_CIVIC_API_KEY',
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    # Confirm that we have the URL where we retrieve voter ballots (VOTER_INFO_URL)
    if not positive_value_exists(VOTER_INFO_URL):
        results = {
            'status':
            'MISSING VOTER_INFO_URL in config/environment_variables.json',
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    # Get voter_id from the voter_device_id so we can figure out which ballot_items to offer
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        results = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        results = {
            'status': "VALID_VOTER_ID_MISSING",
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    google_civic_election_id = 0
    status = ''
    success = False
    election_date_text = ''
    election_description_text = ''
    election_data_retrieved = False
    polling_location_retrieved = False
    contests_retrieved = False
    if not positive_value_exists(text_for_map_search):
        # Retrieve it from voter address
        voter_address_manager = VoterAddressManager()
        text_for_map_search = voter_address_manager.retrieve_ballot_map_text_from_voter_id(
            voter_id)

    if positive_value_exists(text_for_map_search):
        one_ballot_results = retrieve_one_ballot_from_google_civic_api(
            text_for_map_search, google_civic_election_id, use_test_election)

        if one_ballot_results['success']:
            one_ballot_json = one_ballot_results['structured_json']
            election_date_text = one_ballot_json['election']['electionDay']
            election_description_text = one_ballot_json['election']['name']

            # We may receive some election data, but not all of the data we need
            if one_ballot_results['election_data_retrieved']:
                election_data_retrieved = True
                success = True

            if one_ballot_results['polling_location_retrieved']:
                polling_location_retrieved = True
                success = True

            if one_ballot_results['contests_retrieved']:
                contests_retrieved = True

                # Now that we know we have new ballot data, we need to delete prior ballot data for this election
                # because when we change voterAddress, we usually get different ballot items
                ballot_item_list_manager = BallotItemListManager()
                # We include a google_civic_election_id, so only the ballot info for this election is removed
                google_civic_election_id_to_delete = one_ballot_json[
                    'election']['id']  # '0' would mean "delete all"
                if positive_value_exists(google_civic_election_id_to_delete):
                    ballot_item_list_manager.delete_all_ballot_items_for_voter(
                        voter_id, google_civic_election_id_to_delete)

                # store_on_ballot... adds an entry to the BallotReturned table
                # We update VoterAddress with normalized address data in store_one_ballot_from_google_civic_api
                store_one_ballot_results = store_one_ballot_from_google_civic_api(
                    one_ballot_json, voter_id)
                if store_one_ballot_results['success']:
                    status += 'RETRIEVED_FROM_GOOGLE_CIVIC_AND_STORED_BALLOT_FOR_VOTER '
                    success = True
                    google_civic_election_id = store_one_ballot_results[
                        'google_civic_election_id']
                else:
                    status += 'UNABLE_TO-store_one_ballot_from_google_civic_api'
        elif 'error' in one_ballot_results['structured_json']:
            if one_ballot_results['structured_json']['error'][
                    'message'] == 'Election unknown':
                success = False  # It is only successful if new ballot data is retrieved.
            else:
                success = False
            status += "GOOGLE_CIVIC_API_ERROR: " + one_ballot_results[
                'structured_json']['error']['message']

        else:
            status += 'UNABLE_TO-retrieve_one_ballot_from_google_civic_api'
            success = False
    else:
        status += 'MISSING_ADDRESS_TEXT_FOR_BALLOT_SEARCH'
        success = False

    # If a google_civic_election_id was not returned, outside of this function we search again using a test election,
    # so that during our initial user testing, ballot data is returned in areas where elections don't currently exist

    results = {
        'success': success,
        'status': status,
        'voter_device_id': voter_device_id,
        'google_civic_election_id': google_civic_election_id,
        'text_for_map_search': text_for_map_search,
        'election_date_text': election_date_text,
        'election_description_text': election_description_text,
        'election_data_retrieved': election_data_retrieved,
        'polling_location_retrieved': polling_location_retrieved,
        'contests_retrieved': contests_retrieved,
    }
    return results
Example #13
0
def store_one_ballot_from_google_civic_api(one_ballot_json,
                                           voter_id=0,
                                           polling_location_we_vote_id=''):
    """
    When we pass in a voter_id, we want to save this ballot related to the voter.
    When we pass in polling_location_we_vote_id, we want to save a ballot for that area, which is useful for
    getting new voters started by showing them a ballot roughly near them.
    """
    #     "election": {
    #     "electionDay": "2015-11-03",
    #     "id": "4162",
    #     "name": "Virginia General Election",
    #     "ocdDivisionId": "ocd-division/country:us/state:va"
    # },
    if 'election' not in one_ballot_json:
        results = {
            'status': 'BALLOT_JSON_MISSING_ELECTION',
            'success': False,
            'google_civic_election_id': 0,
        }
        return results

    election_date_text = ''
    election_description_text = ''
    if 'electionDay' in one_ballot_json['election']:
        election_date_text = one_ballot_json['election']['electionDay']
    if 'name' in one_ballot_json['election']:
        election_description_text = one_ballot_json['election']['name']

    if 'id' not in one_ballot_json['election']:
        results = {
            'status': 'BALLOT_JSON_MISSING_ELECTION_ID',
            'success': False,
            'google_civic_election_id': 0,
        }
        return results

    voter_address_dict = one_ballot_json[
        'normalizedInput'] if 'normalizedInput' in one_ballot_json else {}
    if positive_value_exists(voter_id):
        if positive_value_exists(voter_address_dict):
            # When saving a ballot for an individual voter, use this data to update voter address with the
            #  normalized address information returned from Google Civic
            # "normalizedInput": {
            #   "line1": "254 hartford st",
            #   "city": "san francisco",
            #   "state": "CA",
            #   "zip": "94114"
            #  },
            voter_address_manager = VoterAddressManager()
            voter_address_manager.update_voter_address_with_normalized_values(
                voter_id, voter_address_dict)
            # Note that neither 'success' nor 'status' are set here because updating the voter_address with normalized
            # values isn't critical to the success of storing the ballot for a voter
    # We don't store the normalized address information when we capture a ballot for a polling location

    google_civic_election_id = one_ballot_json['election']['id']
    ocd_division_id = one_ballot_json['election']['ocdDivisionId']
    state_code = extract_state_from_ocd_division_id(ocd_division_id)
    if not positive_value_exists(state_code):
        # We have a backup method of looking up state from one_ballot_json['state']['name']
        # in case the ocd state fails
        state_name = ''
        if 'state' in one_ballot_json:
            if 'name' in one_ballot_json['state']:
                state_name = one_ballot_json['state']['name']
            elif len(one_ballot_json['state']) > 0:
                # In some cases, like test elections 2000 a list is returned in one_ballot_json['state']
                for one_state_entry in one_ballot_json['state']:
                    if 'name' in one_state_entry:
                        state_name = one_state_entry['name']
        state_code = convert_state_text_to_state_code(state_name)

    # Loop through all contests and store in local db cache
    if 'contests' in one_ballot_json:
        results = process_contests_from_structured_json(
            one_ballot_json['contests'], google_civic_election_id,
            ocd_division_id, state_code, voter_id, polling_location_we_vote_id)

        status = results['status']
        success = results['success']
    else:
        status = "STORE_ONE_BALLOT_NO_CONTESTS_FOUND"
        success = False

    # When saving a ballot for individual voter, loop through all pollingLocations and store in local db
    # process_polling_locations_from_structured_json(one_ballot_json['pollingLocations'])

    # If we successfully save a ballot, create/update a BallotReturned entry
    is_test_election = True if positive_value_exists(google_civic_election_id) \
        and convert_to_int(google_civic_election_id) == 2000 else False
    if success and positive_value_exists(
            voter_address_dict) and not is_test_election:
        ballot_returned_manager = BallotReturnedManager()
        if positive_value_exists(voter_id) and positive_value_exists(
                google_civic_election_id):
            results = ballot_returned_manager.retrieve_ballot_returned_from_voter_id(
                voter_id, google_civic_election_id)
            if results['ballot_returned_found']:
                update_results = ballot_returned_manager.update_ballot_returned_with_normalized_values(
                    voter_address_dict, results['ballot_returned'])
            else:
                create_results = ballot_returned_manager.create_ballot_returned_with_normalized_values(
                    voter_address_dict, election_date_text,
                    election_description_text, google_civic_election_id,
                    voter_id, '')
        if positive_value_exists(
                polling_location_we_vote_id) and positive_value_exists(
                    google_civic_election_id):
            results = ballot_returned_manager.retrieve_ballot_returned_from_polling_location_we_vote_id(
                polling_location_we_vote_id, google_civic_election_id)
            if results['ballot_returned_found']:
                update_results = ballot_returned_manager.update_ballot_returned_with_normalized_values(
                    voter_address_dict, results['ballot_returned'])
            else:
                create_results = ballot_returned_manager.create_ballot_returned_with_normalized_values(
                    voter_address_dict, election_date_text,
                    election_description_text, google_civic_election_id, 0,
                    polling_location_we_vote_id)
        # Currently we don't report the success or failure of storing ballot_returned

    results = {
        'status': status,
        'success': success,
        'google_civic_election_id': google_civic_election_id,
    }
    return results
def store_one_ballot_from_google_civic_api(one_ballot_json, voter_id=0):

    #     "election": {
    #     "electionDay": "2015-11-03",
    #     "id": "4162",
    #     "name": "Virginia General Election",
    #     "ocdDivisionId": "ocd-division/country:us/state:va"
    # },
    if 'election' not in one_ballot_json:
        results = {
            'status': 'BALLOT_JSON_MISSING_ELECTION',
            'success': False,
            'google_civic_election_id': 0,
        }
        return results

    if 'id' not in one_ballot_json['election']:
        results = {
            'status': 'BALLOT_JSON_MISSING_ELECTION_ID',
            'success': False,
            'google_civic_election_id': 0,
        }
        return results

    if positive_value_exists(voter_id):
        voter_address_dict = one_ballot_json['normalizedInput'] if 'normalizedInput' in one_ballot_json else {}
        if positive_value_exists(voter_address_dict):
            # When saving a ballot for an individual voter, use this data to update voter address with the
            #  normalized address information returned from Google Civic
            # "normalizedInput": {
            #   "line1": "254 hartford st",
            #   "city": "san francisco",
            #   "state": "CA",
            #   "zip": "94114"
            #  },
            voter_address_manager = VoterAddressManager()
            voter_address_manager.update_voter_address_with_normalized_values(
                voter_id, voter_address_dict)
            # Note that neither success nor status set here because updating the voter_address with normalized values
            #  isn't critical to the success of storing the ballot for a voter
            # if update_address_results['success']:
            #     status = 'VOTER_ADDRESS_UPDATED_WITH_NORMALIZED_VALUES'
            # else:
            #     status = update_address_results['status']

    google_civic_election_id = one_ballot_json['election']['id']
    ocd_division_id = one_ballot_json['election']['ocdDivisionId']
    state_code = extract_state_from_ocd_division_id(ocd_division_id)
    if not positive_value_exists(state_code):
        # We have a backup method of looking up state from one_ballot_json['state']['name']
        # in case the ocd state fails
        if 'state' in one_ballot_json:
            if 'name' in one_ballot_json['state']:
                state_code = one_ballot_json['state']['name']

    # Loop through all contests and store in local db cache
    results = process_contests_from_structured_json(one_ballot_json['contests'], google_civic_election_id,
                                                    ocd_division_id, state_code, voter_id)

    status = results['status']

    # When saving a ballot for individual voter, loop through all pollingLocations and store in local db
    # process_polling_locations_from_structured_json(one_ballot_json['pollingLocations'])

    results = {
        'status': status,
        'success': results['success'],
        'google_civic_election_id': google_civic_election_id,
    }
    return results
Example #15
0
def positions_count_for_all_ballot_items_for_api(
        voter_device_id,
        google_civic_election_id=0,
        show_positions_this_voter_follows=True):
    """
    We want to return a JSON file with the a list of the support and oppose counts from the orgs, friends and
    public figures the voter follows
    """
    # Get voter_id from the voter_device_id so we can know whose stars to retrieve
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status':
            "VALID_VOTER_DEVICE_ID_MISSING-COUNT_FOR_ALL_BALLOT_ITEMS",
            'success': False,
            'google_civic_election_id': google_civic_election_id,
            'ballot_item_list': [],
        }
        return json_data

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status': "VALID_VOTER_ID_MISSING-COUNT_FOR_ALL_BALLOT_ITEMS",
            'success': False,
            'google_civic_election_id': google_civic_election_id,
            'ballot_item_list': [],
        }
        return json_data

    if not positive_value_exists(google_civic_election_id):
        # We must have an election id to proceed -- otherwise we don't know what ballot items to work with
        voter_device_link_manager = VoterDeviceLinkManager()
        voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(
            voter_device_id)
        if voter_device_link_results['voter_device_link_found']:
            voter_device_link = voter_device_link_results['voter_device_link']
            if positive_value_exists(
                    voter_device_link.google_civic_election_id):
                google_civic_election_id = voter_device_link.google_civic_election_id
        if not positive_value_exists(google_civic_election_id):
            voter_address_manager = VoterAddressManager()
            voter_address_results = voter_address_manager.retrieve_address(
                0, voter_id)
            if voter_address_results['voter_address_found']:
                voter_address = voter_address_results['voter_address']
                if positive_value_exists(
                        voter_address.google_civic_election_id):
                    google_civic_election_id = voter_address.google_civic_election_id
        google_civic_election_id = convert_to_int(google_civic_election_id)

    if not positive_value_exists(google_civic_election_id):
        json_data = {
            'status':
            "GOOGLE_CIVIC_ELECTION_ID_MISSING-COUNT_FOR_ALL_BALLOT_ITEMS",
            'success': False,
            'google_civic_election_id': google_civic_election_id,
            'ballot_item_list': [],
        }
        return json_data

    position_list_manager = PositionListManager()
    candidate_list_object = CandidateCampaignList()

    follow_organization_list_manager = FollowOrganizationList()
    organizations_followed_by_voter = \
        follow_organization_list_manager.retrieve_follow_organization_by_voter_id_simple_id_array(voter_id)

    # Get a list of all candidates and measures from this election (in the active election)
    ballot_item_results = voter_ballot_items_retrieve_for_one_election_for_api(
        voter_device_id, voter_id, google_civic_election_id)
    ballot_item_list = ballot_item_results['ballot_item_list']

    # The list where we capture results
    ballot_item_list_results = []

    # ballot_item_list is populated with contest_office and contest_measure entries
    for one_ballot_item in ballot_item_list:
        # Retrieve all positions for each ballot item
        if one_ballot_item['kind_of_ballot_item'] == OFFICE:
            results = candidate_list_object.retrieve_all_candidates_for_office(
                0, one_ballot_item['we_vote_id'])
            success = results['success']
            candidate_list = results['candidate_list']

            if success:
                for candidate in candidate_list:
                    # Loop through all candidates under this office
                    support_positions_list_for_one_ballot_item = \
                        position_list_manager.retrieve_all_positions_for_candidate_campaign(
                            0, candidate.we_vote_id, SUPPORT)
                    oppose_positions_list_for_one_ballot_item = \
                        position_list_manager.retrieve_all_positions_for_candidate_campaign(
                            0, candidate.we_vote_id, OPPOSE)
                    finalize_results = finalize_support_and_oppose_positions_count(
                        voter_id, show_positions_this_voter_follows,
                        organizations_followed_by_voter,
                        support_positions_list_for_one_ballot_item,
                        oppose_positions_list_for_one_ballot_item)
                    one_ballot_item_results = {
                        'ballot_item_we_vote_id':
                        candidate.we_vote_id,
                        'support_count':
                        finalize_results['support_positions_count'],
                        'oppose_count':
                        finalize_results['oppose_positions_count'],
                    }
                    ballot_item_list_results.append(one_ballot_item_results)
        elif one_ballot_item['kind_of_ballot_item'] == MEASURE:
            support_positions_list_for_one_ballot_item = \
                position_list_manager.retrieve_all_positions_for_contest_measure(0, one_ballot_item['we_vote_id'],
                                                                                 SUPPORT)
            oppose_positions_list_for_one_ballot_item = \
                position_list_manager.retrieve_all_positions_for_contest_measure(0, one_ballot_item['we_vote_id'],
                                                                                 OPPOSE)
            finalize_results = finalize_support_and_oppose_positions_count(
                voter_id, show_positions_this_voter_follows,
                organizations_followed_by_voter,
                support_positions_list_for_one_ballot_item,
                oppose_positions_list_for_one_ballot_item)
            one_ballot_item_results = {
                'ballot_item_we_vote_id': one_ballot_item['we_vote_id'],
                'support_count': finalize_results['support_positions_count'],
                'oppose_count': finalize_results['oppose_positions_count'],
            }
            ballot_item_list_results.append(one_ballot_item_results)
        else:
            # Skip the rest of this loop
            continue

    json_data = {
        'success': True,
        'status': "POSITIONS_COUNT_FOR_ALL_BALLOT_ITEMS",
        'google_civic_election_id': google_civic_election_id,
        'ballot_item_list': ballot_item_list_results,
    }
    return json_data
Example #16
0
def voter_ballot_items_retrieve_for_api(voter_device_id, google_civic_election_id):
    status = ''

    # We retrieve voter_device_link
    voter_device_link_manager = VoterDeviceLinkManager()
    voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(voter_device_id)
    if not voter_device_link_results['voter_device_link_found']:
        status += "VALID_VOTER_DEVICE_ID_MISSING "
        error_json_data = {
            'status':                       status,
            'success':                      False,
            'voter_device_id':              voter_device_id,
            'ballot_found':                 False,
            'ballot_item_list':             [],
            'google_civic_election_id':     google_civic_election_id,
            'text_for_map_search':          '',
            'substituted_address_nearby':   '',
            'ballot_caveat':                '',
            'is_from_substituted_address':  False,
            'is_from_test_ballot':          False,
        }
        return error_json_data

    voter_device_link = voter_device_link_results['voter_device_link']
    voter_id = voter_device_link.voter_id

    if not positive_value_exists(voter_id):
        status += " " + "VALID_VOTER_ID_MISSING"
        error_json_data = {
            'status':                       status,
            'success':                      False,
            'voter_device_id':              voter_device_id,
            'ballot_found':                 False,
            'ballot_item_list':             [],
            'google_civic_election_id':     google_civic_election_id,
            'text_for_map_search':          '',
            'substituted_address_nearby':   '',
            'ballot_caveat':                '',
            'is_from_substituted_address':  False,
            'is_from_test_ballot':          False,
        }
        return error_json_data

    voter_address_manager = VoterAddressManager()
    voter_address_id = 0
    address_type = BALLOT_ADDRESS
    voter_address_results = voter_address_manager.retrieve_address(voter_address_id, voter_id, address_type)
    status += " " + voter_address_results['status']
    if not positive_value_exists(voter_address_results['voter_address_has_value']):
        error_json_data = {
            'status':                       status,
            'success':                      voter_address_results['success'],
            'voter_device_id':              voter_device_id,
            'ballot_found':                 False,
            'ballot_item_list':             [],
            'google_civic_election_id':     0,
            'text_for_map_search':          '',
            'substituted_address_nearby':   '',
            'ballot_caveat':                '',
            'is_from_substituted_address':  False,
            'is_from_test_ballot':          False,
        }
        return error_json_data

    voter_address = voter_address_results['voter_address']

    results = choose_election_and_prepare_ballot_data(voter_device_link, google_civic_election_id, voter_address)
    status += " " + results['status']
    if not results['voter_ballot_saved_found']:
        if positive_value_exists(voter_address.text_for_map_search):
            ballot_caveat = "We could not find a ballot near '{text_for_map_search}'.".format(
                text_for_map_search=voter_address.text_for_map_search)
        else:
            ballot_caveat = "Please save your address so we can find your ballot."

        error_json_data = {
            'status':                       status,
            'success':                      True,
            'voter_device_id':              voter_device_id,
            'ballot_found':                 False,
            'ballot_item_list':             [],
            'google_civic_election_id':     0,
            'text_for_map_search':          voter_address.text_for_map_search,
            'substituted_address_nearby':   '',
            'ballot_caveat':                ballot_caveat,
            'is_from_substituted_address':  False,
            'is_from_test_ballot':          False,
        }
        return error_json_data

    google_civic_election_id = results['google_civic_election_id']
    voter_ballot_saved = results['voter_ballot_saved']

    # Update voter_device_link
    if voter_device_link.google_civic_election_id != google_civic_election_id:
        voter_device_link_manager.update_voter_device_link_with_election_id(voter_device_link, google_civic_election_id)

    # Update voter_address to include matching google_civic_election_id and voter_ballot_saved entry
    if positive_value_exists(google_civic_election_id):
        voter_address.google_civic_election_id = google_civic_election_id
        voter_address_manager.update_existing_voter_address_object(voter_address)

        # Get and return the ballot_item_list
        results = voter_ballot_items_retrieve_for_one_election_for_api(voter_device_id, voter_id,
                                                                       google_civic_election_id)

        status += " " + results['status']
        json_data = {
            'status':                       status,
            'success':                      True,
            'voter_device_id':              voter_device_id,
            'ballot_found':                 True,
            'ballot_item_list':             results['ballot_item_list'],
            'google_civic_election_id':     google_civic_election_id,
            'text_for_map_search':          voter_ballot_saved.original_text_for_map_search,
            'substituted_address_nearby':   voter_ballot_saved.substituted_address_nearby,
            'ballot_caveat':                voter_ballot_saved.ballot_caveat(),
            'is_from_substituted_address':  voter_ballot_saved.is_from_substituted_address,
            'is_from_test_ballot':          voter_ballot_saved.is_from_test_ballot,
        }
        return json_data

    status += " " + "NO_VOTER_BALLOT_SAVED_FOUND"
    error_json_data = {
        'status':                       status,
        'success':                      True,
        'voter_device_id':              voter_device_id,
        'ballot_found':                 False,
        'ballot_item_list':             [],
        'google_civic_election_id':     0,
        'text_for_map_search':          '',
        'substituted_address_nearby':   '',
        'ballot_caveat':                '',
        'is_from_substituted_address':  False,
        'is_from_test_ballot':          False,
    }
    return error_json_data
Example #17
0
def store_one_ballot_from_google_civic_api(one_ballot_json, voter_id=0):

    #     "election": {
    #     "electionDay": "2015-11-03",
    #     "id": "4162",
    #     "name": "Virginia General Election",
    #     "ocdDivisionId": "ocd-division/country:us/state:va"
    # },
    if 'election' not in one_ballot_json:
        results = {
            'status': 'BALLOT_JSON_MISSING_ELECTION',
            'success': False,
            'google_civic_election_id': 0,
        }
        return results

    if 'id' not in one_ballot_json['election']:
        results = {
            'status': 'BALLOT_JSON_MISSING_ELECTION_ID',
            'success': False,
            'google_civic_election_id': 0,
        }
        return results

    if positive_value_exists(voter_id):
        voter_address_dict = one_ballot_json['normalizedInput'] if 'normalizedInput' in one_ballot_json else {}
        if positive_value_exists(voter_address_dict):
            # When saving a ballot for an individual voter, use this data to update voter address with the
            #  normalized address information returned from Google Civic
            # "normalizedInput": {
            #   "line1": "254 hartford st",
            #   "city": "san francisco",
            #   "state": "CA",
            #   "zip": "94114"
            #  },
            voter_address_manager = VoterAddressManager()
            voter_address_manager.update_voter_address_with_normalized_values(
                voter_id, voter_address_dict)
            # Note that neither 'success' nor 'status' are set here because updating the voter_address with normalized
            # values isn't critical to the success of storing the ballot for a voter

    google_civic_election_id = one_ballot_json['election']['id']
    ocd_division_id = one_ballot_json['election']['ocdDivisionId']
    state_code = extract_state_from_ocd_division_id(ocd_division_id)
    if not positive_value_exists(state_code):
        # We have a backup method of looking up state from one_ballot_json['state']['name']
        # in case the ocd state fails
        state_name = ''
        if 'state' in one_ballot_json:
            if 'name' in one_ballot_json['state']:
                state_name = one_ballot_json['state']['name']
            elif len(one_ballot_json['state']) > 0:
                # In some cases, like test elections 2000 a list is returned in one_ballot_json['state']
                for one_state_entry in one_ballot_json['state']:
                    if 'name' in one_state_entry:
                        state_name = one_state_entry['name']
        state_code = convert_state_text_to_state_code(state_name)

    # Loop through all contests and store in local db cache
    if 'contests' in one_ballot_json:
        results = process_contests_from_structured_json(one_ballot_json['contests'], google_civic_election_id,
                                                        ocd_division_id, state_code, voter_id)

        status = results['status']
        success = results['success']
    else:
        status = "STORE_ONE_BALLOT_NO_CONTESTS_FOUND"
        success = False

    # When saving a ballot for individual voter, loop through all pollingLocations and store in local db
    # process_polling_locations_from_structured_json(one_ballot_json['pollingLocations'])

    results = {
        'status': status,
        'success': success,
        'google_civic_election_id': google_civic_election_id,
    }
    return results