def retrieve_address(self, voter_address_id, voter_id, address_type):
        error_result = False
        exception_does_not_exist = False
        exception_multiple_object_returned = False
        voter_address_on_stage = VoterAddress()

        try:
            if positive_value_exists(voter_address_id):
                voter_address_on_stage = VoterAddress.objects.get(id=voter_address_id)
                voter_address_id = voter_address_on_stage.id
            elif positive_value_exists(voter_id) and \
                            address_type in (BALLOT_ADDRESS, MAILING_ADDRESS, FORMER_BALLOT_ADDRESS):
                voter_address_on_stage = VoterAddress.objects.get(voter_id=voter_id, address_type=address_type)
                # If still here, we found an existing address
                voter_address_id = voter_address_on_stage.id
        except VoterAddress.MultipleObjectsReturned as e:
            handle_record_found_more_than_one_exception(e, logger=logger)
            error_result = True
            exception_multiple_object_returned = True
        except VoterAddress.DoesNotExist:
            error_result = True
            exception_does_not_exist = True

        results = {
            'success':                  True if voter_address_id > 0 else False,
            'error_result':             error_result,
            'DoesNotExist':             exception_does_not_exist,
            'MultipleObjectsReturned':  exception_multiple_object_returned,
            'voter_address_found':      True if voter_address_id > 0 else False,
            'voter_address_id':         voter_address_id,
            'voter_address':            voter_address_on_stage,
        }
        return results
Exemple #2
0
    def toggle_off_voter_position_like(self, position_like_id, voter_id, position_entered_id):
        if positive_value_exists(position_like_id):
            try:
                PositionLike.objects.filter(id=position_like_id).delete()
                status = "DELETED_BY_POSITION_LIKE_ID"
                success = True
            except Exception as e:
                status = "UNABLE_TO_DELETE_BY_POSITION_LIKE_ID: {error}".format(
                    error=e
                )
                success = False
        elif positive_value_exists(voter_id) and positive_value_exists(position_entered_id):
            try:
                PositionLike.objects.filter(voter_id=voter_id, position_entered_id=position_entered_id).delete()
                status = "DELETED_BY_VOTER_ID_AND_POSITION_ENTERED_ID"
                success = True
            except Exception as e:
                status = "UNABLE_TO_DELETE_BY_VOTER_ID_AND_POSITION_ENTERED_ID: {error}".format(
                    error=e
                )
                success = False
        else:
            status = "UNABLE_TO_DELETE_NO_VARIABLES"
            success = False

        results = {
            'status':   status,
            'success':  success,
        }
        return results
def quick_info_list_view(request):
    messages_on_stage = get_messages(request)
    google_civic_election_id = request.GET.get('google_civic_election_id', 0)
    kind_of_ballot_item = request.GET.get('kind_of_ballot_item', '')
    language = request.GET.get('language', '')

    quick_info_list = QuickInfo.objects.order_by('id')  # This order_by is temp
    if positive_value_exists(google_civic_election_id):
        quick_info_list = QuickInfo.objects.filter(google_civic_election_id=google_civic_election_id)
    if positive_value_exists(kind_of_ballot_item):
        # Only return entries where the corresponding field has a We Vote id value in it.
        if kind_of_ballot_item == OFFICE:
            quick_info_list = QuickInfo.objects.filter(contest_office_we_vote_id__startswith='wv')
        elif kind_of_ballot_item == CANDIDATE:
            quick_info_list = QuickInfo.objects.filter(candidate_campaign_we_vote_id__startswith='wv')
        elif kind_of_ballot_item == POLITICIAN:
            quick_info_list = QuickInfo.objects.filter(politician_we_vote_id__startswith='wv')
        elif kind_of_ballot_item == MEASURE:
            quick_info_list = QuickInfo.objects.filter(contest_measure_we_vote_id__startswith='wv')
    if positive_value_exists(language):
        quick_info_list = QuickInfo.objects.filter(language=language)

    election_list = Election.objects.order_by('-election_day_text')

    template_values = {
        'messages_on_stage':        messages_on_stage,
        'quick_info_list':          quick_info_list,
        'election_list':            election_list,
        'google_civic_election_id': google_civic_election_id,
        'language_choices':         LANGUAGE_CHOICES,
        'language':                 language,
        'ballot_item_choices':      KIND_OF_BALLOT_ITEM_CHOICES,
        'kind_of_ballot_item':      kind_of_ballot_item,
    }
    return render(request, 'quick_info/quick_info_list.html', template_values)
def voter_position_like_off_save_for_api(voter_device_id, position_like_id, position_entered_id):
    # Get voter_id from the voter_device_id so we can know who is doing the liking
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
        }
        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,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    position_like_manager = PositionLikeManager()
    if positive_value_exists(position_like_id) or \
            (positive_value_exists(voter_id) and positive_value_exists(position_entered_id)):
        results = position_like_manager.toggle_off_voter_position_like(
            position_like_id, voter_id, position_entered_id)
        status = results['status']
        success = results['success']
    else:
        status = 'UNABLE_TO_DELETE_POSITION_LIKE-INSUFFICIENT_VARIABLES'
        success = False

    json_data = {
        'status': status,
        'success': success,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemple #5
0
def voter_ballot_items_retrieve_view(request):
    """
    (voterBallotItemsRetrieve) Request a skeleton of ballot data for this voter location,
    so that the web_app has all of the ids it needs to make more requests for data about each ballot item.
    :param request:
    :return:
    """
    voter_device_id = get_voter_device_id(request)  # We look in the cookies for voter_device_id
    # If passed in, we want to look at
    google_civic_election_id = request.GET.get('google_civic_election_id', 0)
    use_test_election = request.GET.get('use_test_election', False)
    use_test_election = False if use_test_election == 'false' else use_test_election
    use_test_election = False if use_test_election == 'False' else use_test_election

    if positive_value_exists(use_test_election):
        google_civic_election_id = 2000  # The Google Civic API Test election
    elif not positive_value_exists(google_civic_election_id):
        # We look in the cookies for google_civic_election_id
        google_civic_election_id = get_google_civic_election_id_from_cookie(request)

    # This 'voter_ballot_items_retrieve_for_api' lives in apis_v1/controllers.py
    results = voter_ballot_items_retrieve_for_api(voter_device_id, google_civic_election_id)
    response = HttpResponse(json.dumps(results['json_data']), content_type='application/json')

    # Save google_civic_election_id in the cookie so the interface knows
    google_civic_election_id_from_ballot_retrieve = results['google_civic_election_id']
    if positive_value_exists(google_civic_election_id_from_ballot_retrieve):
        set_google_civic_election_id_cookie(request, response, results['google_civic_election_id'])

    return response
    def retrieve_contest_measure(self, contest_measure_id, contest_measure_we_vote_id='', maplight_id=None):
        error_result = False
        exception_does_not_exist = False
        exception_multiple_object_returned = False
        contest_measure_on_stage = ContestMeasure()

        try:
            if positive_value_exists(contest_measure_id):
                contest_measure_on_stage = ContestMeasure.objects.get(id=contest_measure_id)
                contest_measure_id = contest_measure_on_stage.id
            elif positive_value_exists(contest_measure_we_vote_id):
                contest_measure_on_stage = ContestMeasure.objects.get(we_vote_id=contest_measure_we_vote_id)
                contest_measure_id = contest_measure_on_stage.id
            elif positive_value_exists(maplight_id):
                contest_measure_on_stage = ContestMeasure.objects.get(maplight_id=maplight_id)
                contest_measure_id = contest_measure_on_stage.id
        except ContestMeasure.MultipleObjectsReturned as e:
            handle_record_found_more_than_one_exception(e, logger=logger)
            exception_multiple_object_returned = True
        except ContestMeasure.DoesNotExist:
            exception_does_not_exist = True

        results = {
            'success':                      True if contest_measure_id > 0 else False,
            'error_result':                 error_result,
            'DoesNotExist':                 exception_does_not_exist,
            'MultipleObjectsReturned':      exception_multiple_object_returned,
            'contest_measure_found':         True if contest_measure_id > 0 else False,
            'contest_measure_id':            contest_measure_id,
            'contest_measure_we_vote_id':    contest_measure_we_vote_id,
            'contest_measure':               contest_measure_on_stage,
        }
        return results
Exemple #7
0
    def retrieve_daily_summaries(self, kind_of_action="", google_civic_election_id=0):
        # Start with today and cycle backwards in time
        daily_summaries = []
        day_on_stage = date.today()  # TODO: We need to work out the timezone questions
        number_found = 0
        maximum_attempts = 30
        attempt_count = 0

        try:
            # Limit the number of times this runs to EITHER 1) 5 positive numbers
            #  OR 2) 30 days in the past, whichever comes first
            while number_found <= 5 and attempt_count <= maximum_attempts:
                attempt_count += 1
                counter_queryset = GoogleCivicApiCounter.objects.all()
                if positive_value_exists(kind_of_action):
                    counter_queryset = counter_queryset.filter(kind_of_action=kind_of_action)
                if positive_value_exists(google_civic_election_id):
                    counter_queryset = counter_queryset.filter(google_civic_election_id=google_civic_election_id)

                # Find the number of these entries on that particular day
                counter_queryset = counter_queryset.filter(datetime_of_action__contains=day_on_stage)
                api_call_count = len(counter_queryset)

                # If any api calls were found on that date, pass it out for display
                if positive_value_exists(api_call_count):
                    daily_summary = {"date_string": day_on_stage, "count": api_call_count}
                    daily_summaries.append(daily_summary)
                    number_found += 1

                day_on_stage -= timedelta(days=1)
        except Exception:
            pass

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

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

            # We update VoterAddress with normalized address data in store_one_ballot_from_google_civic_api

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

    results = {
        'google_civic_election_id': google_civic_election_id,
        'success': success,
        'status': status,
    }
    return results
def voter_star_on_save_for_api(voter_device_id, office_id, candidate_id, measure_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}
        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}
        return HttpResponse(json.dumps(json_data), content_type="application/json")

    star_item_manager = StarItemManager()
    if positive_value_exists(office_id):
        results = star_item_manager.toggle_on_voter_starred_office(voter_id, office_id)
        status = "STAR_ON_OFFICE " + results["status"]
        success = results["success"]
    elif positive_value_exists(candidate_id):
        results = star_item_manager.toggle_on_voter_starred_candidate(voter_id, candidate_id)
        status = "STAR_ON_CANDIDATE " + results["status"]
        success = results["success"]
    elif positive_value_exists(measure_id):
        results = star_item_manager.toggle_on_voter_starred_measure(voter_id, measure_id)
        status = "STAR_ON_MEASURE " + results["status"]
        success = results["success"]
    else:
        status = "UNABLE_TO_SAVE_ON-OFFICE_ID_AND_CANDIDATE_ID_AND_MEASURE_ID_MISSING"
        success = False

    json_data = {"status": status, "success": success}
    return HttpResponse(json.dumps(json_data), content_type="application/json")
def retrieve_candidate_photos_for_election_view(request, election_id):
    google_civic_election_id = convert_to_int(election_id)

    # We only want to process if a google_civic_election_id comes in
    if not positive_value_exists(google_civic_election_id):
        messages.add_message(request, messages.ERROR, "Google Civic Election ID required.")
        return HttpResponseRedirect(reverse("candidate:candidate_list", args=()))

    try:
        candidate_list = CandidateCampaign.objects.order_by("candidate_name")
        if positive_value_exists(google_civic_election_id):
            candidate_list = candidate_list.filter(google_civic_election_id=google_civic_election_id)
    except CandidateCampaign.DoesNotExist:
        pass

    display_messages = False
    force_retrieve = False
    # Loop through all of the candidates in this election
    for we_vote_candidate in candidate_list:
        retrieve_candidate_results = retrieve_candidate_photos(we_vote_candidate, force_retrieve)

        if retrieve_candidate_results["status"] and display_messages:
            messages.add_message(request, messages.INFO, retrieve_candidate_results["status"])

    return HttpResponseRedirect(
        reverse("candidate:candidate_list", args=())
        + "?google_civic_election_id={var}".format(var=google_civic_election_id)
    )
Exemple #11
0
    def retrieve_ballot_item_for_voter(self, voter_id, google_civic_election_id, google_civic_district_ocd_id):
        exception_does_not_exist = False
        exception_multiple_object_returned = False
        google_civic_ballot_item_on_stage = BallotItem()
        google_civic_ballot_item_id = 0

        if positive_value_exists(voter_id) and positive_value_exists(google_civic_election_id) and \
                positive_value_exists(google_civic_district_ocd_id):
            try:
                google_civic_ballot_item_on_stage = BallotItem.objects.get(
                    voter_id__exact=voter_id,
                    google_civic_election_id__exact=google_civic_election_id,
                    district_ocd_id=google_civic_district_ocd_id,  # TODO This needs to be rethunk
                )
                google_civic_ballot_item_id = google_civic_ballot_item_on_stage.id
            except BallotItem.MultipleObjectsReturned as e:
                handle_record_found_more_than_one_exception(e, logger=logger)
                exception_multiple_object_returned = True
            except BallotItem.DoesNotExist:
                exception_does_not_exist = True

        results = {
            'success':                          True if google_civic_ballot_item_id > 0 else False,
            'DoesNotExist':                     exception_does_not_exist,
            'MultipleObjectsReturned':          exception_multiple_object_returned,
            'google_civic_ballot_item':         google_civic_ballot_item_on_stage,
        }
        return results
def polling_location_list_view(request):
    polling_location_state = request.GET.get('polling_location_state')
    no_limit = False

    polling_location_count_query = PollingLocation.objects.all()
    if positive_value_exists(polling_location_state):
        polling_location_count_query = polling_location_count_query.filter(state__iexact=polling_location_state)
    polling_location_count = polling_location_count_query.count()
    messages.add_message(request, messages.INFO, '{polling_location_count} polling locations found.'.format(
        polling_location_count=polling_location_count))

    polling_location_query = PollingLocation.objects.all()
    if positive_value_exists(polling_location_state):
        polling_location_query = polling_location_query.filter(state__iexact=polling_location_state)
    if no_limit:
        polling_location_query = polling_location_query.order_by('location_name')
    else:
        polling_location_query = polling_location_query.order_by('location_name')[:100]
    polling_location_list = polling_location_query

    state_list = STATE_LIST_IMPORT

    messages_on_stage = get_messages(request)

    template_values = {
        'messages_on_stage':        messages_on_stage,
        'polling_location_list':    polling_location_list,
        'polling_location_count':   polling_location_count,
        'polling_location_state':   polling_location_state,
        'state_list':               state_list,
    }
    return render(request, 'polling_location/polling_location_list.html', template_values)
Exemple #13
0
 def get_ballot_item_we_vote_id(self):
     if positive_value_exists(self.contest_office_we_vote_id):
         return self.contest_office_we_vote_id
     elif positive_value_exists(self.candidate_campaign_we_vote_id):
         return self.candidate_campaign_we_vote_id
     elif positive_value_exists(self.politician_we_vote_id):
         return self.politician_we_vote_id
     elif positive_value_exists(self.contest_measure_we_vote_id):
         return self.contest_measure_we_vote_id
     return None
Exemple #14
0
 def get_kind_of_ballot_item(self):
     if positive_value_exists(self.contest_office_we_vote_id):
         return OFFICE
     elif positive_value_exists(self.candidate_campaign_we_vote_id):
         return CANDIDATE
     elif positive_value_exists(self.politician_we_vote_id):
         return POLITICIAN
     elif positive_value_exists(self.contest_measure_we_vote_id):
         return MEASURE
     return None
Exemple #15
0
def admin_home_view(request):
    results = voter_setup(request)
    voter_device_id = results['voter_device_id']
    store_new_voter_device_id_in_cookie = results['store_new_voter_device_id_in_cookie']
    template_values = {
    }
    response = render(request, 'admin_tools/index.html', template_values)

    # We want to store the voter_device_id cookie if it is new
    if positive_value_exists(voter_device_id) and positive_value_exists(store_new_voter_device_id_in_cookie):
        set_voter_device_id(request, response, voter_device_id)

    return response
Exemple #16
0
    def retrieve_candidate_campaign(
            self, candidate_campaign_id, we_vote_id=None, candidate_maplight_id=None,
            candidate_name=None, candidate_vote_smart_id=None):
        error_result = False
        exception_does_not_exist = False
        exception_multiple_object_returned = False
        candidate_campaign_on_stage = CandidateCampaign()

        try:
            if positive_value_exists(candidate_campaign_id):
                candidate_campaign_on_stage = CandidateCampaign.objects.get(id=candidate_campaign_id)
                candidate_campaign_id = candidate_campaign_on_stage.id
                status = "RETRIEVE_CANDIDATE_FOUND_BY_ID"
            elif positive_value_exists(we_vote_id):
                candidate_campaign_on_stage = CandidateCampaign.objects.get(we_vote_id=we_vote_id)
                candidate_campaign_id = candidate_campaign_on_stage.id
                status = "RETRIEVE_CANDIDATE_FOUND_BY_WE_VOTE_ID"
            elif positive_value_exists(candidate_maplight_id):
                candidate_campaign_on_stage = CandidateCampaign.objects.get(maplight_id=candidate_maplight_id)
                candidate_campaign_id = candidate_campaign_on_stage.id
                status = "RETRIEVE_CANDIDATE_FOUND_BY_MAPLIGHT_ID"
            elif positive_value_exists(candidate_vote_smart_id):
                candidate_campaign_on_stage = CandidateCampaign.objects.get(vote_smart_id=candidate_vote_smart_id)
                candidate_campaign_id = candidate_campaign_on_stage.id
                status = "RETRIEVE_CANDIDATE_FOUND_BY_VOTE_SMART_ID"
            elif positive_value_exists(candidate_name):
                candidate_campaign_on_stage = CandidateCampaign.objects.get(candidate_name=candidate_name)
                candidate_campaign_id = candidate_campaign_on_stage.id
                status = "RETRIEVE_CANDIDATE_FOUND_BY_NAME"
            else:
                status = "RETRIEVE_CANDIDATE_SEARCH_INDEX_MISSING"
        except CandidateCampaign.MultipleObjectsReturned as e:
            handle_record_found_more_than_one_exception(e, logger=logger)
            exception_multiple_object_returned = True
            status = "RETRIEVE_CANDIDATE_MULTIPLE_OBJECTS_RETURNED"
        except CandidateCampaign.DoesNotExist:
            exception_does_not_exist = True
            status = "RETRIEVE_CANDIDATE_NOT_FOUND"

        results = {
            'success':                  True if candidate_campaign_id > 0 else False,
            'status':                   status,
            'error_result':             error_result,
            'DoesNotExist':             exception_does_not_exist,
            'MultipleObjectsReturned':  exception_multiple_object_returned,
            'candidate_campaign_found': True if candidate_campaign_id > 0 else False,
            'candidate_campaign_id':    candidate_campaign_id,
            'candidate_campaign':       candidate_campaign_on_stage,
        }
        return results
def organization_search_for_api(organization_name, organization_twitter_handle, organization_website,
                                organization_email):
    organization_name = organization_name.strip()
    organization_twitter_handle = organization_twitter_handle.strip()
    organization_website = organization_website.strip()
    organization_email = organization_email.strip()

    # We need at least one term to search for
    if not positive_value_exists(organization_name) \
            and not positive_value_exists(organization_twitter_handle)\
            and not positive_value_exists(organization_website)\
            and not positive_value_exists(organization_email):
        json_data = {
            'status':               "ORGANIZATION_SEARCH_ALL_TERMS_MISSING",
            'success':              False,
            'organization_name':    organization_name,
            'organization_twitter_handle': organization_twitter_handle,
            'organization_website': organization_website,
            'organization_email':   organization_email,
            'organizations_list':   [],
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    organization_list_manager = OrganizationListManager()
    results = organization_list_manager.organization_search_find_any_possibilities(
        organization_name, organization_twitter_handle, organization_website, organization_email)

    if results['organizations_found']:
        organizations_list = results['organizations_list']
        json_data = {
            'status': results['status'],
            'success': True,
            'organization_name':    organization_name,
            'organization_twitter_handle': organization_twitter_handle,
            'organization_website': organization_website,
            'organization_email':   organization_email,
            'organizations_list':   organizations_list,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
    else:
        json_data = {
            'status':               results['status'],
            'success':              False,
            'organization_name':    organization_name,
            'organization_twitter_handle': organization_twitter_handle,
            'organization_website': organization_website,
            'organization_email':   organization_email,
            'organizations_list':   [],
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemple #18
0
    def retrieve_vote_smart_candidate(
            self, vote_smart_candidate_id=None, first_name=None, last_name=None, state_code=None):
        """
        We want to return one and only one candidate
        :param vote_smart_candidate_id:
        :param first_name:
        :param last_name:
        :param state_code:
        :return:
        """
        error_result = False
        exception_does_not_exist = False
        exception_multiple_object_returned = False
        vote_smart_candidate = VoteSmartCandidate()

        try:
            if positive_value_exists(vote_smart_candidate_id):
                vote_smart_candidate = VoteSmartCandidate.objects.get(candidateId=vote_smart_candidate_id)
                vote_smart_candidate_id = convert_to_int(vote_smart_candidate.candidateId)
                status = "RETRIEVE_VOTE_SMART_CANDIDATE_FOUND_BY_ID"
            elif positive_value_exists(first_name) or positive_value_exists(last_name):
                candidate_queryset = VoteSmartCandidate.objects.all()
                if positive_value_exists(first_name):
                    first_name = first_name.replace("`", "'")  # Vote Smart doesn't like this kind of apostrophe: `
                    candidate_queryset = candidate_queryset.filter(Q(firstName__istartswith=first_name) |
                                                                   Q(nickName__istartswith=first_name) |
                                                                   Q(preferredName__istartswith=first_name))
                if positive_value_exists(last_name):
                    last_name = last_name.replace("`", "'")  # Vote Smart doesn't like this kind of apostrophe: `
                    candidate_queryset = candidate_queryset.filter(lastName__iexact=last_name)
                if positive_value_exists(state_code):
                    candidate_queryset = candidate_queryset.filter(Q(electionStateId__iexact=state_code) |
                                                                   Q(electionStateId__iexact="NA"))
                vote_smart_candidate_list = list(candidate_queryset[:1])
                if vote_smart_candidate_list:
                    vote_smart_candidate = vote_smart_candidate_list[0]
                else:
                    vote_smart_candidate = VoteSmartCandidate()
                vote_smart_candidate_id = convert_to_int(vote_smart_candidate.candidateId)
                status = "RETRIEVE_VOTE_SMART_CANDIDATE_FOUND_BY_NAME"
            else:
                status = "RETRIEVE_VOTE_SMART_CANDIDATE_SEARCH_INDEX_MISSING"
        except VoteSmartCandidate.MultipleObjectsReturned as e:
            exception_multiple_object_returned = True
            status = "RETRIEVE_VOTE_SMART_CANDIDATE_MULTIPLE_OBJECTS_RETURNED"
        except VoteSmartCandidate.DoesNotExist:
            exception_does_not_exist = True
            status = "RETRIEVE_VOTE_SMART_CANDIDATE_NOT_FOUND"

        results = {
            'success':                      True if positive_value_exists(vote_smart_candidate_id) else False,
            'status':                       status,
            'error_result':                 error_result,
            'DoesNotExist':                 exception_does_not_exist,
            'MultipleObjectsReturned':      exception_multiple_object_returned,
            'vote_smart_candidate_found':   True if positive_value_exists(vote_smart_candidate_id) else False,
            'vote_smart_candidate_id':      vote_smart_candidate_id,
            'vote_smart_candidate':         vote_smart_candidate,
        }
        return results
def voter_position_like_status_retrieve_for_api(voter_device_id, position_entered_id):
    # Get voter_id from the voter_device_id so we can know who is doing the liking
    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_liked':             False,
            'position_entered_id':  position_entered_id,
            'position_like_id':     0,
        }
        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_liked':             False,
            'position_entered_id':  position_entered_id,
            'position_like_id':     0,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    position_like_manager = PositionLikeManager()
    if positive_value_exists(position_entered_id):
        position_like_id = 0
        results = position_like_manager.retrieve_position_like(position_like_id, voter_id, position_entered_id)
        status = results['status']
        success = results['success']
        is_liked = results['is_liked']
        position_like_id = results['position_like_id']
    else:
        status = 'UNABLE_TO_RETRIEVE-POSITION_ENTERED_ID_MISSING'
        success = False
        is_liked = False
        position_like_id = 0

    json_data = {
        'status':               status,
        'success':              success,
        'voter_device_id':      voter_device_id,
        'is_liked':             is_liked,
        'position_entered_id':  position_entered_id,
        'position_like_id':     position_like_id,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemple #20
0
    def retrieve_all_candidates_for_office(self, office_id, office_we_vote_id):
        candidate_list = []
        candidate_list_found = False

        if not positive_value_exists(office_id) and not positive_value_exists(office_we_vote_id):
            status = 'VALID_OFFICE_ID_AND_OFFICE_WE_VOTE_ID_MISSING'
            results = {
                'success':              True if candidate_list_found else False,
                'status':               status,
                'office_id':            office_id,
                'office_we_vote_id':    office_we_vote_id,
                'candidate_list_found': candidate_list_found,
                'candidate_list':       candidate_list,
            }
            return results

        try:
            candidate_queryset = CandidateCampaign.objects.all()
            if positive_value_exists(office_id):
                candidate_queryset = candidate_queryset.filter(contest_office_id=office_id)
            elif positive_value_exists(office_we_vote_id):
                candidate_queryset = candidate_queryset.filter(contest_office_we_vote_id=office_we_vote_id)
            candidate_queryset = candidate_queryset.order_by('candidate_name')
            candidate_list = candidate_queryset

            if len(candidate_list):
                candidate_list_found = True
                status = 'CANDIDATES_RETRIEVED'
            else:
                status = 'NO_CANDIDATES_RETRIEVED'
        except CandidateCampaign.DoesNotExist:
            # No candidates found. Not a problem.
            status = 'NO_CANDIDATES_FOUND_DoesNotExist'
            candidate_list = []
        except Exception as e:
            handle_exception(e, logger=logger)
            status = 'FAILED retrieve_all_candidates_for_office ' \
                     '{error} [type: {error_type}]'.format(error=e.message, error_type=type(e))

        results = {
            'success':              True if candidate_list_found else False,
            'status':               status,
            'office_id':            office_id,
            'office_we_vote_id':    office_we_vote_id,
            'candidate_list_found': candidate_list_found,
            'candidate_list':       candidate_list,
        }
        return results
Exemple #21
0
    def retrieve_organization(self, organization_id, we_vote_id=None, vote_smart_id=None):
        error_result = False
        exception_does_not_exist = False
        exception_multiple_object_returned = False
        organization_on_stage = Organization()
        organization_on_stage_id = 0
        status = "ERROR_ENTERING_RETRIEVE_ORGANIZATION"
        try:
            if positive_value_exists(organization_id):
                status = "ERROR_RETRIEVING_ORGANIZATION_WITH_ID"
                organization_on_stage = Organization.objects.get(id=organization_id)
                organization_on_stage_id = organization_on_stage.id
                status = "ORGANIZATION_FOUND_WITH_ID"
            elif positive_value_exists(we_vote_id):
                status = "ERROR_RETRIEVING_ORGANIZATION_WITH_WE_VOTE_ID"
                organization_on_stage = Organization.objects.get(we_vote_id=we_vote_id)
                organization_on_stage_id = organization_on_stage.id
                status = "ORGANIZATION_FOUND_WITH_WE_VOTE_ID"
            elif positive_value_exists(vote_smart_id):
                status = "ERROR_RETRIEVING_ORGANIZATION_WITH_VOTE_SMART_ID"
                organization_on_stage = Organization.objects.get(vote_smart_id=vote_smart_id)
                organization_on_stage_id = organization_on_stage.id
                status = "ORGANIZATION_FOUND_WITH_VOTE_SMART_ID"
        except Organization.MultipleObjectsReturned as e:
            handle_record_found_more_than_one_exception(e, logger)
            error_result = True
            exception_multiple_object_returned = True
            status = "ERROR_MORE_THAN_ONE_ORGANIZATION_FOUND"
            # logger.warn("Organization.MultipleObjectsReturned")
        except Organization.DoesNotExist:
            error_result = True
            exception_does_not_exist = True
            status += ", ORGANIZATION_NOT_FOUND"
            # logger.warn("Organization.DoesNotExist")

        organization_on_stage_found = True if organization_on_stage_id > 0 else False
        results = {
            "success": True if organization_on_stage_found else False,
            "status": status,
            "organization_found": organization_on_stage_found,
            "organization_id": organization_on_stage.id if organization_on_stage.id else organization_on_stage_id,
            "we_vote_id": organization_on_stage.we_vote_id if organization_on_stage.we_vote_id else we_vote_id,
            "organization": organization_on_stage,
            "error_result": error_result,
            "DoesNotExist": exception_does_not_exist,
            "MultipleObjectsReturned": exception_multiple_object_returned,
        }
        return results
def organization_retrieve_for_api(organization_id, organization_we_vote_id):
    organization_id = convert_to_int(organization_id)

    we_vote_id = organization_we_vote_id.strip()
    if not positive_value_exists(organization_id) and not positive_value_exists(organization_we_vote_id):
        json_data = {
            'status': "ORGANIZATION_RETRIEVE_BOTH_IDS_MISSING",
            'success': False,
            'organization_id': organization_id,
            'organization_we_vote_id': organization_we_vote_id,
            'organization_name': '',
            'organization_email': '',
            'organization_website': '',
            'organization_twitter_handle': '',
            'organization_facebook': '',
            'organization_photo_url': '',
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    organization_manager = OrganizationManager()
    results = organization_manager.retrieve_organization(organization_id, organization_we_vote_id)

    if results['organization_found']:
        organization = results['organization']
        json_data = {
            'success': True,
            'status': results['status'],
            'organization_id': organization.id,
            'organization_we_vote_id': organization.we_vote_id,
            'organization_name':
                organization.organization_name if positive_value_exists(organization.organization_name) else '',
            'organization_website': organization.organization_website if positive_value_exists(
                organization.organization_website) else '',
            'organization_twitter_handle':
                organization.organization_twitter_handle if positive_value_exists(
                    organization.organization_twitter_handle) else '',
            'organization_email':
                organization.organization_email if positive_value_exists(organization.organization_email) else '',
            'organization_facebook':
                organization.organization_facebook if positive_value_exists(organization.organization_facebook) else '',
            'organization_photo_url': organization.organization_photo_url()
                if positive_value_exists(organization.organization_photo_url()) else '',
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
    else:
        json_data = {
            'status': results['status'],
            'success': False,
            'organization_id': organization_id,
            'organization_we_vote_id': we_vote_id,
            'organization_name': '',
            'organization_email': '',
            'organization_website': '',
            'organization_twitter_handle': '',
            'organization_facebook': '',
            'organization_photo_url': '',
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
    def delete_voter(self, email):
        email = self.normalize_email(email)
        voter_id = 0
        voter_deleted = False

        if positive_value_exists(email) and validate_email(email):
            email_valid = True
        else:
            email_valid = False

        try:
            if email_valid:
                results = self.retrieve_voter(voter_id, email)
                if results['voter_found']:
                    voter = results['voter']
                    voter_id = voter.id
                    voter.delete()
                    voter_deleted = True
        except Exception as e:
            handle_exception(e, logger=logger)

        results = {
            'email_not_valid':      True if not email_valid else False,
            'voter_deleted':        voter_deleted,
            'voter_id':             voter_id,
        }
        return results
Exemple #24
0
def ballot_item_retrieve_view(request):
    kind_of_ballot_item = request.GET.get('kind_of_ballot_item', "")
    ballot_item_id = request.GET.get('ballot_item_id', 0)
    ballot_item_we_vote_id = request.GET.get('ballot_item_we_vote_id', None)

    if not positive_value_exists(kind_of_ballot_item) or kind_of_ballot_item not in(OFFICE, CANDIDATE, MEASURE):
        status = 'VALID_BALLOT_ITEM_TYPE_MISSING'
        json_data = {
            'status':                   status,
            'success':                  False,
            'kind_of_ballot_item':         kind_of_ballot_item,
            'ballot_item_id':           ballot_item_id,
            'ballot_item_we_vote_id':   ballot_item_we_vote_id,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    if kind_of_ballot_item == OFFICE:
        return office_retrieve_for_api(ballot_item_id, ballot_item_we_vote_id)
    elif kind_of_ballot_item == CANDIDATE:
        return candidate_retrieve_for_api(ballot_item_id, ballot_item_we_vote_id)
    elif kind_of_ballot_item == MEASURE:
        return measure_retrieve_for_api(ballot_item_id, ballot_item_we_vote_id)
    else:
        status = 'BALLOT_ITEM_RETRIEVE_UNKNOWN_ERROR'
        json_data = {
            'status':                   status,
            'success':                  False,
            'kind_of_ballot_item':      kind_of_ballot_item,
            'ballot_item_id':           ballot_item_id,
            'ballot_item_we_vote_id':   ballot_item_we_vote_id,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemple #25
0
    def retrieve_all_ballot_items_for_voter(self, voter_id, google_civic_election_id):
        ballot_item_list = []
        ballot_item_list_found = False
        try:
            ballot_item_queryset = BallotItem.objects.order_by('local_ballot_order')
            ballot_item_queryset = ballot_item_queryset.filter(voter_id=voter_id)
            if positive_value_exists(google_civic_election_id):
                ballot_item_queryset = ballot_item_queryset.filter(google_civic_election_id=google_civic_election_id)
            ballot_item_list = ballot_item_queryset

            if len(ballot_item_list):
                ballot_item_list_found = True
                status = 'BALLOT_ITEMS_FOUND, retrieve_all_ballot_items_for_voter'
            else:
                status = 'NO_BALLOT_ITEMS_FOUND_0'
        except BallotItem.DoesNotExist:
            # No ballot items found. Not a problem.
            status = 'NO_BALLOT_ITEMS_FOUND_DoesNotExist'
            ballot_item_list = []
        except Exception as e:
            handle_exception(e, logger=logger)
            status = 'FAILED retrieve_all_ballot_items_for_voter ' \
                     '{error} [type: {error_type}]'.format(error=e.message, error_type=type(e))

        results = {
            'success':                      True if ballot_item_list_found else False,
            'status':                       status,
            'google_civic_election_id':     google_civic_election_id,
            'voter_id':                     voter_id,
            'ballot_item_list_found':       ballot_item_list_found,
            'ballot_item_list':             ballot_item_list,
        }
        return results
Exemple #26
0
    def delete_all_ballot_items_for_voter(self, voter_id, google_civic_election_id):
        ballot_item_list_deleted = False
        try:
            ballot_item_queryset = BallotItem.objects.filter(voter_id=voter_id)
            if positive_value_exists(google_civic_election_id):
                ballot_item_queryset = ballot_item_queryset.filter(google_civic_election_id=google_civic_election_id)
            ballot_item_queryset.delete()

            ballot_item_list_deleted = True
            status = 'BALLOT_ITEMS_DELETED'
        except BallotItem.DoesNotExist:
            # No ballot items found. Not a problem.
            status = 'NO_BALLOT_ITEMS_DELETED_DoesNotExist'
        except Exception as e:
            handle_exception(e, logger=logger)
            status = 'FAILED delete_all_ballot_items_for_voter ' \
                     '{error} [type: {error_type}]'.format(error=e.message, error_type=type(e))

        results = {
            'success':                      True if ballot_item_list_deleted else False,
            'status':                       status,
            'google_civic_election_id':     google_civic_election_id,
            'voter_id':                     voter_id,
            'ballot_item_list_deleted':     ballot_item_list_deleted,
        }
        return results
def voter_guide_possibility_retrieve_for_api(voter_device_id, voter_guide_possibility_url):
    results = is_voter_device_id_valid(voter_device_id)
    voter_guide_possibility_url = voter_guide_possibility_url  # TODO Use scrapy here
    if not results['success']:
        return HttpResponse(json.dumps(results['json_data']), content_type='application/json')

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

    # TODO We will need the voter_id here so we can control volunteer actions

    voter_guide_possibility_manager = VoterGuidePossibilityManager()
    results = voter_guide_possibility_manager.retrieve_voter_guide_possibility_from_url(voter_guide_possibility_url)

    json_data = {
        'voter_device_id':              voter_device_id,
        'voter_guide_possibility_url':  results['voter_guide_possibility_url'],
        'voter_guide_possibility_id':   results['voter_guide_possibility_id'],
        'organization_we_vote_id':      results['organization_we_vote_id'],
        'public_figure_we_vote_id':     results['public_figure_we_vote_id'],
        'owner_we_vote_id':             results['owner_we_vote_id'],
        'status':                       results['status'],
        'success':                      results['success'],
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_guide_list_view(request):
    google_civic_election_id = request.GET.get('google_civic_election_id', 0)

    voter_guide_list = []
    voter_guide_list_object = VoterGuideList()
    if positive_value_exists(google_civic_election_id):
        results = voter_guide_list_object.retrieve_voter_guides_for_election(
            google_civic_election_id=google_civic_election_id)

        if results['success']:
            voter_guide_list = results['voter_guide_list']
    else:
        results = voter_guide_list_object.retrieve_all_voter_guides()

        if results['success']:
            voter_guide_list = results['voter_guide_list']

    election_list = Election.objects.order_by('-election_day_text')

    messages_on_stage = get_messages(request)
    template_values = {
        'election_list': election_list,
        'google_civic_election_id': google_civic_election_id,
        'messages_on_stage': messages_on_stage,
        'voter_guide_list': voter_guide_list,
    }
    return render(request, 'voter_guide/voter_guide_list.html', template_values)
Exemple #29
0
    def retrieve_voter(self, voter_id, email='', voter_we_vote_id=''):
        voter_id = convert_to_int(voter_id)
        if not validate_email(email):
            # We do not want to search for an invalid email
            email = None
        if positive_value_exists(voter_we_vote_id):
            voter_we_vote_id = voter_we_vote_id.strip()
        error_result = False
        exception_does_not_exist = False
        exception_multiple_object_returned = False
        voter_on_stage = Voter()

        try:
            if positive_value_exists(voter_id):
                voter_on_stage = Voter.objects.get(id=voter_id)
                # If still here, we found an existing voter
                voter_id = voter_on_stage.id
            elif email is not '' and email is not None:
                voter_on_stage = Voter.objects.get(
                    email=email)
                # If still here, we found an existing voter
                voter_id = voter_on_stage.id
            elif positive_value_exists(voter_we_vote_id):
                voter_on_stage = Voter.objects.get(
                    we_vote_id=voter_we_vote_id)
                # If still here, we found an existing voter
                voter_id = voter_on_stage.id
            else:
                voter_id = 0
                error_result = True
        except Voter.MultipleObjectsReturned as e:
            handle_record_found_more_than_one_exception(e, logger=logger)
            error_result = True
            exception_multiple_object_returned = True
        except Voter.DoesNotExist as e:
            error_result = True
            exception_does_not_exist = True

        results = {
            'error_result':             error_result,
            'DoesNotExist':             exception_does_not_exist,
            'MultipleObjectsReturned':  exception_multiple_object_returned,
            'voter_found':              True if voter_id > 0 else False,
            'voter_id':                 voter_id,
            'voter':                    voter_on_stage,
        }
        return results
Exemple #30
0
    def retrieve_position_like(self, position_like_id, voter_id, position_entered_id):
        error_result = False
        exception_does_not_exist = False
        exception_multiple_object_returned = False
        position_like = PositionLike()

        try:
            if positive_value_exists(position_like_id):
                position_like = PositionLike.objects.get(id=position_like_id)
                position_like_id = position_like.id
                status = 'POSITION_LIKE_FOUND_WITH_ID'
                success = True
            elif positive_value_exists(voter_id) and positive_value_exists(position_entered_id):
                position_like = PositionLike.objects.get(
                    voter_id=voter_id,
                    position_entered_id=position_entered_id)
                position_like_id = position_like.id
                status = 'POSITION_LIKE_FOUND_WITH_VOTER_ID_AND_POSITION_ID'
                success = True
            else:
                status = 'POSITION_LIKE_NOT_FOUND-MISSING_VARIABLES'
                success = False
        except PositionLike.MultipleObjectsReturned as e:
            handle_record_found_more_than_one_exception(e, logger=logger)
            error_result = True
            exception_multiple_object_returned = True
            status = 'POSITION_LIKE_NOT_FOUND_MultipleObjectsReturned'
            success = False
        except PositionLike.DoesNotExist:
            error_result = False
            exception_does_not_exist = True
            status = 'POSITION_LIKE_NOT_FOUND_DoesNotExist'
            success = True

        position_like_found = True if position_like_id > 0 else False
        results = {
            'status':                   status,
            'success':                  success,
            'position_like_found':      position_like_found,
            'position_like_id':         position_like_id,
            'position_like':            position_like,
            'is_liked':                 position_like_found,
            'error_result':             error_result,
            'DoesNotExist':             exception_does_not_exist,
            'MultipleObjectsReturned':  exception_multiple_object_returned,
        }
        return results