Exemple #1
0
    def on_get(self, req, resp, id):
        Privilege.checkOrganizer(req.context['user'], int(id))
        tournament = m.Tournament.get(id=id)
        matches = Queries.getMatches(tournamentId=id)

        missingSpirits = []
        for match in matches:
            if match['terminated'] != True:
                continue
            if match['homeTeam']['spirit'] is None:
                missingSpirits.append({
                    'teamId': match['homeTeam']['id'],
                    'teamName': match['awayTeam']['name'],
                    'matchId': match['id'],
                    'ide': match['ide']
                })
            if match['awayTeam']['spirit'] is None:
                missingSpirits.append({
                    'teamId': match['homeTeam']['id'],
                    'teamName': match['homeTeam']['name'],
                    'matchId': match['id'],
                    'ide': match['ide']
                })

        collection = {'count': len(missingSpirits), 'items': missingSpirits}
        req.context['result'] = collection
Exemple #2
0
    def on_put(self, req, resp, id):
        match = m.Match.get(id=id)
        Privilege.checkOrganizer(req.context['user'], match.tournamentId)
        data = req.context['data']

        tournament = m.Tournament.get(id=match.tournamentId)

        activated = False
        if not match.active and data.get('active'):
            if not tournament.ready:
                raise ValueError("Tournament is not ready yet")

            self.activeMatch(id)
            activated = True

        # after active, because it rewrites score
        super(Match, self).on_put(req, resp, id, [
            'homeScore', 'awayScore', 'fieldId', 'startTime', 'endTime',
            'description'
        ])

        if 'homeScore' in data and 'awayScore' in data:
            pass
            # TODO: pri zmene skore smazat vsechny doposud odehrane body

        terminated = False
        if (match.active or
                activated) and not match.terminated and data.get('terminated'):
            self.terminateMatch(id)
            terminated = True

        if activated or terminated:
            resp.status = falcon.HTTP_200

        req.context['result'] = Queries.getMatches(matchId=id)[0]
Exemple #3
0
    def on_post(self, req, resp, id):
        match = m.Match.get(id=id)
        Privilege.checkOrganizer(req.context['user'], match.tournamentId)

        data = req.context['data']
        assistPlayerId = data.get('assistPlayerId')
        scorePlayerId = data.get('scorePlayerId')
        callahan = data.get('callahan', False)
        homePoint = bool(data['homePoint'])
        tournament = m.Tournament.get(id=match.tournamentId)

        if not tournament.ready:
            raise ValueError("Tournament isn't ready")

        if not match.active:
            raise ValueError("Match isn't active")

        teamId = match.homeTeamId if homePoint else match.awayTeamId

        self.checkPlayers(match.tournamentId, teamId, assistPlayerId,
                          scorePlayerId, callahan)
        with m.db.transaction():

            if not callahan:
                if assistPlayerId:
                    self.updatePlayerStatistic(match.tournamentId,
                                               assistPlayerId, match.id, 'A')
            if scorePlayerId:
                self.updatePlayerStatistic(match.tournamentId, scorePlayerId,
                                           match.id, 'S')

            order, homeScore, awayScore = Queries.getLastPoint(match.id)

            order += 1

            if homePoint:
                homeScore += 1
            else:
                awayScore += 1

            m.Point.insert(
                homePoint=homePoint,
                matchId=match.id,
                order=order,
                assistPlayerId=assistPlayerId if not callahan else None,
                scorePlayerId=scorePlayerId if not callahan else None,
                homeScore=homeScore,
                awayScore=awayScore,
                callahan=callahan).execute()

            self.updateMatchScore(match.id, homePoint)

            point = Queries.getPoints(matchId=match.id, order=order)[0]

        req.context['result'] = point
        resp.status = falcon.HTTP_201
Exemple #4
0
    def on_put(self, req, resp, id, order):
        match = m.Match.get(id=id)
        Privilege.checkOrganizer(req.context['user'], match.tournamentId)

        editableCols = ['assistPlayerId', 'scorePlayerId', 'callahan']
        point = m.Point.get(matchId=match.id, order=order)
        data = req.context['data']
        assistPlayerId = data.get('assistPlayerId')
        scorePlayerId = data.get('scorePlayerId')
        callahan = data.get('callahan', False)

        teamId = match.homeTeamId if point.homePoint else match.awayTeamId

        self.checkPlayers(match.tournamentId, teamId, assistPlayerId,
                          scorePlayerId, callahan)

        params = None
        qr = None
        if editableCols is not None:
            params = {key: data[key] for key in data if key in editableCols}
            if callahan and 'assistPlayerId' in params:
                del params['assistPlayerId']

        with m.db.transaction():
            # delete players statistics, if they are changed
            if callahan:
                self.updatePlayerStatistic(match.tournamentId,
                                           point.assistPlayerId, match.id, 'A',
                                           (-1))

            if assistPlayerId and point.assistPlayerId != assistPlayerId and not callahan:
                self.updatePlayerStatistic(match.tournamentId,
                                           point.assistPlayerId, match.id, 'A',
                                           (-1))
                self.updatePlayerStatistic(match.tournamentId, assistPlayerId,
                                           match.id, 'A', 1)

            if scorePlayerId and point.scorePlayerId != scorePlayerId:
                self.updatePlayerStatistic(match.tournamentId,
                                           point.scorePlayerId, match.id, 'S',
                                           (-1))
                self.updatePlayerStatistic(match.tournamentId, scorePlayerId,
                                           match.id, 'S', 1)

            if params:
                qr = m.Point.update(**params).where(
                    m.Point.matchId == match.id,
                    m.Point.order == order).execute()

        req.context['result'] = m.Point.select().where(
            m.Point.matchId == match.id, m.Point.order == order).get()
        resp.status = falcon.HTTP_200 if qr else falcon.HTTP_304
Exemple #5
0
    def on_post(self, req, resp, id):
        teamId = req.context['data']['teamId']
        playerId = req.context['data']['playerId']
        Privilege.checkOrganizer(req.context['user'], int(id))
        Privilege.checkClub(req.context['user'], m.Team.get(id=teamId).clubId)

        tournament = m.Tournament.get(id=id)
        if not tournament.ready:
            raise ValueError("Tournament is not ready")
        newPlayer, created = m.PlayerAtTournament.create_or_get(
            tournamentId=int(id), teamId=teamId, playerId=playerId)
        resp.status = falcon.HTTP_201 if created else falcon.HTTP_200
        req.context['result'] = newPlayer
Exemple #6
0
class Club(Item):
    def on_get(self, req, resp, id):
        req.context['result'] = Queries.getClubs(id)[0]

    @falcon.before(Privilege(["club", "admin"]))
    def on_put(self, req, resp, id):
        Privilege.checkClub(req.context['user'], int(id))
        super(Club, self).on_put(req, resp, id,
                                 ['shortcut', 'city', 'country'])
        req.context['result'] = Queries.getClubs(id)[0]

    @falcon.before(Privilege(["admin"]))
    def on_delete(self, req, resp, id):
        super(Club, self).on_delete(req, resp, id)
Exemple #7
0
    def on_delete(self, req, resp, id):
        teamId = req.context['data']['teamId']
        playerId = req.context['data']['playerId']
        Privilege.checkOrganizer(req.context['user'], int(id))
        Privilege.checkClub(req.context['user'], m.Team.get(id=teamId).clubId)

        matches = m.PlayerAtTournament.get(tournamentId=id,
                                           teamId=teamId,
                                           playerId=playerId).matches

        if matches == 0:
            player = m.PlayerAtTournament.get(
                tournamentId=id, teamId=teamId,
                playerId=playerId).delete_instance()
        else:
            raise ValueError("Player has played matches")
Exemple #8
0
    def on_post(self, req, resp, id):
        teamId   = req.context['data']['teamId']
        playerId = req.context['data']['playerId']
        Privilege.checkOrganizer(req.context['user'], int(id))
        Privilege.checkClub(req.context['user'], m.Team.get(id=teamId).clubId)

        tournament = m.Tournament.get(id=id)
        if not tournament.ready:
            raise ValueError("Tournament is not ready")
        newPlayer, created = m.PlayerAtTournament.create_or_get(
            tournamentId = int(id),
            teamId       = teamId,
            playerId     = playerId
            )
        resp.status = falcon.HTTP_201 if created else falcon.HTTP_200
        req.context['result'] = newPlayer
Exemple #9
0
class TournamentTeams(object):
    def on_get(self, req, resp, id):
        teams = Queries.getTeams(id)
        collection = {'count': len(teams), 'items': teams}
        req.context['result'] = collection

    @falcon.before(Privilege(["organizer", "admin"]))
    def on_put(self, req, resp, id):
        Privilege.checkOrganizer(req.context['user'], int(id))

        tournament = m.Tournament.get(id=id)
        if tournament.ready:
            raise ValueError("Tournament is ready and teams can't be changed")
        data = req.context['data']
        qr = m.TeamAtTournament.\
            update(
                teamId = data['teamId']
                ).\
            where(
                m.TeamAtTournament.tournamentId == id,
                m.TeamAtTournament.seeding == data['seeding']
            ).execute()
        resp.status = falcon.HTTP_200 if qr else falcon.HTTP_304

        req.context['result'] = m.TeamAtTournament.get(tournamentId=id,
                                                       seeding=data['seeding'])
Exemple #10
0
class Clubs(Collection):
    def on_get(self, req, resp):
        clubs = Queries.getClubs()
        collection = {'count': len(clubs), 'items': clubs}
        req.context['result'] = collection

    @falcon.before(Privilege(["admin"]))
    def on_post(self, req, resp):
        super(Clubs, self).on_post(req, resp)
Exemple #11
0
    def on_put(self, req, resp, id):
        Privilege.checkOrganizer(req.context['user'], int(id))

        tournament = m.Tournament.get(id=id)
        if tournament.ready:
            raise ValueError("Tournament is ready and teams can't be changed")
        data = req.context['data']
        qr = m.TeamAtTournament.\
            update(
                teamId = data['teamId']
                ).\
            where(
                m.TeamAtTournament.tournamentId == id,
                m.TeamAtTournament.seeding == data['seeding']
            ).execute()
        resp.status = falcon.HTTP_200 if qr else falcon.HTTP_304

        req.context['result'] = m.TeamAtTournament.get(tournamentId=id,
                                                       seeding=data['seeding'])
Exemple #12
0
    def on_delete(self, req, resp, id):
        teamId   = req.context['data']['teamId']
        playerId = req.context['data']['playerId']
        Privilege.checkOrganizer(req.context['user'], int(id))
        Privilege.checkClub(req.context['user'], m.Team.get(id=teamId).clubId)
        
        matches = m.PlayerAtTournament.get(
            tournamentId = id,
            teamId       = teamId,
            playerId     = playerId
            ).matches

        if matches == 0:
            player = m.PlayerAtTournament.get(
                tournamentId = id,
                teamId       = teamId,
                playerId     = playerId
                ).delete_instance()
        else:
            raise ValueError("Player has played matches")
Exemple #13
0
 def on_put(self, req, resp, id):
     Privilege.checkOrganizer(req.context['user'], int(id))
     
     tournament = m.Tournament.get(id=id)
     if tournament.ready:
         raise ValueError("Tournament is ready and teams can't be changed")
     data = req.context['data']
     qr = m.TeamAtTournament.\
         update(
             teamId = data['teamId']
             ).\
         where(
             m.TeamAtTournament.tournamentId == id,
             m.TeamAtTournament.seeding == data['seeding']
         ).execute()
     resp.status = falcon.HTTP_200 if qr else falcon.HTTP_304
     
     req.context['result'] =  m.TeamAtTournament.get(
         tournamentId = id,
         seeding = data['seeding']
         )
Exemple #14
0
    def on_put(self, req, resp, id):
        Privilege.checkOrganizer(req.context['user'], int(id))
        
        data = req.context['data']
        tournament = m.Tournament.select(m.Tournament).where(m.Tournament.id==id).get()

        super(Tournament, self).on_put(req, resp, id,
            ['name', 'startDate', 'endDate', 'city', 'country', 'caldTournamentId']
            )

        edited = False
        if tournament.ready is False and data.get('ready') is True:
            self.prepareTournament(id)
            edited = True

        if tournament.terminated is False and data.get('terminated') is True:
            self.terminateTournament(id)
            edited = True

        if edited:
            resp.status = falcon.HTTP_200 
Exemple #15
0
class TournamentPlayers(object):
    def on_get(self, req, resp, id):
        players = Queries.getPlayers(id, req.params.get('teamId'),
                                     req.params.get('limit'))
        collection = {'count': len(players), 'items': players}
        req.context['result'] = collection

    @falcon.before(Privilege(["club", "organizer", "admin"]))
    def on_post(self, req, resp, id):
        teamId = req.context['data']['teamId']
        playerId = req.context['data']['playerId']
        Privilege.checkOrganizer(req.context['user'], int(id))
        Privilege.checkClub(req.context['user'], m.Team.get(id=teamId).clubId)

        tournament = m.Tournament.get(id=id)
        if not tournament.ready:
            raise ValueError("Tournament is not ready")
        newPlayer, created = m.PlayerAtTournament.create_or_get(
            tournamentId=int(id), teamId=teamId, playerId=playerId)
        resp.status = falcon.HTTP_201 if created else falcon.HTTP_200
        req.context['result'] = newPlayer

    @falcon.before(Privilege(["club", "organizer", "admin"]))
    def on_delete(self, req, resp, id):
        teamId = req.context['data']['teamId']
        playerId = req.context['data']['playerId']
        Privilege.checkOrganizer(req.context['user'], int(id))
        Privilege.checkClub(req.context['user'], m.Team.get(id=teamId).clubId)

        matches = m.PlayerAtTournament.get(tournamentId=id,
                                           teamId=teamId,
                                           playerId=playerId).matches

        if matches == 0:
            player = m.PlayerAtTournament.get(
                tournamentId=id, teamId=teamId,
                playerId=playerId).delete_instance()
        else:
            raise ValueError("Player has played matches")
Exemple #16
0
    def on_put(self, req, resp, id):
        Privilege.checkOrganizer(req.context['user'], int(id))

        data = req.context['data']
        tournament = m.Tournament.select(
            m.Tournament).where(m.Tournament.id == id).get()

        super(Tournament, self).on_put(req, resp, id, [
            'name', 'startDate', 'endDate', 'city', 'country',
            'caldTournamentId'
        ])

        edited = False
        if tournament.ready is False and data.get('ready') is True:
            self.prepareTournament(id)
            edited = True

        if tournament.terminated is False and data.get('terminated') is True:
            self.terminateTournament(id)
            edited = True

        if edited:
            resp.status = falcon.HTTP_200
Exemple #17
0
    def on_delete(self, req, resp, id):
        match = m.Match.get(id=id)
        Privilege.checkOrganizer(req.context['user'], match.tournamentId)
        # TODO: unite this two queries
        order, homeScore, awayScore = Queries.getLastPoint(match.id)
        point = Queries.getPoints(match.id, order)[0]

        assistPlayerId = point['assistPlayer']['id']
        scorePlayerId = point['scorePlayer']['id']

        with m.db.transaction():
            # delete from match table
            self.updateMatchScore(match.id, point['homePoint'], (-1))
            # delete players statistics
            if assistPlayerId:
                self.updatePlayerStatistic(match.tournamentId, assistPlayerId,
                                           match.id, 'A', (-1))
            if scorePlayerId:
                self.updatePlayerStatistic(match.tournamentId, scorePlayerId,
                                           match.id, 'S', (-1))
            # delete point
            m.Point.delete().where(m.Point.matchId == match.id,
                                   m.Point.order == order).execute()
Exemple #18
0
    def on_get(self, req, resp, id):
        loggedUser = req.context['user']
        match = Queries.getMatches(matchId=id)[0]
        Privilege.checkOrganizer(loggedUser, m.Match.get(id=id).tournamentId)

        homeSpirit = None
        awaySpirit = None
        try:
            homeSpirit = model_to_dict(
                m.Spirit.get(matchId=id, teamId=match['homeTeam']['id']))
            del homeSpirit['matchId'], homeSpirit['teamId'], homeSpirit[
                'givingTeamId']
            # if spirit is not club's
            team = m.Team.get(id=match['homeTeam']['id'])
            if loggedUser.role == "club" and not loggedUser.clubId == team.clubId:
                homeSpirit = None
        except m.Spirit.DoesNotExist:
            pass
        finally:
            match['homeTeam']['spirit'] = homeSpirit

        try:
            awaySpirit = model_to_dict(
                m.Spirit.get(matchId=id, teamId=match['awayTeam']['id']))
            del awaySpirit['matchId'], awaySpirit['teamId'], awaySpirit[
                'givingTeamId']
            # if spirit is not club's
            team = m.Team.get(id=match['awayTeam']['id'])
            if loggedUser.role == "club" and not loggedUser.clubId == team.clubId:
                homeSpirit = None
        except m.Spirit.DoesNotExist:
            pass
        finally:
            match['awayTeam']['spirit'] = awaySpirit

        req.context['result'] = match
Exemple #19
0
class Tournaments(Collection):
    def on_get(self, req, resp):
        tournaments = Queries.getTournaments(
            req.params.get('country'),
            req.params.get('divisionId'),
            req.get_param_as_bool('active'),
            req.get_param_as_bool('terminated'),
            req.params.get('userId'),
        )

        collection = {'count': len(tournaments), 'items': tournaments}
        req.context['result'] = collection

    @falcon.before(Privilege(["organizer", "admin"]))
    def on_post(self, req, resp):
        tournamentCreater = TournamentCreater()
        createdTurnament = tournamentCreater.createTournament(
            req, resp, req.context['user'])
        req.context['result'] = createdTurnament
        resp.status = falcon.HTTP_201
Exemple #20
0
class Tournament(Item):
    @m.db.atomic()
    def prepareTournament(self, id):
        tournament = m.Tournament.get(id=id)

        if tournament.ready:
            raise ValueError("Tournament %s is already ready" % id)

        teams = m.TeamAtTournament.select().where(
            m.TeamAtTournament.tournamentId == id)

        if len(teams) != tournament.teams:
            logging.error("Tournament has different number of teams")
            raise RuntimeError("Tournament has different number of teams"
                               " in contrast to TeamAtTournament" % matchId)

        # ready Tournament
        m.Tournament.update(ready=True).where(m.Tournament.id == id).execute()

        # Standing
        for x in range(1, len(teams) + 1):
            m.Standing.insert(tournamentId=id, standing=x).execute()

        # Matches and Spirit overalls
        seedings = {}
        for team in teams:
            seedings[team.seeding] = team.teamId
            m.SpiritAvg.insert(teamId=team.teamId,
                               tournamentId=tournament.id).execute()

        matches = m.Match.select().where(
                m.Match.tournamentId == 1 and \
                (m.Match.homeSeed != None or m.Match.awaySeed != None)
            )

        for match in matches:
            m.Match.update(homeTeamId=seedings[match.homeSeed],
                           awayTeamId=seedings[match.awaySeed]).where(
                               m.Match.id == match.id).execute()

    @m.db.atomic()
    def terminateTournament(self, id):
        '''terminate tournament'''
        tournament = m.Tournament.get(id=id)

        standings = m.Standing.select().where(
            m.Standing.tournamentId == tournament.id)
        for standing in standings:
            if standing.teamId is None:
                raise falcon.HTTPBadRequest(
                    "Tournanent can't be terminated",
                    "All standings aren't known. Probably some matches are still active."
                )

        matches = Queries.getMatches(tournamentId=tournament.id)
        for match in matches:
            if match['homeTeam']['spirit'] is None or match['awayTeam'][
                    'spirit'] is None:
                raise falcon.HTTPBadRequest(
                    "Tournanent can't be terminated",
                    ("Spirit from match %s is still missing" % match['ide']))

        tournament.terminated = True
        tournament.save()

    @falcon.before(Privilege(["organizer", "admin"]))
    def on_put(self, req, resp, id):
        Privilege.checkOrganizer(req.context['user'], int(id))

        data = req.context['data']
        tournament = m.Tournament.select(
            m.Tournament).where(m.Tournament.id == id).get()

        super(Tournament, self).on_put(req, resp, id, [
            'name', 'startDate', 'endDate', 'city', 'country',
            'caldTournamentId'
        ])

        edited = False
        if tournament.ready is False and data.get('ready') is True:
            self.prepareTournament(id)
            edited = True

        if tournament.terminated is False and data.get('terminated') is True:
            self.terminateTournament(id)
            edited = True

        if edited:
            resp.status = falcon.HTTP_200
Exemple #21
0
class MatchPoints(Point):
    def on_get(self, req, resp, id):
        match = Queries.getMatches(matchId=id)[0]
        match['points'] = Queries.getPoints(id)
        req.context['result'] = match

    @falcon.before(Privilege(["organizer", "admin"]))
    def on_post(self, req, resp, id):
        match = m.Match.get(id=id)
        Privilege.checkOrganizer(req.context['user'], match.tournamentId)

        data = req.context['data']
        assistPlayerId = data.get('assistPlayerId')
        scorePlayerId = data.get('scorePlayerId')
        callahan = data.get('callahan', False)
        homePoint = bool(data['homePoint'])
        tournament = m.Tournament.get(id=match.tournamentId)

        if not tournament.ready:
            raise ValueError("Tournament isn't ready")

        if not match.active:
            raise ValueError("Match isn't active")

        teamId = match.homeTeamId if homePoint else match.awayTeamId

        self.checkPlayers(match.tournamentId, teamId, assistPlayerId,
                          scorePlayerId, callahan)
        with m.db.transaction():

            if not callahan:
                if assistPlayerId:
                    self.updatePlayerStatistic(match.tournamentId,
                                               assistPlayerId, match.id, 'A')
            if scorePlayerId:
                self.updatePlayerStatistic(match.tournamentId, scorePlayerId,
                                           match.id, 'S')

            order, homeScore, awayScore = Queries.getLastPoint(match.id)

            order += 1

            if homePoint:
                homeScore += 1
            else:
                awayScore += 1

            m.Point.insert(
                homePoint=homePoint,
                matchId=match.id,
                order=order,
                assistPlayerId=assistPlayerId if not callahan else None,
                scorePlayerId=scorePlayerId if not callahan else None,
                homeScore=homeScore,
                awayScore=awayScore,
                callahan=callahan).execute()

            self.updateMatchScore(match.id, homePoint)

            point = Queries.getPoints(matchId=match.id, order=order)[0]

        req.context['result'] = point
        resp.status = falcon.HTTP_201

    @falcon.before(Privilege(["organizer", "admin"]))
    def on_delete(self, req, resp, id):
        match = m.Match.get(id=id)
        Privilege.checkOrganizer(req.context['user'], match.tournamentId)
        # TODO: unite this two queries
        order, homeScore, awayScore = Queries.getLastPoint(match.id)
        point = Queries.getPoints(match.id, order)[0]

        assistPlayerId = point['assistPlayer']['id']
        scorePlayerId = point['scorePlayer']['id']

        with m.db.transaction():
            # delete from match table
            self.updateMatchScore(match.id, point['homePoint'], (-1))
            # delete players statistics
            if assistPlayerId:
                self.updatePlayerStatistic(match.tournamentId, assistPlayerId,
                                           match.id, 'A', (-1))
            if scorePlayerId:
                self.updatePlayerStatistic(match.tournamentId, scorePlayerId,
                                           match.id, 'S', (-1))
            # delete point
            m.Point.delete().where(m.Point.matchId == match.id,
                                   m.Point.order == order).execute()
Exemple #22
0
class Spirit(object):
    def getGivingTeamId(self, receivingTeamId, match):
        if receivingTeamId == match.homeTeamId:
            return match.awayTeamId
        elif receivingTeamId == match.awayTeamId:
            return match.homeTeamId
        else:
            raise ValueError("In match %s isn't team %s" %
                             (match.id, receivingTeamId))

    def getNewAvg(self, avg, matches, newValue, oldValue=None):
        if oldValue is None:
            return ((avg * matches) + newValue) / (matches + 1)
        else:
            return ((avg * matches) - oldValue + newValue) / (matches)

    def updateSpirit(self, matchId, data, user, put=False):
        logging.info("Match %s has new spirit" % matchId)

        match = m.Match.get(id=matchId)
        tournament = m.Tournament.get(id=match.tournamentId)

        if tournament.terminated:
            raise ValueError("Tournament is terminated")

        if not match.terminated:
            raise ValueError("Match is not terminated still")

        # check team ids
        receivingTeamId = int(data['teamId'])
        givingTeamId = self.getGivingTeamId(receivingTeamId, match)

        # check rights, if user is giving team
        Privilege.checkOrganizer(user, match.tournamentId)
        team = m.Team.get(id=givingTeamId)
        Privilege.checkClub(user, team.clubId)

        logging.info("Team %s gives spirit to team %s " %
                     (givingTeamId, receivingTeamId))

        data['givingTeamId'] = givingTeamId

        newSotg = Sotg(data['fair'], data['communication'], data['fouls'],
                       data['positive'], data['rules'])

        with m.db.transaction():

            # TODO: upravit spirit na prehledu zapasu!!! a otestovat

            oldSotg = Sotg()
            if put:
                # delete old spirit
                spirit = m.Spirit.get(matchId=matchId, teamId=receivingTeamId)
                oldSotg = Sotg(spirit.fair, spirit.communication, spirit.fouls,
                               spirit.positive, spirit.rules)
                spirit.delete_instance()

            data['total'] = newSotg.total
            spirit, created = m.Spirit.get_or_create(matchId=matchId,
                                                     teamId=receivingTeamId,
                                                     defaults=data)
            logging.info("spirit: %s" % (spirit))

            # given ---------------------------------------------------------------

            spiritAvg = m.SpiritAvg.get(tournamentId=match.tournamentId,
                                        teamId=givingTeamId)

            spiritAvg.communicationGiven = self.getNewAvg(
                spiritAvg.communicationGiven, spiritAvg.matchesGiven,
                newSotg.communication, oldSotg.communication)
            spiritAvg.fairGiven = self.getNewAvg(spiritAvg.fairGiven,
                                                 spiritAvg.matchesGiven,
                                                 newSotg.fair, oldSotg.fair)
            spiritAvg.foulsGiven = self.getNewAvg(spiritAvg.foulsGiven,
                                                  spiritAvg.matchesGiven,
                                                  newSotg.fouls, oldSotg.fouls)
            spiritAvg.positiveGiven = self.getNewAvg(spiritAvg.positiveGiven,
                                                     spiritAvg.matchesGiven,
                                                     newSotg.positive,
                                                     oldSotg.positive)
            spiritAvg.rulesGiven = self.getNewAvg(spiritAvg.rulesGiven,
                                                  spiritAvg.matchesGiven,
                                                  newSotg.rules, oldSotg.rules)
            spiritAvg.totalGiven = self.getNewAvg(spiritAvg.totalGiven,
                                                  spiritAvg.matchesGiven,
                                                  newSotg.total, oldSotg.total)
            if not put:
                spiritAvg.matchesGiven = (spiritAvg.matchesGiven + 1)

            spiritAvg.save()

            # received ------------------------------------------------------------

            spiritAvg = m.SpiritAvg.get(tournamentId=match.tournamentId,
                                        teamId=receivingTeamId)

            spiritAvg.communication = self.getNewAvg(spiritAvg.communication,
                                                     spiritAvg.matches,
                                                     newSotg.communication,
                                                     oldSotg.communication)
            spiritAvg.fair = self.getNewAvg(spiritAvg.fair, spiritAvg.matches,
                                            newSotg.fair, oldSotg.fair)
            spiritAvg.fouls = self.getNewAvg(spiritAvg.fouls,
                                             spiritAvg.matches, newSotg.fouls,
                                             oldSotg.fouls)
            spiritAvg.positive = self.getNewAvg(spiritAvg.positive,
                                                spiritAvg.matches,
                                                newSotg.positive,
                                                oldSotg.positive)
            spiritAvg.rules = self.getNewAvg(spiritAvg.rules,
                                             spiritAvg.matches, newSotg.rules,
                                             oldSotg.rules)
            spiritAvg.total = self.getNewAvg(spiritAvg.total,
                                             spiritAvg.matches, newSotg.total,
                                             oldSotg.total)
            if not put:
                spiritAvg.matches = (spiritAvg.matches + 1)

            spiritAvg.save()

            if match.homeTeamId == receivingTeamId:
                match.spiritHome = newSotg.total
            else:
                match.spiritAway = newSotg.total
            match.save()
            # ---------------------------------------------------------------------

        return spirit, created

    @falcon.before(Privilege(["club", "organizer", "admin"]))
    def on_get(self, req, resp, id):
        loggedUser = req.context['user']
        match = Queries.getMatches(matchId=id)[0]
        Privilege.checkOrganizer(loggedUser, m.Match.get(id=id).tournamentId)

        homeSpirit = None
        awaySpirit = None
        try:
            homeSpirit = model_to_dict(
                m.Spirit.get(matchId=id, teamId=match['homeTeam']['id']))
            del homeSpirit['matchId'], homeSpirit['teamId'], homeSpirit[
                'givingTeamId']
            # if spirit is not club's
            team = m.Team.get(id=match['homeTeam']['id'])
            if loggedUser.role == "club" and not loggedUser.clubId == team.clubId:
                homeSpirit = None
        except m.Spirit.DoesNotExist:
            pass
        finally:
            match['homeTeam']['spirit'] = homeSpirit

        try:
            awaySpirit = model_to_dict(
                m.Spirit.get(matchId=id, teamId=match['awayTeam']['id']))
            del awaySpirit['matchId'], awaySpirit['teamId'], awaySpirit[
                'givingTeamId']
            # if spirit is not club's
            team = m.Team.get(id=match['awayTeam']['id'])
            if loggedUser.role == "club" and not loggedUser.clubId == team.clubId:
                homeSpirit = None
        except m.Spirit.DoesNotExist:
            pass
        finally:
            match['awayTeam']['spirit'] = awaySpirit

        req.context['result'] = match

    @falcon.before(Privilege(["club", "organizer", "admin"]))
    def on_put(self, req, resp, id):
        spirit, created = self.updateSpirit(int(id), req.context['data'],
                                            req.context['user'], True)
        resp.status = falcon.HTTP_200 if created else falcon.HTTP_304
        req.context['result'] = spirit

    @falcon.before(Privilege(["club", "organizer", "admin"]))
    def on_post(self, req, resp, id):
        spirit, created = self.updateSpirit(int(id), req.context['data'],
                                            req.context['user'])
        resp.status = falcon.HTTP_201 if created else falcon.HTTP_200
        req.context['result'] = spirit
Exemple #23
0
    def updateSpirit(self, matchId, data, user, put=False):
        logging.info("Match %s has new spirit" % matchId)

        match = m.Match.get(id=matchId)
        tournament = m.Tournament.get(id=match.tournamentId)

        if tournament.terminated:
            raise ValueError("Tournament is terminated")

        if not match.terminated:
            raise ValueError("Match is not terminated still")

        # check team ids
        receivingTeamId = int(data['teamId'])
        givingTeamId = self.getGivingTeamId(receivingTeamId, match)

        # check rights, if user is giving team
        Privilege.checkOrganizer(user, match.tournamentId)
        team = m.Team.get(id=givingTeamId)
        Privilege.checkClub(user, team.clubId)

        logging.info("Team %s gives spirit to team %s " %
                     (givingTeamId, receivingTeamId))

        data['givingTeamId'] = givingTeamId

        newSotg = Sotg(data['fair'], data['communication'], data['fouls'],
                       data['positive'], data['rules'])

        with m.db.transaction():

            # TODO: upravit spirit na prehledu zapasu!!! a otestovat

            oldSotg = Sotg()
            if put:
                # delete old spirit
                spirit = m.Spirit.get(matchId=matchId, teamId=receivingTeamId)
                oldSotg = Sotg(spirit.fair, spirit.communication, spirit.fouls,
                               spirit.positive, spirit.rules)
                spirit.delete_instance()

            data['total'] = newSotg.total
            spirit, created = m.Spirit.get_or_create(matchId=matchId,
                                                     teamId=receivingTeamId,
                                                     defaults=data)
            logging.info("spirit: %s" % (spirit))

            # given ---------------------------------------------------------------

            spiritAvg = m.SpiritAvg.get(tournamentId=match.tournamentId,
                                        teamId=givingTeamId)

            spiritAvg.communicationGiven = self.getNewAvg(
                spiritAvg.communicationGiven, spiritAvg.matchesGiven,
                newSotg.communication, oldSotg.communication)
            spiritAvg.fairGiven = self.getNewAvg(spiritAvg.fairGiven,
                                                 spiritAvg.matchesGiven,
                                                 newSotg.fair, oldSotg.fair)
            spiritAvg.foulsGiven = self.getNewAvg(spiritAvg.foulsGiven,
                                                  spiritAvg.matchesGiven,
                                                  newSotg.fouls, oldSotg.fouls)
            spiritAvg.positiveGiven = self.getNewAvg(spiritAvg.positiveGiven,
                                                     spiritAvg.matchesGiven,
                                                     newSotg.positive,
                                                     oldSotg.positive)
            spiritAvg.rulesGiven = self.getNewAvg(spiritAvg.rulesGiven,
                                                  spiritAvg.matchesGiven,
                                                  newSotg.rules, oldSotg.rules)
            spiritAvg.totalGiven = self.getNewAvg(spiritAvg.totalGiven,
                                                  spiritAvg.matchesGiven,
                                                  newSotg.total, oldSotg.total)
            if not put:
                spiritAvg.matchesGiven = (spiritAvg.matchesGiven + 1)

            spiritAvg.save()

            # received ------------------------------------------------------------

            spiritAvg = m.SpiritAvg.get(tournamentId=match.tournamentId,
                                        teamId=receivingTeamId)

            spiritAvg.communication = self.getNewAvg(spiritAvg.communication,
                                                     spiritAvg.matches,
                                                     newSotg.communication,
                                                     oldSotg.communication)
            spiritAvg.fair = self.getNewAvg(spiritAvg.fair, spiritAvg.matches,
                                            newSotg.fair, oldSotg.fair)
            spiritAvg.fouls = self.getNewAvg(spiritAvg.fouls,
                                             spiritAvg.matches, newSotg.fouls,
                                             oldSotg.fouls)
            spiritAvg.positive = self.getNewAvg(spiritAvg.positive,
                                                spiritAvg.matches,
                                                newSotg.positive,
                                                oldSotg.positive)
            spiritAvg.rules = self.getNewAvg(spiritAvg.rules,
                                             spiritAvg.matches, newSotg.rules,
                                             oldSotg.rules)
            spiritAvg.total = self.getNewAvg(spiritAvg.total,
                                             spiritAvg.matches, newSotg.total,
                                             oldSotg.total)
            if not put:
                spiritAvg.matches = (spiritAvg.matches + 1)

            spiritAvg.save()

            if match.homeTeamId == receivingTeamId:
                match.spiritHome = newSotg.total
            else:
                match.spiritAway = newSotg.total
            match.save()
            # ---------------------------------------------------------------------

        return spirit, created
Exemple #24
0
 def on_put(self, req, resp, id):
     Privilege.checkClub(req.context['user'], int(id))
     super(Club, self).on_put(req, resp, id,
                              ['shortcut', 'city', 'country'])
     req.context['result'] = Queries.getClubs(id)[0]
Exemple #25
0
 def on_put(self, req, resp, id):
     Privilege.checkClub(req.context['user'], int(id))
     super(Club, self).on_put(req, resp, id, ['shortcut', 'city', 'country'])
     req.context['result'] = Queries.getClubs(id)[0]
Exemple #26
0
class Match(Item):
    @staticmethod
    def updateStanding(tournamentId, teamId, standing):
        m.Standing.update(teamId=teamId).where(
            m.Standing.standing == standing,
            m.Standing.tournamentId == tournamentId).execute()

    @staticmethod
    def addTeamInNextStep(tournamentId, teamId, ide):
        identificator = m.Identificator.get(ide=ide)
        match = m.Match.get(tournamentId=tournamentId, ide=ide)

        if identificator.matchId:
            logging.info("4: Saving team in match %s" % identificator.ide)
            # doplnim do dalsiho zapasu
            if match.homeTeamId is None:
                logging.info("5: Team will play as home")
                match.homeTeamId = teamId
            elif match.awayTeamId is None:
                logging.info("5: Team will play as away")
                match.awayTeamId = teamId
            else:
                raise RuntimeError(
                    "In the match %s want to be more than two teams" % ide)
        else:
            logging.info("4: Saving team in group %s" % identificator.ide)
            # TODO: continue in group

        match.save()

    @m.db.atomic()
    def activeMatch(self, matchId):

        match = m.Match.get(id=matchId)

        # fill in tables with players per match
        homeTeamPlayers = m.PlayerAtTournament.select().where(
            m.PlayerAtTournament.tournamentId == match.tournamentId,
            m.PlayerAtTournament.teamId == match.homeTeamId)
        for player in homeTeamPlayers:
            m.PlayerAtMatch.insert(matchId=matchId,
                                   playerId=player.playerId).execute()
        awayTeamPlayers = m.PlayerAtTournament.select().where(
            m.PlayerAtTournament.tournamentId == match.tournamentId,
            m.PlayerAtTournament.teamId == match.awayTeamId)
        for player in awayTeamPlayers:
            m.PlayerAtMatch.insert(matchId=matchId,
                                   playerId=player.playerId).execute()

        # TODO: vsem hracum pridelat jednicku v total PlayerAtTournament a otestovat

        match.homeScore = 0
        match.awayScore = 0
        match.active = True
        match.save()

    def updateGroupTable(self, winner, looser, winnerScore, looserScore):
        winner.matches = winner.matches + 1
        winner.wins = winner.wins + 1
        winner.plus = winner.plus + winnerScore
        winner.minus = winner.minus + looserScore
        winner.points = winner.points + 2
        looser.matches = looser.matches + 1
        looser.losses = looser.losses + 1
        looser.plus = looser.plus + looserScore
        looser.minus = looser.minus + winnerScore
        winner.save()
        looser.save()

    def recomputeGroup(self, tournamentId, groupIde):
        # prepocitat vysledky
        # teams = []

        teams = m.GroupHasTeam.select().where(
            m.GroupHasTeam.tournamentId == tournamentId,
            m.GroupHasTeam.ide == groupIde).order_by(
                m.GroupHasTeam.points.desc(), (m.GroupHasTeam.plus).desc())

        standing = 1
        for team in teams:
            team.standing = standing
            team.save()
            standing += 1
            print team

        matches = m.Match.select().where(m.Match.groupIde == groupIde)
        for match in matches:
            print match
            if not match.terminated:
                return

        logging.info("Group is complete")

        for team in teams:
            advancement = m.Advancement.get(tournamentId=tournamentId,
                                            ide=groupIde,
                                            standing=team.standing)

            if advancement.finalStanding:
                Match.updateStanding(tournamentId, team.teamId,
                                     advancement.finalStanding)
            elif advancement.nextStepIde:
                Match.addTeamInNextStep(tournamentId, team.teamId,
                                        advancement.nextStepIde)
            else:
                raise RuntimeError(
                    "Team %s doesn't know, where continue from %s group" %
                    (team.teamId, groupIde))

    @m.db.atomic()
    def terminateMatch(self, matchId):
        logging.info("1: Match %s is in terminating" % matchId)

        match = m.Match.get(id=matchId)
        match.terminated = True
        match.save()

        if match.homeScore > match.awayScore:
            logging.info("2: Home team won: %s vs %s" %
                         (match.homeTeamId, match.awayTeamId))
            winnerTeamId = match.homeTeamId
            winnerScore = match.homeScore
            looserTeamId = match.awayTeamId
            looserScore = match.awayScore
        elif match.homeScore < match.awayScore:
            logging.info("2: Away team won: %s vs %s" %
                         (match.homeTeamId, match.awayTeamId))
            winnerTeamId = match.awayTeamId
            winnerScore = match.awayScore
            looserTeamId = match.homeTeamId
            looserScore = match.homeScore
        else:
            raise ValueError("Match have to have the one winner")

        # if match has next step, there have to be winner (playoff)
        if not match.groupIde:
            if match.winnerFinalStanding:
                logging.info("3: Winner ends on %s. place" %
                             match.winnerFinalStanding)
                Match.updateStanding(match.tournamentId, winnerTeamId,
                                     match.winnerFinalStanding)
            if match.winnerNextStepIde:
                identificator = m.Identificator.get(
                    ide=match.winnerNextStepIde)
                logging.info("3: Winner's next match is %s (%s)" %
                             (identificator.matchId, identificator.ide))
                Match.addTeamInNextStep(match.tournamentId, winnerTeamId,
                                        match.winnerNextStepIde)

            if match.looserFinalStanding:
                logging.info("3: Looser ends on %s. place" %
                             match.looserFinalStanding)
                Match.updateStanding(match.tournamentId, looserTeamId,
                                     match.looserFinalStanding)
            if match.looserNextStepIde:
                identificator = m.Identificator.get(
                    ide=match.looserNextStepIde)
                logging.info("3: Looser's next match is %s (%s)" %
                             (identificator.matchId, identificator.ide))
                Match.addTeamInNextStep(match.tournamentId, looserTeamId,
                                        match.looserNextStepIde)
        else:
            print match.homeScore, match.awayScore

            winner = m.GroupHasTeam.get(tournamentId=match.tournamentId,
                                        ide=match.groupIde,
                                        teamId=winnerTeamId)

            looser = m.GroupHasTeam.get(tournamentId=match.tournamentId,
                                        ide=match.groupIde,
                                        teamId=looserTeamId)

            self.updateGroupTable(winner, looser, winnerScore, looserScore)

            self.recomputeGroup(match.tournamentId, match.groupIde)

        # now is allowed consigning Spirit of the Game

    def on_get(self, req, resp, id):
        req.context['result'] = Queries.getMatches(matchId=id)[0]

    @falcon.before(Privilege(["organizer", "admin"]))
    def on_put(self, req, resp, id):
        match = m.Match.get(id=id)
        Privilege.checkOrganizer(req.context['user'], match.tournamentId)
        data = req.context['data']

        tournament = m.Tournament.get(id=match.tournamentId)

        activated = False
        if not match.active and data.get('active'):
            if not tournament.ready:
                raise ValueError("Tournament is not ready yet")

            self.activeMatch(id)
            activated = True

        # after active, because it rewrites score
        super(Match, self).on_put(req, resp, id, [
            'homeScore', 'awayScore', 'fieldId', 'startTime', 'endTime',
            'description'
        ])

        if 'homeScore' in data and 'awayScore' in data:
            pass
            # TODO: pri zmene skore smazat vsechny doposud odehrane body

        terminated = False
        if (match.active or
                activated) and not match.terminated and data.get('terminated'):
            self.terminateMatch(id)
            terminated = True

        if activated or terminated:
            resp.status = falcon.HTTP_200

        req.context['result'] = Queries.getMatches(matchId=id)[0]