def transfer_candidate_twitter_handles_from_google_civic(google_civic_election_id=0):
    twitter_handles_transferred = 0
    status = ""
    google_civic_election_id = convert_to_int(google_civic_election_id)

    candidate_list_object = CandidateCampaignList()
    return_list_of_objects = True
    results = candidate_list_object.retrieve_all_candidates_for_upcoming_election(google_civic_election_id,
                                                                                  return_list_of_objects)
    status += results['status']
    if results['success']:
        candidate_list = results['candidate_list_objects']
    else:
        candidate_list = []

    for candidate in candidate_list:
        if not candidate.twitter_url:
            continue
        # Only proceed if we don't already have a twitter_handle
        if not positive_value_exists(candidate.candidate_twitter_handle):
            candidate.candidate_twitter_handle = candidate.twitter_url.replace("https://twitter.com/", "")
            candidate.save()
            twitter_handles_transferred += 1

        # ######################################
        # We refresh the Twitter information in another function

    status += " CANDIDATE_TWITTER_HANDLES_TRANSFERRED"
    results = {
        'success':                      True,
        'status':                       status,
        'twitter_handles_transferred':  twitter_handles_transferred,
    }
    return results
def refresh_twitter_candidate_details_for_election(google_civic_election_id):
    twitter_handles_added = 0
    profiles_refreshed_with_twitter_data = 0

    google_civic_election_id = convert_to_int(google_civic_election_id)

    candidate_list_manager = CandidateCampaignList()
    return_list_of_objects = True
    candidates_results = candidate_list_manager.retrieve_all_candidates_for_upcoming_election(
        google_civic_election_id, return_list_of_objects)
    if candidates_results['candidate_list_found']:
        candidate_list = candidates_results['candidate_list_objects']

        for candidate in candidate_list:
            # Extract twitter_handle from google_civic_election information
            if positive_value_exists(candidate.twitter_url) \
                    and not positive_value_exists(candidate.candidate_twitter_handle):
                # If we got a twitter_url from Google Civic, and we haven't already stored a twitter handle, move it
                candidate.candidate_twitter_handle = candidate.twitter_url.replace("https://twitter.com/", "")
                candidate.save()
                twitter_handles_added += 1
            if positive_value_exists(candidate.candidate_twitter_handle):
                refresh_twitter_candidate_details(candidate)
                profiles_refreshed_with_twitter_data += 1

    status = "CANDIDATE_SOCIAL_MEDIA_RETRIEVED"
    results = {
        'success':                              True,
        'status':                               status,
        'twitter_handles_added':                twitter_handles_added,
        'profiles_refreshed_with_twitter_data': profiles_refreshed_with_twitter_data,
    }
    return results
def organization_add_new_position_form_view(request, organization_id):
    messages_on_stage = get_messages(request)
    organization_id = convert_to_int(organization_id)
    all_is_well = True
    organization_on_stage_found = False
    try:
        organization_on_stage = Organization.objects.get(id=organization_id)
        organization_on_stage_found = True
    except Organization.MultipleObjectsReturned as e:
        handle_record_found_more_than_one_exception(e, logger=logger)
    except Organization.DoesNotExist:
        # This is fine, create new
        pass

    if not organization_on_stage_found:
        messages.add_message(request, messages.INFO,
                             'Could not find organization when trying to create a new position.')
        return HttpResponseRedirect(reverse('organization:organization_position_list', args=([organization_id])))

    # Prepare a drop down of candidates competing in this election
    candidate_campaign_list = CandidateCampaignList()
    candidate_campaigns_for_this_election_list \
        = candidate_campaign_list.retrieve_candidate_campaigns_for_this_election_list()

    if all_is_well:
        template_values = {
            'candidate_campaigns_for_this_election_list':   candidate_campaigns_for_this_election_list,
            'messages_on_stage':                            messages_on_stage,
            'organization':                                 organization_on_stage,
            'organization_position_candidate_campaign_id':  0,
            'possible_stances_list':                        ORGANIZATION_STANCE_CHOICES,
            'stance_selected':                              SUPPORT,  # Default stance
        }
    return render(request, 'organization/organization_position_edit.html', template_values)
def scrape_and_save_social_media_for_candidates_in_one_election(
        google_civic_election_id=0):
    facebook_pages_found = 0
    twitter_handles_found = 0
    force_retrieve = False
    status = ""
    google_civic_election_id = convert_to_int(google_civic_election_id)

    candidate_manager = CandidateCampaignManager()
    candidate_list_manager = CandidateCampaignList()
    return_list_of_objects = True
    results = candidate_list_manager.retrieve_all_candidates_for_upcoming_election(
        google_civic_election_id, return_list_of_objects)
    status += results['status']
    if results['success']:
        candidate_list = results['candidate_list_objects']
    else:
        candidate_list = []

    for candidate in candidate_list:
        twitter_handle = False
        facebook_page = False
        if not candidate.candidate_url:
            continue
        if (not positive_value_exists(
                candidate.candidate_twitter_handle)) or force_retrieve:
            scrape_results = scrape_social_media_from_one_site(
                candidate.candidate_url)

            # Only include a change if we have a new value (do not try to save blank value)
            if scrape_results['twitter_handle_found'] and positive_value_exists(
                    scrape_results['twitter_handle']):
                twitter_handle = scrape_results['twitter_handle']
                twitter_handles_found += 1

            if scrape_results['facebook_page_found'] and positive_value_exists(
                    scrape_results['facebook_page']):
                facebook_page = scrape_results['facebook_page']
                facebook_pages_found += 1

            save_results = candidate_manager.update_candidate_social_media(
                candidate, twitter_handle, facebook_page)

        # ######################################
        # We refresh the Twitter information in another function

    status = "ORGANIZATION_SOCIAL_MEDIA_RETRIEVED"
    results = {
        'success': True,
        'status': status,
        'twitter_handles_found': twitter_handles_found,
        'facebook_pages_found': facebook_pages_found,
    }
    return results
def scrape_and_save_social_media_for_candidates_in_one_election(google_civic_election_id=0):
    facebook_pages_found = 0
    twitter_handles_found = 0
    force_retrieve = False
    status = ""
    google_civic_election_id = convert_to_int(google_civic_election_id)

    candidate_manager = CandidateCampaignManager()
    candidate_list_manager = CandidateCampaignList()
    return_list_of_objects = True
    results = candidate_list_manager.retrieve_all_candidates_for_upcoming_election(google_civic_election_id,
                                                                                  return_list_of_objects)
    status += results['status']
    if results['success']:
        candidate_list = results['candidate_list_objects']
    else:
        candidate_list = []

    for candidate in candidate_list:
        twitter_handle = False
        facebook_page = False
        if not candidate.candidate_url:
            continue
        if (not positive_value_exists(candidate.candidate_twitter_handle)) or force_retrieve:
            scrape_results = scrape_social_media_from_one_site(candidate.candidate_url)

            # Only include a change if we have a new value (do not try to save blank value)
            if scrape_results['twitter_handle_found'] and positive_value_exists(scrape_results['twitter_handle']):
                twitter_handle = scrape_results['twitter_handle']
                twitter_handles_found += 1

            if scrape_results['facebook_page_found'] and positive_value_exists(scrape_results['facebook_page']):
                facebook_page = scrape_results['facebook_page']
                facebook_pages_found += 1

            save_results = candidate_manager.update_candidate_social_media(candidate, twitter_handle, facebook_page)

        # ######################################
        # We refresh the Twitter information in another function

    status = "ORGANIZATION_SOCIAL_MEDIA_RETRIEVED"
    results = {
        'success':                  True,
        'status':                   status,
        'twitter_handles_found':    twitter_handles_found,
        'facebook_pages_found':     facebook_pages_found,
    }
    return results
Exemple #6
0
def organization_add_new_position_form_view(request, organization_id):
    messages_on_stage = get_messages(request)
    organization_id = convert_to_int(organization_id)
    all_is_well = True
    organization_on_stage_found = False
    try:
        organization_on_stage = Organization.objects.get(id=organization_id)
        organization_on_stage_found = True
    except Organization.MultipleObjectsReturned as e:
        handle_record_found_more_than_one_exception(e, logger=logger)
    except Organization.DoesNotExist:
        # This is fine, create new
        pass

    if not organization_on_stage_found:
        messages.add_message(
            request, messages.INFO,
            'Could not find organization when trying to create a new position.'
        )
        return HttpResponseRedirect(
            reverse('organization:organization_position_list',
                    args=([organization_id])))

    # Prepare a drop down of candidates competing in this election
    candidate_campaign_list = CandidateCampaignList()
    candidate_campaigns_for_this_election_list \
        = candidate_campaign_list.retrieve_candidate_campaigns_for_this_election_list()

    if all_is_well:
        template_values = {
            'candidate_campaigns_for_this_election_list':
            candidate_campaigns_for_this_election_list,
            'messages_on_stage': messages_on_stage,
            'organization': organization_on_stage,
            'organization_position_candidate_campaign_id': 0,
            'possible_stances_list': ORGANIZATION_STANCE_CHOICES,
            'stance_selected': SUPPORT,  # Default stance
        }
    return render(request, 'organization/organization_position_edit.html',
                  template_values)
def refresh_twitter_candidate_details_for_election(google_civic_election_id):
    twitter_handles_added = 0
    profiles_refreshed_with_twitter_data = 0

    google_civic_election_id = convert_to_int(google_civic_election_id)

    candidate_list_manager = CandidateCampaignList()
    return_list_of_objects = True
    candidates_results = candidate_list_manager.retrieve_all_candidates_for_upcoming_election(
        google_civic_election_id, return_list_of_objects)
    if candidates_results['candidate_list_found']:
        candidate_list = candidates_results['candidate_list_objects']

        for candidate in candidate_list:
            # Extract twitter_handle from google_civic_election information
            if positive_value_exists(candidate.twitter_url) \
                    and not positive_value_exists(candidate.candidate_twitter_handle):
                # If we got a twitter_url from Google Civic, and we haven't already stored a twitter handle, move it
                candidate.candidate_twitter_handle = candidate.twitter_url.replace(
                    "https://twitter.com/", "")
                candidate.save()
                twitter_handles_added += 1
            if positive_value_exists(candidate.candidate_twitter_handle):
                refresh_twitter_candidate_details(candidate)
                profiles_refreshed_with_twitter_data += 1

    status = "CANDIDATE_SOCIAL_MEDIA_RETRIEVED"
    results = {
        'success':
        True,
        'status':
        status,
        'twitter_handles_added':
        twitter_handles_added,
        'profiles_refreshed_with_twitter_data':
        profiles_refreshed_with_twitter_data,
    }
    return results
def transfer_candidate_twitter_handles_from_google_civic(
        google_civic_election_id=0):
    twitter_handles_transferred = 0
    status = ""
    google_civic_election_id = convert_to_int(google_civic_election_id)

    candidate_list_object = CandidateCampaignList()
    return_list_of_objects = True
    results = candidate_list_object.retrieve_all_candidates_for_upcoming_election(
        google_civic_election_id, return_list_of_objects)
    status += results['status']
    if results['success']:
        candidate_list = results['candidate_list_objects']
    else:
        candidate_list = []

    for candidate in candidate_list:
        if not candidate.twitter_url:
            continue
        # Only proceed if we don't already have a twitter_handle
        if not positive_value_exists(candidate.candidate_twitter_handle):
            candidate.candidate_twitter_handle = candidate.twitter_url.replace(
                "https://twitter.com/", "")
            candidate.save()
            twitter_handles_transferred += 1

        # ######################################
        # We refresh the Twitter information in another function

    status += " CANDIDATE_TWITTER_HANDLES_TRANSFERRED"
    results = {
        'success': True,
        'status': status,
        'twitter_handles_transferred': twitter_handles_transferred,
    }
    return results
def ballot_item_options_retrieve_for_api(google_civic_election_id=0):
    """
    This function returns a normalized list of candidates and measures so we can pre-populate form fields.
    Not specific to one voter.
    :param google_civic_election_id:
    :return:
    """

    status = ""
    try:
        candidate_list_object = CandidateCampaignList()
        results = candidate_list_object.retrieve_all_candidates_for_upcoming_election(google_civic_election_id)
        candidate_success = results['success']
        status += results['status']
        candidate_list = results['candidate_list_light']
    except Exception as e:
        status += 'FAILED ballot_item_options_retrieve_for_api, candidate_list. ' \
                 '{error} [type: {error_type}]'.format(error=e, error_type=type(e))
        handle_exception(e, logger=logger, exception_message=status)
        candidate_list = []
        candidate_success = False

    try:
        office_list_object = ContestOfficeList()
        results = office_list_object.retrieve_all_offices_for_upcoming_election(google_civic_election_id)
        office_success = results['success']
        status += ' ' + results['status']
        office_list = results['office_list_light']
    except Exception as e:
        status += 'FAILED ballot_item_options_retrieve_for_api, office_list. ' \
                 '{error} [type: {error_type}]'.format(error=e, error_type=type(e))
        handle_exception(e, logger=logger, exception_message=status)
        office_list = []
        office_success = False

    try:
        measure_list_object = ContestMeasureList()
        results = measure_list_object.retrieve_all_measures_for_upcoming_election(google_civic_election_id)
        measure_success = results['success']
        status += ' ' + results['status']
        measure_list = results['measure_list_light']
    except Exception as e:
        status += 'FAILED ballot_item_options_retrieve_for_api, measure_list. ' \
                 '{error} [type: {error_type}]'.format(error=e, error_type=type(e))
        handle_exception(e, logger=logger, exception_message=status)
        measure_list = []
        measure_success = False

    ballot_items_to_display = []
    if candidate_success and len(candidate_list):
        for candidate in candidate_list:
            ballot_items_to_display.append(candidate.copy())

    if office_success and len(office_list):
        for office in office_list:
            ballot_items_to_display.append(office.copy())

    if measure_success and len(measure_list):
        for measure in measure_list:
            ballot_items_to_display.append(measure.copy())

    json_data = {
        'status': status,
        'success': candidate_success or measure_success,
        'ballot_item_list': ballot_items_to_display,
        'google_civic_election_id': google_civic_election_id,
    }
    results = {
        'status': status,
        'success': candidate_success or measure_success,
        'google_civic_election_id': google_civic_election_id,  # We want to save google_civic_election_id in cookie
        'json_data': json_data,
    }
    return results
Exemple #10
0
def voter_ballot_items_retrieve_for_one_election_for_api(voter_device_id, voter_id, google_civic_election_id):
    """

    :param voter_device_id:
    :param google_civic_election_id: This variable either was stored in a cookie, or passed in explicitly so we can
    get the ballot items related to that election.
    :return:
    """

    ballot_item_list_manager = BallotItemListManager()

    ballot_item_list = []
    ballot_items_to_display = []
    try:
        results = ballot_item_list_manager.retrieve_all_ballot_items_for_voter(voter_id, google_civic_election_id)
        success = results['success']
        status = results['status']
        ballot_item_list = results['ballot_item_list']
    except Exception as e:
        status = 'FAILED voter_ballot_items_retrieve. ' \
                 '{error} [type: {error_type}]'.format(error=e, error_type=type(e))
        handle_exception(e, logger=logger, exception_message=status)
        success = False

    if success:
        for ballot_item in ballot_item_list:
            if ballot_item.contest_office_we_vote_id:
                kind_of_ballot_item = OFFICE
                ballot_item_id = ballot_item.contest_office_id
                we_vote_id = ballot_item.contest_office_we_vote_id
                try:
                    candidate_list_object = CandidateCampaignList()
                    results = candidate_list_object.retrieve_all_candidates_for_office(ballot_item_id, we_vote_id)
                    candidates_to_display = []
                    if results['candidate_list_found']:
                        candidate_list = results['candidate_list']
                        for candidate in candidate_list:
                            # This should match values returned in candidates_retrieve_for_api
                            one_candidate = {
                                'id':                           candidate.id,
                                'we_vote_id':                   candidate.we_vote_id,
                                'ballot_item_display_name':     candidate.candidate_name,
                                'candidate_photo_url':          candidate.candidate_photo_url(),
                                'party':                        candidate.party_display(),
                                'order_on_ballot':              candidate.order_on_ballot,
                                'kind_of_ballot_item':          CANDIDATE,
                                'twitter_description':          candidate.twitter_description,
                                'twitter_followers_count':      candidate.twitter_followers_count,
                            }
                            candidates_to_display.append(one_candidate.copy())
                except Exception as e:
                    # status = 'FAILED candidates_retrieve. ' \
                    #          '{error} [type: {error_type}]'.format(error=e.message, error_type=type(e))
                    candidates_to_display = []
                one_ballot_item = {
                    'ballot_item_display_name':     ballot_item.ballot_item_display_name,
                    'google_civic_election_id':     ballot_item.google_civic_election_id,
                    'google_ballot_placement':      ballot_item.google_ballot_placement,
                    'local_ballot_order':           ballot_item.local_ballot_order,
                    'kind_of_ballot_item':          kind_of_ballot_item,
                    'id':                           ballot_item_id,
                    'we_vote_id':                   we_vote_id,
                    'candidate_list':               candidates_to_display,
                }
                ballot_items_to_display.append(one_ballot_item.copy())
            elif ballot_item.contest_measure_we_vote_id:
                kind_of_ballot_item = MEASURE
                ballot_item_id = ballot_item.contest_measure_id
                we_vote_id = ballot_item.contest_measure_we_vote_id
                one_ballot_item = {
                    'ballot_item_display_name':     ballot_item.ballot_item_display_name,
                    'google_civic_election_id':     ballot_item.google_civic_election_id,
                    'google_ballot_placement':      ballot_item.google_ballot_placement,
                    'local_ballot_order':           ballot_item.local_ballot_order,
                    'measure_subtitle':             ballot_item.measure_subtitle,
                    'kind_of_ballot_item':          kind_of_ballot_item,
                    'id':                           ballot_item_id,
                    'we_vote_id':                   we_vote_id,
                }
                ballot_items_to_display.append(one_ballot_item.copy())

        results = {
            'status': 'VOTER_BALLOT_ITEMS_RETRIEVED',
            'success': True,
            'voter_device_id': voter_device_id,
            'ballot_item_list': ballot_items_to_display,
            'google_civic_election_id': google_civic_election_id,
        }
    else:
        results = {
            'status': status,
            'success': False,
            'voter_device_id': voter_device_id,
            'ballot_item_list': [],
            'google_civic_election_id': google_civic_election_id,
        }
    return results
Exemple #11
0
def voter_ballot_items_retrieve_for_api(voter_device_id, google_civic_election_id):
    """

    :param voter_device_id:
    :param google_civic_election_id: This variable either was stored in a cookie, or passed in explicitly so we can
    get the ballot items related to that election.
    :return:
    """
    # Get voter_id from the voter_device_id so we can figure out which ballot_items to offer
    results = is_voter_device_id_valid(voter_device_id)
    if not results["success"]:
        json_data = {
            "status": "VALID_VOTER_DEVICE_ID_MISSING",
            "success": False,
            "voter_id": 0,
            "voter_device_id": voter_device_id,
            "ballot_item_list": [],
            "google_civic_election_id": google_civic_election_id,
        }
        results = {
            "success": False,
            "json_data": json_data,
            "google_civic_election_id": 0,  # Force the clearing of google_civic_election_id
        }
        return results

    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_id": voter_id,
            "voter_device_id": voter_device_id,
            "ballot_item_list": [],
            "google_civic_election_id": google_civic_election_id,
        }
        results = {
            "success": False,
            "json_data": json_data,
            "google_civic_election_id": 0,  # Force the clearing of google_civic_election_id
        }
        return results

    ballot_item_list_manager = BallotItemListManager()
    # If we get here without a google_civic_election_id, we need to choose one from the ballot items that are already
    #  stored. If we proceed to retrieve_all_ballot_items_for_voter without a google_civic_election_id, we will get
    #  ballot items from a variety of elections.
    # This logic looks for all of the elections we have ballot information for, and displays the most recent election
    #  (not counting the test election)
    if not positive_value_exists(google_civic_election_id):
        google_civic_election_id = ballot_item_list_manager.fetch_most_recent_google_civic_election_id()

    # If an election id STILL wasn't found, then we probably don't have any ballot items stored locally, so we
    #  need to go out to google civic. BUT we will proceed and attempt to retrieve ballot items without an election_id

    ballot_item_list = []
    ballot_items_to_display = []
    try:
        results = ballot_item_list_manager.retrieve_all_ballot_items_for_voter(voter_id, google_civic_election_id)
        success = results["success"]
        status = results["status"]
        ballot_item_list = results["ballot_item_list"]
    except Exception as e:
        status = "FAILED voter_ballot_items_retrieve. " "{error} [type: {error_type}]".format(
            error=e, error_type=type(e)
        )
        handle_exception(e, logger=logger, exception_message=status)
        success = False

    if success:
        for ballot_item in ballot_item_list:
            if ballot_item.contest_office_we_vote_id:
                kind_of_ballot_item = OFFICE
                ballot_item_id = ballot_item.contest_office_id
                we_vote_id = ballot_item.contest_office_we_vote_id
                try:
                    candidate_list_object = CandidateCampaignList()
                    results = candidate_list_object.retrieve_all_candidates_for_office(ballot_item_id, we_vote_id)
                    candidates_to_display = []
                    if results["candidate_list_found"]:
                        candidate_list = results["candidate_list"]
                        for candidate in candidate_list:
                            # This should match values returned in candidates_retrieve_for_api
                            one_candidate = {
                                "id": candidate.id,
                                "we_vote_id": candidate.we_vote_id,
                                "ballot_item_display_name": candidate.candidate_name,
                                "candidate_photo_url": candidate.fetch_photo_url(),
                                "order_on_ballot": candidate.order_on_ballot,
                                "kind_of_ballot_item": CANDIDATE,
                            }
                            candidates_to_display.append(one_candidate.copy())
                except Exception as e:
                    # status = 'FAILED candidates_retrieve. ' \
                    #          '{error} [type: {error_type}]'.format(error=e.message, error_type=type(e))
                    candidates_to_display = []
                one_ballot_item = {
                    "ballot_item_display_name": ballot_item.ballot_item_display_name,
                    "google_civic_election_id": ballot_item.google_civic_election_id,
                    "google_ballot_placement": ballot_item.google_ballot_placement,
                    "local_ballot_order": ballot_item.local_ballot_order,
                    "kind_of_ballot_item": kind_of_ballot_item,
                    "id": ballot_item_id,
                    "we_vote_id": we_vote_id,
                    "candidate_list": candidates_to_display,
                }
                ballot_items_to_display.append(one_ballot_item.copy())
            elif ballot_item.contest_measure_we_vote_id:
                kind_of_ballot_item = MEASURE
                ballot_item_id = ballot_item.contest_measure_id
                we_vote_id = ballot_item.contest_measure_we_vote_id
                one_ballot_item = {
                    "ballot_item_display_name": ballot_item.ballot_item_display_name,
                    "google_civic_election_id": ballot_item.google_civic_election_id,
                    "google_ballot_placement": ballot_item.google_ballot_placement,
                    "local_ballot_order": ballot_item.local_ballot_order,
                    "kind_of_ballot_item": kind_of_ballot_item,
                    "id": ballot_item_id,
                    "we_vote_id": we_vote_id,
                }
                ballot_items_to_display.append(one_ballot_item.copy())

        json_data = {
            "status": "VOTER_BALLOT_ITEMS_RETRIEVED",
            "success": True,
            "voter_device_id": voter_device_id,
            "ballot_item_list": ballot_items_to_display,
            "google_civic_election_id": google_civic_election_id,
        }
    else:
        json_data = {
            "status": status,
            "success": False,
            "voter_device_id": voter_device_id,
            "ballot_item_list": [],
            "google_civic_election_id": google_civic_election_id,
        }
    results = {
        "success": success,
        "google_civic_election_id": google_civic_election_id,  # We want to save google_civic_election_id in cookie
        "json_data": json_data,
    }
    return results
Exemple #12
0
def ballot_item_options_retrieve_for_api(google_civic_election_id=0):
    """
    This function returns a normalized list of candidates and measures so we can pre-populate form fields
    :param google_civic_election_id:
    :return:
    """

    status = ""
    try:
        candidate_list_object = CandidateCampaignList()
        results = candidate_list_object.retrieve_all_candidates_for_upcoming_election(google_civic_election_id)
        candidate_success = results["success"]
        status += results["status"]
        candidate_list = results["candidate_list_light"]
    except Exception as e:
        status += "FAILED ballot_item_options_retrieve_for_api, candidate_list. " "{error} [type: {error_type}]".format(
            error=e, error_type=type(e)
        )
        handle_exception(e, logger=logger, exception_message=status)
        candidate_list = []
        candidate_success = False

    try:
        office_list_object = ContestOfficeList()
        results = office_list_object.retrieve_all_offices_for_upcoming_election(google_civic_election_id)
        office_success = results["success"]
        status += " " + results["status"]
        office_list = results["office_list_light"]
    except Exception as e:
        status += "FAILED ballot_item_options_retrieve_for_api, office_list. " "{error} [type: {error_type}]".format(
            error=e, error_type=type(e)
        )
        handle_exception(e, logger=logger, exception_message=status)
        office_list = []
        office_success = False

    try:
        measure_list_object = ContestMeasureList()
        results = measure_list_object.retrieve_all_measures_for_upcoming_election(google_civic_election_id)
        measure_success = results["success"]
        status += " " + results["status"]
        measure_list = results["measure_list_light"]
    except Exception as e:
        status += "FAILED ballot_item_options_retrieve_for_api, measure_list. " "{error} [type: {error_type}]".format(
            error=e, error_type=type(e)
        )
        handle_exception(e, logger=logger, exception_message=status)
        measure_list = []
        measure_success = False

    ballot_items_to_display = []
    if candidate_success and len(candidate_list):
        for candidate in candidate_list:
            ballot_items_to_display.append(candidate.copy())

    if office_success and len(office_list):
        for office in office_list:
            ballot_items_to_display.append(office.copy())

    if measure_success and len(measure_list):
        for measure in measure_list:
            ballot_items_to_display.append(measure.copy())

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

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

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

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

    position_list_manager = PositionListManager()
    candidate_list_object = CandidateCampaignList()

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

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

    # The list where we capture results
    ballot_item_list_results = []

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

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

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

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

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

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

    position_list_manager = PositionListManager()
    candidate_list_object = CandidateCampaignList()

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

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

    # The list where we capture results
    ballot_item_list_results = []

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

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

    json_data = {
        'success':                  True,
        'status':                   "POSITIONS_COUNT_FOR_ALL_BALLOT_ITEMS",
        'google_civic_election_id': google_civic_election_id,
        'ballot_item_list':         ballot_item_list_results,
    }
    return json_data
Exemple #15
0
def ballot_item_options_retrieve_for_api(google_civic_election_id=0):
    """
    This function returns a normalized list of candidates and measures so we can pre-populate form fields.
    Not specific to one voter.
    :param google_civic_election_id:
    :return:
    """

    status = ""
    try:
        candidate_list_object = CandidateCampaignList()
        results = candidate_list_object.retrieve_all_candidates_for_upcoming_election(
            google_civic_election_id)
        candidate_success = results['success']
        status += results['status']
        candidate_list = results['candidate_list_light']
    except Exception as e:
        status += 'FAILED ballot_item_options_retrieve_for_api, candidate_list. ' \
                 '{error} [type: {error_type}]'.format(error=e, error_type=type(e))
        handle_exception(e, logger=logger, exception_message=status)
        candidate_list = []
        candidate_success = False

    try:
        office_list_object = ContestOfficeList()
        results = office_list_object.retrieve_all_offices_for_upcoming_election(
            google_civic_election_id)
        office_success = results['success']
        status += ' ' + results['status']
        office_list = results['office_list_light']
    except Exception as e:
        status += 'FAILED ballot_item_options_retrieve_for_api, office_list. ' \
                 '{error} [type: {error_type}]'.format(error=e, error_type=type(e))
        handle_exception(e, logger=logger, exception_message=status)
        office_list = []
        office_success = False

    try:
        measure_list_object = ContestMeasureList()
        results = measure_list_object.retrieve_all_measures_for_upcoming_election(
            google_civic_election_id)
        measure_success = results['success']
        status += ' ' + results['status']
        measure_list = results['measure_list_light']
    except Exception as e:
        status += 'FAILED ballot_item_options_retrieve_for_api, measure_list. ' \
                 '{error} [type: {error_type}]'.format(error=e, error_type=type(e))
        handle_exception(e, logger=logger, exception_message=status)
        measure_list = []
        measure_success = False

    ballot_items_to_display = []
    if candidate_success and len(candidate_list):
        for candidate in candidate_list:
            ballot_items_to_display.append(candidate.copy())

    if office_success and len(office_list):
        for office in office_list:
            ballot_items_to_display.append(office.copy())

    if measure_success and len(measure_list):
        for measure in measure_list:
            ballot_items_to_display.append(measure.copy())

    json_data = {
        'status': status,
        'success': candidate_success or measure_success,
        'ballot_item_list': ballot_items_to_display,
        'google_civic_election_id': google_civic_election_id,
    }
    results = {
        'status': status,
        'success': candidate_success or measure_success,
        'google_civic_election_id':
        google_civic_election_id,  # We want to save google_civic_election_id in cookie
        'json_data': json_data,
    }
    return results
Exemple #16
0
def voter_ballot_items_retrieve_for_one_election_for_api(
        voter_device_id, voter_id, google_civic_election_id):
    """

    :param voter_device_id:
    :param google_civic_election_id: This variable either was stored in a cookie, or passed in explicitly so we can
    get the ballot items related to that election.
    :return:
    """

    ballot_item_list_manager = BallotItemListManager()

    ballot_item_list = []
    ballot_items_to_display = []
    try:
        results = ballot_item_list_manager.retrieve_all_ballot_items_for_voter(
            voter_id, google_civic_election_id)
        success = results['success']
        status = results['status']
        ballot_item_list = results['ballot_item_list']
    except Exception as e:
        status = 'FAILED voter_ballot_items_retrieve. ' \
                 '{error} [type: {error_type}]'.format(error=e, error_type=type(e))
        handle_exception(e, logger=logger, exception_message=status)
        success = False

    if success:
        for ballot_item in ballot_item_list:
            if ballot_item.contest_office_we_vote_id:
                kind_of_ballot_item = OFFICE
                ballot_item_id = ballot_item.contest_office_id
                we_vote_id = ballot_item.contest_office_we_vote_id
                try:
                    candidate_list_object = CandidateCampaignList()
                    results = candidate_list_object.retrieve_all_candidates_for_office(
                        ballot_item_id, we_vote_id)
                    candidates_to_display = []
                    if results['candidate_list_found']:
                        candidate_list = results['candidate_list']
                        for candidate in candidate_list:
                            # This should match values returned in candidates_retrieve_for_api
                            one_candidate = {
                                'id':
                                candidate.id,
                                'we_vote_id':
                                candidate.we_vote_id,
                                'ballot_item_display_name':
                                candidate.candidate_name,
                                'candidate_photo_url':
                                candidate.candidate_photo_url(),
                                'party':
                                candidate.party_display(),
                                'order_on_ballot':
                                candidate.order_on_ballot,
                                'kind_of_ballot_item':
                                CANDIDATE,
                                'twitter_description':
                                candidate.twitter_description,
                                'twitter_followers_count':
                                candidate.twitter_followers_count,
                            }
                            candidates_to_display.append(one_candidate.copy())
                except Exception as e:
                    # status = 'FAILED candidates_retrieve. ' \
                    #          '{error} [type: {error_type}]'.format(error=e.message, error_type=type(e))
                    candidates_to_display = []
                one_ballot_item = {
                    'ballot_item_display_name':
                    ballot_item.ballot_item_display_name,
                    'google_civic_election_id':
                    ballot_item.google_civic_election_id,
                    'google_ballot_placement':
                    ballot_item.google_ballot_placement,
                    'local_ballot_order': ballot_item.local_ballot_order,
                    'kind_of_ballot_item': kind_of_ballot_item,
                    'id': ballot_item_id,
                    'we_vote_id': we_vote_id,
                    'candidate_list': candidates_to_display,
                }
                ballot_items_to_display.append(one_ballot_item.copy())
            elif ballot_item.contest_measure_we_vote_id:
                kind_of_ballot_item = MEASURE
                ballot_item_id = ballot_item.contest_measure_id
                we_vote_id = ballot_item.contest_measure_we_vote_id
                one_ballot_item = {
                    'ballot_item_display_name':
                    ballot_item.ballot_item_display_name,
                    'google_civic_election_id':
                    ballot_item.google_civic_election_id,
                    'google_ballot_placement':
                    ballot_item.google_ballot_placement,
                    'local_ballot_order': ballot_item.local_ballot_order,
                    'measure_subtitle': ballot_item.measure_subtitle,
                    'kind_of_ballot_item': kind_of_ballot_item,
                    'id': ballot_item_id,
                    'we_vote_id': we_vote_id,
                }
                ballot_items_to_display.append(one_ballot_item.copy())

        results = {
            'status': 'VOTER_BALLOT_ITEMS_RETRIEVED',
            'success': True,
            'voter_device_id': voter_device_id,
            'ballot_item_list': ballot_items_to_display,
            'google_civic_election_id': google_civic_election_id,
        }
    else:
        results = {
            'status': status,
            'success': False,
            'voter_device_id': voter_device_id,
            'ballot_item_list': [],
            'google_civic_election_id': google_civic_election_id,
        }
    return results