Ejemplo n.º 1
0
def make_folders_public_gdrive(request):
    """
    makes a list of requested google drive folders publicly available
    """
    logger.info(
        f"[resource_management/gdrive_views.py make_folders_public_gdrive()] request.POST={request.POST}")
    (render_value, error_message, context) = verify_access_logged_user_and_create_context(request, TAB_STRING)
    if context is None:  # if the user accessing the page is not authorized to access it
        request.session[ERROR_MESSAGE_KEY] = '{}<br>'.format(error_message)
        return render_value
    gdrive = GoogleDrive(settings.GDRIVE_TOKEN_LOCATION, settings.GDRIVE_ROOT_FOLDER_ID)
    if gdrive.connection_successful:
        post_dict = parser.parse(request.POST.urlencode())
        if there_are_multiple_entries(post_dict, GOOGLE_DRIVE_USERS_FILE_ID_KEY):
            number_of_entries = len(post_dict[GOOGLE_DRIVE_USERS_FILE_ID_KEY])
            logger.info(
                f"[resource_management/gdrive_views.py make_folders_public_gdrive()] {number_of_entries} "
                "total multiple entries detected"
            )
            for index in range(number_of_entries):
                success, result = make_folder_public_gdrive(gdrive, post_dict[GOOGLE_DRIVE_USERS_FILE_ID_KEY][index])
                if not success:
                    if ERROR_MESSAGE_KEY in request.session:
                        request.session[ERROR_MESSAGE_KEY] += '{}<br>'.format(result)
                    else:
                        request.session[ERROR_MESSAGE_KEY] = '{}<br>'.format(result)
        else:
            success, result = make_folder_public_gdrive(gdrive, post_dict[GOOGLE_DRIVE_USERS_FILE_ID_KEY])
            if not success:
                if ERROR_MESSAGE_KEY in request.session:
                    request.session[ERROR_MESSAGE_KEY] += '{}<br>'.format(result)
                else:
                    request.session[ERROR_MESSAGE_KEY] = '{}<br>'.format(result)
    return HttpResponseRedirect(f'{settings.URL_ROOT}resource_management/gdrive/')
Ejemplo n.º 2
0
def validate_new_nominees_for_new_election(nominees):
    """
    takes in a list of nominees to validate

    Keyword Arguments
    nominees -- a dictionary that contains a list of all the nominees to save under specified election

    Return
    Boolean -- true if election was saved and false if it was not
    error_message -- populated if the nominee[s] could not be saved
    """
    nominee_names_so_far = []
    for nominee in nominees:
        if not all_relevant_nominee_keys_exist(nominee):
            return False, f"It seems that one of the nominees is missing one of the following fields:" \
                          f" {ELECTION_JSON_KEY__NOM_NAME}, {ELECTION_JSON_KEY__NOM_POSITION_AND_SPEECH_PAIRINGS}, " \
                          f"{ELECTION_JSON_KEY__NOM_FACEBOOK},  {ELECTION_JSON_KEY__NOM_LINKEDIN}, " \
                          f"{ELECTION_JSON_KEY__NOM_EMAIL}, {ELECTION_JSON_KEY__NOM_DISCORD}"
        if not there_are_multiple_entries(
                nominee, ELECTION_JSON_KEY__NOM_POSITION_AND_SPEECH_PAIRINGS):
            return False, f"It seems that the nominee {nominee[ELECTION_JSON_KEY__NOM_NAME]} " \
                          f"does not have a list of speeches and positions they are running for"
        success, error_message = validate_new_nominee(
            nominee_names_so_far, nominee[ELECTION_JSON_KEY__NOM_NAME],
            nominee[ELECTION_JSON_KEY__NOM_POSITION_AND_SPEECH_PAIRINGS],
            nominee[ELECTION_JSON_KEY__NOM_FACEBOOK],
            nominee[ELECTION_JSON_KEY__NOM_LINKEDIN],
            nominee[ELECTION_JSON_KEY__NOM_EMAIL],
            nominee[ELECTION_JSON_KEY__NOM_DISCORD])
        if not success:
            return False, error_message
    return True, None
Ejemplo n.º 3
0
def process_new_election_information_from_webform(request):
    """Processes the user's input from the WebForm page for creating a new election"""
    logger.info(
        f"[elections/election_management.py process_new_election_information_from_webform()] "
        f"request.POST={request.POST}")
    (render_value, error_message,
     context) = verify_access_logged_user_and_create_context(
         request, TAB_STRING)
    if context is None:
        request.session[ERROR_MESSAGE_KEY] = '{}<br>'.format(error_message)
        return render_value
    updated_elections_information = parser.parse(request.POST.urlencode())
    if ELECTION_TYPE_POST_KEY in updated_elections_information and \
            ELECTION_DATE_POST_KEY in updated_elections_information and \
            ELECTION_TIME_POST_KEY in updated_elections_information and \
            ELECTION_WEBSURVEY_LINK_POST_KEY in updated_elections_information and \
            NOM_NAME_POST_KEY in updated_elections_information and \
            NOM_POSITION_POST_KEY in updated_elections_information and \
            NOM_SPEECH_POST_KEY in updated_elections_information and \
            NOM_FACEBOOK_POST_KEY in updated_elections_information and \
            NOM_LINKEDIN_POST_KEY in updated_elections_information and \
            NOM_EMAIL_POST_KEY in updated_elections_information and \
            NOM_DISCORD_USERNAME_POST_KEY in updated_elections_information:
        logger.info(
            f"[elections/election_management.py "
            f"process_new_election_information_from_webform()] "
            f"updated_elections_information={updated_elections_information}")
        election = _create_new_election_from_webform(
            updated_elections_information)
        if there_are_multiple_entries(updated_elections_information,
                                      NOM_NAME_POST_KEY):
            _save_nominees_for_new_election_from_webform(
                election, updated_elections_information)
        else:
            success, nominee, error_message = _validate_and_return_new_nominee(
                updated_elections_information[NOM_NAME_POST_KEY],
                updated_elections_information[NOM_POSITION_POST_KEY],
                updated_elections_information[NOM_SPEECH_POST_KEY],
                updated_elections_information[NOM_FACEBOOK_POST_KEY],
                updated_elections_information[NOM_LINKEDIN_POST_KEY],
                updated_elections_information[NOM_EMAIL_POST_KEY],
                updated_elections_information[NOM_DISCORD_USERNAME_POST_KEY],
                0)
            if success and nominee is not None:
                nominee.nomination_page = election
                nominee.save()
                logger.info(
                    "[elections/election_management.py save_new_nominee()] saved user "
                    f"full_name={nominee.name} position_index={nominee.position_index}"
                    f" facebook_link={nominee.facebook} linkedin_link={nominee.linked_in} "
                    f"email_address={nominee.email} discord_username={nominee.discord}"
                )
        return HttpResponseRedirect(
            f'{settings.URL_ROOT}elections/{election.slug}/')
    else:
        request.session[ERROR_MESSAGE_KEY] = '{}<br>'.format(
            "Not all necessary fields were detected in your input")
        return render_value
Ejemplo n.º 4
0
def add_users_to_gdrive(request):
    """Takes in the users who need to be given access to the SFU CSSS Google Drive

    """
    logger.info(
        f"[resource_management/gdrive_views.py add_users_to_gdrive()] request.POST={request.POST}"
    )
    (render_value, error_message,
     context) = verify_access_logged_user_and_create_context(
         request, TAB_STRING)
    if context is None:  # if the user accessing the page is not authorized to access it
        request.session[ERROR_MESSAGE_KEY] = '{}<br>'.format(error_message)
        return render_value
    gdrive = GoogleDrive(settings.GDRIVE_TOKEN_LOCATION,
                         settings.GDRIVE_ROOT_FOLDER_ID)
    if gdrive.connection_successful:
        post_dict = parser.parse(request.POST.urlencode())
        if there_are_multiple_entries(post_dict, GOOGLE_DRIVE_USERS_NAME_KEY):
            number_of_entries = len(post_dict[GOOGLE_DRIVE_USERS_NAME_KEY])
            logger.info(
                f"[resource_management/gdrive_views.py add_users_to_gdrive()] {number_of_entries} "
                "total multiple entries detected")
            for index in range(number_of_entries):
                gmail = post_dict[GOOGLE_DRIVE_USERS_GMAIL_KEY][index]
                logger.info(
                    f"[resource_management/gdrive_views.py add_users_to_gdrive()] processing user {gmail}"
                )
                success, name, error_message = add_user_to_gdrive(
                    gdrive, post_dict[GOOGLE_DRIVE_USERS_NAME_KEY][index],
                    post_dict[GOOGLE_DRIVE_USERS_FILE_ID_KEY][index],
                    post_dict[GOOGLE_DRIVE_USERS_GMAIL_KEY][index])
                if not success:
                    if ERROR_MESSAGE_KEY in request.session:
                        request.session[ERROR_MESSAGE_KEY] += '{}<br>'.format(
                            error_message)
                    else:
                        request.session[ERROR_MESSAGE_KEY] = '{}<br>'.format(
                            error_message)
        else:
            logger.info(
                f"[resource_management/gdrive_views.py add_users_to_gdrive()] "
                f"only one user detected: {post_dict[GOOGLE_DRIVE_USERS_GMAIL_KEY]}"
            )
            success, name, error_message = add_user_to_gdrive(
                gdrive, post_dict[GOOGLE_DRIVE_USERS_NAME_KEY],
                post_dict[GOOGLE_DRIVE_USERS_FILE_ID_KEY],
                post_dict[GOOGLE_DRIVE_USERS_GMAIL_KEY])
            if not success:
                request.session[ERROR_MESSAGE_KEY] = '{}<br>'.format(
                    error_message)
    return HttpResponseRedirect(
        f'{settings.URL_ROOT}resource_management/gdrive/')
Ejemplo n.º 5
0
def process_existing_election_information_from_webform(request):
    """Updates the specified election using the WebForm input"""
    logger.info(
        "[elections/election_management.py process_existing_election_information_from_webform()] "
        f"request.POST={request.POST}")
    (render_value, error_message,
     context) = verify_access_logged_user_and_create_context(
         request, TAB_STRING)
    if context is None:
        request.session[ERROR_MESSAGE_KEY] = '{}<br>'.format(error_message)
        return render_value
    updated_elections_information = parser.parse(request.POST.urlencode())
    if ELECTION_TYPE_POST_KEY in updated_elections_information and \
            ELECTION_DATE_POST_KEY in updated_elections_information and \
            ELECTION_TIME_POST_KEY in updated_elections_information and \
            ELECTION_WEBSURVEY_LINK_POST_KEY in updated_elections_information and \
            ELECTION_ID_POST_KEY in updated_elections_information and \
            NOM_NAME_POST_KEY in updated_elections_information and \
            NOM_POSITION_POST_KEY in updated_elections_information and \
            NOM_SPEECH_POST_KEY in updated_elections_information and \
            NOM_FACEBOOK_POST_KEY in updated_elections_information and \
            NOM_LINKEDIN_POST_KEY in updated_elections_information and \
            NOM_EMAIL_POST_KEY in updated_elections_information and \
            NOM_DISCORD_USERNAME_POST_KEY in updated_elections_information:
        logger.info(
            "[elections/election_management.py process_existing_election_information_from_webform()] "
            "creating new election")
        logger.info(
            "[elections/election_management.py process_existing_election_information_from_webform()] "
            f"updated_elections_information={updated_elections_information}")
        nomination_page = _get_existing_election_by_id(
            updated_elections_information[ELECTION_ID_POST_KEY])
        if nomination_page is None:
            request.session[ERROR_MESSAGE_KEY] = '{}<br>'.format(
                f"The Selected election for date {updated_elections_information[ELECTION_DATE_POST_KEY]} "
                "does not exist")
            return render_value
        nom_page = _validate_information_for_existing_election_from_webform_and_return_it(
            nomination_page, updated_elections_information)
        if there_are_multiple_entries(updated_elections_information,
                                      NOM_NAME_POST_KEY):
            _validate_nominees_information_for_existing_election_from_webform_and_return_them(
                nom_page, updated_elections_information)
        else:
            _update_nominee_information_for_existing_election_from_webform(
                nomination_page, updated_elections_information)
        nom_page.save()
        return HttpResponseRedirect(
            f"{settings.URL_ROOT}elections/{nom_page.slug}")
    return HttpResponseRedirect(
        f"{settings.URL_ROOT}elections/select_election_to_update")
Ejemplo n.º 6
0
def extract_valid_officers_positions_selected_for_github_team(post_dict):
    """
    extracts the officer position indices that have been selected to add to a github team

    Keyword Argument
    post_dict -- the dictionary created from the POST object that has the selected position indices
     mapped to the value "github_mapping_selected_officer_position"

    Return
    success - a bool, True if position indices were found
    error_message -- the error message if not successful, otherwise None
    officer_position_indices -- an int list of officer position indices that have been selected, if any were selected
    """
    if not (GITHUB_MAPPING_SELECTED_OFFICER_POSITION_KEY in post_dict):
        error_message = "Did not find any positions that were selected"
        logger.info(
            "[about/position_mapping_helper.py extract_valid_officers_positions_selected_for_github_team()]"
            f" {error_message}")
        return False, error_message, None

    if there_are_multiple_entries(
            post_dict, GITHUB_MAPPING_SELECTED_OFFICER_POSITION_KEY):
        officer_positions = [
            f"{officer_position_index}".strip() for officer_position_index in
            post_dict[GITHUB_MAPPING_SELECTED_OFFICER_POSITION_KEY]
            if len(f"{officer_position_index}".strip()) > 0
        ]
        success = len(officer_positions) > 0
        logger.info(
            "[about/position_mapping_helper.py extract_valid_officers_positions_selected_for_github_team()] found "
            "multiple officer positions. Transformed "
            f"{post_dict[GITHUB_MAPPING_SELECTED_OFFICER_POSITION_KEY]} to {officer_positions}"
            f" which has of {len(officer_positions)}")
    else:
        officer_positions = f"{post_dict[GITHUB_MAPPING_SELECTED_OFFICER_POSITION_KEY]}".strip(
        )
        success = len(officer_positions) > 0
        officer_positions = [officer_positions]
        logger.info(
            "[about/position_mapping_helper.py extract_valid_officers_positions_selected_for_github_team()] found a "
            "single officer position index. Transformed "
            f"{post_dict[GITHUB_MAPPING_SELECTED_OFFICER_POSITION_KEY]} to {officer_positions},"
            f" and has a success of {success}")
    if not success:
        error_message = "No valid officer position indices detected"
        logger.info(
            f"[about/position_mapping_helper.py extract_valid_officers_positions_selected_for_github_team()]"
            f" {error_message}")
        return False, error_message, None

    return True, None, officer_positions
Ejemplo n.º 7
0
def validate_new_nominee(nominee_names_so_far, name,
                         position_names_and_speech_pairings, facebook_link,
                         linkedin_link, email_address, discord_username):
    """
    validates the nominee info to validate it

    Keyword Arguments
    name -- the full name of the nominee
    position_names_and_speech_pairing -- a list of the pairings of the nominee's speeches and position_names
    facebook_link -- the link to the nominee's facebook profile
    linkedin_link -- the link to the nominee's linkedin page
    email_address -- the nominee's email address
    discord_username -- the nominee's discord username

    Return
    Boolean -- indicates whether or not nominee information is valid which happens when any of the
    specified fields are empty
    error_message -- the error message if the nominees had an invalid input
    """
    success, error_message = validate_nominee_obj_info(nominee_names_so_far,
                                                       name, facebook_link,
                                                       linkedin_link,
                                                       email_address,
                                                       discord_username)
    if not success:
        return success, error_message
    specified_position_names = []
    for position_names_and_speech_pairing in position_names_and_speech_pairings:
        if not all_relevant_position_names_and_speech_pairing_keys_exist(
                position_names_and_speech_pairing):
            return False, f"It seems that one of speech/position pairings for nominee" \
                          f" {name} has a missing position name or position speech"
        if not there_are_multiple_entries(
                position_names_and_speech_pairing,
                ELECTION_JSON_KEY__NOM_POSITION_NAMES):
            return False, f"It seems that the nominee {name}" \
                          f" does not have a list of positions they are running for"
        for position_name in position_names_and_speech_pairing[
                ELECTION_JSON_KEY__NOM_POSITION_NAMES]:
            if not validate_position_name(position_name):
                return False, f"Detected invalid position of {position_name} for nominee {name}"
            if position_name in specified_position_names:
                return False, f"the nominee {name} has the position {position_name} specified more than once"
            specified_position_names.append(position_name)
        if not (len(position_names_and_speech_pairing[
                ELECTION_JSON_KEY__NOM_SPEECH]) > 0):
            return False, f"No valid speech detected for nominee" \
                          f" {name}, please set to \"NONE\" if there is no speech"

    return True, None
Ejemplo n.º 8
0
def transform_nominee_webform_to_json(nominee):
    """
    converts the nominee dict from the webform into the form that the JSON also creates as that is the
     one that is more indigestable by the code

    Keyword Arguments:
    nominee -- the dict that contains the nominee info that will be updated
    """
    if ELECTION_JSON_KEY__NOM_POSITION_AND_SPEECH_PAIRINGS in nominee and \
            type(nominee[ELECTION_JSON_KEY__NOM_POSITION_AND_SPEECH_PAIRINGS]) == dict:
        nominee[ELECTION_JSON_KEY__NOM_POSITION_AND_SPEECH_PAIRINGS] = list(
            nominee[ELECTION_JSON_KEY__NOM_POSITION_AND_SPEECH_PAIRINGS].values()
        )
        for position_and_speech_pairing in nominee[ELECTION_JSON_KEY__NOM_POSITION_AND_SPEECH_PAIRINGS]:
            if ELECTION_JSON_KEY__NOM_POSITION_NAMES in position_and_speech_pairing:
                if there_are_multiple_entries(position_and_speech_pairing,
                                              ELECTION_JSON_KEY__NOM_POSITION_NAMES):
                    positions = []
                    for position_info in position_and_speech_pairing[ELECTION_JSON_KEY__NOM_POSITION_NAMES]:
                        position_info = position_info.split("_")
                        if len(position_info) == 2 and f"{position_info[1]}".isdigit():
                            positions.append(
                                {
                                    ELECTION_JSON_KEY__NOM_POSITION_NAME: position_info[0],
                                    ID_KEY: position_info[1]
                                }
                            )
                        else:
                            positions.append(position_info[0])
                    position_and_speech_pairing[ELECTION_JSON_KEY__NOM_POSITION_NAMES] = positions
                else:
                    position_info = position_and_speech_pairing[ELECTION_JSON_KEY__NOM_POSITION_NAMES]
                    position_info = position_info.split("_")
                    if len(position_info) == 2 and f"{position_info[1]}".isdigit():
                        position_and_speech_pairing[ELECTION_JSON_KEY__NOM_POSITION_NAMES] = [
                            {
                                ELECTION_JSON_KEY__NOM_POSITION_NAME: position_info[0],
                                ID_KEY: position_info[1]
                            }
                        ]
                    else:
                        position_and_speech_pairing[ELECTION_JSON_KEY__NOM_POSITION_NAMES] = \
                            [position_info[0]]
            if ID_KEY in position_and_speech_pairing:
                if (
                        position_and_speech_pairing[ID_KEY] == "" or
                        not f"{position_and_speech_pairing[ID_KEY]}".isdigit()
                ):
                    del position_and_speech_pairing[ID_KEY]
Ejemplo n.º 9
0
def validate_access(request):
    """
    takes in the inputs from the user on what resources to validate
    """
    logger.info(f"[administration/resource_views.py validate_access()] request.POST={request.POST}")
    (render_value, error_message, context) = verify_access_logged_user_and_create_context(request, TAB_STRING)
    if context is None:  # if the user accessing the page is not authorized to access it
        request.session[ERROR_MESSAGE_KEY] = '{}<br>'.format(error_message)
        return render_value
    if there_are_multiple_entries(request.POST, RESOURCES_KEY):
        for resource in request.POST[RESOURCES_KEY]:
            determine_resource_to_validate(resource)
    else:
        determine_resource_to_validate(request.POST[RESOURCES_KEY])
    return HttpResponseRedirect(f'{settings.URL_ROOT}resource_management/show_resources_for_validation')
def validate_position_in_pairing(position_ids_so_far,
                                 speech_and_position_pairing,
                                 specified_position_names, election_id, name):
    """
    Ensures that the position is valid

    Keyword Argument
    speech_and_position_pairing -- the dict that contains the list of positions
    specified_position_names -- the position names that have been specified so far
    election_id -- the ID for the election that the position name belongs to
    name -- the name of the nominee that is running for the specified position names

    Return
    Bool -- true or false depending on if the validation of the position and possible ID passed
    error_message -- error message if the validation is False, None otherwise
    """
    if ELECTION_JSON_KEY__NOM_POSITION_NAMES not in speech_and_position_pairing:
        return False, f"positions are not specified for one of the speeches for nominee {name}"
    if not there_are_multiple_entries(speech_and_position_pairing,
                                      ELECTION_JSON_KEY__NOM_POSITION_NAMES):
        return False, f"It seems that the nominee {name} does not have a list of positions " \
                      f"for one of the positions they are running for"
    for position in speech_and_position_pairing[
            ELECTION_JSON_KEY__NOM_POSITION_NAMES]:
        if type(position) is dict:
            if ID_KEY in position:
                success, error_message = validate_id_for_position_pairing(
                    position_ids_so_far, position, election_id)
                if not success:
                    return success, error_message
            if not (ELECTION_JSON_KEY__NOM_POSITION_NAME in position):
                return False, f"No position name[s] found for one of the speeches for nominee {name}"
            position_name = position[ELECTION_JSON_KEY__NOM_POSITION_NAME]
        else:
            position_name = position
        if not validate_position_name(position_name):
            return False, f"Detected invalid position of {position_name} for nominee {name}"
        if position_name in specified_position_names:
            return False, f"the nominee {name} has the position {position_name} specified more than once"
        specified_position_names.append(position_name)
    return True, None
Ejemplo n.º 11
0
def add_non_officer_to_github_team(request):
    """
    takes in the specified user and team from the user and attempts to give them the request github team
    membership
    """
    logger.info(
        f"[resource_management/github_views.py add_non_officer_to_github_team()] request.POST={request.POST}"
    )
    (render_value, error_message,
     context) = verify_access_logged_user_and_create_context(
         request, TAB_STRING)
    if context is None:  # if the user accessing the page is not authorized to access it
        request.session[ERROR_MESSAGE_KEY] = '{}<br>'.format(error_message)
        return render_value
    github = GitHubAPI(settings.GITHUB_ACCESS_TOKEN)
    if github.connection_successful:
        post_dict = parser.parse(request.POST.urlencode())
        if there_are_multiple_entries(post_dict, GITHUB_USERNAME_KEY):

            number_of_entries = len(post_dict[GITHUB_USERNAME_KEY])
            logger.info(
                f"[resource_management/github_views.py add_non_officer_to_github_team()] "
                f"{number_of_entries} multiple "
                f"entries detected")
            for index in range(number_of_entries):
                team_name = post_dict[GITHUB_TEAM_KEY][index]
                user_name = post_dict[GITHUB_USERNAME_KEY][index]
                name = post_dict[LEGAL_NAME_KEY][index]
                logger.info(
                    f"[resource_management/github_views.py add_non_officer_to_github_team()] "
                    f"adding user \"{name}\" with github username \"{user_name}\" to team \"{team_name}\""
                )
                success, error_message = github.validate_user(user_name)
                if not success:
                    if ERROR_MESSAGES_KEY in request.session:
                        request.session[ERROR_MESSAGES_KEY] += '{}<br>'.format(
                            error_message)
                    else:
                        request.session[ERROR_MESSAGES_KEY] = '{}<br>'.format(
                            error_message)
                    continue
                github.create_team(team_name)
                success, message = github.add_users_to_a_team([user_name],
                                                              team_name)
                if not success:
                    if ERROR_MESSAGES_KEY in request.session:
                        request.session[ERROR_MESSAGES_KEY] += '{}<br>'.format(
                            message)
                    else:
                        request.session[ERROR_MESSAGES_KEY] = '{}<br>'.format(
                            message)
                    continue
                NonOfficerGithubMember(team_name=team_name,
                                       username=user_name,
                                       legal_name=name).save()
        else:
            logger.info(
                "[resource_management/github_views.py add_non_officer_to_github_team()] "
                f"only one user detected: {post_dict[GITHUB_USERNAME_KEY]}")
            team_name = post_dict[GITHUB_TEAM_KEY]
            user_name = post_dict[GITHUB_USERNAME_KEY]
            name = post_dict[LEGAL_NAME_KEY]
            logger.info(
                f"[resource_management/github_views.py add_non_officer_to_github_team()] "
                f"adding user \"{name}\" with github username \"{user_name}\" to team \"{team_name}\""
            )
            success, error_message = github.validate_user(user_name)
            if not success:
                if ERROR_MESSAGES_KEY in request.session:
                    request.session[ERROR_MESSAGES_KEY] += '{}<br>'.format(
                        error_message)
                else:
                    request.session[ERROR_MESSAGES_KEY] = '{}<br>'.format(
                        error_message)
                return HttpResponseRedirect(
                    f'{settings.URL_ROOT}resource_management/github')
            github.create_team(team_name)
            success, message = github.add_users_to_a_team([user_name],
                                                          team_name)
            if not success:
                if ERROR_MESSAGES_KEY in request.session:
                    request.session[ERROR_MESSAGES_KEY] += '{}<br>'.format(
                        message)
                else:
                    request.session[ERROR_MESSAGES_KEY] = '{}<br>'.format(
                        message)
                return HttpResponseRedirect(
                    f'{settings.URL_ROOT}resource_management/github')
            NonOfficerGithubMember(team_name=team_name,
                                   username=user_name,
                                   legal_name=name).save()
    return HttpResponseRedirect(
        f'{settings.URL_ROOT}resource_management/github')
def transform_webform_to_json(election_dict):
    """
    Converts the given election_dict from webform into the same format that the JSON pages return

    Keyword Argument
    election_dict -- the dictionary that the webform creates

    Return
    new_election_dict -- the dictionary format that the JSON pages create
    """
    logger.info(
        "[elections/transform_webform_to_json.py transform_webform_to_json()] transforming"
    )
    logger.info(json.dumps(election_dict, indent=3))
    new_election_dict = {}
    if ELECTION_JSON_KEY__NOMINEES in election_dict and type(
            election_dict[ELECTION_JSON_KEY__NOMINEES]) == dict:
        new_election_dict[ELECTION_JSON_KEY__NOMINEES] = list(
            election_dict[ELECTION_JSON_KEY__NOMINEES].values())
        for nominee in new_election_dict[ELECTION_JSON_KEY__NOMINEES]:
            if verify_that_position_and_speech_pairing_dict_is_in_nominee_dict(
                    nominee):
                nominee[
                    ELECTION_JSON_KEY__NOM_POSITION_AND_SPEECH_PAIRINGS] = list(
                        nominee[
                            ELECTION_JSON_KEY__NOM_POSITION_AND_SPEECH_PAIRINGS]
                        .values())
                for position_and_speech_pairing in nominee[
                        ELECTION_JSON_KEY__NOM_POSITION_AND_SPEECH_PAIRINGS]:
                    if ELECTION_JSON_KEY__NOM_POSITION_NAMES in position_and_speech_pairing:
                        if there_are_multiple_entries(
                                position_and_speech_pairing,
                                ELECTION_JSON_KEY__NOM_POSITION_NAMES):
                            positions = []
                            for position_info in position_and_speech_pairing[
                                    ELECTION_JSON_KEY__NOM_POSITION_NAMES]:
                                position_info = position_info.split("_")
                                if len(
                                        position_info
                                ) == 2 and f"{position_info[1]}".isdigit():
                                    positions.append({
                                        ELECTION_JSON_KEY__NOM_POSITION_NAME:
                                        position_info[0],
                                        ID_KEY:
                                        position_info[1]
                                    })
                                else:
                                    positions.append(position_info[0])
                            position_and_speech_pairing[
                                ELECTION_JSON_KEY__NOM_POSITION_NAMES] = positions
                        else:
                            position_info = position_and_speech_pairing[
                                ELECTION_JSON_KEY__NOM_POSITION_NAMES]
                            position_info = position_info.split("_")
                            if len(position_info
                                   ) == 2 and f"{position_info[1]}".isdigit():
                                position_and_speech_pairing[
                                    ELECTION_JSON_KEY__NOM_POSITION_NAMES] = [{
                                        ELECTION_JSON_KEY__NOM_POSITION_NAME:
                                        position_info[0],
                                        ID_KEY:
                                        position_info[1]
                                    }]
                            else:
                                position_and_speech_pairing[ELECTION_JSON_KEY__NOM_POSITION_NAMES] = \
                                    [position_info[0]]
                    if ID_KEY in position_and_speech_pairing:
                        if position_and_speech_pairing[ID_KEY] == "" or \
                                not f"{position_and_speech_pairing[ID_KEY]}".isdigit():
                            del position_and_speech_pairing[ID_KEY]
    if ELECTION_JSON_KEY__DATE in election_dict:
        new_election_dict[ELECTION_JSON_KEY__DATE] = election_dict[
            ELECTION_JSON_KEY__DATE]
    if ELECTION_JSON_WEBFORM_KEY__TIME in election_dict:
        new_election_dict[ELECTION_JSON_WEBFORM_KEY__TIME] = election_dict[
            ELECTION_JSON_WEBFORM_KEY__TIME]
    if ELECTION_JSON_KEY__ELECTION_TYPE in election_dict:
        new_election_dict[ELECTION_JSON_KEY__ELECTION_TYPE] = election_dict[
            ELECTION_JSON_KEY__ELECTION_TYPE]
    if ELECTION_JSON_KEY__WEBSURVEY in election_dict:
        new_election_dict[ELECTION_JSON_KEY__WEBSURVEY] = election_dict[
            ELECTION_JSON_KEY__WEBSURVEY]
    if ELECTION_ID in election_dict:
        new_election_dict[ELECTION_ID] = election_dict[ELECTION_ID]
    logger.info(
        "[elections/transform_webform_to_json.py transform_webform_to_json()] to"
    )
    logger.info(json.dumps(new_election_dict, indent=3))
    return new_election_dict
Ejemplo n.º 13
0
def _add_new_position_mapping(post_dict):
    """
    Adds a new officer position mapping

    Keyword Argument
    post_dict -- request.POST in dictionary object

    Return
    success -- bool that is True or false
    error_message -- an error_message if the specified position index and position name are already used
    unsaved_position_mappings -- a dict that contains the unsaved position index
     and position names if one of them was invalid
    """
    error_messages = []
    if there_are_multiple_entries(post_dict, POSITION_NAME_KEY):
        logger.info(
            "[about/input_new_officer_positions.py _add_new_position_mapping()] it appears "
            "that the user wants to create multiple new officers")
        error_detected = False
        unsaved_position_mappings = [
        ]  # used to display all the submitted position if one of them had an
        # error which causes none of them to be saved

        # saves the position and position indexes checked so far so that the validator can check the
        # given position and its index against all in the database and the previous checked
        # positions and their indices
        submitted_position_names = []
        submitted_position_indices = []
        number_of_entries = len(post_dict[POSITION_NAME_KEY])
        for index in range(number_of_entries):
            position_name = post_dict[POSITION_NAME_KEY][index]
            position_index = post_dict[POSITION_INDEX_KEY][index]
            position_email = post_dict[POSITION_EMAIL_KEY][index]
            elected_via_election_officer = post_dict[
                ELECTED_VIA_ELECTION_OFFICER_KEY][index]
            unsaved_position_mappings.append({
                POSITION_NAME_KEY:
                position_name,
                POSITION_INDEX_KEY:
                position_index,
                POSITION_EMAIL_KEY:
                position_email,
                ELECTED_VIA_ELECTION_OFFICER_KEY:
                elected_via_election_officer == 'True'
            })
            success, error_message = _validate_position_mappings(
                position_index,
                position_name,
                elected_via_election_officer,
                submitted_position_names=submitted_position_names,
                submitted_position_indices=submitted_position_indices)
            submitted_position_names.append(position_name)
            submitted_position_indices.append(position_index)
            if not success:
                error_messages.append(f"{error_message}")
                logger.info(
                    "[about/input_new_officer_positions.py _add_new_position_mapping()] "
                    f"unable to validate the new position {position_name} due to {error_message}"
                )
                error_detected = True
        if error_detected:
            return False, error_messages, unsaved_position_mappings
        else:
            logger.info(
                "[about/input_new_officer_positions.py _add_new_position_mapping()] "
                "all new positions passed validation")
            for index in range(number_of_entries):
                OfficerEmailListAndPositionMapping(
                    position_name=post_dict[POSITION_NAME_KEY][index],
                    position_index=post_dict[POSITION_INDEX_KEY][index],
                    email=post_dict[POSITION_EMAIL_KEY][index],
                    elected_via_election_officer=post_dict[
                        ELECTED_VIA_ELECTION_OFFICER_KEY][index] ==
                    'True').save()
    else:
        success, error_message = \
            _validate_position_mappings(post_dict[POSITION_INDEX_KEY], post_dict[POSITION_NAME_KEY],
                                        post_dict[ELECTED_VIA_ELECTION_OFFICER_KEY])
        if success:
            logger.info(
                f"[about/input_new_officer_positions.py _add_new_position_mapping()] "
                f"new position {post_dict[POSITION_NAME_KEY]} passed validation"
            )

            OfficerEmailListAndPositionMapping(
                position_name=post_dict[POSITION_NAME_KEY],
                position_index=post_dict[POSITION_INDEX_KEY],
                email=post_dict[POSITION_EMAIL_KEY],
                elected_via_election_officer=post_dict[
                    ELECTED_VIA_ELECTION_OFFICER_KEY] == 'True').save()
        else:
            logger.info(
                f"[about/input_new_officer_positions.py _add_new_position_mapping()] unable to "
                f"save new position {post_dict[POSITION_NAME_KEY]} due to error {error_message}"
            )
            unsaved_position_mappings = [{
                POSITION_NAME_KEY:
                post_dict[POSITION_NAME_KEY],
                POSITION_INDEX_KEY:
                post_dict[POSITION_INDEX_KEY],
                POSITION_EMAIL_KEY:
                post_dict[POSITION_EMAIL_KEY],
                ELECTED_VIA_ELECTION_OFFICER_KEY:
                post_dict[ELECTED_VIA_ELECTION_OFFICER_KEY] == 'True'
            }]
            error_messages.append(error_message)
            return False, error_messages, unsaved_position_mappings
    return True, error_messages, None