Exemplo n.º 1
0
    def get(self, id):
        tourney = GetTourneyWithIdAndMaybeReturnStatus(self.response, id)
        if not tourney:
            return

        if not CheckUserOwnsTournamentAndMaybeReturnStatus(
                self.response, users.get_current_user(), tourney):
            return
        boards = ReadJSONInput(tourney.GetScoredHandList())
        max_rounds = GetMaxRounds(boards)
        summaries = Calculate(boards, max_rounds)
        mp_summaries = summaries
        ap_summaries = summaries
        boards.sort(key=lambda bs: bs._board_no, reverse=False)
        wb = WriteResultsToXlsx(max_rounds,
                                mp_summaries,
                                ap_summaries,
                                boards,
                                name_list=GetPlayerListForTourney(tourney))
        self.response.out.write(OutputWorkbookAsBytesIO(wb).getvalue())
        self.response.headers[
            'Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        self.response.headers['Content-disposition'] = str(
            'attachment; filename=' + tourney.name + 'TournamentResults.xlsx')
        self.response.headers['Content-Transfer-Encoding'] = 'Binary'
        self.response.set_status(200)
Exemplo n.º 2
0
    def get(self, id):
        ''' Returns tournament metadata for tournament with id.

        Args: 
          id: tournament ID to look up. Tournament must already have been
              created.
    '''
        user = users.get_current_user()
        tourney = GetTourneyWithIdAndMaybeReturnStatus(self.response, id)
        if not tourney:
            return

        if not CheckUserOwnsTournamentAndMaybeReturnStatus(
                self.response, user, tourney):
            return

        combined_dict = {
            'no_pairs': tourney.no_pairs,
            'no_boards': tourney.no_boards,
            'name': tourney.name,
            'hands': tourney.GetScoredHandList()
        }
        player_pairs = PlayerPair.query(ancestor=tourney.key).fetch()
        player_pairs.sort(key=lambda p: p.pair_no)
        combined_dict['pair_ids'] = [p.id for p in player_pairs]
        for player_pair in player_pairs:
            if player_pair.players:
                for player in player_pair.player_list():
                    player['pair_no'] = player_pair.pair_no
                    combined_dict.setdefault('players', []).append(player)

        self.response.headers['Content-Type'] = 'application/json'
        self.response.set_status(200)
        self.response.out.write(json.dumps(combined_dict, indent=2))
Exemplo n.º 3
0
  def get(self, id):
    ''' Returns tournament metadata for tournament with id.

        Args: 
          id: tournament ID to look up. Tournament must already have been
              created.
    ''' 
    user = users.get_current_user()
    tourney = GetTourneyWithIdAndMaybeReturnStatus(self.response, id)
    if not tourney:
      return

    if not CheckUserOwnsTournamentAndMaybeReturnStatus(self.response, user,
                                                       tourney):
      return
    combined_dict = {'no_pairs' : tourney.no_pairs,
                     'no_boards' :tourney.no_boards,
                     'name' : tourney.name,
                     'allow_score_overwrites' : tourney.IsUnlocked(),
                     'hands' : tourney.GetScoredHandList()}
    player_futures = tourney.GetAllPlayerPairsAsync();             
    for player_pair in player_futures:
      pp = player_pair.get_result()
      if pp.players:
        for player in pp.player_list():
          player['pair_no'] = pp.pair_no
          combined_dict.setdefault('players', []).append(player)
    combined_dict['pair_ids'] = [p.get_result().id for p in player_futures]

    self.response.headers['Content-Type'] = 'application/json'
    self.response.set_status(200)
    self.response.out.write(json.dumps(combined_dict, indent=2))
Exemplo n.º 4
0
    def get(self, id):
        tourney = GetTourneyWithIdAndMaybeReturnStatus(self.response, id)
        if not tourney:
            return

        if not CheckUserOwnsTournamentAndMaybeReturnStatus(
                self.response, users.get_current_user(), tourney):
            return

        movement = BuildMovementAndMaybeSetStatus(self.response,
                                                  tourney.no_pairs,
                                                  tourney.no_boards,
                                                  tourney.legacy_version_id)
        if not movement:
            return

        name_list = GetPlayerListForTourney(tourney)
        scored_hands = self._TuplesToDict(tourney.ScoredHands())
        unscored_hands = []
        round_list = []
        for round_no in xrange(1, movement.GetNumRounds() + 1):
            round_dict = {}
            round_dict["round"] = round_no
            round_dict["scored_hands"] = []
            round_dict["unscored_hands"] = []
            for team_no in xrange(1, tourney.no_pairs + 1):
                round = movement.GetMovement(team_no)[round_no - 1]
                hands = round.hands
                if not hands or not round.is_north:
                    continue
                for hand in hands:
                    hand_dict = {
                        "hand": hand,
                        "ns_pair": team_no,
                        "ns_names": list(name_list[team_no - 1]),
                        "ew_pair": round.opponent,
                        "ew_names": list(name_list[round.opponent - 1]),
                        "table": round.table
                    }
                    if hand in scored_hands.get(team_no, []):
                        scored_unscored = "scored_hands"
                    else:
                        scored_unscored = "unscored_hands"
                    round_dict[scored_unscored].append(hand_dict)
            round_dict["scored_hands"].sort(key=lambda x: x["table"])
            round_dict["unscored_hands"].sort(key=lambda x: x["table"])
            round_dict["scored_hands"].sort(key=lambda x: x["hand"])
            round_dict["unscored_hands"].sort(key=lambda x: x["hand"])
            round_list.append(round_dict)
        self.response.headers['Content-Type'] = 'application/json'
        self.response.set_status(200)
        self.response.out.write(json.dumps({"rounds": round_list}, indent=2))
Exemplo n.º 5
0
    def put(self, id):
        user = users.get_current_user()
        tourney = GetTourneyWithIdAndMaybeReturnStatus(self.response, id)
        if not tourney:
            return

        if not CheckUserOwnsTournamentAndMaybeReturnStatus(
                self.response, user, tourney):
            return

        request_dict = self._ParseRequestInfoAndMaybeSetStatus()
        if not request_dict:
            return

        name = request_dict['name']
        no_pairs = request_dict['no_pairs']
        no_boards = request_dict['no_boards']
        player_list = request_dict.get('players')
        if not self._CheckValidTournamentInfoAndMaybeSetStatus(
                name, no_pairs, no_boards, player_list):
            return
        if ((tourney.no_pairs != no_pairs or tourney.no_boards != no_boards)
                and len(tourney.GetScoredHandList()) != 0):
            SetErrorStatus(self.response, 400, "Invalid Request",
                           "Tournament already has registered hands")
            return
        self.response.set_status(204)
        tourney.no_pairs = no_pairs
        tourney.no_boards = no_boards
        tourney.name = name
        tourney_key = tourney.put()
        tourney.PutPlayers(player_list, no_pairs)
    def get(self, id, pair_no):
        ''' Fetch movement for tournament with id and team pair_no. 

    Args:
      id: String. Tournament id. 
      pair_no: Integer. Pair number for the team whose movement we're getting.

    See api for request and response documentation.
    '''
        tourney = GetTourneyWithIdAndMaybeReturnStatus(self.response, id)
        if not tourney:
            return

        if not self._CheckValidPairMaybeSetStatus(tourney, pair_no):
            return

        player_pair = PlayerPair.GetByPairNo(tourney, int(pair_no))
        if not player_pair:
            SetErrorStatus(self.response, 404, "Invalid Request",
                           "Player pair {} not in tournament".format(pair_no))
            return

        if not self._CheckUserAllowedToSeeMovementMaybeSetStatus(
                tourney, player_pair):
            return

        no_hands_per_round, no_rounds = Movement.NumBoardsPerRoundFromTotal(
            tourney.no_pairs, tourney.no_boards)
        try:
            movement = Movement.CreateMovement(
                tourney.no_pairs, no_hands_per_round, no_rounds,
                tourney.legacy_version_id).GetMovement(int(pair_no))
        except ValueError:
            SetErrorStatus(self.response, 500, "Corrupted Data",
                           "No valid movement for this tourney's config")
            return

        movement_list = self._GetMovementHandsAsync(tourney, movement,
                                                    int(pair_no))

        combined_dict = {
            'name': tourney.name,
            'players': player_pair.player_list(),
            'allow_score_overwrites': tourney.IsUnlocked(),
            'movement': movement_list
        }

        self.response.headers['Content-Type'] = 'application/json'
        self.response.set_status(200)
        self.response.out.write(json.dumps(combined_dict, indent=2))
Exemplo n.º 7
0
    def get(self, id):
        tourney = GetTourneyWithIdAndMaybeReturnStatus(self.response, id)
        if not tourney:
            return

        if not CheckUserOwnsTournamentAndMaybeReturnStatus(
                self.response, users.get_current_user(), tourney):
            return
        hand_list = tourney.GetScoredHandList()
        boards = ReadJSONInput(hand_list)
        summaries = Calculate(boards, GetMaxRounds(boards))
        self.response.headers['Content-Type'] = 'application/json'
        self.response.set_status(200)
        self.response.out.write(OutputJSON(hand_list, summaries))
Exemplo n.º 8
0
  def get(self, id, board_no, ns_pair, ew_pair):
    ''' Returns the complete change log for a hand to tournament owners.
    ''' 
    tourney = GetTourneyWithIdAndMaybeReturnStatus(self.response, id)
    if not tourney:
      return

    if not CheckUserOwnsTournamentAndMaybeReturnStatus(self.response, 
        users.get_current_user(), tourney):
      return

    if not CheckValidHandPlayersCombinationAndMaybeSetStatus(
        self.response, tourney, board_no, ns_pair, ew_pair):
      return

    change_logs = ChangeLog._query(
        ancestor=HandScore.CreateKey(tourney, board_no, ns_pair, ew_pair)).order(
            -ChangeLog.key).fetch()

    change_dict = { 'changes' : [] }
    for cl in change_logs:
      change_dict['changes'].append(cl.to_dict())

    self.response.headers['Content-Type'] = 'application/json'
    self.response.set_status(200)
    self.response.out.write(json.dumps(change_dict, indent=2))
Exemplo n.º 9
0
  def get(self, id, board_no, ns_pair, ew_pair):
    ''' Gets the information about a particular hand in the tournament.

    Args:
      id: String. Tournament id. 
      board_no: Integer. Hand number.
      ns_pair: Integer. Pair number of team playing North/South.
      ew_pair: Integer. Pair number of team playing East/West.

    See api for request and response documentation.
    '''
    tourney = GetTourneyWithIdAndMaybeReturnStatus(self.response, id)
    if not tourney:
      return

    if not CheckValidHandPlayersCombinationAndMaybeSetStatus(
        self.response, tourney, board_no, ns_pair, ew_pair):
      return

    hand_score = HandScore.GetByHandParams(tourney, board_no, ns_pair, ew_pair)
    if hand_score:
      response = {
            'calls' : hand_score.calls_dict(),
            'ns_score' : hand_score.get_ns_score(),
            'ew_score' : hand_score.get_ew_score(),
            'notes' : hand_score.notes,
      }
      self.response.headers['Content-Type'] = 'application/json'
      self.response.set_status(200)
      self.response.out.write(json.dumps(response, indent=2))
    else:
      self.response.set_status(204)
Exemplo n.º 10
0
  def delete(self, id, board_no, ns_pair, ew_pair):
    ''' Delete hand with these hand number and opponents from this tournament.

    Args:
      id: String. Tournament id. 
      board_no: Integer. Hand number.
      ns_pair: Integer. Pair number of team playing North/South.
      ew_pair: Integer. Pair number of team playing East/West.
    
    See api for request and response documentation.
    '''
    tourney = GetTourneyWithIdAndMaybeReturnStatus(self.response, id)
    if not tourney:
      return

    if not CheckUserOwnsTournamentAndMaybeReturnStatus(self.response,
        users.get_current_user(), tourney):
      return

    if not CheckValidHandPlayersCombinationAndMaybeSetStatus(
        self.response, tourney, board_no, ns_pair, ew_pair):
      return

    hand_score = HandScore.GetByHandParams(tourney, board_no, ns_pair, ew_pair)
    if not hand_score:
      SetErrorStatus(self.response, 404, "Invalid Request",
                     "Hand {} between pairs {} and {} is not set".format(
                         board_no, ns_pair, ew_pair))
      return
    hand_score.Delete()
    self.response.set_status(204) 
Exemplo n.º 11
0
    def head(self, id, board_no, ns_pair, ew_pair):
        ''' Check if a hand with this configuration is present in tournament id. 

    Args:
      id: String. Tournament id. 
      board_no: Integer. Hand number.
      ns_pair: Integer. Pair number of team playing North/South.
      ew_pair: Integer. Pair number of team playing East/West.

    See api for request and response documentation.
    '''
        tourney = GetTourneyWithIdAndMaybeReturnStatus(self.response, id)
        if not tourney:
            return

        if not CheckValidHandPlayersCombinationAndMaybeSetStatus(
                self.response, tourney, board_no, ns_pair, ew_pair):
            return

        hand_score = HandScore.GetByHandParams(tourney, board_no, ns_pair,
                                               ew_pair)
        if hand_score:
            self.response.set_status(200)
            return
        self.response.set_status(204)
    def get(self, id):
        ''' Returns tournament and pair number information this pair_id.

        Args: 
          id: Tournament ID for this tournament
        Returns: 
          a list of all unique ids in order. Length will necessarily equal
          to the number of pairs in this tournament.
    '''
        tourney = GetTourneyWithIdAndMaybeReturnStatus(self.response, id)
        if not tourney:
            return

        if not CheckUserOwnsTournamentAndMaybeReturnStatus(
                self.response, users.get_current_user(), tourney):
            return

        player_pairs = PlayerPair._query(ancestor=tourney.key).fetch(
            projection=[PlayerPair.id, PlayerPair.pair_no])
        player_pairs.sort(key=lambda p: p.pair_no)
        if not player_pairs:
            SetErrorStatus(
                self.response, 500, "Corrupted Data",
                "Could not find any players for this tournament. " +
                "Consider resetting tournament info.")

        self.response.headers['Content-Type'] = 'application/json'
        self.response.set_status(200)
        self.response.out.write(
            json.dumps({"pair_ids": [p.id for p in player_pairs]}, indent=2))
    def get(self, id, pair_no):
        ''' Returns the opaque pair ID for pair with pair nubmer pair_no in this
        Tournament.

        Args: 
          id: Tournament ID for this tournament.
          pair_no: The pair number whose ID has to be looked up.
    '''
        if not is_int(pair_no):
            SetErrorStatus(
                self.response, 404, "Invalid Pair Number",
                "Pair number must be an integer, was {}".format(pair_no))
            return

        tourney = GetTourneyWithIdAndMaybeReturnStatus(self.response, id)
        if not tourney:
            return

        if not CheckUserOwnsTournamentAndMaybeReturnStatus(
                self.response, users.get_current_user(), tourney):
            return
        player_pairs = PlayerPair._query(
            ndb.GenericProperty('pair_no') == int(pair_no),
            ancestor=tourney.key).fetch(1, projection=[PlayerPair.id])
        if not player_pairs:
            SetErrorStatus(
                self.response, 404, "Invalid Id",
                "Pair pair number {} does not exist in this " +
                "tournament".format(pair_no))
            return
        self.response.headers['Content-Type'] = 'application/json'
        self.response.set_status(200)
        self.response.out.write(
            json.dumps({'pair_id': player_pairs[0].id}, indent=2))
Exemplo n.º 14
0
  def put(self, id, board_no, ns_pair, ew_pair):
    ''' Add a scored hand to the tournament with this id. 

    Args:
      id: String. Tournament id. 
      board_no: Integer. Hand number.
      ns_pair: Integer. Pair number of team playing North/South.
      ew_pair: Integer. Pair number of team playing East/West.
    
    See api for request and response documentation.
    '''
    tourney = GetTourneyWithIdAndMaybeReturnStatus(self.response, id)
    if not tourney:
      return      

    if not CheckValidHandPlayersCombinationAndMaybeSetStatus(
        self.response, tourney, board_no, ns_pair, ew_pair):
      return

    user_has_access, change_pair_no = self._CheckUserHasAccessMaybeSetStatus(
        tourney, int(ns_pair), int(ew_pair))
    if not user_has_access:
      return

    if not self._CanPutHandAndMaybeSetResponse(tourney, board_no, ns_pair, ew_pair):
      return

    request_dict = self._ParsePutRequestInfoAndMaybeSetStatus()
    if not request_dict:
      return

    calls = request_dict.setdefault("calls", {})
    ns_score = request_dict.get("ns_score")
    ew_score = request_dict.get("ew_score")
    notes = request_dict.get("notes")

    if not ValidateHandResultMaybeSetStatus(self.response, int(board_no),
                                            int(ns_pair), int(ew_pair),
                                            ns_score, ew_score, calls):
      return

    tourney.PutHandScore(int(board_no), int(ns_pair), int(ew_pair), calls,
                         ns_score, ew_score, notes, change_pair_no)
    self.response.set_status(204)
Exemplo n.º 15
0
  def put(self, id):
    user = users.get_current_user()
    tourney = GetTourneyWithIdAndMaybeReturnStatus(self.response, id)
    if not tourney:
      return

    if not CheckUserOwnsTournamentAndMaybeReturnStatus(self.response, user,
                                                       tourney):
      return

    request_dict = self._ParseRequestInfoAndMaybeSetStatus()
    if not request_dict:
      return

    name = request_dict['name']
    no_pairs = request_dict['no_pairs']
    no_boards = request_dict['no_boards']
    player_list = request_dict.get('players')
    allow_score_overwrites = request_dict.get('allow_score_overwrites', False)
    if not self._CheckValidTournamentInfoAndMaybeSetStatus(name, no_pairs,
                                                           no_boards,
                                                           player_list,
                                                           tourney.legacy_version_id):
      return
    if ((tourney.no_pairs != no_pairs or tourney.no_boards != no_boards) and
         len(tourney.GetScoredHandList()) != 0):
      SetErrorStatus(self.response, 400, "Invalid Request",
                     "Tournament already has registered hands")
      return
   
    old_no_pairs = tourney.no_pairs   
    tourney.no_pairs = no_pairs
    tourney.no_boards = no_boards
    tourney.name = name
    if allow_score_overwrites:
      tourney.Unlock()
    else:
      tourney.MakeLockable()
    tourney.PutPlayers(player_list, old_no_pairs)
    tourney_key = tourney.put_async()
    self.response.set_status(204)
Exemplo n.º 16
0
    def delete(self, id):
        user = users.get_current_user()
        tourney = GetTourneyWithIdAndMaybeReturnStatus(self.response, id)
        if not tourney:
            return

        if not CheckUserOwnsTournamentAndMaybeReturnStatus(
                self.response, user, tourney):
            return

        self.response.set_status(204)
        ndb.delete_multi(ndb.Query(ancestor=tourney.key).iter(keys_only=True))
Exemplo n.º 17
0
    def get(self, id):
        ''' Returns tournament and pair number information this pair_id.

    Args: 
      id: tournament ID whose hands are being prepared. Tournament must already
          have been created.

    See api for request and response documentation.
    '''
        tourney = GetTourneyWithIdAndMaybeReturnStatus(self.response, id)
        if not tourney:
            return

        if not CheckUserOwnsTournamentAndMaybeReturnStatus(
                self.response, users.get_current_user(), tourney):
            return

        movement = BuildMovementAndMaybeSetStatus(self.response,
                                                  tourney.no_pairs,
                                                  tourney.no_boards,
                                                  tourney.legacy_version_id)
        if not movement:
            return

        unplayed_list = []
        for pair_no in range(1, tourney.no_pairs + 1):
            unplayed_list.append({
                "pair_no": pair_no,
                "hands": movement.GetUnplayedHands(pair_no)
            })
        suggested_prep_list = []
        for pair_no in range(1, tourney.no_pairs + 1):
            suggested_prep_list.append({
                "pair_no":
                pair_no,
                "hands":
                movement.GetSuggestedHandPrep(pair_no)
            })

        self.response.headers['Content-Type'] = 'application/json'
        self.response.set_status(200)
        self.response.out.write(
            json.dumps(
                {
                    "unplayed_hands": unplayed_list,
                    "preparation": suggested_prep_list
                },
                indent=2))
Exemplo n.º 18
0
    def get(self, id, board_no):
        '''Gets all the scored results for a particular hand in the tournament.

    Args:
      id: String. Tournament id. 
      board_no: Integer. Hand number.

    See api for request and response documentation.
    '''
        tourney = GetTourneyWithIdAndMaybeReturnStatus(self.response, id)
        if not tourney:
            return

        if (not is_int(board_no)
            ) or int(board_no) < 1 or int(board_no) > tourney.no_boards:
            SetErrorStatus(self.response, 404, "Invalid Hand Parameters",
                           "Board number {} is invalid".format(board_no))
            return

        has_access, pair_no, all_matchups = self._CheckUserHasAccessMaybeSetStatus(
            tourney, int(board_no))
        if not has_access:
            return

        position = self.request.headers.get('X-position')
        if not self._CheckValidPositionAndMaybeSetStatus(position):
            return

        scores = self._GetAllPlayedScores(tourney, int(board_no), all_matchups)
        if not self._CheckPlayerScoredHandsAndMaybeSetStatus(
                pair_no, all_matchups, scores):
            return

        list_of_results = self._ScoresToJson(position, scores, all_matchups)
        self.response.headers['Content-Type'] = 'application/json'
        self.response.set_status(200)
        self.response.out.write(
            json.dumps({"results": list_of_results}, indent=2))