Exemplo n.º 1
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
Exemplo n.º 2
0
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
Exemplo n.º 3
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
Exemplo n.º 4
0
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
Exemplo n.º 5
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
Exemplo n.º 6
0
def position_list_for_ballot_item_for_api(voter_device_id,  # positionListForBallotItem
                                          office_id, office_we_vote_id,
                                          candidate_id, candidate_we_vote_id,
                                          measure_id, measure_we_vote_id,
                                          stance_we_are_looking_for=ANY_STANCE,
                                          show_positions_this_voter_follows=True):
    """
    We want to return a JSON file with the position identifiers from orgs, friends and public figures the voter follows
    This list of information is used to retrieve the detailed information
    """
    position_manager = PositionEnteredManager()
    # Get voter_id from the voter_device_id so we can know who is supporting/opposing
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        position_list = []
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
            'count':            0,
            'kind_of_ballot_item': "UNKNOWN",
            'ballot_item_id':   0,
            'position_list':    position_list,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

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

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

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

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

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

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

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

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

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

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

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

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

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

    json_data = {
        'status':                   status,
        'success':                  success,
        'count':                    positions_count,
        'kind_of_ballot_item':      kind_of_ballot_item,
        'ballot_item_id':           ballot_item_id,
        'ballot_item_we_vote_id':   ballot_item_we_vote_id,
        'position_list':            position_list,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemplo n.º 7
0
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