def unregister_member_from_tournament_play(request):
    """
    POST -- Given a member_id, mark member as not participating in tournament
    :param request:
    :return:
    """
    post_dict = dict(request.POST.items())
    validate_keys(["member_id"], post_dict)
    member_id = post_dict["member_id"]

    # Check if member is even participating in a tournament in the first place
    rawquery = Member.objects.raw(
        "SELECT * FROM api_member WHERE interested_ptr_id=%s", [member_id])
    if len(list(rawquery)) > 0:
        member = rawquery[0]
        if member.in_tournament == 0:
            return http_response(
                message="Member was not in a tournament to begin with",
                code=400)
    else:
        return http_response(message="Specified member does not exist",
                             code=400)

    return run_connection(
        "UPDATE api_member SET in_tournament=0 WHERE interested_ptr_id=%s",
        member_id)
示例#2
0
def campaignRouter(request):
    """
    POST -- Edits the corresponding campaign
        Required Keys: id
        Optional Keys: job, email
    DELETE -- Deletes a campaign
        Required Keys: id
    :param request:
    :return:
    """

    if request.method == "POST":
        dict_post = dict(request.POST.items())
        validate_keys(["id", "job", "pitch", "email"], dict_post)
        return edit_campaign(dict_post)
    elif request.method == "DELETE":
        # django doesn't have anything that handles delete so...
        dict_delete = json.loads(request.body.decode('utf8').replace("'", '"'))
        print(dict_delete)
        if not validate_keys(["id", "job", "email"], dict_delete):
            HttpResponse(json.dumps({'message': 'Missing parameters'}),
                         content_type='application/json',
                         status=400)
        print(dict_delete)
        return delete_campaign(dict_delete["id"], dict_delete["email"],
                               dict_delete["job"])
def get_bracket_node(request):
    dict_get = dict(request.GET.items())
    validate_keys(['tournament_id', 'level', 'index'], dict_get)

    tournament_id = int(dict_get['tournament_id'])
    level = int(dict_get['level'])
    index = int(dict_get['index'])

    nodes = BracketNode.objects.raw(
        "SELECT * FROM api_bracketnode WHERE tournament_id = %s AND sibling_index = %s AND level = %s",
        [tournament_id, index, level])
    if len(list(nodes)) > 0:
        node = nodes[0]
        node_dict = serializeModel(node)
        matches_array = []
        # Get the matches associated with this bracket node
        node_matches = Match.objects.raw(
            "SELECT * FROM api_match WHERE bracket_node_id=%s", [node.id])
        if len(list(node_matches)) > 0:
            for node_match in list(node_matches):
                node_match_dict = serializeModel(node_match)
                matches_array.append(node_match_dict)
        node_dict["matches"] = matches_array
        print("BRACKET NODE DICT: " + str(node_dict))
        context = {'bracket_node': node_dict}
        return http_response(context)
    else:
        return http_response(message='No such bracket node', code=400)
def register_member_for_tournament_play(request):
    """
    POST -- Given a member_id, mark the member as participating in a tournament.
    :param request:
    :return:
    """
    post_dict = dict(request.POST.items())
    validate_keys(["member_id"], post_dict)
    member_id = post_dict["member_id"]

    # Check if member is already participating in a tournament
    rawquery = Member.objects.raw(
        "SELECT * FROM api_member WHERE interested_ptr_id=%s", [member_id])
    if len(list(rawquery)) > 0:
        member = rawquery[0]
        if member.in_tournament == 1:
            return http_response(message="Member is already in a tournament",
                                 code=400)
    else:
        return http_response(message="Specified member does not exist",
                             code=400)

    return run_connection(
        "UPDATE api_member SET in_tournament=1 WHERE interested_ptr_id=%s",
        member_id)
def create_queue(request):
    """
    POST -- need the queue_type key (CASUAL, RANKED, KOTH)
    :param request:
    :return:
    """

    if request.method == "POST":
        dict_post = dict(request.POST.items())
        validate_keys('queue_type', dict_post)
        return call_create_queue(dict_post["queue_type"])
def settingsBoardMemberRouter(request):
    """
    Allow board members to get/edit list of boardmembers.
    Expect input/output dictionary to be of the form
    {
        'boardmembers': [
            {
                'member_id': _
                'first_name': _
                'last_name': _
                'email': _
                'job': _
            },
            ...
        ]
    }
    :param request:
    :return:
    """

    session_id = id_for_member(request.user.email)

    if request.method == "GET":
        return boardmembers_config()
    elif request.method == "POST":
        # Can only change their jobs
        json_post_data = json.loads(request.body)
        if not validate_keys(["boardmembers"], json_post_data):
            HttpResponse(json.dumps(
                {'message': 'Missing parameters member_id or job'}),
                         content_type='application/json',
                         status=400)
        return boardmembers_config_edit(json_post_data)
def settingsRouter(request):
    """
    Allow members to get and edit their own settings.
    Expect input/output dictionary to be of the form
    {
        'private': _,
        'bio': _
    }
    :param request:
    :return:
    """

    session_id = id_for_member(request.user.email)
    if request.method == "GET":
        if session_id is None:
            return HttpResponse(json.dumps({"message": "No such member"}),
                                content_type="application/json")
        return member_config(session_id)
    elif request.method == "POST":
        dict_post = dict(request.POST.items())
        if not validate_keys(["private", "bio"], dict_post):
            HttpResponse(json.dumps(
                {'message': 'Missing parameters private or bio'}),
                         content_type='application/json',
                         status=400)
        if session_id is None:
            return HttpResponse(json.dumps({"message": "No such member"}),
                                content_type="application/json")
        return member_config_edit(session_id, dict_post)
def settingsQueueRouter(request):
    """
    Allows boardmembers to get all the current queues in db or add more queue types
    Expect the input/output dictionary to be of the form
    {
        'queues': [
            {
                'queue_id': _,
                'queue_type': _
            },
            ...
        ]
    }
    :param request:
    :return:
    """
    session_id = id_for_member(request.user.email)
    if not is_board_member(session_id):
        return HttpResponse(json.dumps(
            {"message": "You are not a board member."}),
                            content_type="application/json")
    if request.method == "GET":
        return get_all_queues_formatted()
    elif request.method == "POST":
        # Used to add more queue types to the db
        # dict_post = dict(request.POST.items()) <- For some reason, can't read POST dictionary from PostMan like this
        json_post_data = json.loads(request.body)
        if not validate_keys('queues', json_post_data):
            HttpResponse(json.dumps({'message': 'Missing parameter queues'}),
                         content_type='application/json',
                         status=400)
        return add_queues_formatted(json_post_data)
    elif request.method == "DELETE":
        # The input dictionary should hold information ONLY for the queues to be deleted
        json_delete_data = json.loads(request.body)
        if not validate_keys('queues', json_delete_data):
            HttpResponse(json.dumps({'message': 'Missing parameter queues'}),
                         content_type='application/json',
                         status=400)
        return delete_queues_formatted(json_delete_data)
def settingsSchedulesRouter(request):
    """
    POST/DELETE -- Allows board members to get the whole schedule and add to/edit/delete from schedule
    Expect input/output dictionary to be of the form
    {
        'schedule': [
            {
                'date': _,
                'number_of_courts': _
            },
            ...
        ]
    }
    :param request:
    :return:
    """
    session_id = id_for_member(request.user.email)
    if not is_board_member(session_id):
        return HttpResponse(json.dumps(
            {"message": "You are not a board member."}),
                            content_type="application/json")
    if request.method == "POST":
        # INSERT or UPDATE
        # dict_post = dict(request.POST.items())
        print(request.body)
        json_post_data = json.loads(request.body.decode('utf8'))
        if not validate_keys(["schedule"], json_post_data):
            HttpResponse(json.dumps({'message': 'Missing parameter schedule'}),
                         content_type='application/json',
                         status=400)
        return addto_edit_schedule(json_post_data)
    elif request.method == "DELETE":
        # The provided dictionary should ONLY contain information on the entries that are
        # intended to be deleted.
        dict_delete = json.loads(request.body.decode('utf8').replace("'", '"'))
        if not validate_keys(["schedule"], dict_delete):
            HttpResponse(json.dumps({'message': 'Missing parameter schedule'}),
                         content_type='application/json',
                         status=400)
        return delete_multiple_from_schedule(dict_delete)
def view_member_profile(request):
    """
        input:
        {
            "id": int # Needs to be a valid member
        }
    """
    dict_get = dict(request.GET.items())
    if not validate_keys(['id'] in dict_get):
        return http_response(message='Missing id', code=400)

    member_id = int(dict_get['id'])
    return member_profile(member_id)
示例#11
0
def campaignFindRouter(request):
    """
        I should probably change this later so it's a get request but no one seems to be using this route anyway so
        POST -- Takes json data with campaign id, job, and email to find a corresponding campaign
    :param request:
    :return:
    """
    dict_post = dict(request.POST.items())
    if not validate_keys(["id", "job", "email"], dict_post):
        HttpResponse(json.dumps({'message': 'Missing parameters'}),
                     content_type='application/json',
                     status=400)
    return get_campaign(dict_post["id"], dict_post["email"], dict_post["job"])
def add_queues_formatted(dict_post):
    """
    POST
    :return:
    """
    queues = dict_post['queues']
    for q in queues:
        if validate_keys(['queue_type'], q):
            queue_type = q['queue_type']
            add_queue(queue_type)
    return HttpResponse(json.dumps(
        {"message": "Successfully added queue type."}),
                        content_type="application/json")
def delete_queues_formatted(dict_delete):
    """
    DELETE
    :param dict_delete:
    :return:
    """
    queues = dict_delete['queues']
    for q in queues:
        if validate_keys(['queue_id', 'queue_type'], q):
            queue_type = q['queue_type']
            delete_queue(queue_type)
    return HttpResponse(json.dumps(
        {"message": "Successfully deleted queue type."}),
                        content_type="application/json")
def finish_tournament_router(request):
    """
        Finish a tournament on this date.
    Expect the dictionary to be
    {
        "tournament_id": _
    }
    :param request:
    :return:
    """
    post_dict = dict(request.POST.items())
    if not validate_keys(["tournament_id"], post_dict):
        http_response(message="Missing parameter tournament_id", code=400)
    return finish_tournament(post_dict)
def delete_member(request):
    """
    DELETE -- (labeled as POST because Django doesn't handle DELETE)
        Delete ONE member from the db completely
        Example: {"member_id": 39}
    :param request:
    :return:
    """
    # Here, the dictionary should be {"member_id": _}
    post_dict = dict(request.POST.items())
    if not validate_keys(["member_id"], post_dict):
        HttpResponse(json.dumps({'message': 'Missing parameter member_id'}),
                     content_type='application/json',
                     status=400)
    return delete_club_member(post_dict)
def add_match(request):
    """
    Start a NEW match and associate it with the specified bracket node.
    'team_A' and 'team_B' are both strings of comma-separated member_id's
    Ex: ("2,3")
    :param request:
    :return:
    """
    post_dict = dict(request.POST.items())
    validate_keys(['bracket_node_id', 'team_A', 'team_B'], post_dict)

    bracket_node_id = int(post_dict['bracket_node_id'])
    team_A_str = post_dict['team_A']
    team_A = team_A_str.split(',')
    team_B_str = post_dict['team_B']
    team_B = team_B_str.split(',')

    # Assert bracket node exists
    nodes = BracketNode.objects.raw(
        "SELECT * FROM api_bracketnode WHERE id=%s", [bracket_node_id])
    if len(list(nodes)) <= 0:
        return http_response(message='Invalid bracket_node_id', code=400)

    return add_match_call(bracket_node_id, team_A, team_B)
def settingsCourtRouter(request):
    """
    Allows board members to get the info on all courts and add/edit courts.
    Expect the input/output dictionary to be of the form
    {
        'courts': [
            {
                'court_id': _,
                'queue_id': _
            },
            ...
        ]
        'court_types': [str, ...]
    }
    :param request:
    :return:
    """
    session_id = id_for_member(request.user.email)
    if request.method == "GET":
        return get_all_courts_formmated()
    elif request.method == "POST":
        # Used to add new courts OR change the queue types for the courts
        json_post_data = request.POST
        if not validate_keys('courts', json_post_data):
            HttpResponse(json.dumps({'message': 'Missing parameter courts'}),
                         content_type='application/json',
                         status=400)
        return addto_edit_courts_formatted(json_post_data)
    elif request.method == "DELETE":
        # The input dictionary should hold information ONLY for the courts to be deleted
        json_delete_data = json.loads(request.body.decode('utf8'))
        if not validate_keys('courts', json_delete_data):
            HttpResponse(json.dumps({'message': 'Missing parameter courts'}),
                         content_type='application/json',
                         status=400)
        return delete_courts_formatted(json_delete_data)
def delete_courts_formatted(dict_delete):
    """
    DELETE
    :param dict_delete:
    :return:
    """
    courts = dict_delete['courts']
    print(courts)
    for c in courts:
        if validate_keys(['court_id'], c):
            court_id = c['court_id']
            delete_court(court_id)
    return HttpResponse(json.dumps(
        {"message": "Successfully deleted specified courts."}),
                        content_type="application/json")
示例#19
0
def create_campaign(request):
    """
    POST -- Takes json data with campaign job, pitch, and campaigner id to create a new campaign
        Required Keys: job, pitch, id
    :param request:
    :return:
    """
    dict_post = dict(request.POST.items())
    jobKey = "job"
    pitchKey = "pitch"
    campaignerKey = "campaigner_id"

    keys = [jobKey, pitchKey, campaignerKey]

    if not validate_keys(keys, dict_post):
        return http_response({}, message="Missing parameters", code=400)

    job = dict_post[jobKey]
    pitch = dict_post[pitchKey]
    campaigner_id = dict_post[campaignerKey]

    campaigner_query = """
    SELECT * FROM api_interested WHERE api_interested.id = %s AND EXISTS(SELECT * FROM api_member WHERE interested_ptr_id = id)
    """
    interesteds = Interested.objects.raw(campaigner_query, [campaigner_id])

    if len(list(interesteds)) <= 0:
        return http_response({},
                             message="No such member found",
                             status="down",
                             code=400)

    interested = interesteds[0]

    curr_election_dict = get_current_election()
    curr_election = curr_election_dict['election']
    if curr_election is not None:
        return run_connection(
            "INSERT INTO api_campaign (job, pitch, election_id, campaigner_id) VALUES\
                                    (%s, %s, %s, %s)", job, pitch,
            curr_election.id, interested.id)
    else:
        return http_response({},
                             message="There is no election to campaign for!",
                             status="down",
                             code=400)
示例#20
0
def mail(request):
    if request.method == "GET":
        mailing_lists = [
            {
                "name": "Interested Members",
                "key": interested_mail_key
            },
            {
                "name": "Current Member",
                "key": member_mail_key
            },
            {
                "name": "Board Member",
                "key": board_mail_key
            }
        ]
        return HttpResponse(json.dumps(mailing_lists), content_type="application/json")
    elif request.method == "POST":
        """
            Expecting
            {
                "mailing_list": str
                "title": str
                "body": str
            }
        """
        list_mail_key = "mailing_list"
        title_mail_key = "title"
        body_mail_key = "body"
        keys = [list_mail_key, title_mail_key, body_mail_key]

        if not validate_keys(keys, request.POST):
            return HttpResponse("Missing key, one of %s".format(','.join(keys)), status=400)

        emails = emails_for_key(request.POST[list_mail_key])
        subject = request.POST[title_mail_key]
        message = request.POST[body_mail_key]
        send_mail(
            subject,
            message,
            BFF_EMAIL,
            emails,
            fail_silently=False,
        )
示例#21
0
def cast_vote(request):
    """
    POST -- Casts/updates a vote for the current election
        Required Keys: campaign_id
    :param request:
    :param job:
    :return:
    """
    voter_id = get_member_id_from_email(request.user.email)

    dict_post = dict(request.POST.items())
    if not validate_keys(["campaign_id"], dict_post):
        return http_response(message='Missing campaign_id', code=400)

    campaign_id = int(dict_post['campaign_id'])

    campaign_query = Campaign.objects.raw(
        "SELECT * FROM api_campaign WHERE id = %s", [campaign_id])
    if len(list(campaign_query)) == 0:
        return http_response(message='Campaign does not exist')

    campaign = campaign_query[0]

    this_job = campaign.job

    my_votes = Vote.objects.raw("SELECT * FROM api_vote WHERE voter_id = %s",
                                [voter_id])

    for vote in my_votes:
        if vote.campaign.job == this_job:
            # Already voted for a campaign with the same job, must update
            response = run_connection(
                "UPDATE api_vote SET campaign_id = %s WHERE voter_id = %s",
                campaign.id, voter_id)
            return response

    # add the vote
    query = """
            INSERT INTO api_vote(voter_id, campaign_id) VALUES(%s, %s)
            """
    response = run_connection(query, voter_id, campaign.id)
    return response
def create_tournament_router(request):
    """
    POST function to create a new tournament entry.
    Expect the input dictionary to be
    {
        "num_players": _
        "tournament_type": _ (DOUBLES, SINGLES)
        "elimination_type": _ (SINGLE)
    }
    :param request:
    :return:
    """
    post_dict = dict(request.POST.items())
    if not validate_keys(
        ["num_players", "tournament_type", "elimination_type"], post_dict):
        HttpResponse(json.dumps(
            {'message': 'Missing parameters num_players or tournament_type'}),
                     content_type='application/json',
                     status=400)
    return create_tournament(post_dict)
示例#23
0
def add_member(request):
    """
        POST -- Adds a member to the logged in user's party
            Required Keys: id, delete
            Optional Keys: queue_id, add_members, remove_members
                NOTE: `add_members` and `remove_members` are comma separated lists of
                    member id's to add or remove from the party respectively

        :param request:
        :return:
    """

    post_dict = dict(request.POST.items())
    if not validate_keys(['member_id'], post_dict):
        return http_response({}, message="Keys not found", code=400)

    member_id = post_dict['member_id']
    my_id = id_for_member(request.user.email)
    party = party_for_member(my_id)
    party_id = party.id

    rawquery = Member.objects.raw(
        "SELECT * FROM api_member WHERE interested_ptr_id=%s AND party_id NOT NULL",
        [member_id])
    member_is_in_party = len(list(rawquery)) > 0
    if member_is_in_party:
        return http_response(message="Member is already in a party", code=400)

    members = Member.objects.raw(
        "SELECT * FROM api_member WHERE party_id NOT NULL AND party_id = %s AND interested_ptr_id = %s",
        [party_id, member_id])
    if len(list(members)) > 0:
        return http_response(message="Member is already part of party")

    response = run_connection(
        "UPDATE api_member SET party_id = %s WHERE interested_ptr_id = %s",
        party_id, member_id)
    return response
示例#24
0
def join_party(request):
    session_email = request.user.username
    if not request.user.is_authenticated:
        return http_response({}, message="You are not logged in", code=302)

    try:
        user = Member.objects.get(email=session_email)
    except Member.DoesNotExist:
        return http_response(
            {}, message="You do not have the required permissions", code=403)

    member_id = user.id
    curr_party_id = user.party_id
    if curr_party_id is not None:
        return http_response(message="You are already in a party", code=400)

    post_dict = dict(request.POST.items())
    if not validate_keys(['party_id'], post_dict):
        return http_response({}, message="Keys not found", code=400)
    party_id = post_dict["party_id"]

    return run_connection(
        "UPDATE api_member SET party_id=%s WHERE interested_ptr_id=%s",
        party_id, member_id)
def settingsAllMembersRouter(request):
    """
    Allows boardmembers to get information on all the people in the club (interested, members, boardmembers)
    AND promote/demote people
    Expect GET OUTPUT dictionary to be of the form
    {
        'members': [
            {
                'member_id': _, (Used for promoting/demoting/deletion)
                'first_name': _,
                'last_name': _,
                'email': _,
                'status': _ (Interested, Member, BoardMember)
            },
            ...
        ]
    }
    Expect POST INPUT dictionary
        Example: {"member_id": 39, "status": "Interested"}

    Look at POST branch below for specific input dictionaries
    :param request:
    :return:
    """

    if request.method == "GET":
        return get_all_club_members()
    elif request.method == "POST":
        # Promote/demote ONE member (Interested, Member, BoardMember)
        # {"member_id": _, "status": _}
        # Going to BoardMember, the default 'job'='OFFICER'
        post_dict = dict(request.POST)
        print(post_dict)
        if not validate_keys(["member_id", "status"], post_dict):
            return http_response({}, message="Keys not found", code=400)
        return update_club_member_status(post_dict)
示例#26
0
def create_party(request):
    """
    POST -- Creates a party. Anyone with Member permission or above can do this.
        Required Keys: queue_type, member_ids
            NOTE: member_ids is a comma separated list of ids to add to the party (EXCLUDES the user themselves)
    :param request:
    :return:
    """
    post_dict = dict(request.POST.items())
    print(post_dict)
    if not validate_keys(['queue_id', 'member_ids'], post_dict):
        return http_response({}, message="Keys not found", code=400)

    queue_id = post_dict['queue_id']
    queues = Queue.objects.raw("SELECT * FROM api_queue WHERE id = %s",
                               [queue_id])
    if len(list(queues)) <= 0:
        return http_response(message='Queue does not exist', code=400)

    queue = queues[0]

    queue_id = queue.id
    user_id = id_for_member(request.user.email)
    member_ids = post_dict['member_ids']
    member_ids = member_ids.split(",")  # list of ids to add to the party
    if user_id not in member_ids:
        member_ids.append(
            str(user_id))  # add self to the party, if not already specified

    # Check if the user is already in a party
    rawquery = Member.objects.raw(
        "SELECT * FROM api_member WHERE interested_ptr_id=%s AND party_id NOT NULL",
        [user_id])
    member_is_in_party = len(list(rawquery)) > 0
    if member_is_in_party:
        return http_response(message="User is already in a party", code=400)

    parties_with_max_id = Party.objects.raw(
        "SELECT * FROM api_party WHERE id = (SELECT MAX(id) FROM api_party)")
    if len(list(parties_with_max_id)) == 0:
        new_id = 0
    else:
        party_with_max_id = parties_with_max_id[0]
        new_id = party_with_max_id.id + 1

    # Check if there are other parties on this queue. If not, for each court associated with
    # this queue, check if there are matches with NULL endDateTime with the court id. If for a court_id, there
    # are no matches with a NULL endDateTime, that means there is no ongoing match on that court. In that case,
    # skip creating a party and just throw this group into a match on that empty court.
    open_court_id = queue_is_empty_with_open_court(queue_id)
    if open_court_id:
        # Create match
        # Randomize the member_id's into two teams (preferably equal numbers on each team)
        a_players = []
        b_players = []
        num_players = len(member_ids)
        for member_id in member_ids:
            choice = random.choice([True, False])
            if choice and len(a_players) < num_players / 2:
                # Add to a_players, if half of players aren't already on there
                a_players.append(member_id)
            else:
                if len(b_players) < num_players / 2:
                    b_players.append(member_id)
                else:
                    a_players.append(member_id)

        create_match(a_players=a_players,
                     b_players=b_players,
                     court_id=open_court_id)
        return http_response(message="OK", code=200)
    else:
        # Create party on the queue
        response = run_connection(
            "INSERT INTO api_party(id, queue_id) VALUES (%s, %s)", new_id,
            queue_id)
        if response.status_code != 200:
            return response

        # response = run_connection("UPDATE api_member SET party_id = %s WHERE interested_ptr_id = %s", new_id, member_id)
        # if response.status_code != 200:
        #     return response
        add_members_to_party(new_id, member_ids)

        return response