Exemplo n.º 1
0
def voter_position_like_off_save_for_api(voter_device_id, position_like_id, position_entered_id):
    # Get voter_id from the voter_device_id so we can know who is doing the liking
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

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

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

    json_data = {
        'status': status,
        'success': success,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemplo n.º 2
0
def voter_star_on_save_for_api(voter_device_id, office_id, candidate_id, measure_id):
    # Get voter_id from the voter_device_id so we can know who is doing the starring
    results = is_voter_device_id_valid(voter_device_id)
    if not results["success"]:
        json_data = {"status": "VALID_VOTER_DEVICE_ID_MISSING", "success": False}
        return HttpResponse(json.dumps(json_data), content_type="application/json")

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

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

    json_data = {"status": status, "success": success}
    return HttpResponse(json.dumps(json_data), content_type="application/json")
Exemplo n.º 3
0
def voter_authenticate_manually_process_view(request):
    voter_api_device_id = get_voter_api_device_id(
        request)  # We look in the cookies for voter_api_device_id
    voter_id = fetch_voter_id_from_voter_device_link(voter_api_device_id)

    voter_id = convert_to_int(voter_id)
    voter_signed_in = False
    try:
        voter_on_stage = Voter.objects.get(id=voter_id)
        # If the account associated with this voter_api_device_id is an admin, complete Django authentication
        if voter_on_stage.is_admin:
            voter_on_stage.backend = 'django.contrib.auth.backends.ModelBackend'
            login(request, voter_on_stage)
            messages.add_message(request, messages.INFO, 'Voter logged in.')
            voter_signed_in = True
        else:
            messages.add_message(request, messages.INFO,
                                 'This account does not have Admin access.')
    except Voter.MultipleObjectsReturned as e:
        handle_record_found_more_than_one_exception(e, logger=logger)
        messages.add_message(
            request, messages.ERROR,
            'More than one voter found. Voter not logged in.')
    except Voter.DoesNotExist:
        # This is fine, we will display an error
        messages.add_message(request, messages.ERROR,
                             'Voter not found. Voter not logged in.')

    if voter_signed_in:
        return HttpResponseRedirect(reverse('admin_tools:admin_home', args=()))
    else:
        return HttpResponseRedirect(
            reverse('voter:authenticate_manually', args=()))
Exemplo n.º 4
0
def voter_authenticate_manually_view(request):
    messages_on_stage = get_messages(request)

    voter_api_device_id = get_voter_api_device_id(
        request)  # We look in the cookies for voter_api_device_id
    store_new_voter_api_device_id_in_cookie = False
    if not positive_value_exists(voter_api_device_id):
        # Create a voter_device_id and voter in the database if one doesn't exist yet
        results = voter_setup(request)
        voter_api_device_id = results['voter_api_device_id']
        store_new_voter_api_device_id_in_cookie = results[
            'store_new_voter_api_device_id_in_cookie']

    voter_id = fetch_voter_id_from_voter_device_link(voter_api_device_id)
    voter_id = convert_to_int(voter_id)
    voter_on_stage_found = False
    voter_on_stage = Voter()
    try:
        voter_on_stage = Voter.objects.get(id=voter_id)
        voter_on_stage_found = True
    except Voter.MultipleObjectsReturned as e:
        handle_record_found_more_than_one_exception(e, logger=logger)
    except Voter.DoesNotExist:
        # This is fine, we will display an error
        pass

    if voter_on_stage_found:
        set_this_voter_as_admin = "UPDATE voter_voter SET is_admin=True WHERE id={voter_id};".format(
            voter_id=voter_id)
        unset_this_voter_as_admin = "UPDATE voter_voter SET is_admin=False WHERE id={voter_id};".format(
            voter_id=voter_id)

        set_as_verified_volunteer = "UPDATE voter_voter SET is_verified_volunteer=True WHERE id={voter_id};" \
                                    "".format(voter_id=voter_id)
        unset_as_verified_volunteer = "UPDATE voter_voter SET is_verified_volunteer=False WHERE id={voter_id};" \
                                      "".format(voter_id=voter_id)
        template_values = {
            'messages_on_stage': messages_on_stage,
            'voter': voter_on_stage,
            'voter_api_device_id': voter_api_device_id,
            'is_authenticated': request.user.is_authenticated(),
            'set_this_voter_as_admin': set_this_voter_as_admin,
            'unset_this_voter_as_admin': unset_this_voter_as_admin,
            'set_as_verified_volunteer': set_as_verified_volunteer,
            'unset_as_verified_volunteer': unset_as_verified_volunteer,
        }
    else:
        template_values = {
            'messages_on_stage': messages_on_stage,
        }
    response = render(request, 'voter/voter_authenticate_manually.html',
                      template_values)

    # We want to store the voter_api_device_id cookie if it is new
    # if positive_value_exists(voter_api_device_id) and positive_value_exists(store_new_voter_api_device_id_in_cookie):
    # DALE 2016-02-15 Always set if we have a voter_api_device_id
    if positive_value_exists(store_new_voter_api_device_id_in_cookie):
        set_voter_api_device_id(request, response, voter_api_device_id)

    return response
Exemplo n.º 5
0
def voter_stop_asking_candidate_campaign_view(request, candidate_campaign_id):
    print "voter_stop_asking_candidate_campaign_view {candidate_campaign_id}".format(
        candidate_campaign_id=candidate_campaign_id)
    voter_device_id = get_voter_device_id(request)
    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)

    return JsonResponse({0: "not working yet - needs to be built"})
Exemplo n.º 6
0
def voter_guide_possibility_retrieve_for_api(voter_device_id,
                                             voter_guide_possibility_url):
    results = is_voter_device_id_valid(voter_device_id)
    voter_guide_possibility_url = voter_guide_possibility_url  # TODO Use scrapy here
    if not results['success']:
        return HttpResponse(json.dumps(results['json_data']),
                            content_type='application/json')

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

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

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

    json_data = {
        'voter_device_id': voter_device_id,
        'voter_guide_possibility_url': results['voter_guide_possibility_url'],
        'voter_guide_possibility_id': results['voter_guide_possibility_id'],
        'organization_we_vote_id': results['organization_we_vote_id'],
        'public_figure_we_vote_id': results['public_figure_we_vote_id'],
        'owner_we_vote_id': results['owner_we_vote_id'],
        'status': results['status'],
        'success': results['success'],
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_position_like_off_save_for_api(voter_device_id, position_like_id, position_entered_id):
    # Get voter_id from the voter_device_id so we can know who is doing the liking
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

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

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

    json_data = {
        'status': status,
        'success': success,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemplo n.º 8
0
def voter_stop_asking_candidate_campaign_view(request, candidate_campaign_id):
    print "voter_stop_asking_candidate_campaign_view {candidate_campaign_id}".format(
        candidate_campaign_id=candidate_campaign_id)
    voter_device_id = get_voter_device_id(request)
    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)

    return JsonResponse({0: "not working yet - needs to be built"})
Exemplo n.º 9
0
def voter_authenticate_manually_process_view(request):
    voter_api_device_id = get_voter_api_device_id(request)  # We look in the cookies for voter_api_device_id
    voter_id = fetch_voter_id_from_voter_device_link(voter_api_device_id)

    voter_id = convert_to_int(voter_id)
    voter_signed_in = False
    try:
        voter_on_stage = Voter.objects.get(id=voter_id)
        # If the account associated with this voter_api_device_id is an admin, complete Django authentication
        if voter_on_stage.is_admin:
            voter_on_stage.backend = 'django.contrib.auth.backends.ModelBackend'
            login(request, voter_on_stage)
            messages.add_message(request, messages.INFO, 'Voter logged in.')
            voter_signed_in = True
        else:
            messages.add_message(request, messages.INFO, 'This account does not have Admin access.')
    except Voter.MultipleObjectsReturned as e:
        handle_record_found_more_than_one_exception(e, logger=logger)
        messages.add_message(request, messages.ERROR, 'More than one voter found. Voter not logged in.')
    except Voter.DoesNotExist:
        # This is fine, we will display an error
        messages.add_message(request, messages.ERROR, 'Voter not found. Voter not logged in.')

    if voter_signed_in:
        return HttpResponseRedirect(reverse('admin_tools:admin_home', args=()))
    else:
        return HttpResponseRedirect(reverse('voter:authenticate_manually', args=()))
Exemplo n.º 10
0
def voter_guide_possibility_retrieve_for_api(voter_device_id, voter_guide_possibility_url):
    results = is_voter_device_id_valid(voter_device_id)
    voter_guide_possibility_url = voter_guide_possibility_url  # TODO Use scrapy here
    if not results['success']:
        return HttpResponse(json.dumps(results['json_data']), content_type='application/json')

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

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

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

    json_data = {
        'voter_device_id':              voter_device_id,
        'voter_guide_possibility_url':  results['voter_guide_possibility_url'],
        'voter_guide_possibility_id':   results['voter_guide_possibility_id'],
        'organization_we_vote_id':      results['organization_we_vote_id'],
        'public_figure_we_vote_id':     results['public_figure_we_vote_id'],
        'owner_we_vote_id':             results['owner_we_vote_id'],
        'status':                       results['status'],
        'success':                      results['success'],
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemplo n.º 11
0
def voter_authenticate_manually_view(request):
    messages_on_stage = get_messages(request)

    voter_api_device_id = get_voter_api_device_id(request)  # We look in the cookies for voter_api_device_id
    store_new_voter_api_device_id_in_cookie = False
    if not positive_value_exists(voter_api_device_id):
        # Create a voter_device_id and voter in the database if one doesn't exist yet
        results = voter_setup(request)
        voter_api_device_id = results['voter_api_device_id']
        store_new_voter_api_device_id_in_cookie = results['store_new_voter_api_device_id_in_cookie']

    voter_id = fetch_voter_id_from_voter_device_link(voter_api_device_id)
    voter_id = convert_to_int(voter_id)
    voter_on_stage_found = False
    voter_on_stage = Voter()
    try:
        voter_on_stage = Voter.objects.get(id=voter_id)
        voter_on_stage_found = True
    except Voter.MultipleObjectsReturned as e:
        handle_record_found_more_than_one_exception(e, logger=logger)
    except Voter.DoesNotExist:
        # This is fine, we will display an error
        pass

    if voter_on_stage_found:
        set_this_voter_as_admin = "UPDATE voter_voter SET is_admin=True WHERE id={voter_id};".format(voter_id=voter_id)
        unset_this_voter_as_admin = "UPDATE voter_voter SET is_admin=False WHERE id={voter_id};".format(
            voter_id=voter_id)

        set_as_verified_volunteer = "UPDATE voter_voter SET is_verified_volunteer=True WHERE id={voter_id};" \
                                    "".format(voter_id=voter_id)
        unset_as_verified_volunteer = "UPDATE voter_voter SET is_verified_volunteer=False WHERE id={voter_id};" \
                                      "".format(voter_id=voter_id)
        template_values = {
            'messages_on_stage':            messages_on_stage,
            'voter':                        voter_on_stage,
            'voter_api_device_id':          voter_api_device_id,
            'is_authenticated':             request.user.is_authenticated(),
            'set_this_voter_as_admin':      set_this_voter_as_admin,
            'unset_this_voter_as_admin':    unset_this_voter_as_admin,
            'set_as_verified_volunteer':    set_as_verified_volunteer,
            'unset_as_verified_volunteer':  unset_as_verified_volunteer,
        }
    else:
        template_values = {
            'messages_on_stage': messages_on_stage,

        }
    response = render(request, 'voter/voter_authenticate_manually.html', template_values)

    # We want to store the voter_api_device_id cookie if it is new
    # if positive_value_exists(voter_api_device_id) and positive_value_exists(store_new_voter_api_device_id_in_cookie):
    # DALE 2016-02-15 Always set if we have a voter_api_device_id
    if positive_value_exists(store_new_voter_api_device_id_in_cookie):
        set_voter_api_device_id(request, response, voter_api_device_id)

    return response
Exemplo n.º 12
0
def voter_create(voter_device_id):
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        return HttpResponse(json.dumps(results['json_data']),
                            content_type='application/json')

    voter_id = 0
    # Make sure a voter record hasn't already been created for this
    existing_voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if existing_voter_id:
        json_data = {
            'status': "VOTER_ALREADY_EXISTS",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    # Create a new voter and return the id
    voter_manager = VoterManager()
    results = voter_manager.create_voter()

    if results['voter_created']:
        voter = results['voter']

        # Now save the voter_device_link
        voter_device_link_manager = VoterDeviceLinkManager()
        results = voter_device_link_manager.save_new_voter_device_link(
            voter_device_id, voter.id)

        if results['voter_device_link_created']:
            voter_device_link = results['voter_device_link']
            voter_id_found = True if voter_device_link.voter_id > 0 else False

            if voter_id_found:
                voter_id = voter_device_link.voter_id

    if voter_id:
        json_data = {
            'status': "VOTER_CREATED",
            'success': False,
            'voter_device_id': voter_device_id,
            'voter_id':
            voter_id,  # We may want to remove this after initial testing
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')
    else:
        json_data = {
            'status': "VOTER_NOT_CREATED",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')
Exemplo n.º 13
0
def voter_stop_asking_candidate_campaign_view(request, candidate_campaign_id):
    logger.debug("voter_stop_asking_candidate_campaign_view {candidate_campaign_id}".format(
        candidate_campaign_id=candidate_campaign_id
    ))
    voter_api_device_id = get_voter_api_device_id(request)
    voter_id = fetch_voter_id_from_voter_device_link(voter_api_device_id)
    logger.debug("voter_stop_asking_candidate_campaign_view NOT BUILT YET, voter_id: {voter_id}".format(
        voter_id=voter_id
    ))

    return JsonResponse({0: "not working yet - needs to be built"})
Exemplo n.º 14
0
def voter_stop_asking_candidate_campaign_view(request, candidate_campaign_id):
    logger.debug(
        "voter_stop_asking_candidate_campaign_view {candidate_campaign_id}".
        format(candidate_campaign_id=candidate_campaign_id))
    voter_api_device_id = get_voter_api_device_id(request)
    voter_id = fetch_voter_id_from_voter_device_link(voter_api_device_id)
    logger.debug(
        "voter_stop_asking_candidate_campaign_view NOT BUILT YET, voter_id: {voter_id}"
        .format(voter_id=voter_id))

    return JsonResponse({0: "not working yet - needs to be built"})
Exemplo n.º 15
0
def voter_stance_for_contest_measure_view(request, contest_measure_id):
    logger.debug("voter_stance_for_contest_measure_view {contest_measure_id}".format(
        contest_measure_id=contest_measure_id
    ))
    voter_api_device_id = get_voter_api_device_id(request)
    voter_id = fetch_voter_id_from_voter_device_link(voter_api_device_id)
    logger.debug("voter_stance_for_contest_measure_view NOT BUILT YET, voter_id: {voter_id}".format(
        voter_id=voter_id
    ))

    return JsonResponse({0: "not working yet - needs to be built"})
Exemplo n.º 16
0
def voter_stance_for_contest_measure_view(request, contest_measure_id):
    logger.debug(
        "voter_stance_for_contest_measure_view {contest_measure_id}".format(
            contest_measure_id=contest_measure_id))
    voter_api_device_id = get_voter_api_device_id(request)
    voter_id = fetch_voter_id_from_voter_device_link(voter_api_device_id)
    logger.debug(
        "voter_stance_for_contest_measure_view NOT BUILT YET, voter_id: {voter_id}"
        .format(voter_id=voter_id))

    return JsonResponse({0: "not working yet - needs to be built"})
Exemplo n.º 17
0
def organization_unfollow_view(request, organization_id):
    print "organization_unfollow_view {organization_id}".format(
        organization_id=organization_id)
    voter_device_id = get_voter_device_id(request)
    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)

    follow_organization_manager = FollowOrganizationManager()
    results = follow_organization_manager.toggle_off_voter_following_organization(voter_id, organization_id)
    if results['success']:
        return JsonResponse({0: "success"})
    else:
        return JsonResponse({0: "failure"})
Exemplo n.º 18
0
def voter_supporting_candidate_campaign_view(request, candidate_campaign_id):
    # print "voter_supporting_candidate_campaign_view {candidate_campaign_id}".format(
    #     candidate_campaign_id=candidate_campaign_id)
    voter_device_id = get_voter_device_id(request)
    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)

    position_entered_manager = PositionEnteredManager()
    results = position_entered_manager.toggle_on_voter_support_for_candidate_campaign(voter_id, candidate_campaign_id)
    if results['success']:
        return JsonResponse({0: "success"})
    else:
        return JsonResponse({0: "failure"})
Exemplo n.º 19
0
def voter_opposing_candidate_campaign_view(request, candidate_campaign_id):
    # print "voter_opposing_candidate_campaign_view {candidate_campaign_id}".format(
    #     candidate_campaign_id=candidate_campaign_id)
    voter_device_id = get_voter_device_id(request)
    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)

    position_entered_manager = PositionEnteredManager()
    results = position_entered_manager.toggle_on_voter_oppose_for_candidate_campaign(
        voter_id, candidate_campaign_id)
    if results['success']:
        return JsonResponse({0: "success"})
    else:
        return JsonResponse({0: "failure"})
Exemplo n.º 20
0
def voter_stop_opposing_candidate_campaign_view(request, candidate_campaign_id):
    logger.debug("voter_stop_opposing_candidate_campaign_view {candidate_campaign_id}".format(
        candidate_campaign_id=candidate_campaign_id
    ))
    voter_api_device_id = get_voter_api_device_id(request)
    voter_id = fetch_voter_id_from_voter_device_link(voter_api_device_id)

    position_entered_manager = PositionEnteredManager()
    results = position_entered_manager.toggle_off_voter_oppose_for_candidate_campaign(voter_id, candidate_campaign_id)
    if results['success']:
        return JsonResponse({0: "success"})
    else:
        return JsonResponse({0: "failure"})
Exemplo n.º 21
0
def organization_unfollow_view(request, organization_id):
    logger.debug("organization_unfollow_view {organization_id}".format(
        organization_id=organization_id))
    voter_device_id = get_voter_device_id(request)
    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)

    follow_organization_manager = FollowOrganizationManager()
    results = follow_organization_manager.toggle_off_voter_following_organization(
        voter_id, organization_id)
    if results['success']:
        return JsonResponse({0: "success"})
    else:
        return JsonResponse({0: "failure"})
Exemplo n.º 22
0
def voter_address_save(voter_device_id, address_raw_text,
                       address_variable_exists):
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        return HttpResponse(json.dumps(results['json_data']),
                            content_type='application/json')

    if not address_variable_exists:
        json_data = {
            'status': "MISSING_POST_VARIABLE-ADDRESS",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

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

    # At this point, we have a valid voter

    voter_address_manager = VoterAddressManager()
    address_type = BALLOT_ADDRESS

    # We wrap get_or_create because we want to centralize error handling
    results = voter_address_manager.update_or_create_voter_address(
        voter_id, address_type, address_raw_text.strip())
    if results['success']:
        json_data = {
            'status': "VOTER_ADDRESS_SAVED",
            'success': True,
            'voter_device_id': voter_device_id,
            'address': address_raw_text,
        }
    # elif results['status'] == 'MULTIPLE_MATCHING_ADDRESSES_FOUND':
    # delete all currently matching addresses and save again
    else:
        json_data = {
            'status': results['status'],
            'success': False,
            'voter_device_id': voter_device_id,
        }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemplo n.º 23
0
def positions_related_to_candidate_campaign_view(
        request, candidate_campaign_id,
        stance_we_are_looking_for):  # TODO DEPRECATE
    """
    We want to return a JSON file with the support positions for a particular candidate's campaign
    :param request:
    :param candidate_campaign_id:
    :return:
    """
    if stance_we_are_looking_for not in (SUPPORT, NO_STANCE, INFORMATION_ONLY,
                                         STILL_DECIDING, OPPOSE,
                                         PERCENT_RATING):
        logger.debug(stance_we_are_looking_for)
        return JsonResponse({0: "stance not recognized"})

    # This implementation is built to make only two database calls. All other calculations are done here in the
    #  application layer

    position_list_manager = PositionListManager()
    candidate_campaign_we_vote_id = ''
    all_positions_list_for_candidate_campaign = \
        position_list_manager.retrieve_all_positions_for_candidate_campaign(
            candidate_campaign_id, candidate_campaign_we_vote_id, stance_we_are_looking_for)

    voter_api_device_id = get_voter_api_device_id(request)
    voter_id = fetch_voter_id_from_voter_device_link(voter_api_device_id)

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

    positions_followed = position_list_manager.calculate_positions_followed_by_voter(
        voter_id, all_positions_list_for_candidate_campaign,
        organizations_followed_by_voter)

    positions_not_followed = position_list_manager.calculate_positions_not_followed_by_voter(
        all_positions_list_for_candidate_campaign,
        organizations_followed_by_voter)

    # TODO: Below we return a snippet of HTML, but this should be converted to returning just the org's name
    #       and id, so the "x, y, and z support" can be assembled and rendered by the client
    # VERSION 1
    # position_html = assemble_candidate_campaign_position_stance_html(
    #     all_positions_list_for_candidate_campaign, stance_we_are_looking_for, candidate_campaign_id)
    # VERSION 2
    position_html = assemble_candidate_campaign_stance_html(
        candidate_campaign_id, stance_we_are_looking_for, positions_followed,
        positions_not_followed)

    return JsonResponse({0: position_html})
Exemplo n.º 24
0
def voter_guide_possibility_save_for_api(voter_device_id,
                                         voter_guide_possibility_url):
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        return HttpResponse(json.dumps(results['json_data']),
                            content_type='application/json')

    if not voter_guide_possibility_url:
        json_data = {
            'status': "MISSING_POST_VARIABLE-URL",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        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': "VOTER_NOT_FOUND_FROM_DEVICE_ID",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    # At this point, we have a valid voter

    voter_guide_possibility_manager = VoterGuidePossibilityManager()

    # We wrap get_or_create because we want to centralize error handling
    results = voter_guide_possibility_manager.update_or_create_voter_guide_possibility(
        voter_guide_possibility_url.strip())
    if results['success']:
        json_data = {
            'status': "VOTER_GUIDE_POSSIBILITY_SAVED",
            'success': True,
            'voter_device_id': voter_device_id,
            'voter_guide_possibility_url': voter_guide_possibility_url,
        }

    # elif results['status'] == 'MULTIPLE_MATCHING_ADDRESSES_FOUND':
    # delete all currently matching addresses and save again?
    else:
        json_data = {
            'status': results['status'],
            'success': False,
            'voter_device_id': voter_device_id,
        }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
def voter_position_like_status_retrieve_for_api(voter_device_id, position_entered_id):
    # Get voter_id from the voter_device_id so we can know who is doing the liking
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status':               'VALID_VOTER_DEVICE_ID_MISSING',
            'success':              False,
            'voter_device_id':      voter_device_id,
            'is_liked':             False,
            'position_entered_id':  position_entered_id,
            'position_like_id':     0,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

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

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

    json_data = {
        'status':               status,
        'success':              success,
        'voter_device_id':      voter_device_id,
        'is_liked':             is_liked,
        'position_entered_id':  position_entered_id,
        'position_like_id':     position_like_id,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemplo n.º 26
0
def voter_create(voter_device_id):
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        return HttpResponse(json.dumps(results['json_data']), content_type='application/json')

    voter_id = 0
    # Make sure a voter record hasn't already been created for this
    existing_voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if existing_voter_id:
        json_data = {
            'status': "VOTER_ALREADY_EXISTS",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    # Create a new voter and return the id
    voter_manager = VoterManager()
    results = voter_manager.create_voter()

    if results['voter_created']:
        voter = results['voter']

        # Now save the voter_device_link
        voter_device_link_manager = VoterDeviceLinkManager()
        results = voter_device_link_manager.save_new_voter_device_link(voter_device_id, voter.id)

        if results['voter_device_link_created']:
            voter_device_link = results['voter_device_link']
            voter_id_found = True if voter_device_link.voter_id > 0 else False

            if voter_id_found:
                voter_id = voter_device_link.voter_id

    if voter_id:
        json_data = {
            'status': "VOTER_CREATED",
            'success': False,
            'voter_device_id': voter_device_id,
            'voter_id': voter_id,  # We may want to remove this after initial testing
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
    else:
        json_data = {
            'status': "VOTER_NOT_CREATED",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemplo n.º 27
0
def voter_position_like_status_retrieve_for_api(voter_device_id, position_entered_id):
    # Get voter_id from the voter_device_id so we can know who is doing the liking
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status':               'VALID_VOTER_DEVICE_ID_MISSING',
            'success':              False,
            'voter_device_id':      voter_device_id,
            'is_liked':             False,
            'position_entered_id':  position_entered_id,
            'position_like_id':     0,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

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

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

    json_data = {
        'status':               status,
        'success':              success,
        'voter_device_id':      voter_device_id,
        'is_liked':             is_liked,
        'position_entered_id':  position_entered_id,
        'position_like_id':     position_like_id,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemplo n.º 28
0
def voter_stop_supporting_candidate_campaign_view(request,
                                                  candidate_campaign_id):
    logger.debug(
        "voter_stop_supporting_candidate_campaign_view {candidate_campaign_id}"
        .format(candidate_campaign_id=candidate_campaign_id))
    voter_api_device_id = get_voter_api_device_id(request)
    voter_id = fetch_voter_id_from_voter_device_link(voter_api_device_id)

    position_entered_manager = PositionEnteredManager()
    results = position_entered_manager.toggle_off_voter_support_for_candidate_campaign(
        voter_id, candidate_campaign_id)
    if results['success']:
        return JsonResponse({0: "success"})
    else:
        return JsonResponse({0: "failure"})
Exemplo n.º 29
0
def positions_count_for_api(voter_device_id, candidate_id,
                            candidate_we_vote_id, measure_id,
                            measure_we_vote_id, stance_we_are_looking_for):
    # 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']:
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

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

    show_positions_this_voter_follows = True
    if positive_value_exists(candidate_id) or positive_value_exists(
            candidate_we_vote_id):
        results = positions_count_for_candidate_campaign(
            voter_id, candidate_id, candidate_we_vote_id,
            stance_we_are_looking_for, show_positions_this_voter_follows)
        json_data = results['json_data']
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')
    elif positive_value_exists(measure_id) or positive_value_exists(
            measure_we_vote_id):
        results = positions_count_for_contest_measure(
            voter_id, measure_id, measure_we_vote_id,
            stance_we_are_looking_for, show_positions_this_voter_follows)
        json_data = results['json_data']
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')
    else:
        status = 'UNABLE_TO_RETRIEVE-CANDIDATE_ID_AND_MEASURE_ID_MISSING'
        success = False

    json_data = {
        'status': status,
        'success': success,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemplo n.º 30
0
def voter_guide_possibility_save_for_api(voter_device_id, voter_guide_possibility_url):
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        return HttpResponse(json.dumps(results['json_data']), content_type='application/json')

    if not voter_guide_possibility_url:
        json_data = {
                'status': "MISSING_POST_VARIABLE-URL",
                'success': False,
                'voter_device_id': voter_device_id,
            }
        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': "VOTER_NOT_FOUND_FROM_DEVICE_ID",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    # At this point, we have a valid voter

    voter_guide_possibility_manager = VoterGuidePossibilityManager()

    # We wrap get_or_create because we want to centralize error handling
    results = voter_guide_possibility_manager.update_or_create_voter_guide_possibility(
        voter_guide_possibility_url.strip())
    if results['success']:
        json_data = {
                'status': "VOTER_GUIDE_POSSIBILITY_SAVED",
                'success': True,
                'voter_device_id': voter_device_id,
                'voter_guide_possibility_url': voter_guide_possibility_url,
            }

    # elif results['status'] == 'MULTIPLE_MATCHING_ADDRESSES_FOUND':
        # delete all currently matching addresses and save again?
    else:
        json_data = {
                'status': results['status'],
                'success': False,
                'voter_device_id': voter_device_id,
            }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemplo n.º 31
0
def voter_retrieve_list_for_api(voter_device_id):
    results = is_voter_device_id_valid(voter_device_id)
    if not results["success"]:
        results2 = {"success": False, "json_data": results["json_data"]}
        return results2

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if voter_id > 0:
        voter_manager = VoterManager()
        results = voter_manager.retrieve_voter_by_id(voter_id)
        if results["voter_found"]:
            voter_id = results["voter_id"]
    else:
        # If we are here, the voter_id could not be found from the voter_device_id
        json_data = {"status": "VOTER_NOT_FOUND_FROM_DEVICE_ID", "success": False, "voter_device_id": voter_device_id}
        results = {"success": False, "json_data": json_data}
        return results

    if voter_id:
        voter_list = Voter.objects.all()
        voter_list = voter_list.filter(id=voter_id)

        if len(voter_list):
            results = {"success": True, "voter_list": voter_list}
            return results

    # Trying to mimic the Google Civic error codes scheme
    errors_list = [
        {
            "domain": "TODO global",
            "reason": "TODO reason",
            "message": "TODO Error message here",
            "locationType": "TODO Error message here",
            "location": "TODO location",
        }
    ]
    error_package = {"errors": errors_list, "code": 400, "message": "Error message here"}
    json_data = {
        "error": error_package,
        "status": "VOTER_ID_COULD_NOT_BE_RETRIEVED",
        "success": False,
        "voter_device_id": voter_device_id,
    }
    results = {"success": False, "json_data": json_data}
    return results
Exemplo n.º 32
0
def positions_count_for_api(voter_device_id,
                            candidate_id, candidate_we_vote_id,
                            measure_id, measure_we_vote_id,
                            stance_we_are_looking_for):
    # 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']:
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

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

    show_positions_this_voter_follows = True
    if positive_value_exists(candidate_id) or positive_value_exists(candidate_we_vote_id):
        results = positions_count_for_candidate_campaign(voter_id,
                                                         candidate_id, candidate_we_vote_id,
                                                         stance_we_are_looking_for,
                                                         show_positions_this_voter_follows)
        json_data = results['json_data']
        return HttpResponse(json.dumps(json_data), content_type='application/json')
    elif positive_value_exists(measure_id) or positive_value_exists(measure_we_vote_id):
        results = positions_count_for_contest_measure(voter_id,
                                                      measure_id, measure_we_vote_id,
                                                      stance_we_are_looking_for,
                                                      show_positions_this_voter_follows)
        json_data = results['json_data']
        return HttpResponse(json.dumps(json_data), content_type='application/json')
    else:
        status = 'UNABLE_TO_RETRIEVE-CANDIDATE_ID_AND_MEASURE_ID_MISSING'
        success = False

    json_data = {
        'status': status,
        'success': success,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemplo n.º 33
0
def voter_address_save(voter_device_id, address_raw_text, address_variable_exists):
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        return HttpResponse(json.dumps(results['json_data']), content_type='application/json')

    if not address_variable_exists:
        json_data = {
                'status': "MISSING_POST_VARIABLE-ADDRESS",
                'success': False,
                'voter_device_id': voter_device_id,
            }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

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

    # At this point, we have a valid voter

    voter_address_manager = VoterAddressManager()
    address_type = BALLOT_ADDRESS

    # We wrap get_or_create because we want to centralize error handling
    results = voter_address_manager.update_or_create_voter_address(voter_id, address_type, address_raw_text.strip())
    if results['success']:
        json_data = {
                'status': "VOTER_ADDRESS_SAVED",
                'success': True,
                'voter_device_id': voter_device_id,
                'address': address_raw_text,
            }
    # elif results['status'] == 'MULTIPLE_MATCHING_ADDRESSES_FOUND':
        # delete all currently matching addresses and save again
    else:
        json_data = {
                'status': results['status'],
                'success': False,
                'voter_device_id': voter_device_id,
            }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemplo n.º 34
0
def voter_list_view(request):
    authority_required = {'admin'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    voter_api_device_id = get_voter_api_device_id(request)  # We look in the cookies for voter_api_device_id
    voter_id = fetch_voter_id_from_voter_device_link(voter_api_device_id)
    voter_id = convert_to_int(voter_id)

    messages_on_stage = get_messages(request)
    voter_list = Voter.objects.order_by('-last_login')

    template_values = {
        'messages_on_stage': messages_on_stage,
        'voter_list': voter_list,
        'voter_id_signed_in': voter_id,
    }
    return render(request, 'voter/voter_list.html', template_values)
Exemplo n.º 35
0
def voter_all_stars_status_retrieve_for_api(voter_device_id):
    # Get voter_id from the voter_device_id so we can know whose stars to retrieve
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status': "VALID_VOTER_DEVICE_ID_MISSING",
            'success': False,
            'star_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):
        json_data = {
            'status': "VALID_VOTER_ID_MISSING",
            'success': False,
            'star_list': [],
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    star_item_list = StarItemList()
    results = star_item_list.retrieve_star_item_list_for_voter(voter_id)
    status = results['status']
    success = results['success']

    star_list = []
    if success:
        star_item_list = results['star_item_list']
        for star_item in star_item_list:
            # Create a list of star information needed by API
            one_star = {
                'ballot_item_we_vote_id': star_item.ballot_item_we_vote_id(),
                'star_on': star_item.is_starred(),
            }
            star_list.append(one_star)

    json_data = {
        'status': status,
        'success': success,
        'star_list': star_list,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemplo n.º 36
0
def positions_count_for_candidate_campaign_view(request,
                                                candidate_campaign_id,
                                                stance_we_are_looking_for,
                                                show_followed_positions=True):
    """
    We want to return a JSON file with the support positions for a particular candidate's campaign
    :param request:
    :param candidate_campaign_id:
    :return:
    """
    if stance_we_are_looking_for not in (ANY, SUPPORT, NO_STANCE,
                                         INFORMATION_ONLY, STILL_DECIDING,
                                         OPPOSE):
        print stance_we_are_looking_for
        return JsonResponse({0: "stance not recognized"})

    # This implementation is built to make only two database calls. All other calculations are done here in the
    #  application layer

    position_list_manager = PositionListForCandidateCampaign()
    all_positions_list_for_candidate_campaign = \
        position_list_manager.retrieve_all_positions_for_candidate_campaign(
            candidate_campaign_id, stance_we_are_looking_for)

    voter_device_id = get_voter_device_id(request)
    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)

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

    if show_followed_positions:
        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)
        return JsonResponse({0: positions_followed_count})
    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)
        return JsonResponse({0: positions_not_followed_count})
Exemplo n.º 37
0
def positions_related_to_candidate_campaign_view(request, candidate_campaign_id, stance_we_are_looking_for):  # TODO DEPRECATE
    """
    We want to return a JSON file with the support positions for a particular candidate's campaign
    :param request:
    :param candidate_campaign_id:
    :return:
    """
    if stance_we_are_looking_for not in(SUPPORT, NO_STANCE, INFORMATION_ONLY, STILL_DECIDING, OPPOSE, PERCENT_RATING):
        logger.debug(stance_we_are_looking_for)
        return JsonResponse({0: "stance not recognized"})

    # This implementation is built to make only two database calls. All other calculations are done here in the
    #  application layer

    position_list_manager = PositionListManager()
    candidate_campaign_we_vote_id = ''
    all_positions_list_for_candidate_campaign = \
        position_list_manager.retrieve_all_positions_for_candidate_campaign(
            candidate_campaign_id, candidate_campaign_we_vote_id, stance_we_are_looking_for)

    voter_api_device_id = get_voter_api_device_id(request)
    voter_id = fetch_voter_id_from_voter_device_link(voter_api_device_id)

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

    positions_followed = position_list_manager.calculate_positions_followed_by_voter(
        voter_id, all_positions_list_for_candidate_campaign, organizations_followed_by_voter)

    positions_not_followed = position_list_manager.calculate_positions_not_followed_by_voter(
        all_positions_list_for_candidate_campaign, organizations_followed_by_voter)

    # TODO: Below we return a snippet of HTML, but this should be converted to returning just the org's name
    #       and id, so the "x, y, and z support" can be assembled and rendered by the client
    # VERSION 1
    # position_html = assemble_candidate_campaign_position_stance_html(
    #     all_positions_list_for_candidate_campaign, stance_we_are_looking_for, candidate_campaign_id)
    # VERSION 2
    position_html = assemble_candidate_campaign_stance_html(
        candidate_campaign_id, stance_we_are_looking_for, positions_followed, positions_not_followed)

    return JsonResponse({0: position_html})
Exemplo n.º 38
0
def voter_all_stars_status_retrieve_for_api(voter_device_id):
    # Get voter_id from the voter_device_id so we can know whose stars to retrieve
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status':       "VALID_VOTER_DEVICE_ID_MISSING",
            'success':      False,
            'star_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):
        json_data = {
            'status':       "VALID_VOTER_ID_MISSING",
            'success':      False,
            'star_list':    [],
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    star_item_list = StarItemList()
    results = star_item_list.retrieve_star_item_list_for_voter(voter_id)
    status = results['status']
    success = results['success']

    star_list = []
    if success:
        star_item_list = results['star_item_list']
        for star_item in star_item_list:
            # Create a list of star information needed by API
            one_star = {
                'ballot_item_we_vote_id':   star_item.ballot_item_we_vote_id(),
                'star_on':                  star_item.is_starred(),
            }
            star_list.append(one_star)

    json_data = {
        'status':       status,
        'success':      success,
        'star_list':    star_list,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemplo n.º 39
0
def voter_stance_for_candidate_campaign_view(request, candidate_campaign_id):
    # print "voter_stance_for_candidate_campaign_view {candidate_campaign_id}".format(
    #     candidate_campaign_id=candidate_campaign_id)
    voter_device_id = get_voter_device_id(request)
    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)

    position_entered_manager = PositionEnteredManager()
    results = position_entered_manager.retrieve_voter_candidate_campaign_position(voter_id, candidate_campaign_id)
    if results['position_found']:
        if results['is_support']:
            return JsonResponse({0: "support"})
        elif results['is_oppose']:
            return JsonResponse({0: "oppose"})
        elif results['is_no_stance']:
            return JsonResponse({0: "no_stance"})
        elif results['is_information_only']:
            return JsonResponse({0: "information_only"})
        elif results['is_still_deciding']:
            return JsonResponse({0: "still_deciding"})
    return JsonResponse({0: "failure"})
Exemplo n.º 40
0
def positions_display_list_related_to_candidate_campaign(
        request, candidate_campaign_id, stance_we_are_looking_for):
    show_only_followed_positions = convert_to_int(request.GET.get('f', 0))
    show_only_not_followed_positions = convert_to_int(request.GET.get('nf', 0))

    messages_on_stage = get_messages(request)
    candidate_campaign_id = convert_to_int(candidate_campaign_id)

    position_list_manager = PositionListForCandidateCampaign()
    all_positions_list_for_candidate_campaign = \
        position_list_manager.retrieve_all_positions_for_candidate_campaign(
            candidate_campaign_id, stance_we_are_looking_for)

    voter_device_id = get_voter_device_id(request)
    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)

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

    if show_only_followed_positions == 1:
        logger.debug("positions_display_list: show only followed positions")
        list_to_display = position_list_manager.calculate_positions_followed_by_voter(
            voter_id, all_positions_list_for_candidate_campaign,
            organizations_followed_by_voter)
    elif show_only_not_followed_positions == 1:
        logger.debug(
            "positions_display_list: show only NOT followed positions")
        list_to_display = position_list_manager.calculate_positions_not_followed_by_voter(
            all_positions_list_for_candidate_campaign,
            organizations_followed_by_voter)
    else:
        list_to_display = all_positions_list_for_candidate_campaign

    template_values = {
        'error': True,
        'messages_on_stage': messages_on_stage,
        'position_list': list_to_display,
        'organizations_followed_by_voter': organizations_followed_by_voter,
    }
    return render(request, 'position/position_list.html', template_values)
Exemplo n.º 41
0
def voter_stance_for_candidate_campaign_view(request, candidate_campaign_id):
    # print "voter_stance_for_candidate_campaign_view {candidate_campaign_id}".format(
    #     candidate_campaign_id=candidate_campaign_id)
    voter_device_id = get_voter_device_id(request)
    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)

    position_entered_manager = PositionEnteredManager()
    results = position_entered_manager.retrieve_voter_candidate_campaign_position(
        voter_id, candidate_campaign_id)
    if results['position_found']:
        if results['is_support']:
            return JsonResponse({0: "support"})
        elif results['is_oppose']:
            return JsonResponse({0: "oppose"})
        elif results['is_no_stance']:
            return JsonResponse({0: "no_stance"})
        elif results['is_information_only']:
            return JsonResponse({0: "information_only"})
        elif results['is_still_deciding']:
            return JsonResponse({0: "still_deciding"})
    return JsonResponse({0: "failure"})
Exemplo n.º 42
0
def voter_address_retrieve(voter_device_id):
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        return HttpResponse(json.dumps(results['json_data']), content_type='application/json')

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

    voter_address_manager = VoterAddressManager()
    results = voter_address_manager.retrieve_ballot_address_from_voter_id(voter_id)

    if results['voter_address_found']:
        voter_address = results['voter_address']
        json_data = {
            'voter_device_id': voter_device_id,
            'address_type': voter_address.address_type if voter_address.address_type else '',
            'address': voter_address.address if voter_address.address else '',
            'latitude': voter_address.latitude if voter_address.latitude else '',
            'longitude': voter_address.longitude if voter_address.longitude else '',
            'normalized_line1': voter_address.normalized_line1 if voter_address.normalized_line1 else '',
            'normalized_line2': voter_address.normalized_line2 if voter_address.normalized_line2 else '',
            'normalized_city': voter_address.normalized_city if voter_address.normalized_city else '',
            'normalized_state': voter_address.normalized_state if voter_address.normalized_state else '',
            'normalized_zip': voter_address.normalized_zip if voter_address.normalized_zip else '',
            'success': True,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
    else:
        json_data = {
            'status': "VOTER_ADDRESS_NOT_RETRIEVED",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemplo n.º 43
0
def voter_list_view(request):
    authority_required = {'admin'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    voter_api_device_id = get_voter_api_device_id(
        request)  # We look in the cookies for voter_api_device_id
    voter_id = fetch_voter_id_from_voter_device_link(voter_api_device_id)
    voter_id = convert_to_int(voter_id)

    messages_on_stage = get_messages(request)
    voter_list = Voter.objects.order_by('-is_admin', '-is_verified_volunteer',
                                        'facebook_email',
                                        'twitter_screen_name', 'last_name',
                                        'first_name')
    voter_list = voter_list  # [:200]

    template_values = {
        'messages_on_stage': messages_on_stage,
        'voter_list': voter_list,
        'voter_id_signed_in': voter_id,
    }
    return render(request, 'voter/voter_list.html', template_values)
Exemplo n.º 44
0
def positions_count_for_candidate_campaign_view(request, candidate_campaign_id, stance_we_are_looking_for,
                                                show_followed_positions=True):
    """
    We want to return a JSON file with the support positions for a particular candidate's campaign
    :param request:
    :param candidate_campaign_id:
    :return:
    """
    if stance_we_are_looking_for not in(ANY, SUPPORT, NO_STANCE, INFORMATION_ONLY, STILL_DECIDING, OPPOSE):
        logger.debug(stance_we_are_looking_for)
        return JsonResponse({0: "stance not recognized"})

    # This implementation is built to make only two database calls. All other calculations are done here in the
    #  application layer

    position_list_manager = PositionListForCandidateCampaign()
    all_positions_list_for_candidate_campaign = \
        position_list_manager.retrieve_all_positions_for_candidate_campaign(
            candidate_campaign_id, stance_we_are_looking_for)

    voter_device_id = get_voter_device_id(request)
    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)

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

    if show_followed_positions:
        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)
        return JsonResponse({0: positions_followed_count})
    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)
        return JsonResponse({0: positions_not_followed_count})
Exemplo n.º 45
0
def voter_opposing_save(voter_device_id, candidate_id, measure_id):
    # 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']:
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

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

    position_entered_manager = PositionEnteredManager()
    if positive_value_exists(candidate_id):
        results = position_entered_manager.toggle_on_voter_oppose_for_candidate_campaign(voter_id, candidate_id)
        # toggle_off_voter_support_for_candidate_campaign
        status = "OPPOSING_CANDIDATE " + results['status']
        success = results['success']
    elif positive_value_exists(measure_id):
        results = position_entered_manager.toggle_on_voter_oppose_for_contest_measure(voter_id, measure_id)
        status = "OPPOSING_MEASURE " + results['status']
        success = results['success']
    else:
        status = 'UNABLE_TO_SAVE-CANDIDATE_ID_AND_MEASURE_ID_MISSING'
        success = False

    json_data = {
        'status': status,
        'success': success,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemplo n.º 46
0
def positions_display_list_related_to_candidate_campaign(request, candidate_campaign_id, stance_we_are_looking_for):
    show_only_followed_positions = convert_to_int(request.GET.get('f', 0))
    show_only_not_followed_positions = convert_to_int(request.GET.get('nf', 0))

    messages_on_stage = get_messages(request)
    candidate_campaign_id = convert_to_int(candidate_campaign_id)

    position_list_manager = PositionListForCandidateCampaign()
    all_positions_list_for_candidate_campaign = \
        position_list_manager.retrieve_all_positions_for_candidate_campaign(
            candidate_campaign_id, stance_we_are_looking_for)

    voter_device_id = get_voter_device_id(request)
    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)

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

    if show_only_followed_positions == 1:
        logger.debug("positions_display_list: show only followed positions")
        list_to_display = position_list_manager.calculate_positions_followed_by_voter(
            voter_id, all_positions_list_for_candidate_campaign, organizations_followed_by_voter)
    elif show_only_not_followed_positions == 1:
        logger.debug("positions_display_list: show only NOT followed positions")
        list_to_display = position_list_manager.calculate_positions_not_followed_by_voter(
            all_positions_list_for_candidate_campaign, organizations_followed_by_voter)
    else:
        list_to_display = all_positions_list_for_candidate_campaign

    template_values = {
        'error':                            True,
        'messages_on_stage':                messages_on_stage,
        'position_list':                    list_to_display,
        'organizations_followed_by_voter':  organizations_followed_by_voter,
    }
    return render(request, 'position/position_list.html', template_values)
Exemplo n.º 47
0
def organization_follow_all(voter_device_id,
                            organization_id,
                            organization_we_vote_id,
                            follow_kind=FOLLOWING):
    if not positive_value_exists(voter_device_id):
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
            'voter_device_id': voter_device_id,
            'organization_id': organization_id,
        }
        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,
            'organization_id': organization_id,
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    organization_id = convert_to_int(organization_id)
    if not positive_value_exists(
            organization_id) and not positive_value_exists(
                organization_we_vote_id):
        json_data = {
            'status': 'VALID_ORGANIZATION_ID_MISSING',
            'success': False,
            'voter_device_id': voter_device_id,
            'organization_id': organization_id,
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    if follow_kind == FOLLOWING:
        follow_organization_manager = FollowOrganizationManager()
        results = follow_organization_manager.toggle_on_voter_following_organization(
            voter_id, organization_id, organization_we_vote_id)
        if results['follow_organization_found']:
            status = 'FOLLOWING'
            success = True
            follow_organization = results['follow_organization']
            organization_id = follow_organization.organization_id
            organization_we_vote_id = follow_organization.organization_we_vote_id
        else:
            status = results['status']
            success = False

    elif follow_kind == FOLLOW_IGNORE:
        follow_organization_manager = FollowOrganizationManager()
        results = follow_organization_manager.toggle_ignore_voter_following_organization(
            voter_id, organization_id, organization_we_vote_id)
        if results['follow_organization_found']:
            status = 'IGNORING'
            success = True
            follow_organization = results['follow_organization']
            organization_id = follow_organization.organization_id
            organization_we_vote_id = follow_organization.organization_we_vote_id
        else:
            status = results['status']
            success = False
    elif follow_kind == STOP_FOLLOWING:
        follow_organization_manager = FollowOrganizationManager()
        results = follow_organization_manager.toggle_off_voter_following_organization(
            voter_id, organization_id, organization_we_vote_id)
        if results['follow_organization_found']:
            status = 'STOPPED_FOLLOWING'
            success = True
            follow_organization = results['follow_organization']
            organization_id = follow_organization.organization_id
            organization_we_vote_id = follow_organization.organization_we_vote_id
        else:
            status = results['status']
            success = False
    else:
        status = 'INCORRECT_FOLLOW_KIND'
        success = False

    json_data = {
        'status': status,
        'success': success,
        'voter_device_id': voter_device_id,
        'organization_id': organization_id,
        'organization_we_vote_id': organization_we_vote_id,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemplo n.º 48
0
def organizations_followed_retrieve_for_api(voter_device_id,
                                            maximum_number_to_retrieve=0):
    """
    Return a list of the organizations followed. See also voter_guides_followed_retrieve_for_api, which starts with
    organizations followed, but returns data as a list of voter guides.
    :param voter_device_id:
    :param maximum_number_to_retrieve:
    :return:
    """
    if not positive_value_exists(voter_device_id):
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
            'voter_device_id': voter_device_id,
            'organization_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):
        json_data = {
            'status': 'VALID_VOTER_ID_MISSING',
            'success': False,
            'voter_device_id': voter_device_id,
            'organization_list': [],
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    results = retrieve_organizations_followed(voter_id)
    status = results['status']
    organizations_for_api = []
    if results['organization_list_found']:
        organization_list = results['organization_list']
        number_added_to_list = 0
        for organization in organization_list:
            one_organization = {
                'organization_id':
                organization.id,
                'organization_we_vote_id':
                organization.we_vote_id,
                'organization_name':
                organization.organization_name if positive_value_exists(
                    organization.organization_name) else '',
                'organization_website':
                organization.organization_website if positive_value_exists(
                    organization.organization_website) else '',
                'organization_twitter_handle':
                organization.organization_twitter_handle
                if positive_value_exists(
                    organization.organization_twitter_handle) else '',
                'twitter_followers_count':
                organization.twitter_followers_count if positive_value_exists(
                    organization.twitter_followers_count) else 0,
                'organization_email':
                organization.organization_email if positive_value_exists(
                    organization.organization_email) else '',
                'organization_facebook':
                organization.organization_facebook if positive_value_exists(
                    organization.organization_facebook) else '',
                'organization_photo_url':
                organization.organization_photo_url() if positive_value_exists(
                    organization.organization_photo_url()) else '',
            }
            organizations_for_api.append(one_organization.copy())
            if positive_value_exists(maximum_number_to_retrieve):
                number_added_to_list += 1
                if number_added_to_list >= maximum_number_to_retrieve:
                    break

        if len(organizations_for_api):
            status = 'ORGANIZATIONS_FOLLOWED_RETRIEVED'
            success = True
        else:
            status = 'NO_ORGANIZATIONS_FOLLOWED_FOUND'
            success = True
    else:
        success = False

    json_data = {
        'status': status,
        'success': success,
        'voter_device_id': voter_device_id,
        'organization_list': organizations_for_api,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemplo n.º 49
0
def voter_ballot_items_retrieve_for_api(voter_device_id, google_civic_election_id):
    """

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

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        json_data = {
            "status": "VALID_VOTER_ID_MISSING",
            "success": False,
            "voter_id": voter_id,
            "voter_device_id": voter_device_id,
            "ballot_item_list": [],
            "google_civic_election_id": google_civic_election_id,
        }
        results = {
            "success": False,
            "json_data": json_data,
            "google_civic_election_id": 0,  # Force the clearing of google_civic_election_id
        }
        return results

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

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

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

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

        json_data = {
            "status": "VOTER_BALLOT_ITEMS_RETRIEVED",
            "success": True,
            "voter_device_id": voter_device_id,
            "ballot_item_list": ballot_items_to_display,
            "google_civic_election_id": google_civic_election_id,
        }
    else:
        json_data = {
            "status": status,
            "success": False,
            "voter_device_id": voter_device_id,
            "ballot_item_list": [],
            "google_civic_election_id": google_civic_election_id,
        }
    results = {
        "success": success,
        "google_civic_election_id": google_civic_election_id,  # We want to save google_civic_election_id in cookie
        "json_data": json_data,
    }
    return results
Exemplo n.º 50
0
def voter_guides_followed_retrieve_for_api(voter_device_id,
                                           maximum_number_to_retrieve=0):
    """
    Start with the organizations followed and return a list of voter_guides. voterGuidesFollowedRetrieve
    See also organizations_followed_for_api, which returns a list of organizations.

    :param voter_device_id:
    :param maximum_number_to_retrieve:
    :return:
    """
    if not positive_value_exists(voter_device_id):
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
            'voter_device_id': voter_device_id,
            'maximum_number_to_retrieve': maximum_number_to_retrieve,
            'voter_guides': [],
        }
        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,
            'maximum_number_to_retrieve': maximum_number_to_retrieve,
            'voter_guides': [],
        }
        return HttpResponse(json.dumps(json_data),
                            content_type='application/json')

    results = retrieve_voter_guides_followed(voter_id)
    status = results['status']
    voter_guide_list = results['voter_guide_list']
    voter_guides = []
    if results['voter_guide_list_found']:
        number_added_to_list = 0
        for voter_guide in voter_guide_list:
            one_voter_guide = {
                'we_vote_id':
                voter_guide.we_vote_id,
                'google_civic_election_id':
                voter_guide.google_civic_election_id,
                'time_span':
                voter_guide.vote_smart_time_span,
                'voter_guide_display_name':
                voter_guide.voter_guide_display_name(),
                'voter_guide_image_url':
                voter_guide.voter_guide_image_url(),
                'voter_guide_owner_type':
                voter_guide.voter_guide_owner_type,
                'organization_we_vote_id':
                voter_guide.organization_we_vote_id,
                'public_figure_we_vote_id':
                voter_guide.public_figure_we_vote_id,
                'twitter_description':
                voter_guide.twitter_description,
                'twitter_followers_count':
                voter_guide.twitter_followers_count,
                'owner_voter_id':
                voter_guide.owner_voter_id,
                'last_updated':
                voter_guide.last_updated.strftime('%Y-%m-%d %H:%M'),
            }
            voter_guides.append(one_voter_guide.copy())
            if positive_value_exists(maximum_number_to_retrieve):
                number_added_to_list += 1
                if number_added_to_list >= maximum_number_to_retrieve:
                    break

        if len(voter_guides):
            status = 'VOTER_GUIDES_FOLLOWED_RETRIEVED'
            success = True
        else:
            status = 'NO_VOTER_GUIDES_FOLLOWED_FOUND'
            success = True
    else:
        success = False

    json_data = {
        'status': status,
        'success': success,
        'voter_device_id': voter_device_id,
        'maximum_number_to_retrieve': maximum_number_to_retrieve,
        'voter_guides': voter_guides,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemplo n.º 51
0
def search_all_for_api(text_from_search_field, voter_device_id):
    """

    :param text_from_search_field:
    :param voter_device_id:
    :return:
    """
    if not positive_value_exists(text_from_search_field):
        results = {
            'status':                   'TEXT_FROM_SEARCH_FIELD_MISSING',
            'success':                  True,
            'text_from_search_field':   text_from_search_field,
            'voter_device_id':          voter_device_id,
            'search_results_found':     False,
            'search_results':           [],
        }
        return results

    if not positive_value_exists(ELASTIC_SEARCH_CONNECTION_STRING):
        results = {
            'status':                   'MISSING_ELASTIC_SEARCH_CONNECTION_STRING',
            'success':                  False,
            'text_from_search_field':   text_from_search_field,
            'voter_device_id':          voter_device_id,
            'search_results_found':     False,
            'search_results':           [],
        }
        return results

    # 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']:
        results = {
            'status':                   'VALID_VOTER_DEVICE_ID_MISSING',
            'success':                  False,
            'text_from_search_field':   text_from_search_field,
            'voter_device_id':          voter_device_id,
            'search_results_found':     False,
            'search_results':           [],
        }
        return results

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        results = {
            'status':                   "VALID_VOTER_ID_MISSING",
            'success':                  False,
            'text_from_search_field':   text_from_search_field,
            'voter_device_id':          voter_device_id,
            'search_results_found':     False,
            'search_results':           [],
        }
        return results

    elastic_search_object = Elasticsearch([ELASTIC_SEARCH_CONNECTION_STRING],
                                          timeout=2, max_retries=1, retry_on_timeout=True)

    # query = {"query": {"match": {"candidate_name": text_from_search_field}}}
    query = {"query": {"multi_match": {"type": "phrase_prefix",
                                       "query": text_from_search_field,
                                       "fields": ["candidate_name",
                                                  "candidate_twitter_handle", "twitter_name",
                                                  "measure_subtitle", "measure_text", "measure_title",
                                                  "office_name", "first_name", "middle_name", "last_name",
                                                  "party", "organization_name", "organization_twitter_handle",
                                                  "twitter_description"]}}}

    # Example of querying ALL indexes
    search_results = []
    search_count = 0
    try:
        res = elastic_search_object.search(body=query)
        # See bottom of this file for example results from Elastic Search

        for hit in res['hits']['hits']:
            one_search_result_type = hit['_type']
            one_search_result_id = hit['_id']
            one_search_result_dict = hit['_source']
            one_search_result_score = hit['_score']
            if one_search_result_type == "office":
                link_internal = "/office/" + one_search_result_dict['we_vote_id']

                one_search_result = {
                    'result_title':             one_search_result_dict['office_name'],
                    'result_image':             "",
                    'result_subtitle':          "",
                    'result_summary':           "",
                    'result_score':             one_search_result_score,
                    'link_internal':            link_internal,
                    'kind_of_owner':            "OFFICE",
                    'google_civic_election_id': one_search_result_dict['google_civic_election_id'],
                    'state_code':               one_search_result_dict['state_code'],
                    'twitter_handle':           "",
                    'we_vote_id':               one_search_result_dict['we_vote_id'],
                    'local_id':                 one_search_result_id,
                }
                search_results.append(one_search_result)
                search_count += 1
            elif one_search_result_type == "candidate":
                if positive_value_exists(one_search_result_dict['candidate_twitter_handle']):
                    link_internal = "/" + one_search_result_dict['candidate_twitter_handle']
                else:
                    link_internal = "/candidate/" + one_search_result_dict['we_vote_id']

                one_search_result = {
                    'result_title':             one_search_result_dict['candidate_name'],
                    'result_image':             "",
                    'result_subtitle':          "",
                    'result_summary':           "",
                    'result_score':             one_search_result_score,
                    'link_internal':            link_internal,
                    'kind_of_owner':            "CANDIDATE",
                    'google_civic_election_id': one_search_result_dict['google_civic_election_id'],
                    'state_code':               one_search_result_dict['state_code'],
                    'twitter_handle':           one_search_result_dict['candidate_twitter_handle'],
                    'we_vote_id':               one_search_result_dict['we_vote_id'],
                    'local_id':                 one_search_result_id,
                }
                search_results.append(one_search_result)
                search_count += 1
            elif one_search_result_type == "measure":
                if positive_value_exists(one_search_result_dict['measure_twitter_handle']):
                    link_internal = "/" + one_search_result_dict['measure_twitter_handle']
                else:
                    link_internal = "/measure/" + one_search_result_dict['we_vote_id']

                one_search_result = {
                    'result_title':             one_search_result_dict['measure_title'],
                    'result_image':             "",
                    'result_subtitle':          one_search_result_dict['measure_subtitle'],
                    'result_summary':           one_search_result_dict['measure_text'],
                    'result_score':             one_search_result_score,
                    'link_internal':            link_internal,
                    'kind_of_owner':            "MEASURE",
                    'google_civic_election_id': one_search_result_dict['google_civic_election_id'],
                    'state_code':               one_search_result_dict['state_code'],
                    'twitter_handle':           one_search_result_dict['measure_twitter_handle'],
                    'we_vote_id':               one_search_result_dict['we_vote_id'],
                    'local_id':                 one_search_result_id,
                }
                search_results.append(one_search_result)
                search_count += 1
            elif one_search_result_type == "organization":
                if 'organization_twitter_handle' in one_search_result_dict and \
                        positive_value_exists(one_search_result_dict['organization_twitter_handle']):
                    link_internal = "/" + one_search_result_dict['organization_twitter_handle']
                else:
                    link_internal = "/voterguide/" + one_search_result_dict['we_vote_id']

                one_search_result = {
                    'result_title':             one_search_result_dict['organization_name'],
                    'result_image':             "",
                    'result_subtitle':          "",
                    'result_summary':           one_search_result_dict['twitter_description'],
                    'result_score':             one_search_result_score,
                    'link_internal':            link_internal,
                    'kind_of_owner':            "ORGANIZATION",
                    'google_civic_election_id': 0,
                    'state_code':               one_search_result_dict['state_served_code'],
                    'twitter_handle':           one_search_result_dict['organization_twitter_handle'],
                    'we_vote_id':               one_search_result_dict['we_vote_id'],
                    'local_id':                 one_search_result_id,
                }
                search_results.append(one_search_result)
                search_count += 1
            elif one_search_result_type == "politician":
                # If we are here, then we should skip out. We can't display politicians w/o twitter_handle yet
                break
                # if positive_value_exists(one_search_result_dict['politician_twitter_handle']):
                #     link_internal = "/" + one_search_result_dict['politician_twitter_handle']
                # else:
                #     link_internal = "/candidate/" + one_search_result_dict['we_vote_id']
                #
                # one_search_result = {
                #     'result_title': one_search_result_dict['name'],
                #     'result_image':             "",
                #     'result_subtitle':          "",
                #     'result_summary':           "",
                #     'result_score':             one_search_result_score,
                #     'link_internal':            link_internal,
                #     'kind_of_owner':            "POLITICIAN",
                #     'google_civic_election_id': 0,
                #     'state_code':               one_search_result_dict['state_served_code'],
                #     'twitter_handle':           one_search_result_dict['politician_twitter_handle,'],
                #     'we_vote_id':               one_search_result_dict['we_vote_id'],
                #     'local_id':                 one_search_result_id,
                # }
                # search_results.append(one_search_result)
                # search_count += 1
        status = "SEARCH_ALL_COMPLETE"
        success = True

    except Exception as e:
        status = 'ELASTIC_SEARCH_EXCEPTION'
        success = False

    results = {
        'status':                   status,
        'success':                  success,
        'text_from_search_field':   text_from_search_field,
        'voter_device_id':          voter_device_id,
        'search_results_found':     True if search_count > 0 else False,
        'search_results':           search_results,
    }
    return results
def voter_retrieve_list_for_api(voter_device_id):
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        results2 = {
            'success': False,
            'json_data': results['json_data'],
        }
        return results2

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if voter_id > 0:
        voter_manager = VoterManager()
        results = voter_manager.retrieve_voter_by_id(voter_id)
        if results['voter_found']:
            voter_id = results['voter_id']
    else:
        # If we are here, the voter_id could not be found from the voter_device_id
        json_data = {
            'status': "VOTER_NOT_FOUND_FROM_DEVICE_ID",
            'success': False,
            'voter_device_id': voter_device_id,
        }
        results = {
            'success': False,
            'json_data': json_data,
        }
        return results

    if voter_id:
        voter_list = Voter.objects.all()
        voter_list = voter_list.filter(id=voter_id)

        if len(voter_list):
            results = {
                'success': True,
                'voter_list': voter_list,
            }
            return results

    # Trying to mimic the Google Civic error codes scheme
    errors_list = [{
        'domain': "TODO global",
        'reason': "TODO reason",
        'message': "TODO Error message here",
        'locationType': "TODO Error message here",
        'location': "TODO location",
    }]
    error_package = {
        'errors': errors_list,
        'code': 400,
        'message': "Error message here",
    }
    json_data = {
        'error': error_package,
        'status': "VOTER_ID_COULD_NOT_BE_RETRIEVED",
        'success': False,
        'voter_device_id': voter_device_id,
    }
    results = {
        'success': False,
        'json_data': json_data,
    }
    return results
Exemplo n.º 53
0
def voter_star_status_retrieve_for_api(voter_device_id, office_id, candidate_id, measure_id):
    # Get voter_id from the voter_device_id so we can know who is doing the starring
    results = is_voter_device_id_valid(voter_device_id)
    if not results["success"]:
        json_data = {
            "status": "VALID_VOTER_DEVICE_ID_MISSING",
            "success": False,
            "voter_device_id": voter_device_id,
            "is_starred": False,
            "office_id": office_id,
            "candidate_id": candidate_id,
            "measure_id": measure_id,
        }
        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": office_id,
            "candidate_id": candidate_id,
            "measure_id": measure_id,
        }
        return HttpResponse(json.dumps(json_data), content_type="application/json")

    star_item_manager = StarItemManager()
    if positive_value_exists(office_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"]
    elif positive_value_exists(candidate_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"]
    elif positive_value_exists(measure_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"]
    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": office_id,
        "candidate_id": candidate_id,
        "measure_id": measure_id,
    }
    return HttpResponse(json.dumps(json_data), content_type="application/json")
Exemplo n.º 54
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')
Exemplo n.º 55
0
def voter_ballot_items_retrieve_from_google_civic_for_api(
        voter_device_id, text_for_map_search='', use_test_election=False):
    """
    We are telling the server to explicitly reach out to the Google Civic API and retrieve the ballot items
    for this voter.
    """
    # Confirm that we have a Google Civic API Key (GOOGLE_CIVIC_API_KEY)
    if not positive_value_exists(GOOGLE_CIVIC_API_KEY):
        results = {
            'status': 'NO_GOOGLE_CIVIC_API_KEY',
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    # Confirm that we have the URL where we retrieve voter ballots (VOTER_INFO_URL)
    if not positive_value_exists(VOTER_INFO_URL):
        results = {
            'status':
            'MISSING VOTER_INFO_URL in config/environment_variables.json',
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    # Get voter_id from the voter_device_id so we can figure out which ballot_items to offer
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        results = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        results = {
            'status': "VALID_VOTER_ID_MISSING",
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    google_civic_election_id = 0
    status = ''
    success = False
    election_date_text = ''
    election_description_text = ''
    election_data_retrieved = False
    polling_location_retrieved = False
    contests_retrieved = False
    if not positive_value_exists(text_for_map_search):
        # Retrieve it from voter address
        voter_address_manager = VoterAddressManager()
        text_for_map_search = voter_address_manager.retrieve_ballot_map_text_from_voter_id(
            voter_id)

    if positive_value_exists(text_for_map_search):
        one_ballot_results = retrieve_one_ballot_from_google_civic_api(
            text_for_map_search, google_civic_election_id, use_test_election)

        if one_ballot_results['success']:
            one_ballot_json = one_ballot_results['structured_json']
            election_date_text = one_ballot_json['election']['electionDay']
            election_description_text = one_ballot_json['election']['name']

            # We may receive some election data, but not all of the data we need
            if one_ballot_results['election_data_retrieved']:
                election_data_retrieved = True
                success = True

            if one_ballot_results['polling_location_retrieved']:
                polling_location_retrieved = True
                success = True

            if one_ballot_results['contests_retrieved']:
                contests_retrieved = True

                # Now that we know we have new ballot data, we need to delete prior ballot data for this election
                # because when we change voterAddress, we usually get different ballot items
                ballot_item_list_manager = BallotItemListManager()
                # We include a google_civic_election_id, so only the ballot info for this election is removed
                google_civic_election_id_to_delete = one_ballot_json[
                    'election']['id']  # '0' would mean "delete all"
                if positive_value_exists(google_civic_election_id_to_delete):
                    ballot_item_list_manager.delete_all_ballot_items_for_voter(
                        voter_id, google_civic_election_id_to_delete)

                # store_on_ballot... adds an entry to the BallotReturned table
                # We update VoterAddress with normalized address data in store_one_ballot_from_google_civic_api
                store_one_ballot_results = store_one_ballot_from_google_civic_api(
                    one_ballot_json, voter_id)
                if store_one_ballot_results['success']:
                    status += 'RETRIEVED_FROM_GOOGLE_CIVIC_AND_STORED_BALLOT_FOR_VOTER '
                    success = True
                    google_civic_election_id = store_one_ballot_results[
                        'google_civic_election_id']
                else:
                    status += 'UNABLE_TO-store_one_ballot_from_google_civic_api'
        elif 'error' in one_ballot_results['structured_json']:
            if one_ballot_results['structured_json']['error'][
                    'message'] == 'Election unknown':
                success = False  # It is only successful if new ballot data is retrieved.
            else:
                success = False
            status += "GOOGLE_CIVIC_API_ERROR: " + one_ballot_results[
                'structured_json']['error']['message']

        else:
            status += 'UNABLE_TO-retrieve_one_ballot_from_google_civic_api'
            success = False
    else:
        status += 'MISSING_ADDRESS_TEXT_FOR_BALLOT_SEARCH'
        success = False

    # If a google_civic_election_id was not returned, outside of this function we search again using a test election,
    # so that during our initial user testing, ballot data is returned in areas where elections don't currently exist

    results = {
        'success': success,
        'status': status,
        'voter_device_id': voter_device_id,
        'google_civic_election_id': google_civic_election_id,
        'text_for_map_search': text_for_map_search,
        'election_date_text': election_date_text,
        'election_description_text': election_description_text,
        'election_data_retrieved': election_data_retrieved,
        'polling_location_retrieved': polling_location_retrieved,
        'contests_retrieved': contests_retrieved,
    }
    return results
Exemplo n.º 56
0
def voter_ballot_items_retrieve_from_google_civic_for_api(
        voter_device_id, text_for_map_search='', use_test_election=False):
    """
    We are telling the server to explicitly reach out to the Google Civic API and retrieve the ballot items
    for this voter.
    """
    # Confirm that we have a Google Civic API Key (GOOGLE_CIVIC_API_KEY)
    if not positive_value_exists(GOOGLE_CIVIC_API_KEY):
        results = {
            'status': 'NO_GOOGLE_CIVIC_API_KEY',
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    # Confirm that we have the URL where we retrieve voter ballots (VOTER_INFO_URL)
    if not positive_value_exists(VOTER_INFO_URL):
        results = {
            'status': 'MISSING VOTER_INFO_URL in config/environment_variables.json',
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    # Get voter_id from the voter_device_id so we can figure out which ballot_items to offer
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        results = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)
    if not positive_value_exists(voter_id):
        results = {
            'status': "VALID_VOTER_ID_MISSING",
            'success': False,
            'voter_device_id': voter_device_id,
            'google_civic_election_id': 0,
            'text_for_map_search': text_for_map_search,
        }
        return results

    google_civic_election_id = 0
    status = ''
    success = False
    election_date_text = ''
    election_description_text = ''
    election_data_retrieved = False
    polling_location_retrieved = False
    contests_retrieved = False
    if not positive_value_exists(text_for_map_search):
        # Retrieve it from voter address
        voter_address_manager = VoterAddressManager()
        text_for_map_search = voter_address_manager.retrieve_ballot_map_text_from_voter_id(voter_id)

    if positive_value_exists(text_for_map_search):
        one_ballot_results = retrieve_one_ballot_from_google_civic_api(
            text_for_map_search, google_civic_election_id, use_test_election)

        if one_ballot_results['success']:
            one_ballot_json = one_ballot_results['structured_json']
            election_date_text = one_ballot_json['election']['electionDay']
            election_description_text = one_ballot_json['election']['name']

            # We may receive some election data, but not all of the data we need
            if one_ballot_results['election_data_retrieved']:
                election_data_retrieved = True
                success = True

            if one_ballot_results['polling_location_retrieved']:
                polling_location_retrieved = True
                success = True

            if one_ballot_results['contests_retrieved']:
                contests_retrieved = True

                # Now that we know we have new ballot data, we need to delete prior ballot data for this election
                # because when we change voterAddress, we usually get different ballot items
                ballot_item_list_manager = BallotItemListManager()
                # We include a google_civic_election_id, so only the ballot info for this election is removed
                google_civic_election_id_to_delete = one_ballot_json['election']['id']  # '0' would mean "delete all"
                if positive_value_exists(google_civic_election_id_to_delete):
                    ballot_item_list_manager.delete_all_ballot_items_for_voter(
                        voter_id, google_civic_election_id_to_delete)

                # store_on_ballot... adds an entry to the BallotReturned table
                # We update VoterAddress with normalized address data in store_one_ballot_from_google_civic_api
                store_one_ballot_results = store_one_ballot_from_google_civic_api(one_ballot_json, voter_id)
                if store_one_ballot_results['success']:
                    status += 'RETRIEVED_FROM_GOOGLE_CIVIC_AND_STORED_BALLOT_FOR_VOTER '
                    success = True
                    google_civic_election_id = store_one_ballot_results['google_civic_election_id']
                else:
                    status += 'UNABLE_TO-store_one_ballot_from_google_civic_api'
        elif 'error' in one_ballot_results['structured_json']:
            if one_ballot_results['structured_json']['error']['message'] == 'Election unknown':
                success = False  # It is only successful if new ballot data is retrieved.
            else:
                success = False
            status += "GOOGLE_CIVIC_API_ERROR: " + one_ballot_results['structured_json']['error']['message']

        else:
            status += 'UNABLE_TO-retrieve_one_ballot_from_google_civic_api'
            success = False
    else:
        status += 'MISSING_ADDRESS_TEXT_FOR_BALLOT_SEARCH'
        success = False

    # If a google_civic_election_id was not returned, outside of this function we search again using a test election,
    # so that during our initial user testing, ballot data is returned in areas where elections don't currently exist

    results = {
        'success': success,
        'status': status,
        'voter_device_id': voter_device_id,
        'google_civic_election_id': google_civic_election_id,
        'text_for_map_search': text_for_map_search,
        'election_date_text': election_date_text,
        'election_description_text': election_description_text,
        'election_data_retrieved': election_data_retrieved,
        'polling_location_retrieved': polling_location_retrieved,
        'contests_retrieved': contests_retrieved,
    }
    return results
Exemplo n.º 57
0
def organizations_followed_retrieve_for_api(voter_device_id, maximum_number_to_retrieve=0):
    """
    Return a list of the organizations followed. See also voter_guides_followed_retrieve_for_api, which starts with
    organizations followed, but returns data as a list of voter guides.
    :param voter_device_id:
    :param maximum_number_to_retrieve:
    :return:
    """
    if not positive_value_exists(voter_device_id):
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
            'voter_device_id': voter_device_id,
            'organization_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):
        json_data = {
            'status': 'VALID_VOTER_ID_MISSING',
            'success': False,
            'voter_device_id': voter_device_id,
            'organization_list': [],
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    results = retrieve_organizations_followed(voter_id)
    status = results['status']
    organizations_for_api = []
    if results['organization_list_found']:
        organization_list = results['organization_list']
        number_added_to_list = 0
        for organization in organization_list:
            one_organization = {
                'organization_id': organization.id,
                'organization_we_vote_id': organization.we_vote_id,
                'organization_name':
                    organization.organization_name if positive_value_exists(organization.organization_name) else '',
                'organization_website': organization.organization_website if positive_value_exists(
                    organization.organization_website) else '',
                'organization_twitter_handle':
                    organization.organization_twitter_handle if positive_value_exists(
                        organization.organization_twitter_handle) else '',
                'twitter_followers_count':
                    organization.twitter_followers_count if positive_value_exists(
                        organization.twitter_followers_count) else 0,
                'organization_email':
                    organization.organization_email if positive_value_exists(organization.organization_email) else '',
                'organization_facebook': organization.organization_facebook
                    if positive_value_exists(organization.organization_facebook) else '',
                'organization_photo_url': organization.organization_photo_url()
                    if positive_value_exists(organization.organization_photo_url()) else '',
          }
            organizations_for_api.append(one_organization.copy())
            if positive_value_exists(maximum_number_to_retrieve):
                number_added_to_list += 1
                if number_added_to_list >= maximum_number_to_retrieve:
                    break

        if len(organizations_for_api):
            status = 'ORGANIZATIONS_FOLLOWED_RETRIEVED'
            success = True
        else:
            status = 'NO_ORGANIZATIONS_FOLLOWED_FOUND'
            success = True
    else:
        success = False

    json_data = {
        'status': status,
        'success': success,
        'voter_device_id': voter_device_id,
        'organization_list': organizations_for_api,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemplo n.º 58
0
def organization_follow_all(voter_device_id, organization_id, organization_we_vote_id, follow_kind=FOLLOWING):
    if not positive_value_exists(voter_device_id):
        json_data = {
            'status': 'VALID_VOTER_DEVICE_ID_MISSING',
            'success': False,
            'voter_device_id': voter_device_id,
            'organization_id': organization_id,
        }
        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,
            'organization_id': organization_id,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    organization_id = convert_to_int(organization_id)
    if not positive_value_exists(organization_id) and not positive_value_exists(organization_we_vote_id):
        json_data = {
            'status': 'VALID_ORGANIZATION_ID_MISSING',
            'success': False,
            'voter_device_id': voter_device_id,
            'organization_id': organization_id,
        }
        return HttpResponse(json.dumps(json_data), content_type='application/json')

    if follow_kind == FOLLOWING:
        follow_organization_manager = FollowOrganizationManager()
        results = follow_organization_manager.toggle_on_voter_following_organization(
            voter_id, organization_id, organization_we_vote_id)
        if results['follow_organization_found']:
            status = 'FOLLOWING'
            success = True
            follow_organization = results['follow_organization']
            organization_id = follow_organization.organization_id
            organization_we_vote_id = follow_organization.organization_we_vote_id
        else:
            status = results['status']
            success = False

    elif follow_kind == FOLLOW_IGNORE:
        follow_organization_manager = FollowOrganizationManager()
        results = follow_organization_manager.toggle_ignore_voter_following_organization(
            voter_id, organization_id, organization_we_vote_id)
        if results['follow_organization_found']:
            status = 'IGNORING'
            success = True
            follow_organization = results['follow_organization']
            organization_id = follow_organization.organization_id
            organization_we_vote_id = follow_organization.organization_we_vote_id
        else:
            status = results['status']
            success = False
    elif follow_kind == STOP_FOLLOWING:
        follow_organization_manager = FollowOrganizationManager()
        results = follow_organization_manager.toggle_off_voter_following_organization(
            voter_id, organization_id, organization_we_vote_id)
        if results['follow_organization_found']:
            status = 'STOPPED_FOLLOWING'
            success = True
            follow_organization = results['follow_organization']
            organization_id = follow_organization.organization_id
            organization_we_vote_id = follow_organization.organization_we_vote_id
        else:
            status = results['status']
            success = False
    else:
        status = 'INCORRECT_FOLLOW_KIND'
        success = False

    json_data = {
        'status': status,
        'success': success,
        'voter_device_id': voter_device_id,
        'organization_id': organization_id,
        'organization_we_vote_id': organization_we_vote_id,
    }
    return HttpResponse(json.dumps(json_data), content_type='application/json')
Exemplo n.º 59
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')
Exemplo n.º 60
0
def positions_count_for_all_ballot_items_for_api(
        voter_device_id,
        google_civic_election_id=0,
        show_positions_this_voter_follows=True):
    """
    We want to return a JSON file with the a list of the support and oppose counts from the orgs, friends and
    public figures the voter follows
    """
    # Get voter_id from the voter_device_id so we can know whose stars to retrieve
    results = is_voter_device_id_valid(voter_device_id)
    if not results['success']:
        json_data = {
            'status':
            "VALID_VOTER_DEVICE_ID_MISSING-COUNT_FOR_ALL_BALLOT_ITEMS",
            'success': False,
            'google_civic_election_id': google_civic_election_id,
            'ballot_item_list': [],
        }
        return json_data

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

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

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

    position_list_manager = PositionListManager()
    candidate_list_object = CandidateCampaignList()

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

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

    # The list where we capture results
    ballot_item_list_results = []

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

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

    json_data = {
        'success': True,
        'status': "POSITIONS_COUNT_FOR_ALL_BALLOT_ITEMS",
        'google_civic_election_id': google_civic_election_id,
        'ballot_item_list': ballot_item_list_results,
    }
    return json_data