コード例 #1
0
def refresh_twitter_candidate_details(candidate_campaign):
    candidate_campaign_manager = CandidateCampaignManager()

    if not candidate_campaign:
        status = "TWITTER_CANDIDATE_DETAILS_NOT_RETRIEVED-CANDIDATE_MISSING"
        results = {
            'success': False,
            'status': status,
        }
        return results

    if candidate_campaign.candidate_twitter_handle:
        status = "TWITTER_CANDIDATE_DETAILS-REACHING_OUT_TO_TWITTER"
        results = retrieve_twitter_user_info(
            candidate_campaign.candidate_twitter_handle)

        if results['success']:
            status = "TWITTER_CANDIDATE_DETAILS_RETRIEVED_FROM_TWITTER"
            save_results = candidate_campaign_manager.update_candidate_twitter_details(
                candidate_campaign, results['twitter_json'])
    else:
        status = "TWITTER_CANDIDATE_DETAILS-CLEARING_DETAILS"
        save_results = candidate_campaign_manager.clear_candidate_twitter_details(
            candidate_campaign)

    results = {
        'success': True,
        'status': status,
    }
    return results
コード例 #2
0
def import_one_politician_ratings_view(
        request, vote_smart_candidate_id):  # TODO DALE update to politician
    authority_required = {'admin'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    # retrieve_vote_smart_ratings_for_candidate_into_local_db can be used for both We Vote candidate or politician
    one_group_results = retrieve_vote_smart_ratings_for_candidate_into_local_db(
        vote_smart_candidate_id)

    if one_group_results['success']:
        messages.add_message(request, messages.INFO,
                             "Ratings for one candidate retrieved. ")
    else:
        messages.add_message(
            request, messages.ERROR,
            "Ratings for one candidate NOT retrieved. "
            "(error: {error_message})"
            "".format(error_message=one_group_results['status']))

    candidate_manager = CandidateCampaignManager()
    results = candidate_manager.retrieve_candidate_campaign_from_vote_smart_id(
        vote_smart_candidate_id)
    if results['candidate_campaign_found']:
        candidate = results['candidate_campaign']
        candidate_campaign_id = candidate.id
        return HttpResponseRedirect(
            reverse('candidate:candidate_edit',
                    args=(candidate_campaign_id, )))
    else:
        return HttpResponseRedirect(
            reverse('candidate:candidate_list', args=()))
コード例 #3
0
def refresh_twitter_candidate_details(candidate_campaign):
    candidate_campaign_manager = CandidateCampaignManager()

    if not candidate_campaign:
        status = "TWITTER_CANDIDATE_DETAILS_NOT_RETRIEVED-CANDIDATE_MISSING"
        results = {
            'success':                  False,
            'status':                   status,
        }
        return results

    if candidate_campaign.candidate_twitter_handle:
        status = "TWITTER_CANDIDATE_DETAILS-REACHING_OUT_TO_TWITTER"
        results = retrieve_twitter_user_info(candidate_campaign.candidate_twitter_handle)

        if results['success']:
            status = "TWITTER_CANDIDATE_DETAILS_RETRIEVED_FROM_TWITTER"
            save_results = candidate_campaign_manager.update_candidate_twitter_details(
                candidate_campaign, results['twitter_json'])
    else:
        status = "TWITTER_CANDIDATE_DETAILS-CLEARING_DETAILS"
        save_results = candidate_campaign_manager.clear_candidate_twitter_details(candidate_campaign)

    results = {
        'success':                  True,
        'status':                   status,
    }
    return results
コード例 #4
0
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 = CandidateCampaignListManager()
    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
コード例 #5
0
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 = CandidateCampaignListManager()
    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
コード例 #6
0
ファイル: views_admin.py プロジェクト: eternal44/WeVoteServer
def refresh_twitter_candidate_details_view(request, candidate_id):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    candidate_manager = CandidateCampaignManager()
    results = candidate_manager.retrieve_candidate_campaign(candidate_id)

    if not results['candidate_campaign_found']:
        messages.add_message(request, messages.INFO, results['status'])
        return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_id,)))

    candidate_campaign = results['candidate_campaign']

    results = refresh_twitter_candidate_details(candidate_campaign)

    return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_id,)))
コード例 #7
0
def import_one_candidate_ratings_view(request, vote_smart_candidate_id):
    one_group_results = retrieve_vote_smart_ratings_by_candidate_into_local_db(vote_smart_candidate_id)

    if one_group_results['success']:
        messages.add_message(request, messages.INFO, "Ratings for one candidate retrieved. ")
    else:
        messages.add_message(request, messages.ERROR, "Ratings for one candidate NOT retrieved. "
                                                      "(error: {error_message})"
                                                      "".format(error_message=one_group_results['status']))

    candidate_manager = CandidateCampaignManager()
    results = candidate_manager.retrieve_candidate_campaign_from_vote_smart_id(vote_smart_candidate_id)
    if results['candidate_campaign_found']:
        candidate = results['candidate_campaign']
        candidate_campaign_id = candidate.id
        return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_campaign_id,)))
    else:
        return HttpResponseRedirect(reverse('candidate:candidate_list', args=()))
コード例 #8
0
ファイル: models.py プロジェクト: eternal44/WeVoteServer
 def ballot_item_we_vote_id(self):
     if self.candidate_campaign_we_vote_id:
         return self.candidate_campaign_we_vote_id
     elif self.contest_office_we_vote_id:
         return self.contest_office_we_vote_id
     elif self.contest_measure_we_vote_id:
         return self.contest_measure_we_vote_id
     elif self.candidate_campaign_id:
         candidate_campaign_manager = CandidateCampaignManager()
         return candidate_campaign_manager.fetch_candidate_campaign_we_vote_id_from_id(self.candidate_campaign_id)
     elif self.contest_measure_id:
         contest_measure_manager = ContestMeasureManager()
         return contest_measure_manager.fetch_contest_measure_we_vote_id_from_id(self.contest_measure_id)
     elif self.contest_office_id:
         contest_office_manager = ContestOfficeManager()
         return contest_office_manager.fetch_contest_office_we_vote_id_from_id(self.contest_office_id)
     else:
         return 'not_found'
コード例 #9
0
def refresh_twitter_candidate_details_view(request, candidate_id):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    candidate_manager = CandidateCampaignManager()
    results = candidate_manager.retrieve_candidate_campaign(candidate_id)

    if not results['candidate_campaign_found']:
        messages.add_message(request, messages.INFO, results['status'])
        return HttpResponseRedirect(
            reverse('candidate:candidate_edit', args=(candidate_id, )))

    candidate_campaign = results['candidate_campaign']

    results = refresh_twitter_candidate_details(candidate_campaign)

    return HttpResponseRedirect(
        reverse('candidate:candidate_edit', args=(candidate_id, )))
コード例 #10
0
 def ballot_item_we_vote_id(self):
     if self.candidate_campaign_we_vote_id:
         return self.candidate_campaign_we_vote_id
     elif self.contest_office_we_vote_id:
         return self.contest_office_we_vote_id
     elif self.contest_measure_we_vote_id:
         return self.contest_measure_we_vote_id
     elif self.candidate_campaign_id:
         candidate_campaign_manager = CandidateCampaignManager()
         return candidate_campaign_manager.fetch_candidate_campaign_we_vote_id_from_id(
             self.candidate_campaign_id)
     elif self.contest_measure_id:
         contest_measure_manager = ContestMeasureManager()
         return contest_measure_manager.fetch_contest_measure_we_vote_id_from_id(
             self.contest_measure_id)
     elif self.contest_office_id:
         contest_office_manager = ContestOfficeManager()
         return contest_office_manager.fetch_contest_office_we_vote_id_from_id(
             self.contest_office_id)
     else:
         return 'not_found'
コード例 #11
0
def positions_public_count_for_candidate_campaign(candidate_id,
                                                  candidate_we_vote_id,
                                                  stance_we_are_looking_for):
    """
    We want to return a JSON file with the number of orgs and public figures who support
    this particular candidate's campaign
    """
    # This implementation is built to make only two database calls. All other calculations are done here in the
    #  application layer

    position_list_manager = PositionListManager()
    all_positions_count_for_candidate_campaign = \
        position_list_manager.retrieve_public_positions_count_for_candidate_campaign(
            candidate_id,
            candidate_we_vote_id,
            stance_we_are_looking_for)

    if positive_value_exists(candidate_id) or positive_value_exists(
            candidate_we_vote_id):
        candidate_campaign_manager = CandidateCampaignManager()
        # Since we can take in either candidate_id or candidate_we_vote_id, we need to retrieve the value we don't have
        if positive_value_exists(candidate_id):
            candidate_we_vote_id = candidate_campaign_manager.fetch_candidate_campaign_we_vote_id_from_id(
                candidate_id)
        elif positive_value_exists(candidate_we_vote_id):
            candidate_id = candidate_campaign_manager.fetch_candidate_campaign_id_from_we_vote_id(
                candidate_we_vote_id)

    json_data = {
        'status': 'SUCCESSFUL_RETRIEVE_OF_PUBLIC_POSITION_COUNT_RE_CANDIDATE',
        'success': True,
        'count': all_positions_count_for_candidate_campaign,
        'ballot_item_id': convert_to_int(candidate_id),
        'ballot_item_we_vote_id': candidate_we_vote_id,
        'kind_of_ballot_item': CANDIDATE,
    }
    results = {
        'json_data': json_data,
    }
    return results
コード例 #12
0
def import_one_politician_ratings_view(request, vote_smart_candidate_id):  # TODO DALE update to politician
    authority_required = {'admin'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    # retrieve_vote_smart_ratings_for_candidate_into_local_db can be used for both We Vote candidate or politician
    one_group_results = retrieve_vote_smart_ratings_for_candidate_into_local_db(vote_smart_candidate_id)

    if one_group_results['success']:
        messages.add_message(request, messages.INFO, "Ratings for one candidate retrieved. ")
    else:
        messages.add_message(request, messages.ERROR, "Ratings for one candidate NOT retrieved. "
                                                      "(error: {error_message})"
                                                      "".format(error_message=one_group_results['status']))

    candidate_manager = CandidateCampaignManager()
    results = candidate_manager.retrieve_candidate_campaign_from_vote_smart_id(vote_smart_candidate_id)
    if results['candidate_campaign_found']:
        candidate = results['candidate_campaign']
        candidate_campaign_id = candidate.id
        return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_campaign_id,)))
    else:
        return HttpResponseRedirect(reverse('candidate:candidate_list', args=()))
コード例 #13
0
ファイル: controllers.py プロジェクト: eternal44/WeVoteServer
def positions_public_count_for_candidate_campaign(candidate_id, candidate_we_vote_id, stance_we_are_looking_for):
    """
    We want to return a JSON file with the number of orgs and public figures who support
    this particular candidate's campaign
    """
    # This implementation is built to make only two database calls. All other calculations are done here in the
    #  application layer

    position_list_manager = PositionListManager()
    all_positions_count_for_candidate_campaign = \
        position_list_manager.retrieve_public_positions_count_for_candidate_campaign(
            candidate_id,
            candidate_we_vote_id,
            stance_we_are_looking_for)

    if positive_value_exists(candidate_id) or positive_value_exists(candidate_we_vote_id):
        candidate_campaign_manager = CandidateCampaignManager()
        # Since we can take in either candidate_id or candidate_we_vote_id, we need to retrieve the value we don't have
        if positive_value_exists(candidate_id):
            candidate_we_vote_id = candidate_campaign_manager.fetch_candidate_campaign_we_vote_id_from_id(candidate_id)
        elif positive_value_exists(candidate_we_vote_id):
            candidate_id = candidate_campaign_manager.fetch_candidate_campaign_id_from_we_vote_id(candidate_we_vote_id)

    json_data = {
        'status':                   'SUCCESSFUL_RETRIEVE_OF_PUBLIC_POSITION_COUNT_RE_CANDIDATE',
        'success':                  True,
        'count':                    all_positions_count_for_candidate_campaign,
        'ballot_item_id':           convert_to_int(candidate_id),
        'ballot_item_we_vote_id':   candidate_we_vote_id,
        'kind_of_ballot_item':      CANDIDATE,

    }
    results = {
        'json_data': json_data,
    }
    return results
コード例 #14
0
def process_candidates_from_structured_json(candidates_structured_json,
                                            google_civic_election_id,
                                            ocd_division_id, state_code,
                                            contest_office_id,
                                            contest_office_we_vote_id):
    """
    "candidates": [
        {
         "name": "Nancy Pelosi",
         "party": "Democratic"
        },
        {
         "name": "John Dennis",
         "party": "Republican",
         "candidateUrl": "http://www.johndennisforcongress.com/",
         "channels": [
          {
           "type": "Facebook",
           "id": "https://www.facebook.com/johndennis2010"
          },
          {
           "type": "Twitter",
           "id": "https://twitter.com/johndennis2012"
    """
    results = {}
    for one_candidate in candidates_structured_json:
        candidate_name = one_candidate[
            'name'] if 'name' in one_candidate else ''
        # For some reason Google Civic API violates the JSON standard and uses a / in front of '
        candidate_name = candidate_name.replace('/', "'")
        # We want to save the name exactly as it comes from the Google Civic API
        google_civic_candidate_name = one_candidate[
            'name'] if 'name' in one_candidate else ''
        party = one_candidate['party'] if 'party' in one_candidate else ''
        order_on_ballot = one_candidate[
            'orderOnBallot'] if 'orderOnBallot' in one_candidate else 0
        candidate_url = one_candidate[
            'candidateUrl'] if 'candidateUrl' in one_candidate else ''
        photo_url = one_candidate[
            'photoUrl'] if 'photoUrl' in one_candidate else ''
        email = one_candidate['email'] if 'email' in one_candidate else ''
        phone = one_candidate['phone'] if 'phone' in one_candidate else ''

        # Make sure we start with empty channel values
        facebook_url = ''
        twitter_url = ''
        google_plus_url = ''
        youtube_url = ''
        if 'channels' in one_candidate:
            channels = one_candidate['channels']
            for one_channel in channels:
                if 'type' in one_channel:
                    if one_channel['type'] == 'Facebook':
                        facebook_url = one_channel[
                            'id'] if 'id' in one_channel else ''
                    if one_channel['type'] == 'Twitter':
                        twitter_url = one_channel[
                            'id'] if 'id' in one_channel else ''
                    if one_channel['type'] == 'GooglePlus':
                        google_plus_url = one_channel[
                            'id'] if 'id' in one_channel else ''
                    if one_channel['type'] == 'YouTube':
                        youtube_url = one_channel[
                            'id'] if 'id' in one_channel else ''

        # DALE 2016-02-20 It would be helpful to call a service here that disambiguated the candidate
        # ...and linked to a politician
        # ...and looked to see if there were any other candidate_campaign entries for this election (in case the
        #   Google Civic contest_office name changed so we generated another contest)

        we_vote_id = ''
        # Make sure we have the minimum variables required to uniquely identify a candidate
        if google_civic_election_id and contest_office_id and candidate_name:
            # NOT using " and ocd_division_id"

            # Make sure there isn't an alternate entry for this election and contest_office (under a similar but
            # slightly different name TODO
            # Note: This doesn't deal with duplicate Presidential candidates. These duplicates are caused because
            # candidates are tied to a particular google_civic_election_id, so there is a different candidate entry
            # for each Presidential candidate for each state.

            updated_candidate_campaign_values = {
                # Values we search against
                'google_civic_election_id': google_civic_election_id,
                'ocd_division_id': ocd_division_id,
                # Note: When we decide to start updating candidate_name elsewhere within We Vote, we should stop
                #  updating candidate_name via subsequent Google Civic imports
                'candidate_name': candidate_name,
                # The rest of the values
                'state_code':
                state_code,  # Not required due to federal candidates
                'party': party,
                'candidate_email': email,
                'candidate_phone': phone,
                'order_on_ballot': order_on_ballot,
                'candidate_url': candidate_url,
                'photo_url': photo_url,
                'facebook_url': facebook_url,
                'twitter_url': twitter_url,
                'google_plus_url': google_plus_url,
                'youtube_url': youtube_url,
                'google_civic_candidate_name': google_civic_candidate_name,
                # 2016-02-20 Google Civic sometimes changes the name of contests, which can create a new contest
                #  so we may need to update the candidate to a new contest_office_id
                'contest_office_id': contest_office_id,
                'contest_office_we_vote_id': contest_office_we_vote_id,
            }
            candidate_campaign_manager = CandidateCampaignManager()
            results = candidate_campaign_manager.update_or_create_candidate_campaign(
                we_vote_id, google_civic_election_id, ocd_division_id,
                contest_office_id, contest_office_we_vote_id,
                google_civic_candidate_name, updated_candidate_campaign_values)

    return results
コード例 #15
0
ファイル: controllers.py プロジェクト: sammyds/WeVoteServer
def position_list_for_ballot_item_for_api(voter_device_id,  # positionListForBallotItem
                                          office_id, office_we_vote_id,
                                          candidate_id, candidate_we_vote_id,
                                          measure_id, measure_we_vote_id,
                                          stance_we_are_looking_for=ANY_STANCE,
                                          show_positions_this_voter_follows=True):
    """
    We want to return a JSON file with the position identifiers from orgs, friends and public figures the voter follows
    This list of information is used to retrieve the detailed information
    """
    position_manager = PositionEnteredManager()
    # Get voter_id from the voter_device_id so we can know who is supporting/opposing
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        position_list = []
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
            'count':            0,
            'kind_of_ballot_item': "UNKNOWN",
            'ballot_item_id':   0,
            'position_list':    position_list,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

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

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

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

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

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

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

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

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

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

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

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

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

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

    json_data = {
        'status':                   status,
        'success':                  success,
        'count':                    positions_count,
        'kind_of_ballot_item':      kind_of_ballot_item,
        'ballot_item_id':           ballot_item_id,
        'ballot_item_we_vote_id':   ballot_item_we_vote_id,
        'position_list':            position_list,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
コード例 #16
0
def organization_position_new_view(request, organization_id):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    authority_results = retrieve_voter_authority(request)
    if not voter_has_authority(request, authority_required, authority_results):
        return redirect_to_sign_in_page(request, authority_required)

    google_civic_election_id = request.GET.get('google_civic_election_id', 0)
    candidate_we_vote_id = request.GET.get('candidate_we_vote_id', False)
    measure_we_vote_id = request.GET.get('measure_we_vote_id', False)

    # Take in some incoming values
    candidate_and_measure_not_found = request.GET.get('candidate_and_measure_not_found', False)
    stance = request.GET.get('stance', SUPPORT)  # Set a default if stance comes in empty
    statement_text = request.GET.get('statement_text', '')  # Set a default if stance comes in empty
    more_info_url = request.GET.get('more_info_url', '')

    # We pass candidate_we_vote_id to this page to pre-populate the form
    candidate_campaign_id = 0
    if positive_value_exists(candidate_we_vote_id):
        candidate_campaign_manager = CandidateCampaignManager()
        results = candidate_campaign_manager.retrieve_candidate_campaign_from_we_vote_id(candidate_we_vote_id)
        if results['candidate_campaign_found']:
            candidate_campaign = results['candidate_campaign']
            candidate_campaign_id = candidate_campaign.id

    # We pass candidate_we_vote_id to this page to pre-populate the form
    contest_measure_id = 0
    if positive_value_exists(measure_we_vote_id):
        contest_measure_manager = ContestMeasureManager()
        results = contest_measure_manager.retrieve_contest_measure_from_we_vote_id(measure_we_vote_id)
        if results['contest_measure_found']:
            contest_measure = results['contest_measure']
            contest_measure_id = contest_measure.id

    messages_on_stage = get_messages(request)
    organization_id = convert_to_int(organization_id)
    all_is_well = True
    organization_on_stage_found = False
    organization_on_stage = Organization()
    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 = CandidateCampaignListManager()
    candidate_campaigns_for_this_election_list = []
    results = candidate_campaign_list.retrieve_all_candidates_for_upcoming_election(google_civic_election_id, True)
    if results['candidate_list_found']:
        candidate_campaigns_for_this_election_list = results['candidate_list_objects']

    # Prepare a drop down of measures in this election
    contest_measure_list = ContestMeasureList()
    contest_measures_for_this_election_list = []
    results = contest_measure_list.retrieve_all_measures_for_upcoming_election(google_civic_election_id, True)
    if results['measure_list_found']:
        contest_measures_for_this_election_list = results['measure_list_objects']

    try:
        organization_position_list = PositionEntered.objects.order_by('stance')
        organization_position_list = organization_position_list.filter(organization_id=organization_id)
        if positive_value_exists(google_civic_election_id):
            organization_position_list = organization_position_list.filter(
                google_civic_election_id=google_civic_election_id)
        organization_position_list = organization_position_list.order_by(
            'google_civic_election_id', '-vote_smart_time_span')
        if len(organization_position_list):
            organization_position_list_found = True
    except Exception as e:
        organization_position_list = []

    if all_is_well:
        election_list = Election.objects.order_by('-election_day_text')
        template_values = {
            'candidate_campaigns_for_this_election_list':   candidate_campaigns_for_this_election_list,
            'candidate_campaign_id':                        candidate_campaign_id,
            'contest_measures_for_this_election_list':      contest_measures_for_this_election_list,
            'contest_measure_id':                           contest_measure_id,
            'messages_on_stage':                            messages_on_stage,
            'organization':                                 organization_on_stage,
            'organization_position_candidate_campaign_id':  0,
            'possible_stances_list':                        ORGANIZATION_STANCE_CHOICES,
            'stance_selected':                              stance,
            'election_list':                                election_list,
            'google_civic_election_id':                     google_civic_election_id,
            'organization_position_list':                   organization_position_list,
            'voter_authority':                              authority_results,
            # Incoming values from error state
            'candidate_and_measure_not_found':              candidate_and_measure_not_found,
            'stance':                                       stance,
            'statement_text':                               statement_text,
            'more_info_url':                                more_info_url,
        }
    return render(request, 'organization/organization_position_edit.html', template_values)
コード例 #17
0
ファイル: models.py プロジェクト: eternal44/WeVoteServer
    def toggle_voter_starred_item(
            self, voter_id, star_status, candidate_campaign_id=0, contest_office_id=0, contest_measure_id=0,
            contest_office_we_vote_id='', candidate_campaign_we_vote_id='', contest_measure_we_vote_id=''):
        # Does a star_item entry exist from this voter already exist?
        star_item_manager = StarItemManager()
        star_item_id = 0
        results = star_item_manager.retrieve_star_item(
            star_item_id, voter_id,
            contest_office_id, candidate_campaign_id, contest_measure_id)

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

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

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

        results = {
            'success':            True if star_item_on_stage_found else False,
            'status':             status,
            'star_item_found':    star_item_on_stage_found,
            'star_item_id':       star_item_on_stage_id,
            'star_item':          star_item_on_stage,
        }
        return results
コード例 #18
0
def voter_supporting_save_for_api(voter_device_id, candidate_id,
                                  candidate_we_vote_id, measure_id,
                                  measure_we_vote_id):
    # Get voter_id from the voter_device_id so we can know who is supporting/opposing, voterSupportingSave
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
            'ballot_item_id': 0,
            'ballot_item_we_vote_id': '',
            'kind_of_ballot_item': '',
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

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

    position_entered_manager = PositionEnteredManager()
    if positive_value_exists(candidate_id) or positive_value_exists(
            candidate_we_vote_id):
        candidate_campaign_manager = CandidateCampaignManager()
        # Since we can take in either candidate_id or candidate_we_vote_id, we need to retrieve the value we don't have
        if positive_value_exists(candidate_id):
            candidate_we_vote_id = candidate_campaign_manager.fetch_candidate_campaign_we_vote_id_from_id(
                candidate_id)
        elif positive_value_exists(candidate_we_vote_id):
            candidate_id = candidate_campaign_manager.fetch_candidate_campaign_id_from_we_vote_id(
                candidate_we_vote_id)

        results = position_entered_manager.toggle_on_voter_support_for_candidate_campaign(
            voter_id, candidate_id)
        status = "SUPPORTING_CANDIDATE " + results['status']
        success = results['success']

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

        results = position_entered_manager.toggle_on_voter_support_for_contest_measure(
            voter_id, measure_id)
        status = "SUPPORTING_MEASURE " + results['status']
        success = results['success']

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

    json_data = {
        'status': status,
        'success': success,
        'ballot_item_id': 0,
        'ballot_item_we_vote_id': '',
        'kind_of_ballot_item': '',
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
コード例 #19
0
def positions_import_from_sample_file(request=None, load_from_uri=False):
    """
    Get the json data, and either create new entries or update existing
    :return:
    """
    # if load_from_uri:
    #     # Request json file from We Vote servers
    #     messages.add_message(request, messages.INFO, "Loading positions from We Vote Master servers")
    #     request = requests.get(POSITIONS_URL, params={
    #         "key": WE_VOTE_API_KEY,  # This comes from an environment variable
    #     })
    #     structured_json = json.loads(request.text)
    # else:
    # Load saved json from local file
    with open("position/import_data/positions_sample.json") as json_data:
        structured_json = json.load(json_data)

    positions_saved = 0
    positions_updated = 0
    positions_not_processed = 0
    for one_position in structured_json:
        # Make sure we have the minimum required variables
        if not positive_value_exists(one_position["we_vote_id"]) \
                or not positive_value_exists(one_position["organization_we_vote_id"])\
                or not positive_value_exists(one_position["candidate_campaign_we_vote_id"]):
            positions_not_processed += 1
            continue

        # Check to see if this position is already being used anywhere
        position_on_stage_found = False
        try:
            if len(one_position["we_vote_id"]) > 0:
                position_query = PositionEntered.objects.filter(we_vote_id=one_position["we_vote_id"])
                if len(position_query):
                    position_on_stage = position_query[0]
                    position_on_stage_found = True
        except PositionEntered.DoesNotExist as e:
            handle_record_not_found_exception(e, logger=logger)
            pass
        except Exception as e:
            handle_record_not_found_exception(e, logger=logger)

        # We need to look up the local organization_id based on the newly saved we_vote_id
        organization_manager = OrganizationManager()
        organization_id = organization_manager.fetch_organization_id(one_position["organization_we_vote_id"])

        # We need to look up the local candidate_campaign_id
        candidate_campaign_manager = CandidateCampaignManager()
        candidate_campaign_id = candidate_campaign_manager.fetch_candidate_campaign_id_from_we_vote_id(
            one_position["candidate_campaign_we_vote_id"])

        # Find the google_civic_candidate_name so we have a backup way to link position if the we_vote_id is lost
        google_civic_candidate_name = one_position["google_civic_candidate_name"] if \
            "google_civic_candidate_name" in one_position else ''
        if not positive_value_exists(google_civic_candidate_name):
            google_civic_candidate_name = candidate_campaign_manager.fetch_google_civic_candidate_name_from_we_vote_id(
                one_position["candidate_campaign_we_vote_id"])

        # TODO We need to look up measure_campaign_id
        measure_campaign_id = 0

        try:
            if position_on_stage_found:
                # Update
                position_on_stage.we_vote_id = one_position["we_vote_id"]
                position_on_stage.organization_id = organization_id
                position_on_stage.organization_we_vote_id = one_position["organization_we_vote_id"]
                position_on_stage.candidate_campaign_id = candidate_campaign_id
                position_on_stage.candidate_campaign_we_vote_id = one_position["candidate_campaign_we_vote_id"]
                position_on_stage.google_civic_candidate_name = google_civic_candidate_name
                position_on_stage.measure_campaign_id = measure_campaign_id
                position_on_stage.date_entered = one_position["date_entered"]
                position_on_stage.google_civic_election_id = one_position["google_civic_election_id"]
                position_on_stage.stance = one_position["stance"]
                position_on_stage.more_info_url = one_position["more_info_url"]
                position_on_stage.statement_text = one_position["statement_text"]
                position_on_stage.statement_html = one_position["statement_html"]
                position_on_stage.save()
                positions_updated += 1
                # messages.add_message(request, messages.INFO, u"Position updated: {we_vote_id}".format(
                #     we_vote_id=one_position["we_vote_id"]))
            else:
                # Create new
                position_on_stage = PositionEntered(
                    we_vote_id=one_position["we_vote_id"],
                    organization_id=organization_id,
                    organization_we_vote_id=one_position["organization_we_vote_id"],
                    candidate_campaign_id=candidate_campaign_id,
                    candidate_campaign_we_vote_id=one_position["candidate_campaign_we_vote_id"],
                    google_civic_candidate_name=google_civic_candidate_name,
                    measure_campaign_id=measure_campaign_id,
                    date_entered=one_position["date_entered"],
                    google_civic_election_id=one_position["google_civic_election_id"],
                    stance=one_position["stance"],
                    more_info_url=one_position["more_info_url"],
                    statement_text=one_position["statement_text"],
                    statement_html=one_position["statement_html"],
                )
                position_on_stage.save()
                positions_saved += 1
                # messages.add_message(request, messages.INFO, u"New position imported: {we_vote_id}".format(
                #     we_vote_id=one_position["we_vote_id"]))
        except Exception as e:
            handle_record_not_saved_exception(e, logger=logger)
            if request is not None:
                messages.add_message(request, messages.ERROR,
                                     u"Could not save/update position, "
                                     u"position_on_stage_found: {position_on_stage_found}, "
                                     u"we_vote_id: {we_vote_id}, "
                                     u"organization_we_vote_id: {organization_we_vote_id}, "
                                     u"candidate_campaign_we_vote_id: {candidate_campaign_we_vote_id}".format(
                                         position_on_stage_found=position_on_stage_found,
                                         we_vote_id=one_position["we_vote_id"],
                                         organization_we_vote_id=one_position["organization_we_vote_id"],
                                         candidate_campaign_we_vote_id=one_position["candidate_campaign_we_vote_id"],
                                     ))
            positions_not_processed += 1

    positions_results = {
        'saved': positions_saved,
        'updated': positions_updated,
        'not_processed': positions_not_processed,
    }
    return positions_results
コード例 #20
0
ファイル: views.py プロジェクト: pkaiserui/WeVoteServer
def assemble_candidate_campaign_stance_html(
        candidate_campaign_id, stance_we_are_looking_for, positions_followed,
        positions_not_followed):  # TODO DEPRECATE
    """

    :param candidate_campaign_id:
    :param stance_we_are_looking_for:
    :param positions_followed:
    :param positions_not_followed:
    :return:
    """
    #################################
    # Start with positions_followed

    # Assemble some information that is independent of each position
    number_of_positions_followed_total = len(positions_followed)
    popup_box_title_verb = display_stance_we_are_looking_for_title(
        stance_we_are_looking_for, number_of_positions_followed_total)

    candidate_campaign_manager = CandidateCampaignManager()
    results = candidate_campaign_manager.retrieve_candidate_campaign_from_id(
        candidate_campaign_id)
    if results['candidate_campaign_found']:
        candidate_campaign = results['candidate_campaign']
        popup_box_title_candidate_name = candidate_campaign.candidate_name
    else:
        popup_box_title_candidate_name = ""

    popup_box_title = popup_box_title_verb + " " + popup_box_title_candidate_name
    if stance_we_are_looking_for == SUPPORT:
        # This is the class we reference with jquery for opening a div popup to display the supporters
        class_used_to_open_popup = "candidate_campaign_" + candidate_campaign_id + "_supporters"
        # This is the URL that returns the supporters for this candidate
        retrieve_positions_url = "/pos/cand/" + candidate_campaign_id + "/supporters?f=1"  # Only show orgs followed
    elif stance_we_are_looking_for == OPPOSE:
        class_used_to_open_popup = "candidate_campaign_" + candidate_campaign_id + "_opposers"
        retrieve_positions_url = "/pos/cand/" + candidate_campaign_id + "/opposers?f=1"
    elif stance_we_are_looking_for == INFORMATION_ONLY:
        class_used_to_open_popup = "candidate_campaign_" + candidate_campaign_id + "_infoonly"
        retrieve_positions_url = "/pos/cand/" + candidate_campaign_id + "/infoonlylist?f=1"
    elif stance_we_are_looking_for == STILL_DECIDING:
        class_used_to_open_popup = "candidate_campaign_" + candidate_campaign_id + "_deciders"
        retrieve_positions_url = "/pos/cand/" + candidate_campaign_id + "/deciders?f=1"
    else:
        class_used_to_open_popup = ''
        retrieve_positions_url = ''

    # Cycle through these positions and put together a line about who is supporting, opposing, have information
    #  or are still deciding
    positions_followed_stance_html = ""
    is_first = True
    number_of_positions_followed_counter = 0
    only_you = False
    for position in positions_followed:
        if is_first:
            positions_followed_stance_html += ""
        else:
            is_next_to_last = number_of_positions_followed_counter == number_of_positions_followed_total - 1
            positions_followed_stance_html += " and " if is_next_to_last else ", "
        is_first = False

        if position.organization_id > 0:
            organization_manager = OrganizationManager()
            results = organization_manager.retrieve_organization(
                position.organization_id)
            if results['organization_found']:
                organization_on_stage = results['organization']
                link_open = "<a class='{link_class}' href='{link_href}' id='{popup_box_title}'>".format(
                    link_class=class_used_to_open_popup,
                    link_href=retrieve_positions_url,
                    popup_box_title=popup_box_title,
                )
                positions_followed_stance_html += "{link_open}{organization_name}</a>".format(
                    link_open=link_open,
                    organization_name=organization_on_stage.name,
                )
                number_of_positions_followed_counter += 1
        elif position.voter_id > 0:
            positions_followed_stance_html += "You"
            number_of_positions_followed_counter += 1
            if number_of_positions_followed_total == 1:
                only_you = True
    if number_of_positions_followed_total:
        verb_text = display_stance_we_are_looking_for(
            stance_we_are_looking_for, number_of_positions_followed_total,
            only_you)
        if verb_text:
            positions_followed_stance_html = "<span class='positions_followed_text'>" + positions_followed_stance_html
            positions_followed_stance_html += " <span class='position_stance_verb'>{verb_text}</span>".format(
                verb_text=verb_text)
            positions_followed_stance_html += "</span>"

    #################################
    # NOT Followed
    #################################
    # Now create string with html for positions_not_followed
    positions_not_followed_stance_html = ""
    number_of_positions_not_followed_total = len(positions_not_followed)
    # If there aren't any "not followed" positions, just return the positions_followed_stance_html
    if number_of_positions_not_followed_total == 0:
        return positions_followed_stance_html

    # If here we know there is at least one position available that isnt' being followed by voter
    popup_box_title = popup_box_title_verb + " " + popup_box_title_candidate_name
    if stance_we_are_looking_for == SUPPORT:
        # This is the class we reference with jquery for opening a div popup to display the supporters
        class_used_to_open_popup = "candidate_campaign_" + candidate_campaign_id + "_supporters"
        # This is the URL that returns the supporters for this candidate
        retrieve_positions_url = "/pos/cand/" + candidate_campaign_id + "/supporters?nf=1"  # Only show orgs not followed
    elif stance_we_are_looking_for == OPPOSE:
        class_used_to_open_popup = "candidate_campaign_" + candidate_campaign_id + "_opposers"
        retrieve_positions_url = "/pos/cand/" + candidate_campaign_id + "/opposers?nf=1"
    elif stance_we_are_looking_for == INFORMATION_ONLY:
        class_used_to_open_popup = "candidate_campaign_" + candidate_campaign_id + "_infoonly"
        retrieve_positions_url = "/pos/cand/" + candidate_campaign_id + "/infoonlylist?nf=1"
    elif stance_we_are_looking_for == STILL_DECIDING:
        class_used_to_open_popup = "candidate_campaign_" + candidate_campaign_id + "_deciders"
        retrieve_positions_url = "/pos/cand/" + candidate_campaign_id + "/deciders?nf=1"
    else:
        class_used_to_open_popup = ''
        retrieve_positions_url = ''

    link_open = "<a class='{link_class}' href='{link_href}' id='{popup_box_title}'>".format(
        link_class=class_used_to_open_popup,
        link_href=retrieve_positions_url,
        popup_box_title=popup_box_title,
    )

    # How we display the link to the positions NOT followed varies based on the number of *followed* positions
    if number_of_positions_followed_total == 0:
        if number_of_positions_not_followed_total == 1:
            not_followed_stance_verb = display_stance_verb_we_are_looking_for_singular(
                stance_we_are_looking_for)
        else:
            not_followed_stance_verb = display_stance_verb_we_are_looking_for_plural(
                stance_we_are_looking_for)
        positions_not_followed_stance_html += \
            "{link_open}{number} {not_followed_stance_verb}</a> ({link_open}learn more</a>)".format(
                link_open=link_open,
                number=number_of_positions_not_followed_total,
                not_followed_stance_verb=not_followed_stance_verb,
            )
    elif number_of_positions_followed_total < 5:
        if number_of_positions_not_followed_total == 1:
            not_followed_stance_verb = "other " \
                + display_stance_verb_we_are_looking_for_plural(stance_we_are_looking_for)
        else:
            not_followed_stance_verb = "others "\
                + display_stance_verb_we_are_looking_for_singular(stance_we_are_looking_for)
        positions_not_followed_stance_html += \
            "({link_open}{number_of_positions_not_followed_total} {not_followed_stance_verb}</a>)".format(
                link_open=link_open,
                number_of_positions_not_followed_total=number_of_positions_not_followed_total,
                not_followed_stance_verb=not_followed_stance_verb,
            )
    else:  # When there are more than 5 positions from followed organizations
        positions_not_followed_stance_html += "({link_open}show more supporters</a>)".format(
            link_open=link_open, )

    stance_html = positions_followed_stance_html + " " + "<span class='positions_not_followed'>" \
        + positions_not_followed_stance_html + "</span>"

    return stance_html
コード例 #21
0
ファイル: views.py プロジェクト: thaddeusphoenix/WeVoteServer
def assemble_candidate_campaign_stance_html(
        candidate_campaign_id, stance_we_are_looking_for, positions_followed, positions_not_followed):
    """

    :param candidate_campaign_id:
    :param stance_we_are_looking_for:
    :param positions_followed:
    :param positions_not_followed:
    :return:
    """
    #################################
    # Start with positions_followed

    # Assemble some information that is independent of each position
    number_of_positions_followed_total = len(positions_followed)
    popup_box_title_verb = display_stance_we_are_looking_for_title(
        stance_we_are_looking_for, number_of_positions_followed_total)

    candidate_campaign_manager = CandidateCampaignManager()
    results = candidate_campaign_manager.retrieve_candidate_campaign_from_id(candidate_campaign_id)
    if results['candidate_campaign_found']:
        candidate_campaign = results['candidate_campaign']
        popup_box_title_candidate_name = candidate_campaign.candidate_name
    else:
        popup_box_title_candidate_name = ""

    popup_box_title = popup_box_title_verb+" "+popup_box_title_candidate_name
    if stance_we_are_looking_for == SUPPORT:
        # This is the class we reference with jquery for opening a div popup to display the supporters
        class_used_to_open_popup = "candidate_campaign_"+candidate_campaign_id+"_supporters"
        # This is the URL that returns the supporters for this candidate
        retrieve_positions_url = "/pos/cand/"+candidate_campaign_id+"/supporters?f=1"  # Only show orgs followed
    elif stance_we_are_looking_for == OPPOSE:
        class_used_to_open_popup = "candidate_campaign_"+candidate_campaign_id+"_opposers"
        retrieve_positions_url = "/pos/cand/"+candidate_campaign_id+"/opposers?f=1"
    elif stance_we_are_looking_for == INFORMATION_ONLY:
        class_used_to_open_popup = "candidate_campaign_"+candidate_campaign_id+"_infoonly"
        retrieve_positions_url = "/pos/cand/"+candidate_campaign_id+"/infoonlylist?f=1"
    elif stance_we_are_looking_for == STILL_DECIDING:
        class_used_to_open_popup = "candidate_campaign_"+candidate_campaign_id+"_deciders"
        retrieve_positions_url = "/pos/cand/"+candidate_campaign_id+"/deciders?f=1"
    else:
        class_used_to_open_popup = ''
        retrieve_positions_url = ''

    # Cycle through these positions and put together a line about who is supporting, opposing, have information
    #  or are still deciding
    positions_followed_stance_html = ""
    is_first = True
    number_of_positions_followed_counter = 0
    only_you = False
    for position in positions_followed:
        if is_first:
            positions_followed_stance_html += ""
        else:
            is_next_to_last = number_of_positions_followed_counter == number_of_positions_followed_total - 1
            positions_followed_stance_html += " and " if is_next_to_last else ", "
        is_first = False

        if position.organization_id > 0:
            organization_manager = OrganizationManager()
            results = organization_manager.retrieve_organization(position.organization_id)
            if results['organization_found']:
                organization_on_stage = results['organization']
                link_open = "<a class='{link_class}' href='{link_href}' id='{popup_box_title}'>".format(
                    link_class=class_used_to_open_popup,
                    link_href=retrieve_positions_url,
                    popup_box_title=popup_box_title,
                )
                positions_followed_stance_html += "{link_open}{organization_name}</a>".format(
                    link_open=link_open,
                    organization_name=organization_on_stage.name,
                )
                number_of_positions_followed_counter += 1
        elif position.voter_id > 0:
            positions_followed_stance_html += "You"
            number_of_positions_followed_counter += 1
            if number_of_positions_followed_total == 1:
                only_you = True
    if number_of_positions_followed_total:
        verb_text = display_stance_we_are_looking_for(
            stance_we_are_looking_for, number_of_positions_followed_total, only_you)
        if verb_text:
            positions_followed_stance_html = "<span class='positions_followed_text'>" + positions_followed_stance_html
            positions_followed_stance_html += " <span class='position_stance_verb'>{verb_text}</span>".format(
                verb_text=verb_text)
            positions_followed_stance_html += "</span>"

    #################################
    # NOT Followed
    #################################
    # Now create string with html for positions_not_followed
    positions_not_followed_stance_html = ""
    number_of_positions_not_followed_total = len(positions_not_followed)
    # If there aren't any "not followed" positions, just return the positions_followed_stance_html
    if number_of_positions_not_followed_total == 0:
        return positions_followed_stance_html

    # If here we know there is at least one position available that isnt' being followed by voter
    popup_box_title = popup_box_title_verb+" "+popup_box_title_candidate_name
    if stance_we_are_looking_for == SUPPORT:
        # This is the class we reference with jquery for opening a div popup to display the supporters
        class_used_to_open_popup = "candidate_campaign_"+candidate_campaign_id+"_supporters"
        # This is the URL that returns the supporters for this candidate
        retrieve_positions_url = "/pos/cand/"+candidate_campaign_id+"/supporters?nf=1"  # Only show orgs not followed
    elif stance_we_are_looking_for == OPPOSE:
        class_used_to_open_popup = "candidate_campaign_"+candidate_campaign_id+"_opposers"
        retrieve_positions_url = "/pos/cand/"+candidate_campaign_id+"/opposers?nf=1"
    elif stance_we_are_looking_for == INFORMATION_ONLY:
        class_used_to_open_popup = "candidate_campaign_"+candidate_campaign_id+"_infoonly"
        retrieve_positions_url = "/pos/cand/"+candidate_campaign_id+"/infoonlylist?nf=1"
    elif stance_we_are_looking_for == STILL_DECIDING:
        class_used_to_open_popup = "candidate_campaign_"+candidate_campaign_id+"_deciders"
        retrieve_positions_url = "/pos/cand/"+candidate_campaign_id+"/deciders?nf=1"
    else:
        class_used_to_open_popup = ''
        retrieve_positions_url = ''

    link_open = "<a class='{link_class}' href='{link_href}' id='{popup_box_title}'>".format(
        link_class=class_used_to_open_popup,
        link_href=retrieve_positions_url,
        popup_box_title=popup_box_title,
    )

    # How we display the link to the positions NOT followed varies based on the number of *followed* positions
    if number_of_positions_followed_total == 0:
        if number_of_positions_not_followed_total == 1:
            not_followed_stance_verb = display_stance_verb_we_are_looking_for_singular(stance_we_are_looking_for)
        else:
            not_followed_stance_verb = display_stance_verb_we_are_looking_for_plural(stance_we_are_looking_for)
        positions_not_followed_stance_html += \
            "{link_open}{number} {not_followed_stance_verb}</a> ({link_open}learn more</a>)".format(
                link_open=link_open,
                number=number_of_positions_not_followed_total,
                not_followed_stance_verb=not_followed_stance_verb,
            )
    elif number_of_positions_followed_total < 5:
        if number_of_positions_not_followed_total == 1:
            not_followed_stance_verb = "other " \
                + display_stance_verb_we_are_looking_for_plural(stance_we_are_looking_for)
        else:
            not_followed_stance_verb = "others "\
                + display_stance_verb_we_are_looking_for_singular(stance_we_are_looking_for)
        positions_not_followed_stance_html += \
            "({link_open}{number_of_positions_not_followed_total} {not_followed_stance_verb}</a>)".format(
                link_open=link_open,
                number_of_positions_not_followed_total=number_of_positions_not_followed_total,
                not_followed_stance_verb=not_followed_stance_verb,
            )
    else:  # When there are more than 5 positions from followed organizations
        positions_not_followed_stance_html += "({link_open}show more supporters</a>)".format(
            link_open=link_open,
        )

    stance_html = positions_followed_stance_html + " " + "<span class='positions_not_followed'>" \
        + positions_not_followed_stance_html + "</span>"

    return stance_html
コード例 #22
0
    def toggle_voter_starred_item(self,
                                  voter_id,
                                  star_status,
                                  candidate_campaign_id=0,
                                  contest_office_id=0,
                                  contest_measure_id=0,
                                  contest_office_we_vote_id='',
                                  candidate_campaign_we_vote_id='',
                                  contest_measure_we_vote_id=''):
        # Does a star_item entry exist from this voter already exist?
        star_item_manager = StarItemManager()
        star_item_id = 0
        results = star_item_manager.retrieve_star_item(star_item_id, voter_id,
                                                       contest_office_id,
                                                       candidate_campaign_id,
                                                       contest_measure_id)

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

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

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

        results = {
            'success': True if star_item_on_stage_found else False,
            'status': status,
            'star_item_found': star_item_on_stage_found,
            'star_item_id': star_item_on_stage_id,
            'star_item': star_item_on_stage,
        }
        return results
コード例 #23
0
ファイル: controllers.py プロジェクト: eternal44/WeVoteServer
def positions_count_for_candidate_campaign(voter_id, candidate_id, candidate_we_vote_id, stance_we_are_looking_for,
                                           show_positions_this_voter_follows=True):
    """
    We want to return a JSON file with the number of orgs, friends and public figures the voter follows who support
    this particular candidate's campaign
    """
    # This implementation is built to make limited database calls. We do as many calculations as we can here in the
    #  application layer

    position_list_manager = PositionListManager()
    all_positions_list_for_candidate_campaign = \
        position_list_manager.retrieve_all_positions_for_candidate_campaign(
            candidate_id, candidate_we_vote_id, stance_we_are_looking_for)

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

    # Since we can take in either candidate_id or candidate_we_vote_id, we need to retrieve the candidate object
    # so we make sure we have both of these values to return
    if positive_value_exists(candidate_id):
        candidate_campaign_manager = CandidateCampaignManager()
        results = candidate_campaign_manager.retrieve_candidate_campaign_from_id(candidate_id)
        if results['candidate_campaign_found']:
            candidate_campaign = results['candidate_campaign']
            candidate_we_vote_id = candidate_campaign.we_vote_id
    elif positive_value_exists(candidate_we_vote_id):
        candidate_campaign_manager = CandidateCampaignManager()
        results = candidate_campaign_manager.retrieve_candidate_campaign_from_we_vote_id(candidate_we_vote_id)
        if results['candidate_campaign_found']:
            candidate_campaign = results['candidate_campaign']
            candidate_id = candidate_campaign.id

    if show_positions_this_voter_follows:
        positions_followed = position_list_manager.calculate_positions_followed_by_voter(
            voter_id, all_positions_list_for_candidate_campaign, organizations_followed_by_voter)
        positions_followed_count = len(positions_followed)
        json_data = {
            'status': 'SUCCESSFUL_RETRIEVE_OF_POSITIONS_FOLLOWED_RE_CANDIDATE',
            'success': True,
            'count': positions_followed_count,
            'ballot_item_id': convert_to_int(candidate_id),
            'ballot_item_we_vote_id': candidate_we_vote_id,
            'kind_of_ballot_item': CANDIDATE,
        }
        results = {
            'json_data': json_data,
        }
        return results
    else:
        positions_not_followed = position_list_manager.calculate_positions_not_followed_by_voter(
            all_positions_list_for_candidate_campaign, organizations_followed_by_voter)
        positions_not_followed_count = len(positions_not_followed)
        json_data = {
            'status': 'SUCCESSFUL_RETRIEVE_OF_POSITIONS_NOT_FOLLOWED_CC',
            'success': True,
            'count': positions_not_followed_count,
            'ballot_item_id': convert_to_int(candidate_id),
            'ballot_item_we_vote_id': candidate_we_vote_id,
            'kind_of_ballot_item': CANDIDATE,
        }
        results = {
            'json_data': json_data,
        }
        return results
コード例 #24
0
ファイル: controllers.py プロジェクト: eternal44/WeVoteServer
def voter_supporting_save_for_api(voter_device_id, candidate_id, candidate_we_vote_id, measure_id, measure_we_vote_id):
    # Get voter_id from the voter_device_id so we can know who is supporting/opposing, voterSupportingSave
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
            'ballot_item_id':           0,
            'ballot_item_we_vote_id':   '',
            'kind_of_ballot_item':      '',
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

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

    position_entered_manager = PositionEnteredManager()
    if positive_value_exists(candidate_id) or positive_value_exists(candidate_we_vote_id):
        candidate_campaign_manager = CandidateCampaignManager()
        # Since we can take in either candidate_id or candidate_we_vote_id, we need to retrieve the value we don't have
        if positive_value_exists(candidate_id):
            candidate_we_vote_id = candidate_campaign_manager.fetch_candidate_campaign_we_vote_id_from_id(candidate_id)
        elif positive_value_exists(candidate_we_vote_id):
            candidate_id = candidate_campaign_manager.fetch_candidate_campaign_id_from_we_vote_id(candidate_we_vote_id)

        results = position_entered_manager.toggle_on_voter_support_for_candidate_campaign(voter_id, candidate_id)
        status = "SUPPORTING_CANDIDATE " + results['status']
        success = results['success']

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

        results = position_entered_manager.toggle_on_voter_support_for_contest_measure(voter_id, measure_id)
        status = "SUPPORTING_MEASURE " + results['status']
        success = results['success']

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

    json_data = {
        'status': status,
        'success': success,
        'ballot_item_id':           0,
        'ballot_item_we_vote_id':   '',
        'kind_of_ballot_item':      '',
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
コード例 #25
0
def process_candidates_from_structured_json(
        candidates_structured_json, google_civic_election_id, ocd_division_id, state_code, contest_office_id,
        contest_office_we_vote_id):
    """
    "candidates": [
        {
         "name": "Nancy Pelosi",
         "party": "Democratic"
        },
        {
         "name": "John Dennis",
         "party": "Republican",
         "candidateUrl": "http://www.johndennisforcongress.com/",
         "channels": [
          {
           "type": "Facebook",
           "id": "https://www.facebook.com/johndennis2010"
          },
          {
           "type": "Twitter",
           "id": "https://twitter.com/johndennis2012"
    """
    results = {}
    for one_candidate in candidates_structured_json:
        candidate_name = one_candidate['name'] if 'name' in one_candidate else ''
        # For some reason Google Civic API violates the JSON standard and uses a
        candidate_name = candidate_name.replace('/', "'")
        # We want to save the name exactly as it comes from the Google Civic API
        google_civic_candidate_name = one_candidate['name'] if 'name' in one_candidate else ''
        party = one_candidate['party'] if 'party' in one_candidate else ''
        order_on_ballot = one_candidate['orderOnBallot'] if 'orderOnBallot' in one_candidate else 0
        candidate_url = one_candidate['candidateUrl'] if 'candidateUrl' in one_candidate else ''
        photo_url = one_candidate['photoUrl'] if 'photoUrl' in one_candidate else ''
        email = one_candidate['email'] if 'email' in one_candidate else ''
        phone = one_candidate['phone'] if 'phone' in one_candidate else ''

        # set them to channel values to empty
        facebook_url = ''
        twitter_url = ''
        google_plus_url = ''
        youtube_url = ''
        if 'channels' in one_candidate:
            channels = one_candidate['channels']
            for one_channel in channels:
                if 'type' in one_channel:
                    if one_channel['type'] == 'Facebook':
                        facebook_url = one_channel['id'] if 'id' in one_channel else ''
                    if one_channel['type'] == 'Twitter':
                        twitter_url = one_channel['id'] if 'id' in one_channel else ''
                    if one_channel['type'] == 'GooglePlus':
                        google_plus_url = one_channel['id'] if 'id' in one_channel else ''
                    if one_channel['type'] == 'YouTube':
                        youtube_url = one_channel['id'] if 'id' in one_channel else ''

        we_vote_id = ''
        if google_civic_election_id and ocd_division_id and contest_office_id and candidate_name:
            updated_candidate_campaign_values = {
                # Values we search against
                'google_civic_election_id': google_civic_election_id,
                'ocd_division_id': ocd_division_id,
                'contest_office_id': contest_office_id,
                'contest_office_we_vote_id': contest_office_we_vote_id,
                # Note: When we decide to start updating candidate_name elsewhere within We Vote, we should stop
                #  updating candidate_name via subsequent Google Civic imports
                'candidate_name': candidate_name,
                # The rest of the values
                'state_code': state_code,  # Not required due to federal candidates
                'party': party,
                'candidate_email': email,
                'candidate_phone': phone,
                'order_on_ballot': order_on_ballot,
                'candidate_url': candidate_url,
                'photo_url': photo_url,
                'facebook_url': facebook_url,
                'twitter_url': twitter_url,
                'google_plus_url': google_plus_url,
                'youtube_url': youtube_url,
                'google_civic_candidate_name': google_civic_candidate_name,
            }
            candidate_campaign_manager = CandidateCampaignManager()
            results = candidate_campaign_manager.update_or_create_candidate_campaign(
                we_vote_id, google_civic_election_id, ocd_division_id, contest_office_id, contest_office_we_vote_id,
                google_civic_candidate_name, updated_candidate_campaign_values)

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

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status': "VALID_VOTER_ID_MISSING",
            'success': False,
            'voter_device_id': voter_device_id,
            'is_starred': False,
            'office_id': convert_to_int(office_id),
            'candidate_id': convert_to_int(candidate_id),
            'measure_id': convert_to_int(measure_id),
            'ballot_item_id': 0,
            'ballot_item_we_vote_id': '',
            'kind_of_ballot_item': '',
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

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

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

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

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

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

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

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

    json_data = {
        'status': status,
        'success': success,
        'voter_device_id': voter_device_id,
        'is_starred': is_starred,
        'office_id': convert_to_int(office_id),
        'candidate_id': convert_to_int(candidate_id),
        'measure_id': convert_to_int(measure_id),
        'ballot_item_id': 0,
        'ballot_item_we_vote_id': '',
        'kind_of_ballot_item': '',
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
コード例 #27
0
def quick_info_edit_process_view(request):
    """
    Process the new or edit quick_info forms
    :param request:
    :return:
    """
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

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

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

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

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

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

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

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

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

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

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

    last_editor_we_vote_id = ""  # TODO We need to calculate this

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

    return HttpResponseRedirect(reverse('quick_info:quick_info_list', args=()))
コード例 #28
0
def transfer_vote_smart_ratings_to_positions(
        candidate_campaign_id,
        politician_id):  # TODO DALE Update for politician
    we_vote_organizations_created = 0
    organization_positions_that_exist = 0
    organization_positions_created = 0
    candidate_manager = CandidateCampaignManager()
    candidate_results = candidate_manager.retrieve_candidate_campaign_from_id(
        candidate_campaign_id)

    if candidate_results['candidate_campaign_found']:
        # Working with Vote Smart data
        candidate_campaign = candidate_results['candidate_campaign']
        if not positive_value_exists(candidate_campaign.vote_smart_id):
            status = "VOTE_SMART_ID_HAS_NOT_BEEN_RETRIEVED_YET_FOR_THIS_CANDIDATE: " \
                     "{candidate_campaign_id}".format(candidate_campaign_id=candidate_campaign_id)
            success = False
            results = {
                'status': status,
                'success': success,
                'we_vote_organizations_created': we_vote_organizations_created,
                'organization_positions_that_exist':
                organization_positions_that_exist,
                'organization_positions_created':
                organization_positions_created,
            }
            return results
        else:
            try:
                rating_list_query = VoteSmartRatingOneCandidate.objects.order_by(
                    '-timeSpan')  # Desc order
                rating_list = rating_list_query.filter(
                    candidateId=candidate_campaign.vote_smart_id)
            except Exception as error_instance:
                # Catch the error message coming back from Vote Smart and pass it in the status
                error_message = error_instance.args
                status = "EXCEPTION_RAISED: {error_message}".format(
                    error_message=error_message)
                success = False
                results = {
                    'status':
                    status,
                    'success':
                    success,
                    'we_vote_organizations_created':
                    we_vote_organizations_created,
                    'organization_positions_that_exist':
                    organization_positions_that_exist,
                    'organization_positions_created':
                    organization_positions_created,
                }
                return results

        ratings_status = ""
        position_manager = PositionEnteredManager()
        special_interest_group_manager = VoteSmartSpecialInterestGroupManager()
        for one_candidate_rating in rating_list:
            # Make sure we have all of the required variables
            if not one_candidate_rating.sigId:
                ratings_status += "MISSING_SPECIAL_INTEREST_GROUP_ID-{ratingId} * " \
                                  "".format(ratingId=one_candidate_rating.ratingId)
                continue
            # Make sure an organization exists and is updated with Vote Smart info
            update_results = special_interest_group_manager.update_or_create_we_vote_organization(
                one_candidate_rating.sigId)
            if not update_results['organization_found']:
                # TRY AGAIN: Reach out to Vote Smart and try to retrieve this special interest group by sigId
                one_group_results = retrieve_vote_smart_special_interest_group_into_local_db(
                    one_candidate_rating.sigId)

                if one_group_results['success']:
                    update_results = special_interest_group_manager.update_or_create_we_vote_organization(
                        one_candidate_rating.sigId)

            if not update_results['organization_found']:
                ratings_status += "COULD_NOT_FIND_OR_SAVE_NEW_SIG-{sigId}-{status} * " \
                                  "".format(sigId=one_candidate_rating.sigId,
                                            status=update_results['status'])
                continue
            else:
                we_vote_organization = update_results['organization']
                if update_results['organization_created']:
                    we_vote_organizations_created += 1

            # Check to see if a position already exists
            # TODO DALE Note: we need to consider searching with a time span variable
            # (in addition to just org and candidate identifiers) since I believe
            # Google Civic gives a person a new candidate campaign ID each election,
            # while Vote Smart uses the same candidateId from year to year
            organization_position_results = position_manager.retrieve_organization_candidate_campaign_position(
                we_vote_organization.id, candidate_campaign_id)

            if positive_value_exists(
                    organization_position_results['position_found']):
                # For now, we only want to create positions that don't exist
                organization_positions_that_exist += 1
                continue
            else:
                position_results = position_manager.update_or_create_position(
                    position_we_vote_id=False,
                    organization_we_vote_id=we_vote_organization.we_vote_id,
                    public_figure_we_vote_id=False,
                    voter_we_vote_id=False,
                    google_civic_election_id=False,
                    ballot_item_display_name=candidate_campaign.
                    display_candidate_name(),
                    office_we_vote_id=False,
                    candidate_we_vote_id=candidate_campaign.we_vote_id,
                    measure_we_vote_id=False,
                    stance=PERCENT_RATING,
                    set_as_public_position=True,
                    statement_text=one_candidate_rating.ratingText,
                    statement_html=False,
                    more_info_url=False,
                    vote_smart_time_span=one_candidate_rating.timeSpan,
                    vote_smart_rating_id=one_candidate_rating.ratingId,
                    vote_smart_rating=one_candidate_rating.rating,
                    vote_smart_rating_name=one_candidate_rating.ratingName,
                )

                if positive_value_exists(position_results['success']):
                    organization_positions_created += 1
                else:
                    ratings_status += "COULD_NOT_CREATE_POSITION-{sigId}-{status} * " \
                                      "".format(sigId=one_candidate_rating.sigId,
                                                status=position_results['status'])

    success = True
    status = "TRANSFER_PROCESS_COMPLETED: " + ratings_status

    results = {
        'status': status,
        'success': success,
        'we_vote_organizations_created': we_vote_organizations_created,
        'organization_positions_that_exist': organization_positions_that_exist,
        'organization_positions_created': organization_positions_created,
    }

    return results
コード例 #29
0
def transfer_maplight_data_to_we_vote_tables(request):
    # TODO We need to perhaps set up a table for these mappings that volunteers can add to?
    #  We need a plan for how volunteers can help us add to these mappings
    # One possibility -- ask volunteers to update this Google Sheet, then write a csv importer:
    #  https://docs.google.com/spreadsheets/d/1havD7GCxmBhi-zLLMdOpSJlU_DtBjvb5IJNiXgno9Bk/edit#gid=0
    politician_name_mapping_list = []
    one_mapping = {
        "google_civic_name": "Betty T. Yee",
        "maplight_display_name": "Betty Yee",
        "maplight_original_name": "Betty T Yee",
    }
    politician_name_mapping_list.append(one_mapping)
    one_mapping = {
        "google_civic_name": "Edmund G. \"Jerry\" Brown",
        "maplight_display_name": "Jerry Brown",
        "maplight_original_name": "",
    }
    politician_name_mapping_list.append(one_mapping)

    candidate_campaign_manager = CandidateCampaignManager()

    maplight_candidates_current_query = MapLightCandidate.objects.all()

    for one_candidate_from_maplight_table in maplight_candidates_current_query:
        found_by_id = False
        # Try to find a matching candidate
        results = candidate_campaign_manager.retrieve_candidate_campaign_from_id_maplight(
            one_candidate_from_maplight_table.candidate_id)

        if not results['success']:
            logger.warn(u"Candidate NOT found by MapLight id: {name}".format(
                name=one_candidate_from_maplight_table.candidate_id))
            results = candidate_campaign_manager.retrieve_candidate_campaign_from_candidate_name(
                one_candidate_from_maplight_table.display_name)

            if not results['success']:
                logger.warn(
                    u"Candidate NOT found by display_name: {name}".format(
                        name=one_candidate_from_maplight_table.display_name))
                results = candidate_campaign_manager.retrieve_candidate_campaign_from_candidate_name(
                    one_candidate_from_maplight_table.original_name)

                if not results['success']:
                    logger.warn(
                        u"Candidate NOT found by original_name: {name}".format(
                            name=one_candidate_from_maplight_table.
                            original_name))

                    one_mapping_google_civic_name = ''
                    for one_mapping_found in politician_name_mapping_list:
                        if positive_value_exists(one_mapping_found['maplight_display_name']) \
                                and one_mapping_found['maplight_display_name'] == \
                                one_candidate_from_maplight_table.display_name:
                            one_mapping_google_civic_name = one_mapping_found[
                                'google_civic_name']
                            break
                    if positive_value_exists(one_mapping_google_civic_name):
                        results = candidate_campaign_manager.retrieve_candidate_campaign_from_candidate_name(
                            one_mapping_google_civic_name)
                    if not results['success'] or not positive_value_exists(
                            one_mapping_google_civic_name):
                        logger.warn(
                            u"Candidate NOT found by mapping to google_civic name: {name}"
                            .format(name=one_mapping_google_civic_name))

                        continue  # Go to the next candidate

        candidate_campaign_on_stage = results['candidate_campaign']

        # Just in case the logic above let us through to here accidentally without a candidate_name value, don't proceed
        if not positive_value_exists(
                candidate_campaign_on_stage.candidate_name):
            continue

        logger.debug(u"Candidate {name} found".format(
            name=candidate_campaign_on_stage.candidate_name))

        try:
            # Tie the maplight id to our record
            if not found_by_id:
                candidate_campaign_on_stage.id_maplight = one_candidate_from_maplight_table.candidate_id

            # Bring over the photo
            candidate_campaign_on_stage.photo_url_from_maplight = one_candidate_from_maplight_table.photo

            # We can bring over other data as needed, like gender for example
            candidate_campaign_on_stage.save()
        except Exception as e:
            handle_record_not_saved_exception(e, logger=logger)

    messages.add_message(request, messages.INFO,
                         'MapLight data woven into We Vote tables.')

    return HttpResponseRedirect(
        reverse('import_export:import_export_index', args=()))
コード例 #30
0
ファイル: views_admin.py プロジェクト: nf071590/WeVoteServer
def quick_info_edit_process_view(request):
    """
    Process the new or edit quick_info forms
    :param request:
    :return:
    """
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

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

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

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

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

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

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

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

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

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

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

    last_editor_we_vote_id = ""  # TODO We need to calculate this

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

    return HttpResponseRedirect(reverse('quick_info:quick_info_list', args=()))
コード例 #31
0
ファイル: views_admin.py プロジェクト: trinile/WeVoteServer
def organization_position_new_view(request, organization_id):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    authority_results = retrieve_voter_authority(request)
    if not voter_has_authority(request, authority_required, authority_results):
        return redirect_to_sign_in_page(request, authority_required)

    google_civic_election_id = request.GET.get('google_civic_election_id', 0)
    candidate_we_vote_id = request.GET.get('candidate_we_vote_id', False)

    # Take in some incoming values
    candidate_not_found = request.GET.get('candidate_not_found', False)
    stance = request.GET.get('stance', SUPPORT)  # Set a default if stance comes in empty
    statement_text = request.GET.get('statement_text', '')  # Set a default if stance comes in empty
    more_info_url = request.GET.get('more_info_url', '')

    # We pass candidate_we_vote_id to this page to pre-populate the form
    candidate_campaign_id = 0
    if positive_value_exists(candidate_we_vote_id):
        candidate_campaign_manager = CandidateCampaignManager()
        results = candidate_campaign_manager.retrieve_candidate_campaign_from_we_vote_id(candidate_we_vote_id)
        if results['candidate_campaign_found']:
            candidate_campaign = results['candidate_campaign']
            candidate_campaign_id = candidate_campaign.id

    messages_on_stage = get_messages(request)
    organization_id = convert_to_int(organization_id)
    all_is_well = True
    organization_on_stage_found = False
    organization_on_stage = Organization()
    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 = CandidateCampaignListManager()
    candidate_campaigns_for_this_election_list = []
    if positive_value_exists(google_civic_election_id):
        results = candidate_campaign_list.retrieve_all_candidates_for_upcoming_election(google_civic_election_id, True)
        if results['candidate_list_found']:
            candidate_campaigns_for_this_election_list = results['candidate_list_objects']
    else:
        candidate_campaigns_for_this_election_list \
            = candidate_campaign_list.retrieve_candidate_campaigns_from_all_elections_list()

    try:
        organization_position_list = PositionEntered.objects.order_by('stance')
        organization_position_list = organization_position_list.filter(organization_id=organization_id)
        if positive_value_exists(google_civic_election_id):
            organization_position_list = organization_position_list.filter(
                google_civic_election_id=google_civic_election_id)
        organization_position_list = organization_position_list.order_by(
            'google_civic_election_id', '-vote_smart_time_span')
        if len(organization_position_list):
            organization_position_list_found = True
    except Exception as e:
        organization_position_list = []

    if all_is_well:
        election_list = Election.objects.order_by('-election_day_text')
        template_values = {
            'candidate_campaigns_for_this_election_list':   candidate_campaigns_for_this_election_list,
            'candidate_campaign_id':                        candidate_campaign_id,
            'messages_on_stage':                            messages_on_stage,
            'organization':                                 organization_on_stage,
            'organization_position_candidate_campaign_id':  0,
            'possible_stances_list':                        ORGANIZATION_STANCE_CHOICES,
            'stance_selected':                              stance,
            'election_list':                                election_list,
            'google_civic_election_id':                     google_civic_election_id,
            'organization_position_list':                   organization_position_list,
            'voter_authority':                              authority_results,
            # Incoming values from error state
            'candidate_not_found':                          candidate_not_found,
            'stance':                                       stance,
            'statement_text':                               statement_text,
            'more_info_url':                                more_info_url,
        }
    return render(request, 'organization/organization_position_edit.html', template_values)
コード例 #32
0
def quick_info_import_from_sample_file(request=None):  # , load_from_uri=False  # TODO to be converted
    """
    Get the json data, and either create new entries or update existing
    :return:
    """
    # if load_from_uri:
    #     # Request json file from We Vote servers
    #     messages.add_message(request, messages.INFO, "Loading quick_info from We Vote Master servers")
    #     request = requests.get(QUICK_INFO_URL, params={
    #         "key": WE_VOTE_API_KEY,  # This comes from an environment variable
    #     })
    #     structured_json = json.loads(request.text)
    # else:
    # Load saved json from local file
    with open("quick_info/import_data/quick_info_sample.json") as json_data:
        structured_json = json.load(json_data)

    quick_info_saved = 0
    quick_info_updated = 0
    quick_info_not_processed = 0
    for one_quick_info in structured_json:
        # Make sure we have the minimum required variables
        if not positive_value_exists(one_quick_info["we_vote_id"]) \
                or not positive_value_exists(one_quick_info["organization_we_vote_id"])\
                or not positive_value_exists(one_quick_info["candidate_campaign_we_vote_id"]):
            quick_info_not_processed += 1
            continue

        # Check to see if this quick_info is already being used anywhere
        quick_info_found = False
        try:
            if len(one_quick_info["we_vote_id"]) > 0:
                quick_info_query = QuickInfo.objects.filter(we_vote_id=one_quick_info["we_vote_id"])
                if len(quick_info_query):
                    quick_info = quick_info_query[0]
                    quick_info_found = True
        except QuickInfo.DoesNotExist as e:
            handle_record_not_found_exception(e, logger=logger)
            pass
        except Exception as e:
            handle_record_not_found_exception(e, logger=logger)

        # We need to look up the local organization_id based on the newly saved we_vote_id
        organization_manager = OrganizationManager()
        organization_id = organization_manager.fetch_organization_id(one_quick_info["organization_we_vote_id"])

        # We need to look up the local candidate_campaign_id
        candidate_campaign_manager = CandidateCampaignManager()
        candidate_campaign_id = candidate_campaign_manager.fetch_candidate_campaign_id_from_we_vote_id(
            one_quick_info["candidate_campaign_we_vote_id"])

        # Find the google_civic_candidate_name so we have a backup way to link quick_info if the we_vote_id is lost
        google_civic_candidate_name = one_quick_info["google_civic_candidate_name"] if \
            "google_civic_candidate_name" in one_quick_info else ''
        if not positive_value_exists(google_civic_candidate_name):
            google_civic_candidate_name = candidate_campaign_manager.fetch_google_civic_candidate_name_from_we_vote_id(
                one_quick_info["candidate_campaign_we_vote_id"])

        # TODO We need to look up contest_measure_id
        contest_measure_id = 0

        try:
            if quick_info_found:
                # Update
                quick_info.we_vote_id = one_quick_info["we_vote_id"]
                quick_info.organization_id = organization_id
                quick_info.organization_we_vote_id = one_quick_info["organization_we_vote_id"]
                quick_info.candidate_campaign_id = candidate_campaign_id
                quick_info.candidate_campaign_we_vote_id = one_quick_info["candidate_campaign_we_vote_id"]
                quick_info.google_civic_candidate_name = google_civic_candidate_name
                quick_info.contest_measure_id = contest_measure_id
                quick_info.date_entered = one_quick_info["date_entered"]
                quick_info.google_civic_election_id = one_quick_info["google_civic_election_id"]
                quick_info.stance = one_quick_info["stance"]
                quick_info.more_info_url = one_quick_info["more_info_url"]
                quick_info.statement_text = one_quick_info["statement_text"]
                quick_info.statement_html = one_quick_info["statement_html"]
                quick_info.save()
                quick_info_updated += 1
                # messages.add_message(request, messages.INFO, u"QuickInfo updated: {we_vote_id}".format(
                #     we_vote_id=one_quick_info["we_vote_id"]))
            else:
                # Create new
                quick_info = QuickInfo(
                    we_vote_id=one_quick_info["we_vote_id"],
                    organization_id=organization_id,
                    organization_we_vote_id=one_quick_info["organization_we_vote_id"],
                    candidate_campaign_id=candidate_campaign_id,
                    candidate_campaign_we_vote_id=one_quick_info["candidate_campaign_we_vote_id"],
                    google_civic_candidate_name=google_civic_candidate_name,
                    contest_measure_id=contest_measure_id,
                    date_entered=one_quick_info["date_entered"],
                    google_civic_election_id=one_quick_info["google_civic_election_id"],
                    stance=one_quick_info["stance"],
                    more_info_url=one_quick_info["more_info_url"],
                    statement_text=one_quick_info["statement_text"],
                    statement_html=one_quick_info["statement_html"],
                )
                quick_info.save()
                quick_info_saved += 1
                # messages.add_message(request, messages.INFO, u"New quick_info imported: {we_vote_id}".format(
                #     we_vote_id=one_quick_info["we_vote_id"]))
        except Exception as e:
            handle_record_not_saved_exception(e, logger=logger)
            if request is not None:
                messages.add_message(request, messages.ERROR,
                                     u"Could not save/update quick_info, "
                                     u"quick_info_found: {quick_info_found}, "
                                     u"we_vote_id: {we_vote_id}, "
                                     u"organization_we_vote_id: {organization_we_vote_id}, "
                                     u"candidate_campaign_we_vote_id: {candidate_campaign_we_vote_id}".format(
                                         quick_info_found=quick_info_found,
                                         we_vote_id=one_quick_info["we_vote_id"],
                                         organization_we_vote_id=one_quick_info["organization_we_vote_id"],
                                         candidate_campaign_we_vote_id=one_quick_info["candidate_campaign_we_vote_id"],
                                     ))
            quick_info_not_processed += 1

    quick_info_results = {
        'saved': quick_info_saved,
        'updated': quick_info_updated,
        'not_processed': quick_info_not_processed,
    }
    return quick_info_results
コード例 #33
0
def positions_count_for_candidate_campaign(
        voter_id,
        candidate_id,
        candidate_we_vote_id,
        stance_we_are_looking_for,
        show_positions_this_voter_follows=True):
    """
    We want to return a JSON file with the number of orgs, friends and public figures the voter follows who support
    this particular candidate's campaign
    """
    # This implementation is built to make limited database calls. We do as many calculations as we can here in the
    #  application layer

    position_list_manager = PositionListManager()
    all_positions_list_for_candidate_campaign = \
        position_list_manager.retrieve_all_positions_for_candidate_campaign(
            candidate_id, candidate_we_vote_id, stance_we_are_looking_for)

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

    # Since we can take in either candidate_id or candidate_we_vote_id, we need to retrieve the candidate object
    # so we make sure we have both of these values to return
    if positive_value_exists(candidate_id):
        candidate_campaign_manager = CandidateCampaignManager()
        results = candidate_campaign_manager.retrieve_candidate_campaign_from_id(
            candidate_id)
        if results['candidate_campaign_found']:
            candidate_campaign = results['candidate_campaign']
            candidate_we_vote_id = candidate_campaign.we_vote_id
    elif positive_value_exists(candidate_we_vote_id):
        candidate_campaign_manager = CandidateCampaignManager()
        results = candidate_campaign_manager.retrieve_candidate_campaign_from_we_vote_id(
            candidate_we_vote_id)
        if results['candidate_campaign_found']:
            candidate_campaign = results['candidate_campaign']
            candidate_id = candidate_campaign.id

    if show_positions_this_voter_follows:
        positions_followed = position_list_manager.calculate_positions_followed_by_voter(
            voter_id, all_positions_list_for_candidate_campaign,
            organizations_followed_by_voter)
        positions_followed_count = len(positions_followed)
        json_data = {
            'status': 'SUCCESSFUL_RETRIEVE_OF_POSITIONS_FOLLOWED_RE_CANDIDATE',
            'success': True,
            'count': positions_followed_count,
            'ballot_item_id': convert_to_int(candidate_id),
            'ballot_item_we_vote_id': candidate_we_vote_id,
            'kind_of_ballot_item': CANDIDATE,
        }
        results = {
            'json_data': json_data,
        }
        return results
    else:
        positions_not_followed = position_list_manager.calculate_positions_not_followed_by_voter(
            all_positions_list_for_candidate_campaign,
            organizations_followed_by_voter)
        positions_not_followed_count = len(positions_not_followed)
        json_data = {
            'status': 'SUCCESSFUL_RETRIEVE_OF_POSITIONS_NOT_FOLLOWED_CC',
            'success': True,
            'count': positions_not_followed_count,
            'ballot_item_id': convert_to_int(candidate_id),
            'ballot_item_we_vote_id': candidate_we_vote_id,
            'kind_of_ballot_item': CANDIDATE,
        }
        results = {
            'json_data': json_data,
        }
        return results
コード例 #34
0
def quick_info_import_from_sample_file(
        request=None):  # , load_from_uri=False  # TODO to be converted
    """
    Get the json data, and either create new entries or update existing
    :return:
    """
    # if load_from_uri:
    #     # Request json file from We Vote servers
    #     messages.add_message(request, messages.INFO, "Loading quick_info from We Vote Master servers")
    #     request = requests.get(QUICK_INFO_URL, params={
    #         "key": WE_VOTE_API_KEY,  # This comes from an environment variable
    #     })
    #     structured_json = json.loads(request.text)
    # else:
    # Load saved json from local file
    with open("quick_info/import_data/quick_info_sample.json") as json_data:
        structured_json = json.load(json_data)

    quick_info_saved = 0
    quick_info_updated = 0
    quick_info_not_processed = 0
    for one_quick_info in structured_json:
        # Make sure we have the minimum required variables
        if not positive_value_exists(one_quick_info["we_vote_id"]) \
                or not positive_value_exists(one_quick_info["organization_we_vote_id"])\
                or not positive_value_exists(one_quick_info["candidate_campaign_we_vote_id"]):
            quick_info_not_processed += 1
            continue

        # Check to see if this quick_info is already being used anywhere
        quick_info_found = False
        try:
            if len(one_quick_info["we_vote_id"]) > 0:
                quick_info_query = QuickInfo.objects.filter(
                    we_vote_id=one_quick_info["we_vote_id"])
                if len(quick_info_query):
                    quick_info = quick_info_query[0]
                    quick_info_found = True
        except QuickInfo.DoesNotExist as e:
            handle_record_not_found_exception(e, logger=logger)
            pass
        except Exception as e:
            handle_record_not_found_exception(e, logger=logger)

        # We need to look up the local organization_id based on the newly saved we_vote_id
        organization_manager = OrganizationManager()
        organization_id = organization_manager.fetch_organization_id(
            one_quick_info["organization_we_vote_id"])

        # We need to look up the local candidate_campaign_id
        candidate_campaign_manager = CandidateCampaignManager()
        candidate_campaign_id = candidate_campaign_manager.fetch_candidate_campaign_id_from_we_vote_id(
            one_quick_info["candidate_campaign_we_vote_id"])

        # Find the google_civic_candidate_name so we have a backup way to link quick_info if the we_vote_id is lost
        google_civic_candidate_name = one_quick_info["google_civic_candidate_name"] if \
            "google_civic_candidate_name" in one_quick_info else ''
        if not positive_value_exists(google_civic_candidate_name):
            google_civic_candidate_name = candidate_campaign_manager.fetch_google_civic_candidate_name_from_we_vote_id(
                one_quick_info["candidate_campaign_we_vote_id"])

        # TODO We need to look up contest_measure_id
        contest_measure_id = 0

        try:
            if quick_info_found:
                # Update
                quick_info.we_vote_id = one_quick_info["we_vote_id"]
                quick_info.organization_id = organization_id
                quick_info.organization_we_vote_id = one_quick_info[
                    "organization_we_vote_id"]
                quick_info.candidate_campaign_id = candidate_campaign_id
                quick_info.candidate_campaign_we_vote_id = one_quick_info[
                    "candidate_campaign_we_vote_id"]
                quick_info.google_civic_candidate_name = google_civic_candidate_name
                quick_info.contest_measure_id = contest_measure_id
                quick_info.date_entered = one_quick_info["date_entered"]
                quick_info.google_civic_election_id = one_quick_info[
                    "google_civic_election_id"]
                quick_info.stance = one_quick_info["stance"]
                quick_info.more_info_url = one_quick_info["more_info_url"]
                quick_info.statement_text = one_quick_info["statement_text"]
                quick_info.statement_html = one_quick_info["statement_html"]
                quick_info.save()
                quick_info_updated += 1
                # messages.add_message(request, messages.INFO, u"QuickInfo updated: {we_vote_id}".format(
                #     we_vote_id=one_quick_info["we_vote_id"]))
            else:
                # Create new
                quick_info = QuickInfo(
                    we_vote_id=one_quick_info["we_vote_id"],
                    organization_id=organization_id,
                    organization_we_vote_id=one_quick_info[
                        "organization_we_vote_id"],
                    candidate_campaign_id=candidate_campaign_id,
                    candidate_campaign_we_vote_id=one_quick_info[
                        "candidate_campaign_we_vote_id"],
                    google_civic_candidate_name=google_civic_candidate_name,
                    contest_measure_id=contest_measure_id,
                    date_entered=one_quick_info["date_entered"],
                    google_civic_election_id=one_quick_info[
                        "google_civic_election_id"],
                    stance=one_quick_info["stance"],
                    more_info_url=one_quick_info["more_info_url"],
                    statement_text=one_quick_info["statement_text"],
                    statement_html=one_quick_info["statement_html"],
                )
                quick_info.save()
                quick_info_saved += 1
                # messages.add_message(request, messages.INFO, u"New quick_info imported: {we_vote_id}".format(
                #     we_vote_id=one_quick_info["we_vote_id"]))
        except Exception as e:
            handle_record_not_saved_exception(e, logger=logger)
            if request is not None:
                messages.add_message(
                    request, messages.ERROR,
                    u"Could not save/update quick_info, "
                    u"quick_info_found: {quick_info_found}, "
                    u"we_vote_id: {we_vote_id}, "
                    u"organization_we_vote_id: {organization_we_vote_id}, "
                    u"candidate_campaign_we_vote_id: {candidate_campaign_we_vote_id}"
                    .format(
                        quick_info_found=quick_info_found,
                        we_vote_id=one_quick_info["we_vote_id"],
                        organization_we_vote_id=one_quick_info[
                            "organization_we_vote_id"],
                        candidate_campaign_we_vote_id=one_quick_info[
                            "candidate_campaign_we_vote_id"],
                    ))
            quick_info_not_processed += 1

    quick_info_results = {
        'saved': quick_info_saved,
        'updated': quick_info_updated,
        'not_processed': quick_info_not_processed,
    }
    return quick_info_results
コード例 #35
0
ファイル: controllers.py プロジェクト: nf071590/WeVoteServer
def transfer_vote_smart_ratings_to_positions_for_candidate(candidate_campaign_id):
    candidate_manager = CandidateCampaignManager()
    candidate_results = candidate_manager.retrieve_candidate_campaign_from_id(candidate_campaign_id)

    if candidate_results['candidate_campaign_found']:
        # Working with Vote Smart data
        candidate_campaign = candidate_results['candidate_campaign']
        if not positive_value_exists(candidate_campaign.vote_smart_id):
            status = "VOTE_SMART_ID_HAS_NOT_BEEN_RETRIEVED_YET_FOR_THIS_CANDIDATE: " \
                     "{candidate_campaign_id}".format(candidate_campaign_id=candidate_campaign_id)
            success = False
            results = {
                'status':   status,
                'success':  success,
            }
            return results
        else:
            try:
                rating_list_query = VoteSmartRatingOneCandidate.objects.order_by('-timeSpan')  # Desc order
                rating_list = rating_list_query.filter(candidateId=candidate_campaign.vote_smart_id)
            except Exception as error_instance:
                # Catch the error message coming back from Vote Smart and pass it in the status
                error_message = error_instance.args
                status = "EXCEPTION_RAISED: {error_message}".format(error_message=error_message)
                success = False
                results = {
                    'status':   status,
                    'success':  success,
                }
                return results

        ratings_status = ""
        position_manager = PositionEnteredManager()
        special_interest_group_manager = VoteSmartSpecialInterestGroupManager()
        for one_candidate_rating in rating_list:
            # Make sure we have all of the required variables
            if not one_candidate_rating.sigId:
                ratings_status += "MISSING_SPECIAL_INTEREST_GROUP_ID-{ratingId} * " \
                                  "".format(ratingId=one_candidate_rating.ratingId)
                continue
            # Make sure an organization exists and is updated with Vote Smart info
            update_results = special_interest_group_manager.update_or_create_we_vote_organization(
                one_candidate_rating.sigId)
            if not update_results['organization_found']:
                # TRY AGAIN: Reach out to Vote Smart and try to retrieve this special interest group by sigId
                one_group_results = retrieve_vote_smart_special_interest_group_into_local_db(one_candidate_rating.sigId)

                if one_group_results['success']:
                    update_results = special_interest_group_manager.update_or_create_we_vote_organization(
                        one_candidate_rating.sigId)

            if not update_results['organization_found']:
                ratings_status += "COULD_NOT_FIND_OR_SAVE_NEW_SIG-{sigId}-{status} * " \
                                  "".format(sigId=one_candidate_rating.sigId,
                                            status=update_results['status'])
                continue
            else:
                we_vote_organization = update_results['organization']

            # Check to see if a position already exists
            # TODO DALE Note: we need to consider searching with a time span variable
            # (in addition to just org and candidate identifiers) since I believe
            # Google Civic gives a person a new candidate campaign ID each election,
            # while Vote Smart uses the same candidateId from year to year
            organization_position_results = position_manager.retrieve_organization_candidate_campaign_position(
                we_vote_organization.id, candidate_campaign_id)

            if positive_value_exists(organization_position_results['position_found']):
                # For now, we only want to create positions that don't exist
                continue
            else:
                position_results = position_manager.update_or_create_position(
                    position_id=0,
                    position_we_vote_id=False,
                    organization_we_vote_id=we_vote_organization.we_vote_id,
                    public_figure_we_vote_id=False,
                    voter_we_vote_id=False,
                    google_civic_election_id=False,
                    ballot_item_display_name=candidate_campaign.candidate_name,
                    office_we_vote_id=False,
                    candidate_we_vote_id=candidate_campaign.we_vote_id,
                    measure_we_vote_id=False,
                    stance=PERCENT_RATING,
                    statement_text=one_candidate_rating.ratingText,
                    statement_html=False,
                    more_info_url=False,
                    vote_smart_time_span=one_candidate_rating.timeSpan,
                    vote_smart_rating_id=one_candidate_rating.ratingId,
                    vote_smart_rating=one_candidate_rating.rating,
                    vote_smart_rating_name=one_candidate_rating.ratingName,
                )

                if not positive_value_exists(position_results['success']):
                    ratings_status += "COULD_NOT_CREATE_POSITION-{sigId}-{status} * " \
                                      "".format(sigId=one_candidate_rating.sigId,
                                                status=position_results['status'])

    success = True
    status = "TRANSFER_PROCESS_COMPLETED: " + ratings_status

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

    return results
コード例 #36
0
ファイル: controllers.py プロジェクト: eternal44/WeVoteServer
def process_candidates_from_structured_json(
        candidates_structured_json, google_civic_election_id, ocd_division_id, state_code, contest_office_id,
        contest_office_we_vote_id):
    """
    "candidates": [
        {
         "name": "Nancy Pelosi",
         "party": "Democratic"
        },
        {
         "name": "John Dennis",
         "party": "Republican",
         "candidateUrl": "http://www.johndennisforcongress.com/",
         "channels": [
          {
           "type": "Facebook",
           "id": "https://www.facebook.com/johndennis2010"
          },
          {
           "type": "Twitter",
           "id": "https://twitter.com/johndennis2012"
    """
    results = {}
    for one_candidate in candidates_structured_json:
        candidate_name = one_candidate['name'] if 'name' in one_candidate else ''
        # For some reason Google Civic API violates the JSON standard and uses a / in front of '
        candidate_name = candidate_name.replace('/', "'")
        # We want to save the name exactly as it comes from the Google Civic API
        google_civic_candidate_name = one_candidate['name'] if 'name' in one_candidate else ''
        party = one_candidate['party'] if 'party' in one_candidate else ''
        order_on_ballot = one_candidate['orderOnBallot'] if 'orderOnBallot' in one_candidate else 0
        candidate_url = one_candidate['candidateUrl'] if 'candidateUrl' in one_candidate else ''
        photo_url = one_candidate['photoUrl'] if 'photoUrl' in one_candidate else ''
        email = one_candidate['email'] if 'email' in one_candidate else ''
        phone = one_candidate['phone'] if 'phone' in one_candidate else ''

        # Make sure we start with empty channel values
        facebook_url = ''
        twitter_url = ''
        google_plus_url = ''
        youtube_url = ''
        if 'channels' in one_candidate:
            channels = one_candidate['channels']
            for one_channel in channels:
                if 'type' in one_channel:
                    if one_channel['type'] == 'Facebook':
                        facebook_url = one_channel['id'] if 'id' in one_channel else ''
                    if one_channel['type'] == 'Twitter':
                        twitter_url = one_channel['id'] if 'id' in one_channel else ''
                    if one_channel['type'] == 'GooglePlus':
                        google_plus_url = one_channel['id'] if 'id' in one_channel else ''
                    if one_channel['type'] == 'YouTube':
                        youtube_url = one_channel['id'] if 'id' in one_channel else ''

        # DALE 2016-02-20 It would be helpful to call a service here that disambiguated the candidate
        # ...and linked to a politician
        # ...and looked to see if there were any other candidate_campaign entries for this election (in case the
        #   Google Civic contest_office name changed so we generated another contest)

        we_vote_id = ''
        # Make sure we have the minimum variables required to uniquely identify a candidate
        if google_civic_election_id and contest_office_id and candidate_name:
            # NOT using " and ocd_division_id"

            # Make sure there isn't an alternate entry for this election and contest_office (under a similar but
            # slightly different name TODO
            # Note: This doesn't deal with duplicate Presidential candidates. These duplicates are caused because
            # candidates are tied to a particular google_civic_election_id, so there is a different candidate entry
            # for each Presidential candidate for each state.

            updated_candidate_campaign_values = {
                # Values we search against
                'google_civic_election_id': google_civic_election_id,
                'ocd_division_id': ocd_division_id,
                # Note: When we decide to start updating candidate_name elsewhere within We Vote, we should stop
                #  updating candidate_name via subsequent Google Civic imports
                'candidate_name': candidate_name,
                # The rest of the values
                'state_code': state_code,  # Not required due to federal candidates
                'party': party,
                'candidate_email': email,
                'candidate_phone': phone,
                'order_on_ballot': order_on_ballot,
                'candidate_url': candidate_url,
                'photo_url': photo_url,
                'facebook_url': facebook_url,
                'twitter_url': twitter_url,
                'google_plus_url': google_plus_url,
                'youtube_url': youtube_url,
                'google_civic_candidate_name': google_civic_candidate_name,
                # 2016-02-20 Google Civic sometimes changes the name of contests, which can create a new contest
                #  so we may need to update the candidate to a new contest_office_id
                'contest_office_id': contest_office_id,
                'contest_office_we_vote_id': contest_office_we_vote_id,
            }
            candidate_campaign_manager = CandidateCampaignManager()
            results = candidate_campaign_manager.update_or_create_candidate_campaign(
                we_vote_id, google_civic_election_id, ocd_division_id, contest_office_id, contest_office_we_vote_id,
                google_civic_candidate_name, updated_candidate_campaign_values)

    return results
コード例 #37
0
def transfer_maplight_data_to_we_vote_tables(request):
    # TODO We need to perhaps set up a table for these mappings that volunteers can add to?
    #  We need a plan for how volunteers can help us add to these mappings
    # One possibility -- ask volunteers to update this Google Sheet, then write a csv importer:
    #  https://docs.google.com/spreadsheets/d/1havD7GCxmBhi-zLLMdOpSJlU_DtBjvb5IJNiXgno9Bk/edit#gid=0
    politician_name_mapping_list = []
    one_mapping = {
        "google_civic_name": "Betty T. Yee",
        "maplight_display_name": "Betty Yee",
        "maplight_original_name": "Betty T Yee",
    }
    politician_name_mapping_list.append(one_mapping)
    one_mapping = {
        "google_civic_name": "Edmund G. \"Jerry\" Brown",
        "maplight_display_name": "Jerry Brown",
        "maplight_original_name": "",
    }
    politician_name_mapping_list.append(one_mapping)

    candidate_campaign_manager = CandidateCampaignManager()

    maplight_candidates_current_query = MapLightCandidate.objects.all()

    for one_candidate_from_maplight_table in maplight_candidates_current_query:
        found_by_id = False
        # Try to find a matching candidate
        results = candidate_campaign_manager.retrieve_candidate_campaign_from_id_maplight(
            one_candidate_from_maplight_table.candidate_id)

        if not results['success']:
            logger.warn(u"Candidate NOT found by MapLight id: {name}".format(
                name=one_candidate_from_maplight_table.candidate_id
            ))
            results = candidate_campaign_manager.retrieve_candidate_campaign_from_candidate_name(
                one_candidate_from_maplight_table.display_name)

            if not results['success']:
                logger.warn(u"Candidate NOT found by display_name: {name}".format(
                    name=one_candidate_from_maplight_table.display_name
                ))
                results = candidate_campaign_manager.retrieve_candidate_campaign_from_candidate_name(
                    one_candidate_from_maplight_table.original_name)

                if not results['success']:
                    logger.warn(u"Candidate NOT found by original_name: {name}".format(
                        name=one_candidate_from_maplight_table.original_name
                    ))

                    one_mapping_google_civic_name = ''
                    for one_mapping_found in politician_name_mapping_list:
                        if positive_value_exists(one_mapping_found['maplight_display_name']) \
                                and one_mapping_found['maplight_display_name'] == \
                                one_candidate_from_maplight_table.display_name:
                            one_mapping_google_civic_name = one_mapping_found['google_civic_name']
                            break
                    if positive_value_exists(one_mapping_google_civic_name):
                        results = candidate_campaign_manager.retrieve_candidate_campaign_from_candidate_name(
                            one_mapping_google_civic_name)
                    if not results['success'] or not positive_value_exists(one_mapping_google_civic_name):
                        logger.warn(u"Candidate NOT found by mapping to google_civic name: {name}".format(
                            name=one_mapping_google_civic_name
                        ))

                        continue  # Go to the next candidate

        candidate_campaign_on_stage = results['candidate_campaign']

        # Just in case the logic above let us through to here accidentally without a candidate_name value, don't proceed
        if not positive_value_exists(candidate_campaign_on_stage.candidate_name):
            continue

        logger.debug(u"Candidate {name} found".format(
            name=candidate_campaign_on_stage.candidate_name
        ))

        try:
            # Tie the maplight id to our record
            if not found_by_id:
                candidate_campaign_on_stage.id_maplight = one_candidate_from_maplight_table.candidate_id

            # Bring over the photo
            candidate_campaign_on_stage.photo_url_from_maplight = one_candidate_from_maplight_table.photo

            # We can bring over other data as needed, like gender for example
            candidate_campaign_on_stage.save()
        except Exception as e:
            handle_record_not_saved_exception(e, logger=logger)

    messages.add_message(request, messages.INFO, 'MapLight data woven into We Vote tables.')

    return HttpResponseRedirect(reverse('import_export:import_export_index', args=()))
コード例 #38
0
ファイル: controllers.py プロジェクト: sammyds/WeVoteServer
def voter_star_status_retrieve_for_api(voter_device_id,
                                       office_id, office_we_vote_id,
                                       candidate_id, candidate_we_vote_id,
                                       measure_id, measure_we_vote_id):
    # Get voter_id from the voter_device_id so we can know who is doing the starring
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status':                   'VALID_VOTER_DEVICE_ID_MISSING',
            'success':                  False,
            'voter_device_id':          voter_device_id,
            'is_starred':               False,
            'office_id':                convert_to_int(office_id),
            'candidate_id':             convert_to_int(candidate_id),
            'measure_id':               convert_to_int(measure_id),
            'ballot_item_id':           0,
            'ballot_item_we_vote_id':   '',
            'kind_of_ballot_item':      '',
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            'status':                   "VALID_VOTER_ID_MISSING",
            'success':                  False,
            'voter_device_id':          voter_device_id,
            'is_starred':               False,
            'office_id':                convert_to_int(office_id),
            'candidate_id':             convert_to_int(candidate_id),
            'measure_id':               convert_to_int(measure_id),
            'ballot_item_id':           0,
            'ballot_item_we_vote_id':   '',
            'kind_of_ballot_item':      '',
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

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

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

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

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

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

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

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

    json_data = {
        'status':                   status,
        'success':                  success,
        'voter_device_id':          voter_device_id,
        'is_starred':               is_starred,
        'office_id':                convert_to_int(office_id),
        'candidate_id':             convert_to_int(candidate_id),
        'measure_id':               convert_to_int(measure_id),
        'ballot_item_id':           0,
        'ballot_item_we_vote_id':   '',
        'kind_of_ballot_item':      '',
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')