示例#1
0
 def ballot_item_we_vote_id(self):
     if self.candidate_campaign_we_vote_id:
         return self.candidate_campaign_we_vote_id
     elif self.contest_office_we_vote_id:
         return self.contest_office_we_vote_id
     elif self.contest_measure_we_vote_id:
         return self.contest_measure_we_vote_id
     elif self.candidate_campaign_id:
         candidate_campaign_manager = CandidateCampaignManager()
         return candidate_campaign_manager.fetch_candidate_campaign_we_vote_id_from_id(self.candidate_campaign_id)
     elif self.contest_measure_id:
         contest_measure_manager = ContestMeasureManager()
         return contest_measure_manager.fetch_contest_measure_we_vote_id_from_id(self.contest_measure_id)
     elif self.contest_office_id:
         contest_office_manager = ContestOfficeManager()
         return contest_office_manager.fetch_contest_office_we_vote_id_from_id(self.contest_office_id)
     else:
         return 'not_found'
示例#2
0
 def ballot_item_we_vote_id(self):
     if self.candidate_campaign_we_vote_id:
         return self.candidate_campaign_we_vote_id
     elif self.contest_office_we_vote_id:
         return self.contest_office_we_vote_id
     elif self.contest_measure_we_vote_id:
         return self.contest_measure_we_vote_id
     elif self.candidate_campaign_id:
         candidate_campaign_manager = CandidateCampaignManager()
         return candidate_campaign_manager.fetch_candidate_campaign_we_vote_id_from_id(
             self.candidate_campaign_id)
     elif self.contest_measure_id:
         contest_measure_manager = ContestMeasureManager()
         return contest_measure_manager.fetch_contest_measure_we_vote_id_from_id(
             self.contest_measure_id)
     elif self.contest_office_id:
         contest_office_manager = ContestOfficeManager()
         return contest_office_manager.fetch_contest_office_we_vote_id_from_id(
             self.contest_office_id)
     else:
         return 'not_found'
def ballot_item_list_edit_process_view(request):
    """
    Process the new or edit ballot form
    :param request:
    :return:
    """
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    ballot_returned_id = convert_to_int(
        request.POST.get('ballot_returned_id', 0))
    google_civic_election_id = request.POST.get('google_civic_election_id', 0)
    polling_location_id = convert_to_int(
        request.POST.get('polling_location_id', 0))
    polling_location_city = request.POST.get('polling_location_city', '')
    polling_location_zip = request.POST.get('polling_location_zip', '')
    contest_office1_id = request.POST.get('contest_office1_id', 0)
    contest_office1_order = request.POST.get('contest_office1_order', 0)
    contest_measure1_id = request.POST.get('contest_measure1_id', 0)

    election_local_id = 0

    # Find existing ballot_returned
    ballot_returned_found = False
    ballot_returned = BallotReturned()
    if positive_value_exists(ballot_returned_id):
        try:
            ballot_returned_query = BallotReturned.objects.filter(
                id=ballot_returned_id)
            if len(ballot_returned_query):
                ballot_returned = ballot_returned_query[0]
                ballot_returned_found = True
        except Exception as e:
            pass

    election_manager = ElectionManager()
    polling_location_manager = PollingLocationManager()
    polling_location = PollingLocation()
    polling_location_found = False
    try:
        if ballot_returned_found:
            # Update

            # Check to see if this is a We Vote-created election
            is_we_vote_google_civic_election_id = True \
                if convert_to_int(ballot_returned.google_civic_election_id) >= 1000000 \
                else False

            results = election_manager.retrieve_election(
                ballot_returned.google_civic_election_id)
            if results['election_found']:
                election = results['election']
                election_local_id = election.id

            # polling_location must be found
            # We cannot change a polling location once saved, so we ignore the incoming polling_location_id here
            results = polling_location_manager.retrieve_polling_location_by_id(
                0, ballot_returned.polling_location_we_vote_id)
            if results['polling_location_found']:
                polling_location = results['polling_location']
                polling_location_found = True
        else:
            # Create new ballot_returned entry
            # election must be found
            election_results = election_manager.retrieve_election(
                google_civic_election_id)
            if election_results['election_found']:
                election = election_results['election']
                election_local_id = election.id
                state_code = election.get_election_state()
            else:
                messages.add_message(
                    request, messages.ERROR, 'Could not find election -- '
                    'required to save ballot_returned.')
                return HttpResponseRedirect(
                    reverse('ballot:ballot_item_list_edit',
                            args=(ballot_returned_id, )) +
                    "?google_civic_election_id=" +
                    str(google_civic_election_id) + "&polling_location_id=" +
                    str(polling_location_id) + "&polling_location_city=" +
                    polling_location_city + "&polling_location_zip=" +
                    str(polling_location_zip))

            # polling_location must be found
            if positive_value_exists(polling_location_id):
                results = polling_location_manager.retrieve_polling_location_by_id(
                    polling_location_id)
                if results['polling_location_found']:
                    polling_location = results['polling_location']
                    polling_location_found = True

            if not polling_location_found:
                messages.add_message(
                    request, messages.ERROR,
                    'Could not find polling_location -- '
                    'required to save ballot_returned.')
                return HttpResponseRedirect(
                    reverse('ballot:ballot_item_list_edit',
                            args=(ballot_returned_id, )) +
                    "?google_civic_election_id=" +
                    str(google_civic_election_id) + "&polling_location_id=" +
                    str(polling_location_id) + "&polling_location_city=" +
                    polling_location_city + "&polling_location_zip=" +
                    str(polling_location_zip))

            ballot_returned = BallotReturned(
                election_date=election.election_day_text,
                election_description_text=election.election_name,
                google_civic_election_id=google_civic_election_id,
                polling_location_we_vote_id=polling_location.we_vote_id,
                normalized_city=polling_location.city,
                normalized_line1=polling_location.line1,
                normalized_line2=polling_location.line2,
                normalized_state=polling_location.state,
                normalized_zip=polling_location.get_formatted_zip(),
                text_for_map_search=polling_location.get_text_for_map_search(),
            )
            ballot_returned.save()
            ballot_returned_id = ballot_returned.id
            ballot_returned_found = True
            messages.add_message(request, messages.INFO,
                                 'New ballot_returned saved.')

        # #######################################
        # Make sure we have saved a latitude and longitude for the ballot_returned entry
        if ballot_returned_found and positive_value_exists(
                ballot_returned.text_for_map_search):
            if not ballot_returned.latitude or not ballot_returned.longitude:
                google_client = get_geocoder_for_service('google')()
                location = google_client.geocode(
                    ballot_returned.text_for_map_search)
                if location is None:
                    status = 'Could not find location matching "{}"'.format(
                        ballot_returned.text_for_map_search)
                else:
                    ballot_returned.latitude = location.latitude
                    ballot_returned.longitude = location.longitude
                    ballot_returned.save()

        # #######################################
        # Now create new ballot_item entries

        # Contest Office 1
        ballot_item_manager = BallotItemManager()
        contest_office_manager = ContestOfficeManager()
        results = contest_office_manager.retrieve_contest_office(
            contest_office1_id)
        if results['contest_office_found']:
            contest_office = results['contest_office']
            ballot_item_display_name = contest_office.office_name

            google_ballot_placement = 0
            measure_subtitle = ''
            local_ballot_order = contest_office1_order if positive_value_exists(
                contest_office1_order) else 0

            results = ballot_item_manager.update_or_create_ballot_item_for_polling_location(
                polling_location.we_vote_id, google_civic_election_id,
                google_ballot_placement, ballot_item_display_name,
                measure_subtitle, local_ballot_order, contest_office.id,
                contest_office.we_vote_id)

            if results['new_ballot_item_created']:
                messages.add_message(request, messages.INFO, 'Office 1 added.')
            else:
                messages.add_message(request, messages.ERROR,
                                     'Office 1 could not be added.')

        # Contest Measure 1
        ballot_item_manager = BallotItemManager()
        contest_measure_manager = ContestMeasureManager()
        results = contest_measure_manager.retrieve_contest_measure(
            contest_measure1_id)
        if results['contest_measure_found']:
            contest_measure = results['contest_measure']

            google_ballot_placement = 0
            ballot_item_display_name = contest_measure.measure_title
            contest_office_id = 0
            contest_office_we_vote_id = ''
            local_ballot_order = 0

            ballot_item_manager.update_or_create_ballot_item_for_polling_location(
                polling_location.we_vote_id, google_civic_election_id,
                google_ballot_placement, ballot_item_display_name,
                contest_measure.measure_subtitle, local_ballot_order,
                contest_office_id, contest_office_we_vote_id,
                contest_measure.id)
    except Exception as e:
        messages.add_message(request, messages.ERROR,
                             'Could not save ballot_returned.')

    return HttpResponseRedirect(
        reverse('ballot:ballot_item_list_edit', args=(ballot_returned_id, )) +
        "?google_civic_election_id=" + str(google_civic_election_id) +
        "&polling_location_id=" + str(polling_location_id) +
        "&polling_location_city=" + polling_location_city +
        "&polling_location_zip=" + str(polling_location_zip))
示例#4
0
def voter_star_status_retrieve_for_api(voter_device_id, office_id,
                                       office_we_vote_id, candidate_id,
                                       candidate_we_vote_id, measure_id,
                                       measure_we_vote_id):
    # Get voter_id from the voter_device_id so we can know who is doing the starring
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
            'voter_device_id': voter_device_id,
            'is_starred': False,
            'office_id': convert_to_int(office_id),
            'candidate_id': convert_to_int(candidate_id),
            'measure_id': convert_to_int(measure_id),
            'ballot_item_id': 0,
            'ballot_item_we_vote_id': '',
            'kind_of_ballot_item': '',
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    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",
            'success': False,
            'voter_device_id': voter_device_id,
            'is_starred': False,
            'office_id': convert_to_int(office_id),
            'candidate_id': convert_to_int(candidate_id),
            'measure_id': convert_to_int(measure_id),
            'ballot_item_id': 0,
            'ballot_item_we_vote_id': '',
            'kind_of_ballot_item': '',
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    star_item_manager = StarItemManager()
    if positive_value_exists(office_id) or positive_value_exists(
            office_we_vote_id):
        contest_office_manager = ContestOfficeManager()
        # Since we can take in either office_id or office_we_vote_id, we need to retrieve the value we don't have
        if positive_value_exists(office_id):
            office_we_vote_id = contest_office_manager.fetch_contest_office_we_vote_id_from_id(
                office_id)
        elif positive_value_exists(office_we_vote_id):
            office_id = contest_office_manager.fetch_contest_office_id_from_we_vote_id(
                office_we_vote_id)

        # Zero out the unused values
        star_item_id = 0
        candidate_campaign_id = 0
        contest_measure_id = 0
        results = star_item_manager.retrieve_star_item(star_item_id, voter_id,
                                                       office_id,
                                                       candidate_campaign_id,
                                                       contest_measure_id)
        status = results['status']
        success = results['success']
        is_starred = results['is_starred']

        json_data = {
            'status': status,
            'success': success,
            'voter_device_id': voter_device_id,
            'is_starred': is_starred,
            'ballot_item_id': convert_to_int(office_id),
            'ballot_item_we_vote_id': office_we_vote_id,
            'kind_of_ballot_item': OFFICE,
            'office_id': convert_to_int(office_id),
            'candidate_id': convert_to_int(candidate_id),
            'measure_id': convert_to_int(measure_id),
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')
    elif positive_value_exists(candidate_id) or positive_value_exists(
            candidate_we_vote_id):
        candidate_campaign_manager = CandidateCampaignManager()
        # Since we can take in either candidate_id or candidate_we_vote_id, we need to retrieve the value we don't have
        if positive_value_exists(candidate_id):
            candidate_we_vote_id = candidate_campaign_manager.fetch_candidate_campaign_we_vote_id_from_id(
                candidate_id)
        elif positive_value_exists(candidate_we_vote_id):
            candidate_id = candidate_campaign_manager.fetch_candidate_campaign_id_from_we_vote_id(
                candidate_we_vote_id)

        # Zero out the unused values
        star_item_id = 0
        contest_office_id = 0
        contest_measure_id = 0
        results = star_item_manager.retrieve_star_item(star_item_id, voter_id,
                                                       contest_office_id,
                                                       candidate_id,
                                                       contest_measure_id)
        status = results['status']
        success = results['success']
        is_starred = results['is_starred']

        json_data = {
            'status': status,
            'success': success,
            'voter_device_id': voter_device_id,
            'is_starred': is_starred,
            'ballot_item_id': convert_to_int(candidate_id),
            'ballot_item_we_vote_id': candidate_we_vote_id,
            'kind_of_ballot_item': CANDIDATE,
            'office_id': convert_to_int(office_id),
            'candidate_id': convert_to_int(candidate_id),
            'measure_id': convert_to_int(measure_id),
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')
    elif positive_value_exists(measure_id) or positive_value_exists(
            measure_we_vote_id):
        contest_measure_manager = ContestMeasureManager()
        # Since we can take in either measure_id or measure_we_vote_id, we need to retrieve the value we don't have
        if positive_value_exists(measure_id):
            measure_we_vote_id = contest_measure_manager.fetch_contest_measure_we_vote_id_from_id(
                measure_id)
        elif positive_value_exists(measure_we_vote_id):
            measure_id = contest_measure_manager.fetch_contest_measure_id_from_we_vote_id(
                measure_we_vote_id)

        # Zero out the unused values
        star_item_id = 0
        contest_office_id = 0
        candidate_campaign_id = 0
        results = star_item_manager.retrieve_star_item(star_item_id, voter_id,
                                                       contest_office_id,
                                                       candidate_campaign_id,
                                                       measure_id)
        status = results['status']
        success = results['success']
        is_starred = results['is_starred']

        json_data = {
            'status': status,
            'success': success,
            'voter_device_id': voter_device_id,
            'is_starred': is_starred,
            'ballot_item_id': convert_to_int(measure_id),
            'ballot_item_we_vote_id': measure_we_vote_id,
            'kind_of_ballot_item': MEASURE,
            'office_id': convert_to_int(office_id),
            'candidate_id': convert_to_int(candidate_id),
            'measure_id': convert_to_int(measure_id),
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')
    else:
        status = 'UNABLE_TO_SAVE-OFFICE_ID_AND_CANDIDATE_ID_AND_MEASURE_ID_MISSING'
        success = False
        is_starred = False

    json_data = {
        'status': status,
        'success': success,
        'voter_device_id': voter_device_id,
        'is_starred': is_starred,
        'office_id': convert_to_int(office_id),
        'candidate_id': convert_to_int(candidate_id),
        'measure_id': convert_to_int(measure_id),
        'ballot_item_id': 0,
        'ballot_item_we_vote_id': '',
        'kind_of_ballot_item': '',
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
示例#5
0
def voter_star_status_retrieve_for_api(voter_device_id,
                                       office_id, office_we_vote_id,
                                       candidate_id, candidate_we_vote_id,
                                       measure_id, measure_we_vote_id):
    # Get voter_id from the voter_device_id so we can know who is doing the starring
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status':                   'VALID_VOTER_DEVICE_ID_MISSING',
            'success':                  False,
            'voter_device_id':          voter_device_id,
            'is_starred':               False,
            'office_id':                convert_to_int(office_id),
            'candidate_id':             convert_to_int(candidate_id),
            'measure_id':               convert_to_int(measure_id),
            'ballot_item_id':           0,
            'ballot_item_we_vote_id':   '',
            'kind_of_ballot_item':      '',
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    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",
            'success':                  False,
            'voter_device_id':          voter_device_id,
            'is_starred':               False,
            'office_id':                convert_to_int(office_id),
            'candidate_id':             convert_to_int(candidate_id),
            'measure_id':               convert_to_int(measure_id),
            'ballot_item_id':           0,
            'ballot_item_we_vote_id':   '',
            'kind_of_ballot_item':      '',
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    star_item_manager = StarItemManager()
    if positive_value_exists(office_id) or positive_value_exists(office_we_vote_id):
        contest_office_manager = ContestOfficeManager()
        # Since we can take in either office_id or office_we_vote_id, we need to retrieve the value we don't have
        if positive_value_exists(office_id):
            office_we_vote_id = contest_office_manager.fetch_contest_office_we_vote_id_from_id(office_id)
        elif positive_value_exists(office_we_vote_id):
            office_id = contest_office_manager.fetch_contest_office_id_from_we_vote_id(office_we_vote_id)

        # Zero out the unused values
        star_item_id = 0
        candidate_campaign_id = 0
        contest_measure_id = 0
        results = star_item_manager.retrieve_star_item(star_item_id, voter_id, office_id,
                                                       candidate_campaign_id, contest_measure_id)
        status = results['status']
        success = results['success']
        is_starred = results['is_starred']

        json_data = {
            'status':                   status,
            'success':                  success,
            'voter_device_id':          voter_device_id,
            'is_starred':               is_starred,
            'ballot_item_id':           convert_to_int(office_id),
            'ballot_item_we_vote_id':   office_we_vote_id,
            'kind_of_ballot_item':      OFFICE,
            'office_id':                convert_to_int(office_id),
            'candidate_id':             convert_to_int(candidate_id),
            'measure_id':               convert_to_int(measure_id),
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
    elif positive_value_exists(candidate_id) or positive_value_exists(candidate_we_vote_id):
        candidate_campaign_manager = CandidateCampaignManager()
        # Since we can take in either candidate_id or candidate_we_vote_id, we need to retrieve the value we don't have
        if positive_value_exists(candidate_id):
            candidate_we_vote_id = candidate_campaign_manager.fetch_candidate_campaign_we_vote_id_from_id(candidate_id)
        elif positive_value_exists(candidate_we_vote_id):
            candidate_id = candidate_campaign_manager.fetch_candidate_campaign_id_from_we_vote_id(candidate_we_vote_id)

        # Zero out the unused values
        star_item_id = 0
        contest_office_id = 0
        contest_measure_id = 0
        results = star_item_manager.retrieve_star_item(star_item_id, voter_id, contest_office_id, candidate_id,
                                                       contest_measure_id)
        status = results['status']
        success = results['success']
        is_starred = results['is_starred']

        json_data = {
            'status':                   status,
            'success':                  success,
            'voter_device_id':          voter_device_id,
            'is_starred':               is_starred,
            'ballot_item_id':           convert_to_int(candidate_id),
            'ballot_item_we_vote_id':   candidate_we_vote_id,
            'kind_of_ballot_item':      CANDIDATE,
            'office_id':                convert_to_int(office_id),
            'candidate_id':             convert_to_int(candidate_id),
            'measure_id':               convert_to_int(measure_id),
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
    elif positive_value_exists(measure_id) or positive_value_exists(measure_we_vote_id):
        contest_measure_manager = ContestMeasureManager()
        # Since we can take in either measure_id or measure_we_vote_id, we need to retrieve the value we don't have
        if positive_value_exists(measure_id):
            measure_we_vote_id = contest_measure_manager.fetch_contest_measure_we_vote_id_from_id(measure_id)
        elif positive_value_exists(measure_we_vote_id):
            measure_id = contest_measure_manager.fetch_contest_measure_id_from_we_vote_id(measure_we_vote_id)

        # Zero out the unused values
        star_item_id = 0
        contest_office_id = 0
        candidate_campaign_id = 0
        results = star_item_manager.retrieve_star_item(star_item_id, voter_id, contest_office_id, candidate_campaign_id,
                                                       measure_id)
        status = results['status']
        success = results['success']
        is_starred = results['is_starred']

        json_data = {
            'status':                   status,
            'success':                  success,
            'voter_device_id':          voter_device_id,
            'is_starred':               is_starred,
            'ballot_item_id':           convert_to_int(measure_id),
            'ballot_item_we_vote_id':   measure_we_vote_id,
            'kind_of_ballot_item':      MEASURE,
            'office_id':                convert_to_int(office_id),
            'candidate_id':             convert_to_int(candidate_id),
            'measure_id':               convert_to_int(measure_id),
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
    else:
        status = 'UNABLE_TO_SAVE-OFFICE_ID_AND_CANDIDATE_ID_AND_MEASURE_ID_MISSING'
        success = False
        is_starred = False

    json_data = {
        'status':                   status,
        'success':                  success,
        'voter_device_id':          voter_device_id,
        'is_starred':               is_starred,
        'office_id':                convert_to_int(office_id),
        'candidate_id':             convert_to_int(candidate_id),
        'measure_id':               convert_to_int(measure_id),
        'ballot_item_id':           0,
        'ballot_item_we_vote_id':   '',
        'kind_of_ballot_item':      '',
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
示例#6
0
def candidates_import_from_structured_json(structured_json):
    candidate_campaign_manager = CandidateCampaignManager()
    candidates_saved = 0
    candidates_updated = 0
    candidates_not_processed = 0
    for one_candidate in structured_json:
        candidate_name = one_candidate[
            'candidate_name'] if 'candidate_name' in one_candidate else ''
        we_vote_id = one_candidate[
            'we_vote_id'] if 'we_vote_id' in one_candidate else ''
        google_civic_election_id = \
            one_candidate['google_civic_election_id'] if 'google_civic_election_id' in one_candidate else ''
        ocd_division_id = one_candidate[
            'ocd_division_id'] if 'ocd_division_id' in one_candidate else ''
        contest_office_we_vote_id = \
            one_candidate['contest_office_we_vote_id'] if 'contest_office_we_vote_id' in one_candidate else ''

        # This routine imports from another We Vote server, so a contest_office_id doesn't come from import
        # Look up contest_office in this local database.
        # If we don't find a contest_office by we_vote_id, then we know the contest_office hasn't been imported
        # from another server yet, so we fail out.
        contest_office_manager = ContestOfficeManager()
        contest_office_id = contest_office_manager.fetch_contest_office_id_from_we_vote_id(
            contest_office_we_vote_id)

        if positive_value_exists(candidate_name) and positive_value_exists(google_civic_election_id) \
                and positive_value_exists(we_vote_id) and positive_value_exists(contest_office_id):
            proceed_to_update_or_create = True
        else:
            proceed_to_update_or_create = False
        if proceed_to_update_or_create:
            updated_candidate_campaign_values = {
                # Values we search against
                'google_civic_election_id':
                google_civic_election_id,
                'ocd_division_id':
                ocd_division_id,
                'contest_office_we_vote_id':
                contest_office_we_vote_id,
                'candidate_name':
                candidate_name,
                # The rest of the values
                'we_vote_id':
                we_vote_id,
                'maplight_id':
                one_candidate['maplight_id']
                if 'maplight_id' in one_candidate else None,
                'vote_smart_id':
                one_candidate['vote_smart_id']
                if 'vote_smart_id' in one_candidate else None,
                'contest_office_id':
                contest_office_id,  # Retrieved from above
                'politician_we_vote_id':
                one_candidate['politician_we_vote_id']
                if 'politician_we_vote_id' in one_candidate else '',
                'state_code':
                one_candidate['state_code']
                if 'state_code' in one_candidate else '',
                'party':
                one_candidate['party'] if 'party' in one_candidate else '',
                'order_on_ballot':
                one_candidate['order_on_ballot']
                if 'order_on_ballot' in one_candidate else 0,
                'candidate_url':
                one_candidate['candidate_url']
                if 'candidate_url' in one_candidate else '',
                'photo_url':
                one_candidate['photo_url']
                if 'photo_url' in one_candidate else '',
                'photo_url_from_maplight':
                one_candidate['photo_url_from_maplight']
                if 'photo_url_from_maplight' in one_candidate else '',
                'photo_url_from_vote_smart':
                one_candidate['photo_url_from_vote_smart']
                if 'photo_url_from_vote_smart' in one_candidate else '',
                'facebook_url':
                one_candidate['facebook_url']
                if 'facebook_url' in one_candidate else '',
                'twitter_url':
                one_candidate['twitter_url']
                if 'twitter_url' in one_candidate else '',
                'google_plus_url':
                one_candidate['google_plus_url']
                if 'google_plus_url' in one_candidate else '',
                'youtube_url':
                one_candidate['youtube_url']
                if 'youtube_url' in one_candidate else '',
                'google_civic_candidate_name':
                one_candidate['google_civic_candidate_name']
                if 'google_civic_candidate_name' in one_candidate else '',
                'candidate_email':
                one_candidate['candidate_email']
                if 'candidate_email' in one_candidate else '',
                'candidate_phone':
                one_candidate['candidate_phone']
                if 'candidate_phone' in one_candidate else '',
                'twitter_user_id':
                one_candidate['twitter_user_id']
                if 'twitter_user_id' in one_candidate else '',
                'candidate_twitter_handle':
                one_candidate['candidate_twitter_handle']
                if 'candidate_twitter_handle' in one_candidate else '',
                'twitter_name':
                one_candidate['twitter_name']
                if 'twitter_name' in one_candidate else '',
                'twitter_location':
                one_candidate['twitter_location']
                if 'twitter_location' in one_candidate else '',
                'twitter_followers_count':
                one_candidate['twitter_followers_count']
                if 'twitter_followers_count' in one_candidate else '',
                'twitter_profile_image_url_https':
                one_candidate['twitter_profile_image_url_https']
                if 'twitter_profile_image_url_https' in one_candidate else '',
                'twitter_description':
                one_candidate['twitter_description']
                if 'twitter_description' in one_candidate else '',
                'wikipedia_page_id':
                one_candidate['wikipedia_page_id']
                if 'wikipedia_page_id' in one_candidate else '',
                'wikipedia_page_title':
                one_candidate['wikipedia_page_title']
                if 'wikipedia_page_title' in one_candidate else '',
                'wikipedia_photo_url':
                one_candidate['wikipedia_photo_url']
                if 'wikipedia_photo_url' in one_candidate else '',
                'ballotpedia_page_title':
                one_candidate['ballotpedia_page_title']
                if 'ballotpedia_page_title' in one_candidate else '',
                'ballotpedia_photo_url':
                one_candidate['ballotpedia_photo_url']
                if 'ballotpedia_photo_url' in one_candidate else '',
                'ballot_guide_official_statement':
                one_candidate['ballot_guide_official_statement']
                if 'ballot_guide_official_statement' in one_candidate else '',
            }
            results = candidate_campaign_manager.update_or_create_candidate_campaign(
                we_vote_id, google_civic_election_id, ocd_division_id,
                contest_office_id, contest_office_we_vote_id, candidate_name,
                updated_candidate_campaign_values)
        else:
            candidates_not_processed += 1
            results = {
                'success': False,
                'status': 'Required value missing, cannot update or create'
            }

        if results['success']:
            if results['new_candidate_created']:
                candidates_saved += 1
            else:
                candidates_updated += 1

    candidates_results = {
        'success': True,
        'status': "CANDIDATES_IMPORT_PROCESS_COMPLETE",
        'saved': candidates_saved,
        'updated': candidates_updated,
        'not_processed': candidates_not_processed,
    }
    return candidates_results
示例#7
0
def candidates_import_from_structured_json(structured_json):
    candidate_campaign_manager = CandidateCampaignManager()
    candidates_saved = 0
    candidates_updated = 0
    candidates_not_processed = 0
    for one_candidate in structured_json:
        candidate_name = one_candidate['candidate_name'] if 'candidate_name' in one_candidate else ''
        we_vote_id = one_candidate['we_vote_id'] if 'we_vote_id' in one_candidate else ''
        google_civic_election_id = \
            one_candidate['google_civic_election_id'] if 'google_civic_election_id' in one_candidate else ''
        ocd_division_id = one_candidate['ocd_division_id'] if 'ocd_division_id' in one_candidate else ''
        contest_office_we_vote_id = \
            one_candidate['contest_office_we_vote_id'] if 'contest_office_we_vote_id' in one_candidate else ''

        # This routine imports from another We Vote server, so a contest_office_id doesn't come from import
        # Look up contest_office in this local database.
        # If we don't find a contest_office by we_vote_id, then we know the contest_office hasn't been imported
        # from another server yet, so we fail out.
        contest_office_manager = ContestOfficeManager()
        contest_office_id = contest_office_manager.fetch_contest_office_id_from_we_vote_id(
            contest_office_we_vote_id)

        if positive_value_exists(candidate_name) and positive_value_exists(google_civic_election_id) \
                and positive_value_exists(we_vote_id) and positive_value_exists(contest_office_id):
            proceed_to_update_or_create = True
        else:
            proceed_to_update_or_create = False
        if proceed_to_update_or_create:
            updated_candidate_campaign_values = {
                # Values we search against
                'google_civic_election_id': google_civic_election_id,
                'ocd_division_id': ocd_division_id,
                'contest_office_we_vote_id': contest_office_we_vote_id,
                'candidate_name': candidate_name,
                # The rest of the values
                'we_vote_id': we_vote_id,
                'maplight_id': one_candidate['maplight_id'] if 'maplight_id' in one_candidate else None,
                'vote_smart_id': one_candidate['vote_smart_id'] if 'vote_smart_id' in one_candidate else None,
                'contest_office_id': contest_office_id,  # Retrieved from above
                'politician_we_vote_id':
                    one_candidate['politician_we_vote_id'] if 'politician_we_vote_id' in one_candidate else '',
                'state_code': one_candidate['state_code'] if 'state_code' in one_candidate else '',
                'party': one_candidate['party'] if 'party' in one_candidate else '',
                'order_on_ballot': one_candidate['order_on_ballot'] if 'order_on_ballot' in one_candidate else 0,
                'candidate_url': one_candidate['candidate_url'] if 'candidate_url' in one_candidate else '',
                'photo_url': one_candidate['photo_url'] if 'photo_url' in one_candidate else '',
                'photo_url_from_maplight':
                    one_candidate['photo_url_from_maplight'] if 'photo_url_from_maplight' in one_candidate else '',
                'photo_url_from_vote_smart':
                    one_candidate['photo_url_from_vote_smart'] if 'photo_url_from_vote_smart' in one_candidate else '',
                'facebook_url': one_candidate['facebook_url'] if 'facebook_url' in one_candidate else '',
                'twitter_url': one_candidate['twitter_url'] if 'twitter_url' in one_candidate else '',
                'google_plus_url': one_candidate['google_plus_url'] if 'google_plus_url' in one_candidate else '',
                'youtube_url': one_candidate['youtube_url'] if 'youtube_url' in one_candidate else '',
                'google_civic_candidate_name':
                    one_candidate['google_civic_candidate_name']
                    if 'google_civic_candidate_name' in one_candidate else '',
                'candidate_email': one_candidate['candidate_email'] if 'candidate_email' in one_candidate else '',
                'candidate_phone': one_candidate['candidate_phone'] if 'candidate_phone' in one_candidate else '',
                'twitter_user_id': one_candidate['twitter_user_id'] if 'twitter_user_id' in one_candidate else '',
                'candidate_twitter_handle': one_candidate['candidate_twitter_handle']
                    if 'candidate_twitter_handle' in one_candidate else '',
                'twitter_name': one_candidate['twitter_name'] if 'twitter_name' in one_candidate else '',
                'twitter_location': one_candidate['twitter_location'] if 'twitter_location' in one_candidate else '',
                'twitter_followers_count': one_candidate['twitter_followers_count']
                    if 'twitter_followers_count' in one_candidate else '',
                'twitter_profile_image_url_https': one_candidate['twitter_profile_image_url_https']
                    if 'twitter_profile_image_url_https' in one_candidate else '',
                'twitter_description': one_candidate['twitter_description']
                    if 'twitter_description' in one_candidate else '',
                'wikipedia_page_id': one_candidate['wikipedia_page_id']
                    if 'wikipedia_page_id' in one_candidate else '',
                'wikipedia_page_title': one_candidate['wikipedia_page_title']
                    if 'wikipedia_page_title' in one_candidate else '',
                'wikipedia_photo_url': one_candidate['wikipedia_photo_url']
                    if 'wikipedia_photo_url' in one_candidate else '',
                'ballotpedia_page_title': one_candidate['ballotpedia_page_title']
                    if 'ballotpedia_page_title' in one_candidate else '',
                'ballotpedia_photo_url': one_candidate['ballotpedia_photo_url']
                    if 'ballotpedia_photo_url' in one_candidate else '',
                'ballot_guide_official_statement': one_candidate['ballot_guide_official_statement']
                    if 'ballot_guide_official_statement' in one_candidate else '',
            }
            results = candidate_campaign_manager.update_or_create_candidate_campaign(
                we_vote_id, google_civic_election_id, ocd_division_id,
                contest_office_id, contest_office_we_vote_id,
                candidate_name, updated_candidate_campaign_values)
        else:
            candidates_not_processed += 1
            results = {
                'success': False,
                'status': 'Required value missing, cannot update or create'
            }

        if results['success']:
            if results['new_candidate_created']:
                candidates_saved += 1
            else:
                candidates_updated += 1

    candidates_results = {
        'success':          True,
        'status':           "CANDIDATES_IMPORT_PROCESS_COMPLETE",
        'saved':            candidates_saved,
        'updated':          candidates_updated,
        'not_processed':    candidates_not_processed,
    }
    return candidates_results
示例#8
0
def candidates_import_from_sample_file(request=None, load_from_uri=False):
    """
    Get the json data, and either create new entries or update existing
    :return:
    """
    # if load_from_uri:
    #     # Request json file from We Vote servers
    #     messages.add_message(request, messages.INFO, "Loading CandidateCampaign IDs from We Vote Master servers")
    #     request = requests.get(CANDIDATE_CAMPAIGNS_URL, params={
    #         "key": WE_VOTE_API_KEY,  # This comes from an environment variable
    #     })
    #     structured_json = json.loads(request.text)
    # else:
    # Load saved json from local file

    # messages.add_message(request, messages.INFO, "Loading CandidateCampaigns from local file")

    with open("candidate/import_data/candidate_campaigns_sample.json"
              ) as json_data:
        structured_json = json.load(json_data)

    candidate_campaign_manager = CandidateCampaignManager()
    candidates_saved = 0
    candidates_updated = 0
    candidates_not_processed = 0
    for candidate in structured_json:
        candidate_name = candidate[
            'candidate_name'] if 'candidate_name' in candidate else ''
        we_vote_id = candidate[
            'we_vote_id'] if 'we_vote_id' in candidate else ''
        google_civic_election_id = \
            candidate['google_civic_election_id'] if 'google_civic_election_id' in candidate else ''
        ocd_division_id = candidate[
            'ocd_division_id'] if 'ocd_division_id' in candidate else ''
        contest_office_we_vote_id = \
            candidate['contest_office_we_vote_id'] if 'contest_office_we_vote_id' in candidate else ''

        # This routine imports from another We Vote server, so a contest_office_id doesn't come from import
        # Look it up for this local database. If we don't find it, then we know the contest_office hasn't been imported
        # from another server yet, so we fail out.
        contest_office_manager = ContestOfficeManager()
        contest_office_id = contest_office_manager.fetch_contest_office_id_from_we_vote_id(
            contest_office_we_vote_id)
        if positive_value_exists(candidate_name) and positive_value_exists(google_civic_election_id) \
                and positive_value_exists(we_vote_id) and positive_value_exists(contest_office_id):
            proceed_to_update_or_create = True
        # elif positive_value_exists(candidate_name) and positive_value_exists(google_civic_election_id) \
        #         and positive_value_exists(we_vote_id) and positive_value_exists(ocd_division_id) \
        #         and positive_value_exists(contest_office_we_vote_id):
        #     proceed_to_update_or_create = True
        else:
            proceed_to_update_or_create = False
        if proceed_to_update_or_create:
            updated_candidate_campaign_values = {
                # Values we search against
                'google_civic_election_id':
                google_civic_election_id,
                'ocd_division_id':
                ocd_division_id,
                'contest_office_we_vote_id':
                contest_office_we_vote_id,
                'candidate_name':
                candidate_name,
                # The rest of the values
                'we_vote_id':
                we_vote_id,
                'maplight_id':
                candidate['maplight_id']
                if 'maplight_id' in candidate else None,
                'contest_office_id':
                contest_office_id,
                'politician_we_vote_id':
                candidate['politician_we_vote_id']
                if 'politician_we_vote_id' in candidate else '',
                'state_code':
                candidate['state_code'] if 'state_code' in candidate else '',
                'party':
                candidate['party'] if 'party' in candidate else '',
                'order_on_ballot':
                candidate['order_on_ballot']
                if 'order_on_ballot' in candidate else 0,
                'candidate_url':
                candidate['candidate_url']
                if 'candidate_url' in candidate else '',
                'photo_url':
                candidate['photo_url'] if 'photo_url' in candidate else '',
                'photo_url_from_maplight':
                candidate['photo_url_from_maplight']
                if 'photo_url_from_maplight' in candidate else '',
                'facebook_url':
                candidate['facebook_url']
                if 'facebook_url' in candidate else '',
                'twitter_url':
                candidate['twitter_url'] if 'twitter_url' in candidate else '',
                'google_plus_url':
                candidate['google_plus_url']
                if 'google_plus_url' in candidate else '',
                'youtube_url':
                candidate['youtube_url'] if 'youtube_url' in candidate else '',
                'google_civic_candidate_name':
                candidate['google_civic_candidate_name']
                if 'google_civic_candidate_name' in candidate else '',
                'candidate_email':
                candidate['candidate_email']
                if 'candidate_email' in candidate else '',
                'candidate_phone':
                candidate['candidate_phone']
                if 'candidate_phone' in candidate else '',
            }
            results = candidate_campaign_manager.update_or_create_candidate_campaign(
                we_vote_id, google_civic_election_id, ocd_division_id,
                contest_office_id, contest_office_we_vote_id, candidate_name,
                updated_candidate_campaign_values)
        else:
            candidates_not_processed += 1
            results = {
                'success': False,
                'status': 'Required value missing, cannot update or create'
            }

        if results['success']:
            if results['new_candidate_created']:
                candidates_saved += 1
            else:
                candidates_updated += 1
        else:
            candidates_not_processed += 1
            if candidates_not_processed < 5 and request is not None:
                messages.add_message(
                    request, messages.ERROR,
                    results['status'] + "candidate_name: {candidate_name}"
                    ", google_civic_election_id: {google_civic_election_id}"
                    ", we_vote_id: {we_vote_id}"
                    ", contest_office_id: {contest_office_id}"
                    ", contest_office_we_vote_id: {contest_office_we_vote_id}"
                    "".format(
                        candidate_name=candidate_name,
                        google_civic_election_id=google_civic_election_id,
                        we_vote_id=we_vote_id,
                        contest_office_id=contest_office_id,
                        contest_office_we_vote_id=contest_office_we_vote_id,
                    ))
    candidates_results = {
        'saved': candidates_saved,
        'updated': candidates_updated,
        'not_processed': candidates_not_processed,
    }
    return candidates_results
示例#9
0
    def toggle_voter_starred_item(
            self, voter_id, star_status, candidate_campaign_id=0, contest_office_id=0, contest_measure_id=0,
            contest_office_we_vote_id='', candidate_campaign_we_vote_id='', contest_measure_we_vote_id=''):
        # Does a star_item entry exist from this voter already exist?
        star_item_manager = StarItemManager()
        star_item_id = 0
        results = star_item_manager.retrieve_star_item(
            star_item_id, voter_id,
            contest_office_id, candidate_campaign_id, contest_measure_id)

        star_item_on_stage_found = False
        star_item_on_stage_id = 0
        star_item_on_stage = StarItem()
        if results['star_item_found']:
            star_item_on_stage = results['star_item']

            # Update this star_item entry with new values - we do not delete because we might be able to use
            try:
                star_item_on_stage.star_status = star_status
                # We don't need to update date_last_changed here because set set auto_now=True in the field
                star_item_on_stage.save()
                star_item_on_stage_id = star_item_on_stage.id
                star_item_on_stage_found = True
                status = 'UPDATE ' + star_status
            except Exception as e:
                status = 'FAILED_TO_UPDATE ' + star_status
                handle_record_not_saved_exception(e, logger=logger, exception_message_optional=status)
        elif results['MultipleObjectsReturned']:
            logger.warn("star_item: delete all but one and take it over?")
            status = 'TOGGLE_ITEM_STARRED MultipleObjectsReturned ' + star_status
        elif results['DoesNotExist']:
            try:
                # Create new star_item entry
                if candidate_campaign_id and not candidate_campaign_we_vote_id:
                    candidate_campaign_manager = CandidateCampaignManager()
                    candidate_campaign_we_vote_id = \
                        candidate_campaign_manager.fetch_candidate_campaign_we_vote_id_from_id(candidate_campaign_id)
                if contest_measure_id and not contest_measure_we_vote_id:
                    contest_measure_manager = ContestMeasureManager()
                    contest_measure_we_vote_id = contest_measure_manager.fetch_contest_measure_we_vote_id_from_id(
                        contest_measure_id)
                if contest_office_id and not contest_office_we_vote_id:
                    contest_office_manager = ContestOfficeManager()
                    contest_office_we_vote_id = contest_office_manager.fetch_contest_office_we_vote_id_from_id(
                        contest_office_id)

                # NOTE: For speed purposes, we are not validating the existence of the items being starred
                #  although we could if the we_vote_id is not returned.
                star_item_on_stage = StarItem(
                    voter_id=voter_id,
                    candidate_campaign_id=candidate_campaign_id,
                    candidate_campaign_we_vote_id=candidate_campaign_we_vote_id,
                    contest_office_id=contest_office_id,
                    contest_office_we_vote_id=contest_office_we_vote_id,
                    contest_measure_id=contest_measure_id,
                    contest_measure_we_vote_id=contest_measure_we_vote_id,
                    star_status=star_status,
                    # We don't need to update date_last_changed here because set set auto_now=True in the field
                )
                star_item_on_stage.save()
                star_item_on_stage_id = star_item_on_stage.id
                star_item_on_stage_found = True
                status = 'CREATE ' + star_status
            except Exception as e:
                status = 'FAILED_TO_UPDATE ' + star_status
                handle_record_not_saved_exception(e, logger=logger, exception_message_optional=status)
        else:
            status = results['status']

        results = {
            'success':            True if star_item_on_stage_found else False,
            'status':             status,
            'star_item_found':    star_item_on_stage_found,
            'star_item_id':       star_item_on_stage_id,
            'star_item':          star_item_on_stage,
        }
        return results
示例#10
0
    def test_retrieve_with_no_voter_device_id(self):
        #######################################
        # Without a cookie or required variables, we don't expect valid response
        response01 = self.client.get(self.candidates_retrieve_url)
        json_data01 = json.loads(response01.content.decode())

        self.assertEqual(
            'status' in json_data01, True,
            "status expected in the json response, and not found")
        self.assertEqual(
            'success' in json_data01, True,
            "success expected in the json response, and not found")
        self.assertEqual(
            'office_id' in json_data01, True,
            "office_id expected in the json response, and not found")
        self.assertEqual(
            'office_we_vote_id' in json_data01, True,
            "office_we_vote_id expected in the json response, and not found")
        self.assertEqual(
            'google_civic_election_id' in json_data01, True,
            "google_civic_election_id expected in the json response, and not found"
        )
        self.assertEqual(
            'candidate_list' in json_data01, True,
            "candidate_list expected in the json response, and not found")

        self.assertEqual(
            json_data01['status'],
            'VALID_OFFICE_ID_AND_OFFICE_WE_VOTE_ID_MISSING',
            "status: {status} (VALID_OFFICE_ID_AND_OFFICE_WE_VOTE_ID_MISSING expected), "
            .format(status=json_data01['status']))
        self.assertEqual(
            json_data01['success'], False,
            "success: {success} (success 'False' expected), ".format(
                success=json_data01['success']))
        self.assertEqual(
            json_data01['office_id'], 0,
            "office_id: {office_id} ('0' expected), ".format(
                office_id=json_data01['office_id']))
        self.assertEqual(
            json_data01['office_we_vote_id'], '',
            "office_we_vote_id: {office_we_vote_id} ('' expected), ".format(
                office_we_vote_id=json_data01['office_we_vote_id']))
        self.assertEqual(
            json_data01['google_civic_election_id'], 0,
            "google_civic_election_id: {google_civic_election_id} ('0' expected), "
            .format(google_civic_election_id=json_data01[
                'google_civic_election_id']))
        self.assertListEqual(
            json_data01['candidate_list'], [],
            "candidate_list: {candidate_list} (Empty list expected), ".format(
                candidate_list=json_data01['candidate_list']))

        #######################################
        # We want to import some election-related data so we can test lists
        import_data_for_tests()

        #######################################
        # Retrieve contest_office so we can work with it
        contest_office_manager = ContestOfficeManager()
        results = contest_office_manager.retrieve_contest_office_from_we_vote_id(
            contest_office_we_vote_id='wv01off922')

        self.assertEqual(
            'success' in results, True,
            "Unable to retrieve contest_office with contest_office_we_vote_id='wv01off922'"
        )

        if results['success']:
            contest_office = results['contest_office']
        else:
            contest_office = ContestOffice()

        self.assertEqual(
            'wv01off922' in contest_office.we_vote_id, True,
            "contest_office retrieved does not have contest_office.we_vote_id='wv01off922'"
        )

        #######################################
        # We should get a valid response
        response02 = self.client.get(
            self.candidates_retrieve_url,
            {'office_we_vote_id': contest_office.we_vote_id})
        json_data02 = json.loads(response02.content.decode())

        self.assertEqual(
            'status' in json_data02, True,
            "status expected in the json response, and not found")
        self.assertEqual(
            'success' in json_data02, True,
            "success expected in the json response, and not found")
        self.assertEqual(
            'office_id' in json_data02, True,
            "office_id expected in the json response, and not found")
        self.assertEqual(
            'office_we_vote_id' in json_data02, True,
            "office_we_vote_id expected in the json response, and not found")
        self.assertEqual(
            'google_civic_election_id' in json_data02, True,
            "google_civic_election_id expected in the json response, and not found"
        )
        self.assertEqual(
            'candidate_list' in json_data02, True,
            "candidate_list expected in the json response, and not found")

        self.assertEqual(
            json_data02['status'], 'CANDIDATES_RETRIEVED',
            "status: {status} (CANDIDATES_RETRIEVED expected), ".format(
                status=json_data02['status']))
        self.assertEqual(
            json_data02['success'], True,
            "success: {success} (success 'True' expected), ".format(
                success=json_data02['success']))
        # For this test we don't know what the internal office_id should be
        # self.assertEqual(json_data02['office_id'], 0, "office_id: {office_id} ('0' expected), ".format(
        #         office_id=json_data02['office_id']))
        self.assertEqual(
            json_data02['office_we_vote_id'], 'wv01off922',
            "office_we_vote_id: {office_we_vote_id} ('wv01off922' expected), ".
            format(office_we_vote_id=json_data02['office_we_vote_id']))
        self.assertEqual(
            json_data02['google_civic_election_id'], '4162',
            "google_civic_election_id: {google_civic_election_id} ('4162' expected), "
            .format(google_civic_election_id=json_data02[
                'google_civic_election_id']))
        self.assertEqual(
            len(json_data02['candidate_list']), 3,
            "len(candidate_list): {candidate_list_count} (3 candidates expected), "
            .format(candidate_list_count=len(json_data02['candidate_list'])))
示例#11
0
def position_list_for_ballot_item_for_api(voter_device_id,  # positionListForBallotItem
                                          office_id, office_we_vote_id,
                                          candidate_id, candidate_we_vote_id,
                                          measure_id, measure_we_vote_id,
                                          stance_we_are_looking_for=ANY_STANCE,
                                          show_positions_this_voter_follows=True):
    """
    We want to return a JSON file with the position identifiers from orgs, friends and public figures the voter follows
    This list of information is used to retrieve the detailed information
    """
    position_manager = PositionEnteredManager()
    # Get voter_id from the voter_device_id so we can know who is supporting/opposing
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        position_list = []
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
            'count':            0,
            'kind_of_ballot_item': "UNKNOWN",
            'ballot_item_id':   0,
            'position_list':    position_list,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        position_list = []
        json_data = {
            'status': "VALID_VOTER_ID_MISSING ",
            'success': False,
            'count':            0,
            'kind_of_ballot_item': "UNKNOWN",
            'ballot_item_id':   0,
            'position_list':    position_list,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    position_list_manager = PositionListManager()
    ballot_item_found = False
    if positive_value_exists(candidate_id) or positive_value_exists(candidate_we_vote_id):
        all_positions_list = position_list_manager.retrieve_all_positions_for_candidate_campaign(
                candidate_id, candidate_we_vote_id, stance_we_are_looking_for)
        kind_of_ballot_item = CANDIDATE

        # Since we want to return the id and we_vote_id, and we don't know for sure that there are any positions
        # for this ballot_item, we retrieve the following so we can get the id and we_vote_id (per the request of
        # the WebApp team)
        candidate_campaign_manager = CandidateCampaignManager()
        if positive_value_exists(candidate_id):
            results = candidate_campaign_manager.retrieve_candidate_campaign_from_id(candidate_id)
        else:
            results = candidate_campaign_manager.retrieve_candidate_campaign_from_we_vote_id(candidate_we_vote_id)

        if results['candidate_campaign_found']:
            candidate_campaign = results['candidate_campaign']
            ballot_item_id = candidate_campaign.id
            ballot_item_we_vote_id = candidate_campaign.we_vote_id
            ballot_item_found = True
        else:
            ballot_item_id = candidate_id
            ballot_item_we_vote_id = candidate_we_vote_id
    elif positive_value_exists(measure_id) or positive_value_exists(measure_we_vote_id):
        all_positions_list = position_list_manager.retrieve_all_positions_for_contest_measure(
                measure_id, measure_we_vote_id, stance_we_are_looking_for)
        kind_of_ballot_item = MEASURE

        # Since we want to return the id and we_vote_id, and we don't know for sure that there are any positions
        # for this ballot_item, we retrieve the following so we can get the id and we_vote_id (per the request of
        # the WebApp team)
        contest_measure_manager = ContestMeasureManager()
        if positive_value_exists(measure_id):
            results = contest_measure_manager.retrieve_contest_measure_from_id(measure_id)
        else:
            results = contest_measure_manager.retrieve_contest_measure_from_we_vote_id(measure_we_vote_id)

        if results['contest_measure_found']:
            contest_measure = results['contest_measure']
            ballot_item_id = contest_measure.id
            ballot_item_we_vote_id = contest_measure.we_vote_id
            ballot_item_found = True
        else:
            ballot_item_id = measure_id
            ballot_item_we_vote_id = measure_we_vote_id
    elif positive_value_exists(office_id) or positive_value_exists(office_we_vote_id):
        all_positions_list = position_list_manager.retrieve_all_positions_for_contest_office(
                office_id, office_we_vote_id, stance_we_are_looking_for)
        kind_of_ballot_item = OFFICE

        # Since we want to return the id and we_vote_id, and we don't know for sure that there are any positions
        # for this ballot_item, we retrieve the following so we can get the id and we_vote_id (per the request of
        # the WebApp team)
        contest_office_manager = ContestOfficeManager()
        if positive_value_exists(office_id):
            results = contest_office_manager.retrieve_contest_office_from_id(office_id)
        else:
            results = contest_office_manager.retrieve_contest_office_from_we_vote_id(office_we_vote_id)

        if results['contest_office_found']:
            contest_office = results['contest_office']
            ballot_item_id = contest_office.id
            ballot_item_we_vote_id = contest_office.we_vote_id
            ballot_item_found = True
        else:
            ballot_item_id = office_id
            ballot_item_we_vote_id = office_we_vote_id
    else:
        position_list = []
        json_data = {
            'status':                   'POSITION_LIST_RETRIEVE_MISSING_BALLOT_ITEM_ID',
            'success':                  False,
            'count':                    0,
            'kind_of_ballot_item':      "UNKNOWN",
            'ballot_item_id':           0,
            'ballot_item_we_vote_id':   '',
            'position_list':            position_list,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    if not ballot_item_found:
        position_list = []
        json_data = {
            'status':                   'POSITION_LIST_RETRIEVE_BALLOT_ITEM_NOT_FOUND',
            'success':                  False,
            'count':                    0,
            'kind_of_ballot_item':      "UNKNOWN",
            'ballot_item_id':           ballot_item_id,
            'ballot_item_we_vote_id':   ballot_item_we_vote_id,
            'position_list':            position_list,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

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

    if show_positions_this_voter_follows:
        position_objects = position_list_manager.calculate_positions_followed_by_voter(
            voter_id, all_positions_list, organizations_followed_by_voter)
        positions_count = len(position_objects)
        status = 'SUCCESSFUL_RETRIEVE_OF_POSITIONS_FOLLOWED'
        success = True
    else:
        position_objects = position_list_manager.calculate_positions_not_followed_by_voter(
            all_positions_list, organizations_followed_by_voter)
        positions_count = len(position_objects)
        status = 'SUCCESSFUL_RETRIEVE_OF_POSITIONS_NOT_FOLLOWED'
        success = True

    position_list = []
    for one_position in position_objects:
        # Whose position is it?
        if positive_value_exists(one_position.organization_we_vote_id):
            speaker_type = ORGANIZATION
            speaker_id = one_position.organization_id
            speaker_we_vote_id = one_position.organization_we_vote_id
            one_position_success = True
            # Make sure we have this data to display
            if not positive_value_exists(one_position.speaker_display_name) \
                    or not positive_value_exists(one_position.speaker_image_url_https):
                one_position = position_manager.refresh_cached_position_info(one_position)
        elif positive_value_exists(one_position.voter_id):
            speaker_type = VOTER
            speaker_id = one_position.voter_id
            speaker_we_vote_id = one_position.voter_we_vote_id
            one_position_success = True
            # Make sure we have this data to display
            if not positive_value_exists(one_position.speaker_display_name):
                one_position = position_manager.refresh_cached_position_info(one_position)
        elif positive_value_exists(one_position.public_figure_we_vote_id):
            speaker_type = PUBLIC_FIGURE
            speaker_id = one_position.public_figure_id
            speaker_we_vote_id = one_position.public_figure_we_vote_id
            one_position_success = True
            # Make sure we have this data to display
            if not positive_value_exists(one_position.speaker_display_name) \
                    or not positive_value_exists(one_position.speaker_image_url_https):
                one_position = position_manager.refresh_cached_position_info(one_position)
        else:
            speaker_type = UNKNOWN_VOTER_GUIDE
            speaker_id = None
            speaker_we_vote_id = None
            one_position_success = False

        if one_position_success:
            one_position_dict_for_api = {
                'position_id':          one_position.id,
                'position_we_vote_id':  one_position.we_vote_id,
                'ballot_item_display_name': one_position.ballot_item_display_name,
                'speaker_display_name': one_position.speaker_display_name,
                'speaker_image_url_https': one_position.speaker_image_url_https,
                'speaker_type':         speaker_type,
                'speaker_id':           speaker_id,
                'speaker_we_vote_id':   speaker_we_vote_id,
                'is_support':           one_position.is_support(),
                'is_oppose':            one_position.is_oppose(),
                'vote_smart_rating':    one_position.vote_smart_rating,
                'vote_smart_time_span': one_position.vote_smart_time_span,
                'last_updated':         one_position.last_updated(),
            }
            position_list.append(one_position_dict_for_api)

    json_data = {
        'status':                   status,
        'success':                  success,
        'count':                    positions_count,
        'kind_of_ballot_item':      kind_of_ballot_item,
        'ballot_item_id':           ballot_item_id,
        'ballot_item_we_vote_id':   ballot_item_we_vote_id,
        'position_list':            position_list,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
示例#12
0
def process_contest_office_from_structured_json(
        one_contest_office_structured_json, google_civic_election_id,
        ocd_division_id, local_ballot_order, state_code, voter_id,
        polling_location_we_vote_id):
    logger.debug("General contest_type")

    # Protect against the case where this is NOT an office
    if 'candidates' not in one_contest_office_structured_json:
        is_not_office = True
    else:
        is_not_office = False
    if is_not_office:
        update_or_create_contest_office_results = {
            'success': False,
            'saved': 0,
            'updated': 0,
            'not_processed': 1,
        }
        return update_or_create_contest_office_results

    office_name = one_contest_office_structured_json['office']

    # The number of candidates that a voter may vote for in this contest.
    if 'numberVotingFor' in one_contest_office_structured_json:
        number_voting_for = one_contest_office_structured_json[
            'numberVotingFor']
    else:
        number_voting_for = 1

    # The number of candidates that will be elected to office in this contest.
    if 'numberElected' in one_contest_office_structured_json:
        number_elected = one_contest_office_structured_json['numberElected']
    else:
        number_elected = 1

    # These are several fields that are shared in common between offices and measures
    results = process_contest_common_fields_from_structured_json(
        one_contest_office_structured_json)

    # ballot_placement: A number specifying the position of this contest on the voter's ballot.
    google_ballot_placement = results['ballot_placement']
    primary_party = results[
        'primary_party']  # If this is a partisan election, the name of the party it is for.

    # district_scope: The geographic scope of this district. If unspecified the
    # district's geography is not known. One of: national, statewide, congressional, stateUpper, stateLower,
    # countywide, judicial, schoolBoard, cityWide, township, countyCouncil, cityCouncil, ward, special
    district_scope = results['district_scope']
    district_id = results['district_id']
    district_name = results['district_name']  # The name of the district.

    # electorate_specifications: A description of any additional eligibility requirements for voting in this contest.
    electorate_specifications = results['electorate_specifications']

    # special: "Yes" or "No" depending on whether this a contest being held outside the normal election cycle.
    special = results['special']

    # We want to convert this from an array to three fields for the same table
    # levels: string, A list of office levels to filter by. Only offices that serve at least one of these levels
    # will be returned. Divisions that don't contain a matching office will not be returned. (repeated)
    # Allowed values
    #   administrativeArea1 -
    #   administrativeArea2 -
    #   country -
    #   international -
    #   locality -
    #   regional -
    #   special -
    #   subLocality1 -
    #   subLocality2 -
    # The levels of government of the office for this contest. There may be more than one in cases where a
    # jurisdiction effectively acts at two different levels of government; for example, the mayor of the
    # District of Columbia acts at "locality" level, but also effectively at both "administrative-area-2"
    # and "administrative-area-1".
    level_structured_json = \
        one_contest_office_structured_json['level'] if 'level' in one_contest_office_structured_json else ''
    contest_level = []
    for one_level in level_structured_json:
        contest_level.append(one_level)
    if 0 in contest_level:
        contest_level0 = contest_level[0]
    else:
        contest_level0 = ''
    if 1 in contest_level:
        contest_level1 = contest_level[1]
    else:
        contest_level1 = ''
    if 2 in contest_level:
        contest_level2 = contest_level[2]
    else:
        contest_level2 = ''

    # roles: string, A list of office roles to filter by. Only offices fulfilling one of these roles will be returned.
    # Divisions that don't contain a matching office will not be returned. (repeated)
    # Allowed values
    #   deputyHeadOfGovernment -
    #   executiveCouncil -
    #   governmentOfficer -
    #   headOfGovernment -
    #   headOfState -
    #   highestCourtJudge -
    #   judge -
    #   legislatorLowerBody -
    #   legislatorUpperBody -
    #   schoolBoard -
    #   specialPurposeOfficer -
    # roles_structured_json = \
    #     one_contest_office_structured_json['roles'] if 'roles' in one_contest_office_structured_json else ''
    # for one_role in roles_structured_json:
    # Figure out how we are going to use level info

    candidates_structured_json = \
        one_contest_office_structured_json['candidates'] if 'candidates' in one_contest_office_structured_json else ''

    we_vote_id = ''
    # Note that all of the information saved here is independent of a particular voter
    if google_civic_election_id and (district_id
                                     or district_name) and office_name:
        updated_contest_office_values = {
            # Values we search against
            'google_civic_election_id': google_civic_election_id,
            'state_code':
            state_code.lower(),  # Not required for cases of federal offices
            'district_id': district_id,
            'district_name': district_name,
            'office_name': office_name,
            # The rest of the values
            'ocd_division_id': ocd_division_id,
            'number_voting_for': number_voting_for,
            'number_elected': number_elected,
            'contest_level0': contest_level0,
            'contest_level1': contest_level1,
            'contest_level2': contest_level2,
            'primary_party': primary_party,
            'district_scope': district_scope,
            'electorate_specifications': electorate_specifications,
            'special': special,
        }
        contest_office_manager = ContestOfficeManager()
        update_or_create_contest_office_results = contest_office_manager.update_or_create_contest_office(
            we_vote_id, google_civic_election_id, district_id, district_name,
            office_name, state_code, updated_contest_office_values)
    else:
        update_or_create_contest_office_results = {
            'success': False,
            'saved': 0,
            'updated': 0,
            'not_processed': 1,
        }

    if update_or_create_contest_office_results['success']:
        contest_office = update_or_create_contest_office_results[
            'contest_office']
        contest_office_id = contest_office.id
        contest_office_we_vote_id = contest_office.we_vote_id
        ballot_item_display_name = contest_office.office_name
    else:
        contest_office_id = 0
        contest_office_we_vote_id = ''
        ballot_item_display_name = ''

    # If a voter_id was passed in, save an entry for this office for the voter's ballot
    if positive_value_exists(voter_id) and positive_value_exists(google_civic_election_id) \
            and positive_value_exists(contest_office_id):
        ballot_item_manager = BallotItemManager()
        measure_subtitle = ""
        ballot_item_manager.update_or_create_ballot_item_for_voter(
            voter_id, google_civic_election_id, google_ballot_placement,
            ballot_item_display_name, measure_subtitle, local_ballot_order,
            contest_office_id, contest_office_we_vote_id)
        # We leave off these and rely on default empty values: contest_measure_id, contest_measure_we_vote_id

    # If this is a polling location, we want to save the ballot information for it so we can use it as reference
    #  for nearby voters (when we don't have their full address)
    if positive_value_exists(polling_location_we_vote_id) and positive_value_exists(google_civic_election_id) \
            and positive_value_exists(contest_office_id):
        ballot_item_manager = BallotItemManager()
        measure_subtitle = ""
        ballot_item_manager.update_or_create_ballot_item_for_polling_location(
            polling_location_we_vote_id, google_civic_election_id,
            google_ballot_placement, ballot_item_display_name,
            measure_subtitle, local_ballot_order, contest_office_id,
            contest_office_we_vote_id)
        # We leave off these and rely on default empty values: contest_measure_id, contest_measure_we_vote_id

    # Note: We do not need to connect the candidates with the voter here for a ballot item
    process_candidates_from_structured_json(candidates_structured_json,
                                            google_civic_election_id,
                                            ocd_division_id, state_code,
                                            contest_office_id,
                                            contest_office_we_vote_id)

    return update_or_create_contest_office_results
示例#13
0
def quick_info_edit_process_view(request):
    """
    Process the new or edit quick_info forms
    :param request:
    :return:
    """
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    quick_info_id = convert_to_int(request.POST.get('quick_info_id', False))
    quick_info_we_vote_id = convert_to_int(
        request.POST.get('quick_info_we_vote_id', False))

    language = request.POST.get('language', False)
    info_text = request.POST.get('info_text', False)
    info_html = request.POST.get('info_html', False)
    ballot_item_display_name = request.POST.get('ballot_item_display_name',
                                                False)
    more_info_credit = request.POST.get('more_info_credit', False)
    more_info_url = request.POST.get('more_info_url', False)

    contest_office_we_vote_id = request.POST.get('contest_office_we_vote_id',
                                                 False)
    candidate_campaign_we_vote_id = request.POST.get(
        'candidate_campaign_we_vote_id', False)
    politician_we_vote_id = request.POST.get('politician_we_vote_id', False)
    contest_measure_we_vote_id = request.POST.get('contest_measure_we_vote_id',
                                                  False)

    quick_info_master_we_vote_id = request.POST.get(
        'quick_info_master_we_vote_id', False)
    google_civic_election_id = request.POST.get('google_civic_election_id',
                                                False)

    change_election = request.POST.get(
        'change_election', '0')  # *Just* switch the election we are looking at
    change_language = request.POST.get(
        'change_language', '0')  # *Just* switch to different language
    use_unique_text = request.POST.get('use_unique_text', '0')
    use_master_entry = request.POST.get('use_master_entry', '0')
    change_text_vs_master = request.POST.get(
        'change_text_vs_master',
        '0')  # *Just* switch between text entry & master
    change_quick_info_master = request.POST.get(
        'change_quick_info_master', '0')  # *Just* update master display

    number_of_ballot_items = 0
    if positive_value_exists(contest_office_we_vote_id):
        number_of_ballot_items += 1
    if positive_value_exists(candidate_campaign_we_vote_id):
        number_of_ballot_items += 1
    if positive_value_exists(politician_we_vote_id):
        number_of_ballot_items += 1
    if positive_value_exists(contest_measure_we_vote_id):
        number_of_ballot_items += 1

    if positive_value_exists(change_election) or \
            positive_value_exists(change_language) or \
            positive_value_exists(change_text_vs_master) or \
            positive_value_exists(change_quick_info_master):
        # We are just changing an option, and not trying to save
        ready_to_save = False
    elif number_of_ballot_items is 0:
        messages.add_message(request, messages.ERROR,
                             "You must choose at least one ballot item.")
        ready_to_save = False
    elif number_of_ballot_items > 1:
        messages.add_message(request, messages.ERROR,
                             "Please choose only one ballot item.")
        ready_to_save = False
    # Do we have all of the required variables, unique to each mode?
    else:
        # If using a master entry
        if positive_value_exists(use_master_entry):
            if not positive_value_exists(quick_info_master_we_vote_id):
                messages.add_message(
                    request, messages.ERROR,
                    "Please choose a master entry for this ballot item.")
                ready_to_save = False
            else:
                ready_to_save = True
        # If entering text specific to this ballot item
        elif not positive_value_exists(
                use_master_entry) or positive_value_exists(use_unique_text):
            if not positive_value_exists(language):
                messages.add_message(
                    request, messages.ERROR,
                    "Please choose a language for your new entry.")
                ready_to_save = False
            elif not (positive_value_exists(info_text)
                      or positive_value_exists(info_html)):
                messages.add_message(
                    request, messages.ERROR,
                    "Please enter the text/html information about this ballot item."
                )
                ready_to_save = False
            elif not positive_value_exists(more_info_url):
                messages.add_message(
                    request, messages.ERROR,
                    "Please enter the source URL for this description.")
                ready_to_save = False
            else:
                ready_to_save = True
        else:
            messages.add_message(
                request, messages.ERROR,
                "More information needed to save this entry.")
            ready_to_save = False

    if not ready_to_save:
        # Could we also just call the view directly with the request, instead of redirecting the browser?
        if positive_value_exists(quick_info_id):
            return quick_info_edit_view(request, quick_info_id)
            # return HttpResponseRedirect(reverse('quick_info:quick_info_edit', args=()) + url_variables)
        else:
            return quick_info_new_view(request)
            # return HttpResponseRedirect(reverse('quick_info:quick_info_new', args=()) + url_variables)

    # Now that we know we are ready to save, we want to wipe out the values we don't want to save
    if positive_value_exists(use_master_entry):
        info_html = ""
        info_text = ""
        more_info_url = ""
        more_info_credit = NOT_SPECIFIED
    else:
        quick_info_master_we_vote_id = ""

    # Figure out what text to use for the Ballot Item Label
    if not positive_value_exists(ballot_item_display_name):
        if positive_value_exists(contest_office_we_vote_id):
            contest_office_manager = ContestOfficeManager()
            results = contest_office_manager.retrieve_contest_office_from_we_vote_id(
                contest_office_we_vote_id)
            if results['success']:
                contest_office = results['contest_office']
                ballot_item_display_name = contest_office.office_name
            else:
                ballot_item_display_name = ''
        elif positive_value_exists(candidate_campaign_we_vote_id):
            candidate_campaign_manager = CandidateCampaignManager()
            results = candidate_campaign_manager.retrieve_candidate_campaign_from_we_vote_id(
                candidate_campaign_we_vote_id)
            if results['success']:
                candidate_campaign = results['candidate_campaign']
                ballot_item_display_name = candidate_campaign.display_candidate_name(
                )
            else:
                ballot_item_display_name = ''
        # if positive_value_exists(politician_we_vote_id):
        #     ballot_item_display_name = ''
        elif positive_value_exists(contest_measure_we_vote_id):
            contest_measure_manager = ContestMeasureManager()
            results = contest_measure_manager.retrieve_contest_measure_from_we_vote_id(
                contest_measure_we_vote_id)
            if results['success']:
                contest_measure = results['contest_measure']
                ballot_item_display_name = contest_measure.measure_title
            else:
                ballot_item_display_name = ""

    last_editor_we_vote_id = ""  # TODO We need to calculate this

    quick_info_manager = QuickInfoManager()
    results = quick_info_manager.update_or_create_quick_info(
        quick_info_id=quick_info_id,
        quick_info_we_vote_id=quick_info_we_vote_id,
        ballot_item_display_name=ballot_item_display_name,
        contest_office_we_vote_id=contest_office_we_vote_id,
        candidate_campaign_we_vote_id=candidate_campaign_we_vote_id,
        politician_we_vote_id=politician_we_vote_id,
        contest_measure_we_vote_id=contest_measure_we_vote_id,
        info_html=info_html,
        info_text=info_text,
        language=language,
        last_editor_we_vote_id=last_editor_we_vote_id,
        quick_info_master_we_vote_id=quick_info_master_we_vote_id,
        more_info_url=more_info_url,
        more_info_credit=more_info_credit,
        google_civic_election_id=google_civic_election_id)
    if results['success']:
        messages.add_message(request, messages.INFO, results['status'])
    else:
        messages.add_message(
            request, messages.ERROR, results['status'] +
            "language: {language}".format(language=language, ))
        if positive_value_exists(quick_info_id):
            return quick_info_edit_view(request, quick_info_id)
        else:
            return quick_info_new_view(request)

    return HttpResponseRedirect(reverse('quick_info:quick_info_list', args=()))
示例#14
0
def ballot_item_list_edit_process_view(request):
    """
    Process the new or edit ballot form
    :param request:
    :return:
    """
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    ballot_returned_id = convert_to_int(request.POST.get('ballot_returned_id', 0))
    google_civic_election_id = request.POST.get('google_civic_election_id', 0)
    polling_location_id = convert_to_int(request.POST.get('polling_location_id', 0))
    polling_location_city = request.POST.get('polling_location_city', '')
    polling_location_zip = request.POST.get('polling_location_zip', '')
    contest_office1_id = request.POST.get('contest_office1_id', 0)
    contest_office1_order = request.POST.get('contest_office1_order', 0)
    contest_measure1_id = request.POST.get('contest_measure1_id', 0)

    election_local_id = 0

    # Find existing ballot_returned
    ballot_returned_found = False
    ballot_returned = BallotReturned()
    if positive_value_exists(ballot_returned_id):
        try:
            ballot_returned_query = BallotReturned.objects.filter(id=ballot_returned_id)
            if len(ballot_returned_query):
                ballot_returned = ballot_returned_query[0]
                ballot_returned_found = True
        except Exception as e:
            pass

    election_manager = ElectionManager()
    polling_location_manager = PollingLocationManager()
    polling_location = PollingLocation()
    polling_location_found = False
    try:
        if ballot_returned_found:
            # Update

            # Check to see if this is a We Vote-created election
            is_we_vote_google_civic_election_id = True \
                if convert_to_int(ballot_returned.google_civic_election_id) >= 1000000 \
                else False

            results = election_manager.retrieve_election(ballot_returned.google_civic_election_id)
            if results['election_found']:
                election = results['election']
                election_local_id = election.id

            # polling_location must be found
            # We cannot change a polling location once saved, so we ignore the incoming polling_location_id here
            results = polling_location_manager.retrieve_polling_location_by_id(
                0, ballot_returned.polling_location_we_vote_id)
            if results['polling_location_found']:
                polling_location = results['polling_location']
                polling_location_found = True
        else:
            # Create new ballot_returned entry
            # election must be found
            election_results = election_manager.retrieve_election(google_civic_election_id)
            if election_results['election_found']:
                election = election_results['election']
                election_local_id = election.id
                state_code = election.get_election_state()
            else:
                messages.add_message(request, messages.ERROR, 'Could not find election -- '
                                                              'required to save ballot_returned.')
                return HttpResponseRedirect(reverse('ballot:ballot_item_list_edit', args=(ballot_returned_id,)) +
                                            "?google_civic_election_id=" + str(google_civic_election_id) +
                                            "&polling_location_id=" + str(polling_location_id) +
                                            "&polling_location_city=" + polling_location_city +
                                            "&polling_location_zip=" + str(polling_location_zip)
                                            )

            # polling_location must be found
            if positive_value_exists(polling_location_id):
                results = polling_location_manager.retrieve_polling_location_by_id(polling_location_id)
                if results['polling_location_found']:
                    polling_location = results['polling_location']
                    polling_location_found = True

            if not polling_location_found:
                messages.add_message(request, messages.ERROR, 'Could not find polling_location -- '
                                                              'required to save ballot_returned.')
                return HttpResponseRedirect(reverse('ballot:ballot_item_list_edit', args=(ballot_returned_id,)) +
                                            "?google_civic_election_id=" + str(google_civic_election_id) +
                                            "&polling_location_id=" + str(polling_location_id) +
                                            "&polling_location_city=" + polling_location_city +
                                            "&polling_location_zip=" + str(polling_location_zip)
                                            )

            ballot_returned = BallotReturned(
                election_date=election.election_day_text,
                election_description_text=election.election_name,
                google_civic_election_id=google_civic_election_id,
                polling_location_we_vote_id=polling_location.we_vote_id,
                normalized_city=polling_location.city,
                normalized_line1=polling_location.line1,
                normalized_line2=polling_location.line2,
                normalized_state=polling_location.state,
                normalized_zip=polling_location.get_formatted_zip(),
                text_for_map_search=polling_location.get_text_for_map_search(),
            )
            ballot_returned.save()
            ballot_returned_id = ballot_returned.id
            ballot_returned_found = True
            messages.add_message(request, messages.INFO, 'New ballot_returned saved.')

        # #######################################
        # Make sure we have saved a latitude and longitude for the ballot_returned entry
        if ballot_returned_found and positive_value_exists(ballot_returned.text_for_map_search):
            if not ballot_returned.latitude or not ballot_returned.longitude:
                google_client = get_geocoder_for_service('google')()
                location = google_client.geocode(ballot_returned.text_for_map_search)
                if location is None:
                    status = 'Could not find location matching "{}"'.format(ballot_returned.text_for_map_search)
                else:
                    ballot_returned.latitude = location.latitude
                    ballot_returned.longitude = location.longitude
                    ballot_returned.save()

        # #######################################
        # Now create new ballot_item entries

        # Contest Office 1
        ballot_item_manager = BallotItemManager()
        contest_office_manager = ContestOfficeManager()
        results = contest_office_manager.retrieve_contest_office(contest_office1_id)
        if results['contest_office_found']:
            contest_office = results['contest_office']
            ballot_item_display_name = contest_office.office_name

            google_ballot_placement = 0
            measure_subtitle = ''
            local_ballot_order = contest_office1_order if positive_value_exists(contest_office1_order) else 0

            results = ballot_item_manager.update_or_create_ballot_item_for_polling_location(
                polling_location.we_vote_id, google_civic_election_id, google_ballot_placement,
                ballot_item_display_name, measure_subtitle, local_ballot_order,
                contest_office.id, contest_office.we_vote_id)

            if results['new_ballot_item_created']:
                messages.add_message(request, messages.INFO, 'Office 1 added.')
            else:
                messages.add_message(request, messages.ERROR, 'Office 1 could not be added.')

        # Contest Measure 1
        ballot_item_manager = BallotItemManager()
        contest_measure_manager = ContestMeasureManager()
        results = contest_measure_manager.retrieve_contest_measure(contest_measure1_id)
        if results['contest_measure_found']:
            contest_measure = results['contest_measure']

            google_ballot_placement = 0
            ballot_item_display_name = contest_measure.measure_title
            contest_office_id = 0
            contest_office_we_vote_id = ''
            local_ballot_order = 0

            ballot_item_manager.update_or_create_ballot_item_for_polling_location(
                polling_location.we_vote_id, google_civic_election_id, google_ballot_placement,
                ballot_item_display_name, contest_measure.measure_subtitle, local_ballot_order,
                contest_office_id, contest_office_we_vote_id,
                contest_measure.id)
    except Exception as e:
        messages.add_message(request, messages.ERROR, 'Could not save ballot_returned.')

    return HttpResponseRedirect(reverse('ballot:ballot_item_list_edit', args=(ballot_returned_id,)) +
                                "?google_civic_election_id=" + str(google_civic_election_id) +
                                "&polling_location_id=" + str(polling_location_id) +
                                "&polling_location_city=" + polling_location_city +
                                "&polling_location_zip=" + str(polling_location_zip)
                                )
示例#15
0
    def toggle_voter_starred_item(self,
                                  voter_id,
                                  star_status,
                                  candidate_campaign_id=0,
                                  contest_office_id=0,
                                  contest_measure_id=0,
                                  contest_office_we_vote_id='',
                                  candidate_campaign_we_vote_id='',
                                  contest_measure_we_vote_id=''):
        # Does a star_item entry exist from this voter already exist?
        star_item_manager = StarItemManager()
        star_item_id = 0
        results = star_item_manager.retrieve_star_item(star_item_id, voter_id,
                                                       contest_office_id,
                                                       candidate_campaign_id,
                                                       contest_measure_id)

        star_item_on_stage_found = False
        star_item_on_stage_id = 0
        star_item_on_stage = StarItem()
        if results['star_item_found']:
            star_item_on_stage = results['star_item']

            # Update this star_item entry with new values - we do not delete because we might be able to use
            try:
                star_item_on_stage.star_status = star_status
                # We don't need to update date_last_changed here because set set auto_now=True in the field
                star_item_on_stage.save()
                star_item_on_stage_id = star_item_on_stage.id
                star_item_on_stage_found = True
                status = 'UPDATE ' + star_status
            except Exception as e:
                status = 'FAILED_TO_UPDATE ' + star_status
                handle_record_not_saved_exception(
                    e, logger=logger, exception_message_optional=status)
        elif results['MultipleObjectsReturned']:
            logger.warn("star_item: delete all but one and take it over?")
            status = 'TOGGLE_ITEM_STARRED MultipleObjectsReturned ' + star_status
        elif results['DoesNotExist']:
            try:
                # Create new star_item entry
                if candidate_campaign_id and not candidate_campaign_we_vote_id:
                    candidate_campaign_manager = CandidateCampaignManager()
                    candidate_campaign_we_vote_id = \
                        candidate_campaign_manager.fetch_candidate_campaign_we_vote_id_from_id(candidate_campaign_id)
                if contest_measure_id and not contest_measure_we_vote_id:
                    contest_measure_manager = ContestMeasureManager()
                    contest_measure_we_vote_id = contest_measure_manager.fetch_contest_measure_we_vote_id_from_id(
                        contest_measure_id)
                if contest_office_id and not contest_office_we_vote_id:
                    contest_office_manager = ContestOfficeManager()
                    contest_office_we_vote_id = contest_office_manager.fetch_contest_office_we_vote_id_from_id(
                        contest_office_id)

                # NOTE: For speed purposes, we are not validating the existence of the items being starred
                #  although we could if the we_vote_id is not returned.
                star_item_on_stage = StarItem(
                    voter_id=voter_id,
                    candidate_campaign_id=candidate_campaign_id,
                    candidate_campaign_we_vote_id=candidate_campaign_we_vote_id,
                    contest_office_id=contest_office_id,
                    contest_office_we_vote_id=contest_office_we_vote_id,
                    contest_measure_id=contest_measure_id,
                    contest_measure_we_vote_id=contest_measure_we_vote_id,
                    star_status=star_status,
                    # We don't need to update date_last_changed here because set set auto_now=True in the field
                )
                star_item_on_stage.save()
                star_item_on_stage_id = star_item_on_stage.id
                star_item_on_stage_found = True
                status = 'CREATE ' + star_status
            except Exception as e:
                status = 'FAILED_TO_UPDATE ' + star_status
                handle_record_not_saved_exception(
                    e, logger=logger, exception_message_optional=status)
        else:
            status = results['status']

        results = {
            'success': True if star_item_on_stage_found else False,
            'status': status,
            'star_item_found': star_item_on_stage_found,
            'star_item_id': star_item_on_stage_id,
            'star_item': star_item_on_stage,
        }
        return results
示例#16
0
def candidates_import_from_sample_file(request=None, load_from_uri=False):
    """
    Get the json data, and either create new entries or update existing
    :return:
    """
    # if load_from_uri:
    #     # Request json file from We Vote servers
    #     messages.add_message(request, messages.INFO, "Loading CandidateCampaign IDs from We Vote Master servers")
    #     request = requests.get(CANDIDATE_CAMPAIGNS_URL, params={
    #         "key": WE_VOTE_API_KEY,  # This comes from an environment variable
    #     })
    #     structured_json = json.loads(request.text)
    # else:
    # Load saved json from local file

    # messages.add_message(request, messages.INFO, "Loading CandidateCampaigns from local file")

    with open("candidate/import_data/candidate_campaigns_sample.json") as json_data:
        structured_json = json.load(json_data)

    candidate_campaign_manager = CandidateCampaignManager()
    candidates_saved = 0
    candidates_updated = 0
    candidates_not_processed = 0
    for candidate in structured_json:
        candidate_name = candidate['candidate_name'] if 'candidate_name' in candidate else ''
        we_vote_id = candidate['we_vote_id'] if 'we_vote_id' in candidate else ''
        google_civic_election_id = \
            candidate['google_civic_election_id'] if 'google_civic_election_id' in candidate else ''
        ocd_division_id = candidate['ocd_division_id'] if 'ocd_division_id' in candidate else ''
        contest_office_we_vote_id = \
            candidate['contest_office_we_vote_id'] if 'contest_office_we_vote_id' in candidate else ''

        # This routine imports from another We Vote server, so a contest_office_id doesn't come from import
        # Look it up for this local database. If we don't find it, then we know the contest_office hasn't been imported
        # from another server yet, so we fail out.
        contest_office_manager = ContestOfficeManager()
        contest_office_id = contest_office_manager.fetch_contest_office_id_from_contest_office_we_vote_id(
            contest_office_we_vote_id)
        if positive_value_exists(candidate_name) and positive_value_exists(google_civic_election_id) \
                and positive_value_exists(we_vote_id) and positive_value_exists(contest_office_id):
            proceed_to_update_or_create = True
        # elif positive_value_exists(candidate_name) and positive_value_exists(google_civic_election_id) \
        #         and positive_value_exists(we_vote_id) and positive_value_exists(ocd_division_id) \
        #         and positive_value_exists(contest_office_we_vote_id):
        #     proceed_to_update_or_create = True
        else:
            proceed_to_update_or_create = False
        if proceed_to_update_or_create:
            updated_candidate_campaign_values = {
                # Values we search against
                'google_civic_election_id': google_civic_election_id,
                'ocd_division_id': ocd_division_id,
                'contest_office_we_vote_id': contest_office_we_vote_id,
                'candidate_name': candidate_name,
                # The rest of the values
                'we_vote_id': we_vote_id,
                'maplight_id': candidate['maplight_id'] if 'maplight_id' in candidate else None,
                'contest_office_id': contest_office_id,
                'politician_we_vote_id':
                    candidate['politician_we_vote_id'] if 'politician_we_vote_id' in candidate else '',
                'state_code': candidate['state_code'] if 'state_code' in candidate else '',
                'party': candidate['party'] if 'party' in candidate else '',
                'order_on_ballot': candidate['order_on_ballot'] if 'order_on_ballot' in candidate else 0,
                'candidate_url': candidate['candidate_url'] if 'candidate_url' in candidate else '',
                'photo_url': candidate['photo_url'] if 'photo_url' in candidate else '',
                'photo_url_from_maplight':
                    candidate['photo_url_from_maplight'] if 'photo_url_from_maplight' in candidate else '',
                'facebook_url': candidate['facebook_url'] if 'facebook_url' in candidate else '',
                'twitter_url': candidate['twitter_url'] if 'twitter_url' in candidate else '',
                'google_plus_url': candidate['google_plus_url'] if 'google_plus_url' in candidate else '',
                'youtube_url': candidate['youtube_url'] if 'youtube_url' in candidate else '',
                'google_civic_candidate_name':
                    candidate['google_civic_candidate_name'] if 'google_civic_candidate_name' in candidate else '',
                'candidate_email': candidate['candidate_email'] if 'candidate_email' in candidate else '',
                'candidate_phone': candidate['candidate_phone'] if 'candidate_phone' in candidate else '',
            }
            results = candidate_campaign_manager.update_or_create_candidate_campaign(
                we_vote_id, google_civic_election_id, ocd_division_id,
                contest_office_id, contest_office_we_vote_id,
                candidate_name, updated_candidate_campaign_values)
        else:
            candidates_not_processed += 1
            results = {
                'success': False,
                'status': 'Required value missing, cannot update or create'
            }

        if results['success']:
            if results['new_candidate_created']:
                candidates_saved += 1
            else:
                candidates_updated += 1
        else:
            candidates_not_processed += 1
            if candidates_not_processed < 5 and request is not None:
                messages.add_message(request, messages.ERROR,
                                     results['status'] + "candidate_name: {candidate_name}"
                                                         ", google_civic_election_id: {google_civic_election_id}"
                                                         ", we_vote_id: {we_vote_id}"
                                                         ", contest_office_id: {contest_office_id}"
                                                         ", contest_office_we_vote_id: {contest_office_we_vote_id}"
                                                         "".format(
                                         candidate_name=candidate_name,
                                         google_civic_election_id=google_civic_election_id,
                                         we_vote_id=we_vote_id,
                                         contest_office_id=contest_office_id,
                                         contest_office_we_vote_id=contest_office_we_vote_id,
                                     ))
    candidates_results = {
        'saved': candidates_saved,
        'updated': candidates_updated,
        'not_processed': candidates_not_processed,
    }
    return candidates_results
示例#17
0
def process_contest_office_from_structured_json(
        one_contest_office_structured_json, google_civic_election_id, ocd_division_id, local_ballot_order, state_code,
        voter_id, polling_location_we_vote_id):
    logger.debug("General contest_type")

    # Protect against the case where this is NOT an office
    if 'candidates' not in one_contest_office_structured_json:
        is_not_office = True
    else:
        is_not_office = False
    if is_not_office:
        update_or_create_contest_office_results = {
            'success': False,
            'saved': 0,
            'updated': 0,
            'not_processed': 1,
        }
        return update_or_create_contest_office_results

    office_name = one_contest_office_structured_json['office']

    # The number of candidates that a voter may vote for in this contest.
    if 'numberVotingFor' in one_contest_office_structured_json:
        number_voting_for = one_contest_office_structured_json['numberVotingFor']
    else:
        number_voting_for = 1

    # The number of candidates that will be elected to office in this contest.
    if 'numberElected' in one_contest_office_structured_json:
        number_elected = one_contest_office_structured_json['numberElected']
    else:
        number_elected = 1

    # These are several fields that are shared in common between offices and measures
    results = process_contest_common_fields_from_structured_json(one_contest_office_structured_json)

    # ballot_placement: A number specifying the position of this contest on the voter's ballot.
    google_ballot_placement = results['ballot_placement']
    primary_party = results['primary_party']  # If this is a partisan election, the name of the party it is for.

    # district_scope: The geographic scope of this district. If unspecified the
    # district's geography is not known. One of: national, statewide, congressional, stateUpper, stateLower,
    # countywide, judicial, schoolBoard, cityWide, township, countyCouncil, cityCouncil, ward, special
    district_scope = results['district_scope']
    district_id = results['district_id']
    district_name = results['district_name']  # The name of the district.

    # electorate_specifications: A description of any additional eligibility requirements for voting in this contest.
    electorate_specifications = results['electorate_specifications']

    # special: "Yes" or "No" depending on whether this a contest being held outside the normal election cycle.
    special = results['special']

    # We want to convert this from an array to three fields for the same table
    # levels: string, A list of office levels to filter by. Only offices that serve at least one of these levels
    # will be returned. Divisions that don't contain a matching office will not be returned. (repeated)
    # Allowed values
    #   administrativeArea1 -
    #   administrativeArea2 -
    #   country -
    #   international -
    #   locality -
    #   regional -
    #   special -
    #   subLocality1 -
    #   subLocality2 -
    # The levels of government of the office for this contest. There may be more than one in cases where a
    # jurisdiction effectively acts at two different levels of government; for example, the mayor of the
    # District of Columbia acts at "locality" level, but also effectively at both "administrative-area-2"
    # and "administrative-area-1".
    level_structured_json = \
        one_contest_office_structured_json['level'] if 'level' in one_contest_office_structured_json else ''
    contest_level = []
    for one_level in level_structured_json:
        contest_level.append(one_level)
    if 0 in contest_level:
        contest_level0 = contest_level[0]
    else:
        contest_level0 = ''
    if 1 in contest_level:
        contest_level1 = contest_level[1]
    else:
        contest_level1 = ''
    if 2 in contest_level:
        contest_level2 = contest_level[2]
    else:
        contest_level2 = ''

    # roles: string, A list of office roles to filter by. Only offices fulfilling one of these roles will be returned.
    # Divisions that don't contain a matching office will not be returned. (repeated)
    # Allowed values
    #   deputyHeadOfGovernment -
    #   executiveCouncil -
    #   governmentOfficer -
    #   headOfGovernment -
    #   headOfState -
    #   highestCourtJudge -
    #   judge -
    #   legislatorLowerBody -
    #   legislatorUpperBody -
    #   schoolBoard -
    #   specialPurposeOfficer -
    # roles_structured_json = \
    #     one_contest_office_structured_json['roles'] if 'roles' in one_contest_office_structured_json else ''
    # for one_role in roles_structured_json:
    # Figure out how we are going to use level info

    candidates_structured_json = \
        one_contest_office_structured_json['candidates'] if 'candidates' in one_contest_office_structured_json else ''

    we_vote_id = ''
    # Note that all of the information saved here is independent of a particular voter
    if google_civic_election_id and (district_id or district_name) and office_name:
        updated_contest_office_values = {
            # Values we search against
            'google_civic_election_id': google_civic_election_id,
            'state_code': state_code.lower(),  # Not required for cases of federal offices
            'district_id': district_id,
            'district_name': district_name,
            'office_name': office_name,
            # The rest of the values
            'ocd_division_id': ocd_division_id,
            'number_voting_for': number_voting_for,
            'number_elected': number_elected,
            'contest_level0': contest_level0,
            'contest_level1': contest_level1,
            'contest_level2': contest_level2,
            'primary_party': primary_party,
            'district_scope': district_scope,
            'electorate_specifications': electorate_specifications,
            'special': special,
        }
        contest_office_manager = ContestOfficeManager()
        update_or_create_contest_office_results = contest_office_manager.update_or_create_contest_office(
            we_vote_id, google_civic_election_id, district_id, district_name, office_name, state_code,
            updated_contest_office_values)
    else:
        update_or_create_contest_office_results = {
            'success': False,
            'saved': 0,
            'updated': 0,
            'not_processed': 1,
        }

    if update_or_create_contest_office_results['success']:
        contest_office = update_or_create_contest_office_results['contest_office']
        contest_office_id = contest_office.id
        contest_office_we_vote_id = contest_office.we_vote_id
        ballot_item_display_name = contest_office.office_name
    else:
        contest_office_id = 0
        contest_office_we_vote_id = ''
        ballot_item_display_name = ''

    # If a voter_id was passed in, save an entry for this office for the voter's ballot
    if positive_value_exists(voter_id) and positive_value_exists(google_civic_election_id) \
            and positive_value_exists(contest_office_id):
        ballot_item_manager = BallotItemManager()
        measure_subtitle = ""
        ballot_item_manager.update_or_create_ballot_item_for_voter(
            voter_id, google_civic_election_id, google_ballot_placement, ballot_item_display_name,
            measure_subtitle, local_ballot_order, contest_office_id, contest_office_we_vote_id)
        # We leave off these and rely on default empty values: contest_measure_id, contest_measure_we_vote_id

    # If this is a polling location, we want to save the ballot information for it so we can use it as reference
    #  for nearby voters (when we don't have their full address)
    if positive_value_exists(polling_location_we_vote_id) and positive_value_exists(google_civic_election_id) \
            and positive_value_exists(contest_office_id):
        ballot_item_manager = BallotItemManager()
        measure_subtitle = ""
        ballot_item_manager.update_or_create_ballot_item_for_polling_location(
            polling_location_we_vote_id, google_civic_election_id, google_ballot_placement, ballot_item_display_name,
            measure_subtitle, local_ballot_order, contest_office_id, contest_office_we_vote_id)
        # We leave off these and rely on default empty values: contest_measure_id, contest_measure_we_vote_id

    # Note: We do not need to connect the candidates with the voter here for a ballot item
    process_candidates_from_structured_json(
        candidates_structured_json, google_civic_election_id, ocd_division_id, state_code, contest_office_id,
        contest_office_we_vote_id)

    return update_or_create_contest_office_results
    def test_retrieve_with_no_cookie(self):
        #######################################
        # Without a cookie or required variables, we don't expect valid response
        response01 = self.client.get(self.candidates_retrieve_url)
        json_data01 = json.loads(response01.content)

        self.assertEqual('status' in json_data01, True, "status expected in the json response, and not found")
        self.assertEqual('success' in json_data01, True, "success expected in the json response, and not found")
        self.assertEqual('office_id' in json_data01, True, "office_id expected in the json response, and not found")
        self.assertEqual('office_we_vote_id' in json_data01, True,
                         "office_we_vote_id expected in the json response, and not found")
        self.assertEqual('google_civic_election_id' in json_data01, True,
                         "google_civic_election_id expected in the json response, and not found")
        self.assertEqual('candidate_list' in json_data01, True,
                         "candidate_list expected in the json response, and not found")

        self.assertEqual(
            json_data01['status'], 'VALID_OFFICE_ID_AND_OFFICE_WE_VOTE_ID_MISSING',
            "status: {status} (VALID_OFFICE_ID_AND_OFFICE_WE_VOTE_ID_MISSING expected), ".format(
                status=json_data01['status']))
        self.assertEqual(json_data01['success'], False, "success: {success} (success 'False' expected), ".format(
                success=json_data01['success']))
        self.assertEqual(json_data01['office_id'], 0, "office_id: {office_id} ('0' expected), ".format(
                office_id=json_data01['office_id']))
        self.assertEqual(json_data01['office_we_vote_id'], '',
                         "office_we_vote_id: {office_we_vote_id} ('' expected), ".format(
                             office_we_vote_id=json_data01['office_we_vote_id']))
        self.assertEqual(json_data01['google_civic_election_id'], 0,
                         "google_civic_election_id: {google_civic_election_id} ('0' expected), ".format(
                             google_civic_election_id=json_data01['google_civic_election_id']))
        self.assertItemsEqual(json_data01['candidate_list'], [],
                              "candidate_list: {candidate_list} (Empty list expected), ".format(
                candidate_list=json_data01['candidate_list']))

        #######################################
        # We want to import some election-related data so we can test lists
        import_data_for_tests()

        #######################################
        # Retrieve contest_office so we can work with it
        contest_office_manager = ContestOfficeManager()
        results = contest_office_manager.retrieve_contest_office_from_we_vote_id(
            contest_office_we_vote_id='wv01off922')

        self.assertEqual('success' in results, True,
                         "Unable to retrieve contest_office with contest_office_we_vote_id='wv01off922'")

        if results['success']:
            contest_office = results['contest_office']
        else:
            contest_office = ContestOffice()

        self.assertEqual('wv01off922' in contest_office.we_vote_id, True,
                         "contest_office retrieved does not have contest_office.we_vote_id='wv01off922'")

        #######################################
        # We should get a valid response
        response02 = self.client.get(self.candidates_retrieve_url, {'office_we_vote_id': contest_office.we_vote_id})
        json_data02 = json.loads(response02.content)

        self.assertEqual('status' in json_data02, True, "status expected in the json response, and not found")
        self.assertEqual('success' in json_data02, True, "success expected in the json response, and not found")
        self.assertEqual('office_id' in json_data02, True, "office_id expected in the json response, and not found")
        self.assertEqual('office_we_vote_id' in json_data02, True,
                         "office_we_vote_id expected in the json response, and not found")
        self.assertEqual('google_civic_election_id' in json_data02, True,
                         "google_civic_election_id expected in the json response, and not found")
        self.assertEqual('candidate_list' in json_data02, True,
                         "candidate_list expected in the json response, and not found")

        self.assertEqual(
            json_data02['status'], 'CANDIDATES_RETRIEVED',
            "status: {status} (CANDIDATES_RETRIEVED expected), ".format(
                status=json_data02['status']))
        self.assertEqual(json_data02['success'], True, "success: {success} (success 'True' expected), ".format(
                success=json_data02['success']))
        # For this test we don't know what the internal office_id should be
        # self.assertEqual(json_data02['office_id'], 0, "office_id: {office_id} ('0' expected), ".format(
        #         office_id=json_data02['office_id']))
        self.assertEqual(json_data02['office_we_vote_id'], 'wv01off922',
                         "office_we_vote_id: {office_we_vote_id} ('wv01off922' expected), ".format(
                             office_we_vote_id=json_data02['office_we_vote_id']))
        self.assertEqual(json_data02['google_civic_election_id'], '4162',
                         "google_civic_election_id: {google_civic_election_id} ('4162' expected), ".format(
                             google_civic_election_id=json_data02['google_civic_election_id']))
        self.assertEqual(len(json_data02['candidate_list']), 3,
                         "len(candidate_list): {candidate_list_count} (3 candidates expected), ".format(
                             candidate_list_count=len(json_data02['candidate_list'])))
示例#19
0
def quick_info_edit_process_view(request):
    """
    Process the new or edit quick_info forms
    :param request:
    :return:
    """
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    quick_info_id = convert_to_int(request.POST.get('quick_info_id', False))
    quick_info_we_vote_id = convert_to_int(request.POST.get('quick_info_we_vote_id', False))

    language = request.POST.get('language', False)
    info_text = request.POST.get('info_text', False)
    info_html = request.POST.get('info_html', False)
    ballot_item_display_name = request.POST.get('ballot_item_display_name', False)
    more_info_credit = request.POST.get('more_info_credit', False)
    more_info_url = request.POST.get('more_info_url', False)

    contest_office_we_vote_id = request.POST.get('contest_office_we_vote_id', False)
    candidate_campaign_we_vote_id = request.POST.get('candidate_campaign_we_vote_id', False)
    politician_we_vote_id = request.POST.get('politician_we_vote_id', False)
    contest_measure_we_vote_id = request.POST.get('contest_measure_we_vote_id', False)

    quick_info_master_we_vote_id = request.POST.get('quick_info_master_we_vote_id', False)
    google_civic_election_id = request.POST.get('google_civic_election_id', False)

    change_election = request.POST.get('change_election', '0')  # *Just* switch the election we are looking at
    change_language = request.POST.get('change_language', '0')  # *Just* switch to different language
    use_unique_text = request.POST.get('use_unique_text', '0')
    use_master_entry = request.POST.get('use_master_entry', '0')
    change_text_vs_master = request.POST.get('change_text_vs_master', '0')  # *Just* switch between text entry & master
    change_quick_info_master = request.POST.get('change_quick_info_master', '0')  # *Just* update master display

    number_of_ballot_items = 0
    if positive_value_exists(contest_office_we_vote_id):
        number_of_ballot_items += 1
    if positive_value_exists(candidate_campaign_we_vote_id):
        number_of_ballot_items += 1
    if positive_value_exists(politician_we_vote_id):
        number_of_ballot_items += 1
    if positive_value_exists(contest_measure_we_vote_id):
        number_of_ballot_items += 1

    if positive_value_exists(change_election) or \
            positive_value_exists(change_language) or \
            positive_value_exists(change_text_vs_master) or \
            positive_value_exists(change_quick_info_master):
        # We are just changing an option, and not trying to save
        ready_to_save = False
    elif number_of_ballot_items is 0:
        messages.add_message(request, messages.ERROR, "You must choose at least one ballot item.")
        ready_to_save = False
    elif number_of_ballot_items > 1:
        messages.add_message(request, messages.ERROR, "Please choose only one ballot item.")
        ready_to_save = False
    # Do we have all of the required variables, unique to each mode?
    else:
        # If using a master entry
        if positive_value_exists(use_master_entry):
            if not positive_value_exists(quick_info_master_we_vote_id):
                messages.add_message(request, messages.ERROR, "Please choose a master entry for this ballot item.")
                ready_to_save = False
            else:
                ready_to_save = True
        # If entering text specific to this ballot item
        elif not positive_value_exists(use_master_entry) or positive_value_exists(use_unique_text):
            if not positive_value_exists(language):
                messages.add_message(request, messages.ERROR, "Please choose a language for your new entry.")
                ready_to_save = False
            elif not (positive_value_exists(info_text) or positive_value_exists(info_html)):
                messages.add_message(request, messages.ERROR,
                                     "Please enter the text/html information about this ballot item.")
                ready_to_save = False
            elif not positive_value_exists(more_info_url):
                messages.add_message(request, messages.ERROR, "Please enter the source URL for this description.")
                ready_to_save = False
            else:
                ready_to_save = True
        else:
            messages.add_message(request, messages.ERROR, "More information needed to save this entry.")
            ready_to_save = False

    if not ready_to_save:
        # Could we also just call the view directly with the request, instead of redirecting the browser?
        if positive_value_exists(quick_info_id):
            return quick_info_edit_view(request, quick_info_id)
            # return HttpResponseRedirect(reverse('quick_info:quick_info_edit', args=()) + url_variables)
        else:
            return quick_info_new_view(request)
            # return HttpResponseRedirect(reverse('quick_info:quick_info_new', args=()) + url_variables)

    # Now that we know we are ready to save, we want to wipe out the values we don't want to save
    if positive_value_exists(use_master_entry):
        info_html = ""
        info_text = ""
        more_info_url = ""
        more_info_credit = NOT_SPECIFIED
    else:
        quick_info_master_we_vote_id = ""

    # Figure out what text to use for the Ballot Item Label
    if not positive_value_exists(ballot_item_display_name):
        if positive_value_exists(contest_office_we_vote_id):
            contest_office_manager = ContestOfficeManager()
            results = contest_office_manager.retrieve_contest_office_from_we_vote_id(contest_office_we_vote_id)
            if results['success']:
                contest_office = results['contest_office']
                ballot_item_display_name = contest_office.office_name
            else:
                ballot_item_display_name = ''
        elif positive_value_exists(candidate_campaign_we_vote_id):
            candidate_campaign_manager = CandidateCampaignManager()
            results = candidate_campaign_manager.retrieve_candidate_campaign_from_we_vote_id(
                candidate_campaign_we_vote_id)
            if results['success']:
                candidate_campaign = results['candidate_campaign']
                ballot_item_display_name = candidate_campaign.candidate_name
            else:
                ballot_item_display_name = ''
        # if positive_value_exists(politician_we_vote_id):
        #     ballot_item_display_name = ''
        elif positive_value_exists(contest_measure_we_vote_id):
            contest_measure_manager = ContestMeasureManager()
            results = contest_measure_manager.retrieve_contest_measure_from_we_vote_id(contest_measure_we_vote_id)
            if results['success']:
                contest_measure = results['contest_measure']
                ballot_item_display_name = contest_measure.measure_title
            else:
                ballot_item_display_name = ""

    last_editor_we_vote_id = ""  # TODO We need to calculate this

    quick_info_manager = QuickInfoManager()
    results = quick_info_manager.update_or_create_quick_info(
        quick_info_id=quick_info_id,
        quick_info_we_vote_id=quick_info_we_vote_id,
        ballot_item_display_name=ballot_item_display_name,
        contest_office_we_vote_id=contest_office_we_vote_id,
        candidate_campaign_we_vote_id=candidate_campaign_we_vote_id,
        politician_we_vote_id=politician_we_vote_id,
        contest_measure_we_vote_id=contest_measure_we_vote_id,
        info_html=info_html,
        info_text=info_text,
        language=language,
        last_editor_we_vote_id=last_editor_we_vote_id,
        quick_info_master_we_vote_id=quick_info_master_we_vote_id,
        more_info_url=more_info_url,
        more_info_credit=more_info_credit,
        google_civic_election_id=google_civic_election_id
        )
    if results['success']:
        messages.add_message(request, messages.INFO, results['status'])
    else:
        messages.add_message(request, messages.ERROR,
                             results['status'] + "language: {language}".format(
                                     language=language,
                             ))
        if positive_value_exists(quick_info_id):
            return quick_info_edit_view(request, quick_info_id)
        else:
            return quick_info_new_view(request)

    return HttpResponseRedirect(reverse('quick_info:quick_info_list', args=()))
示例#20
0
def candidate_edit_process_view(request):
    """
    Process the new or edit candidate forms
    :param request:
    :return:
    """
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    candidate_id = convert_to_int(request.POST['candidate_id'])
    candidate_name = request.POST.get('candidate_name', False)
    candidate_twitter_handle = request.POST.get('candidate_twitter_handle', False)
    if positive_value_exists(candidate_twitter_handle):
        candidate_twitter_handle = extract_twitter_handle_from_text_string(candidate_twitter_handle)
    candidate_url = request.POST.get('candidate_url', False)
    contest_office_id = request.POST.get('contest_office_id', False)
    ballot_guide_official_statement = request.POST.get('ballot_guide_official_statement', False)
    party = request.POST.get('party', False)

    remove_duplicate_process = request.POST.get('remove_duplicate_process', False)
    google_civic_election_id = request.POST.get('google_civic_election_id', 0)

    # Check to see if this candidate is already being used anywhere
    candidate_on_stage_found = False
    candidate_on_stage = CandidateCampaign()
    if positive_value_exists(candidate_id):
        try:
            candidate_query = CandidateCampaign.objects.filter(id=candidate_id)
            if len(candidate_query):
                candidate_on_stage = candidate_query[0]
                candidate_on_stage_found = True
        except Exception as e:
            handle_record_not_found_exception(e, logger=logger)

    contest_office_we_vote_id = ''
    if positive_value_exists(contest_office_id):
        contest_office_manager = ContestOfficeManager()
        results = contest_office_manager.retrieve_contest_office_from_id(contest_office_id)
        if results['contest_office_found']:
            contest_office = results['contest_office']
            contest_office_we_vote_id = contest_office.we_vote_id

    try:
        if candidate_on_stage_found:
            # Update
            if candidate_twitter_handle is not False:
                candidate_on_stage.candidate_twitter_handle = candidate_twitter_handle
            if candidate_url is not False:
                candidate_on_stage.candidate_url = candidate_url
            if ballot_guide_official_statement is not False:
                candidate_on_stage.ballot_guide_official_statement = ballot_guide_official_statement
            if party is not False:
                candidate_on_stage.party = party

            # Check to see if this is a We Vote-created election
            # is_we_vote_google_civic_election_id = True \
            #     if convert_to_int(candidate_on_stage.google_civic_election_id) >= 1000000 \
            #     else False

            if contest_office_id is not False:
                # We only allow updating of candidates within the We Vote Admin in
                candidate_on_stage.contest_office_id = contest_office_id
                candidate_on_stage.contest_office_we_vote_id = contest_office_we_vote_id
            candidate_on_stage.save()
            messages.add_message(request, messages.INFO, 'Candidate Campaign updated.')
        else:
            # Create new
            # election must be found
            election_manager = ElectionManager()
            election_results = election_manager.retrieve_election(google_civic_election_id)
            if election_results['election_found']:
                election = election_results['election']
                state_code = election.get_election_state()
            else:
                messages.add_message(request, messages.ERROR, 'Could not find election -- required to save candidate.')
                return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_id,)))

            required_candidate_variables = True \
                if positive_value_exists(candidate_name) and positive_value_exists(contest_office_id) \
                else False
            if required_candidate_variables:
                candidate_on_stage = CandidateCampaign(
                    candidate_name=candidate_name,
                    google_civic_election_id=google_civic_election_id,
                    contest_office_id=contest_office_id,
                    contest_office_we_vote_id=contest_office_we_vote_id,
                    state_code=state_code,
                )
                if candidate_twitter_handle is not False:
                    candidate_on_stage.candidate_twitter_handle = candidate_twitter_handle
                if candidate_url is not False:
                    candidate_on_stage.candidate_url = candidate_url
                if ballot_guide_official_statement is not False:
                    candidate_on_stage.ballot_guide_official_statement = ballot_guide_official_statement
                if party is not False:
                    candidate_on_stage.party = party
                candidate_on_stage.save()
                candidate_id = candidate_on_stage.id
                messages.add_message(request, messages.INFO, 'New candidate saved.')
            else:
                messages.add_message(request, messages.INFO, 'Could not save -- missing required variables.')
                if positive_value_exists(candidate_id):
                    return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_id,)) +
                                                "?google_civic_election_id=" + str(google_civic_election_id) +
                                                "&contest_office_id=" + str(contest_office_id)
                                                )
                else:
                    return HttpResponseRedirect(reverse('candidate:candidate_new', args=()) +
                                                "?google_civic_election_id=" + str(google_civic_election_id) +
                                                "&contest_office_id=" + str(contest_office_id)
                                                )

    except Exception as e:
        handle_record_not_saved_exception(e, logger=logger)
        messages.add_message(request, messages.ERROR, 'Could not save candidate.')
        return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_id,)))

    if remove_duplicate_process:
        return HttpResponseRedirect(reverse('candidate:find_and_remove_duplicate_candidates', args=()) +
                                    "?google_civic_election_id=" + str(google_civic_election_id))
    else:
        return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_id,)))