def create_initial_default_prize_structures():

        site_sport_manager = SiteSportManager()
        for sport in SiteSportManager.SPORTS:
            created_default_prize_structures = 0
            site_sport = site_sport_manager.get_site_sport(sport)
            for buyin in DefaultPrizeStructureManager.default_buyin_amounts:
                for size, payout_spots in DefaultPrizeStructureManager.default_contest_sizes:
                    # get the prize structure based on the buyin and # of payout spots
                    prize_structures = PrizeStructure.objects.filter(
                        generator__buyin=buyin, generator__payout_spots=payout_spots)
                    prize_structure = None  # loop until we find it
                    for ps in prize_structures:
                        if size == ps.get_entries():
                            prize_structure = ps
                            break  # we found it
                    if prize_structure is None:
                        logger.warning(
                            ("No PrizeStructure for buyin: %s payout_spots: %s. You can add them "
                             "manually though!") % (buyin, payout_spots))
                        # raise Exception(err_msg)

                    else:
                        #
                        # create the default prize structures for the SiteSport
                        dps = DefaultPrizeStructure()
                        dps.site_sport = site_sport
                        dps.prize_structure = prize_structure
                        dps.save()
                        created_default_prize_structures += 1

            logger.info("%s created_default_prize_structures for %s" % (
                created_default_prize_structures, sport))
示例#2
0
 def get_player_stats_model_class(self):
     site_sport_manager = SiteSportManager()
     site_sport = site_sport_manager.get_site_sport(self.sport)
     player_stats_model_classes = site_sport_manager.get_player_stats_classes(
         site_sport)
     return player_stats_model_classes[
         0]  # return first element - nfl only has 1
示例#3
0
    def create_games(n=20, site_sport=None, round_start_times=False):
        # site_sport, created = SiteSport.objects.get_or_create(name=sport)
        dt_now = timezone.now()
        unix_ts = int(
            dt_now.strftime('%s'))  # unix timestamp as srid ... not bad
        games = []
        ssm = SiteSportManager()
        season_model_class = ssm.get_season_class(site_sport)

        # dum_srid        = '%s'%site_sport
        # dum_season_year = 2016
        # dum_season_type = 'reg'
        # dum_season, created = season_model_class.objects.get_or_create(srid=dum_srid,
        #                             season_year=dum_season_year, season_type=dum_season_type)

        for x in range(0, n):
            game = Dummy.create_game(srid='%s' % (unix_ts + x),
                                     site_sport=site_sport,
                                     round_start_times=round_start_times)
            # game.season = dum_season # cant be null
            game.start = game.start + timedelta(
                minutes=x)  # stagger each game by 1 minute
            game.save()
            games.append(game)

        return games
示例#4
0
    def create_player_stats_model(game, player, site_sport=None):
        """
        If site_sport is not specified, defaults to use PlayerStatsChild model

        may not work to well for baseball since there
        are 2 PlayerStats types (hitter/pitcher)
        """
        player_stats = None
        if site_sport is None:
            player_stats = PlayerStatsChild()
        else:
            ssm = SiteSportManager()
            player_stats_model_list = ssm.get_player_stats_class(site_sport)
            player_stats_model = player_stats_model_list[0]
            player_stats = player_stats_model()

        player_stats.fantasy_points = randint(0, 100)

        player_stats.game = game
        player_stats.player = player
        player_stats.srid_game = game.srid
        player_stats.srid_player = player.srid
        player_stats.position = player.position
        player_stats.save(fantasy_points_override=player_stats.fantasy_points)
        return player_stats
示例#5
0
 def __init__(self, sport):
     """
     Create dummy objects. This could interfere with the live site,
     and is strictly meant for testing environments, and specifically
     the "./manage.py test" tool
     """
     self.ssm = SiteSportManager()
     self.site_sport = self.ssm.get_site_sport(sport)
    def __init__(self,
                 sport,
                 prize_structure,
                 start,
                 duration,
                 draft_group=None,
                 user_entry_limit=None,
                 entry_cap=None,
                 set_name=True):
        """
        :param sport: the name of the sport
        :param prize_structure: the prize.models.PrizeStructure
        :param start: datetime object, the scheduled start time
        :param duration: the integer number of minutes from the start until the end
                         that makes a range of datetime objects, between which to use
                         the sport's games.
        :param draft_group: if specified, the DraftGroup to use. otherwise get an existing one
                            using the DraftGroupManager class.
        """
        site_sport_manager = SSM()
        self.sport = sport
        self.site_sport = site_sport_manager.get_site_sport(self.sport)

        # validate and set the start datetime
        self.start = self.validate_start(start)

        # validate and set the duration (integer minutes)
        self.duration = self.validate_duration(duration)

        # validate and set the prize_structure model
        self.prize_structure = self.validate_prize_structure(prize_structure)

        # if a draft_group is specified, validate it
        self.draft_group = draft_group
        if self.draft_group is not None:
            self.draft_group = self.validate_draft_group(draft_group)

        # set the user entry limit (the max # of Entrys from one user for this ContestPool)
        self.user_entry_limit = self.USER_ENTRY_LIMIT
        if user_entry_limit is not None:
            self.user_entry_limit = user_entry_limit

        # set the entry cap (if there is one, typically there is not)
        self.entry_cap = self.ENTRY_CAP
        if entry_cap is not None:
            self.entry_cap = entry_cap

        # whether or not to set a name at creation time
        self.set_name = set_name

        # skill level
        slm = SkillLevelManager()
        self.skill_level = slm.get_for_amount(self.prize_structure.buyin)
示例#7
0
    def __init__(self, sport):
        self.sport = sport
        self.verbose = False
        self.debug_limit = 0
        self.pbp_parent_api = 'pbp'
        self.stats_parent_api = 'stats'
        self.delay_seconds = 5
        self.delay_seconds_behind = 0

        ssm = SiteSportManager()
        self.site_sport = ssm.get_site_sport(self.sport)
        self.player_class = ssm.get_player_class(self.site_sport)
    def __init__(self, sport, season=None, season_types=None):
        self.data = None
        self.sport = sport
        self.sport_day_class = ScheduleDay.factory(self.sport)
        self.site_sport_manager = SiteSportManager()
        self.site_sport = self.site_sport_manager.get_site_sport(self.sport)
        self.game_model_class = self.site_sport_manager.get_game_class(self.site_sport)
        self.season = season  # season is None, only get games for the season type after 'now'
        self.season_types = season_types
        if self.season_types is None:
            self.season_types = self.default_season_types

        # setup the datetime range with a start and end
        self.start = None
        self.end = None
示例#9
0
    def get(self, request, *args, **kwargs):
        data = {
            'player_updates':
            self.get_serialized_data(PlayerStatus,
                                     PlayerStatusSerializer,
                                     sport=kwargs['sport']),
            # This is for rain delays and things like that. It does not currently work.
            # 'game_updates' : self.get_serialized_data(GameUpdate, GameUpdateSerializer),
        }

        # Attach Probable Pitcher info for MLB.
        if kwargs['sport'] == 'mlb':
            # Find the most current draft group for MLB. We need to know this in order to
            # filter out old PP updates.
            site_sport = SiteSportManager().get_site_sport('mlb')
            latest_mlb_draftgroup = DraftGroup.objects.filter(
                salary_pool__site_sport=site_sport, ).order_by(
                    '-created').first()

            # Get a list of probable pitcher SRIDs. (they are stored in the 'value' column)
            pitcher_srids = GameUpdate.objects.filter(
                type='pp', draft_groups=latest_mlb_draftgroup).values('value')

            # Tweak it a little bit to match the format of other updates.
            data['probable_pitchers'] = [{
                'player_srid': pitcher['value']
            } for pitcher in pitcher_srids]

        return Response(data, status=200)
示例#10
0
    def get(self, request, draft_group_id):

        dgm = DraftGroupManager()
        try:
            draft_group = dgm.get_draft_group(draft_group_id)
        except DraftGroup.DoesNotExist:
            return HttpResponse({},
                                content_type='application/json',
                                status=status.HTTP_404_NOT_FOUND)

        site_sport = draft_group.salary_pool.site_sport
        ssm = SiteSportManager()
        games = dgm.get_games(draft_group)
        game_serializer_class = ssm.get_game_serializer_class(site_sport)

        boxscores = dgm.get_game_boxscores(draft_group)
        boxscore_serializer_class = ssm.get_boxscore_serializer_class(
            site_sport)

        # data = []
        # for b in boxscores:
        #     data.append( b.to_json() )
        data = {}
        for game in games:
            # initial inner_data
            inner_data = {}

            # add the game data
            g = game_serializer_class(game).data
            self.__add_to_dict(inner_data, g)

            # add the boxscore data
            boxscore = None
            try:
                boxscore = boxscores.get(srid_game=game.srid)  # may not exist
            except:
                pass
            b = {}
            if boxscore is not None:
                b = {'boxscore': boxscore_serializer_class(boxscore).data}
            self.__add_to_dict(inner_data, b)

            # finish it by adding the game data to the return data dict
            data[game.srid] = inner_data

        return HttpResponse(json.dumps(data), content_type='application/json')
示例#11
0
    def create_team(srid=None, alias=None, site_sport=None):
        """
        Creates a team with a random srid - based on current milliseconds.
        """
        if not srid:
            srid = "srid-%s" % int(round(time.time() * 1000)),
        if not alias:
            alias = "alias-%s" % int(round(time.time() * 1000)),

        if site_sport is None:
            t, created = TeamChild.objects.get_or_create(srid=srid,
                                                         alias=alias)
        else:
            ssm = SiteSportManager()
            team_model = ssm.get_team_class(site_sport)
            t, created = team_model.objects.get_or_create(srid=srid,
                                                          alias=alias)
        return t
    def handle(self, *args, **options):

        values = []
        for x in options['values']:
            values.append(x)

        game_srid = values[0]
        duration = 500
        try:
            duration = int(values[1])  # defaults to
        except IndexError:
            pass  # there wasnt a duration specified, just use the default

        # find the Game -- check all sports
        ssm = SiteSportManager()
        game = None
        the_sport = None
        for sport in SiteSportManager.SPORTS:
            game_class = ssm.get_game_class(sport)
            try:
                game = game_class.objects.get(srid=game_srid)
                the_sport = sport
                break
            except game_class.DoesNotExist:
                pass
            self.stdout.write('checked %s for Game but it wasnt found' % sport)

        if game is None or the_sport is None:
            self.stdout.write('No game found for any sport '
                              '%s matching srid: %s\n' %
                              (SiteSportManager.SPORTS, game_srid))

        # get a prize structure that hopefully exists
        prize_structures = PrizeStructure.objects.all()
        count = prize_structures.count()
        r = Random()
        prize_structure = prize_structures[r.randint(0, count - 1)]
        self.stdout.write('randomly chosen prize structure: %s' %
                          str(prize_structure))

        #
        contest_pool_creator = ContestPoolCreator(the_sport, prize_structure,
                                                  game.start, duration)
        contest_pool_creator.get_or_create()
示例#13
0
    def get_player_stats(self, draft_group):
        """
        get the sports.<sport>.models.PlayerStats objects for the given draft_group
        returned in a dictionary of:

            {
                <model name> : [ list of objects ],
                <model name> : [ list of objects ],
                ... etc...
            }

        :param draft_group:
        :return:
        """
        ssm = SiteSportManager()
        game_srids = [
            x.game_srid for x in self.get_game_teams(draft_group=draft_group)
        ]
        player_stats_models = ssm.get_player_stats_class(
            sport=draft_group.salary_pool.site_sport)
        data = {}

        # fill with 0s for every player in the draft group first
        for stats_model in player_stats_models:
            # These are draftgroup.Player models!
            draft_group_players = Player.objects.filter(
                draft_group=draft_group).prefetch_related(
                    'salary_player__player__position')
            for draft_group_player in draft_group_players:
                data[draft_group_player.player_id] = {
                    stats_model.field_id: draft_group_player.player_id,
                    stats_model.field_fp: 0.0,
                    stats_model.field_pos: draft_group_player.position,
                }

        # then add the stats for the existing player stats objects
        for stats_model in player_stats_models:
            for player_stat_obj in stats_model.objects.filter(
                    srid_game__in=game_srids).select_related('position'):
                # l.append( player_stat_obj.to_json() )
                data[player_stat_obj.player_id] = player_stat_obj.to_score()

        return data
示例#14
0
    def create_player_stats(sport=DEFAULT_SPORT):
        """
        return a newly created player who could fit in the default roster.

        if 'roster' is None, we will call Dummy.create_roster() and use that data

        :param sport:
        :param roster:
        :return:
        """

        # ('QB',1,0,True)     :['QB'],
        position = None
        for rs_tuple, pos_list in Dummy.DEFAULT_ROSTER_MAP.items():
            for pos_name in pos_list:
                site_sport, c = SiteSport.objects.get_or_create(name=sport)
                position, c = Position.objects.get_or_create(
                    name=pos_name, site_sport=site_sport)
                break
            break
        if position is None:
            raise Exception(
                '>>>>> Dummy.create_player_stats() couldnt find any positions in roster'
            )

        dt_now = timezone.now()
        unix_ts = dt_now.strftime('%s')  # unix timestamp as srid ... not bad

        ssm = SiteSportManager()
        site_sport = ssm.get_site_sport(sport)
        game = Dummy.create_game(srid='game' + unix_ts, site_sport=site_sport)

        player = Dummy.create_player(srid='player' + unix_ts,
                                     position=position,
                                     team=game.home,
                                     site_sport=site_sport)

        if sport == Dummy.DEFAULT_SPORT:
            site_sport = None  # hack for backwards compatability, to not break older code
        player_stats = Dummy.create_player_stats_model(game, player,
                                                       site_sport)

        return player_stats
    def handle(self, *args, **options):
        """
        calculate a single players salary (for debugging purposes) using
        the sports main salary algorithm.

        this command will infer the sport using SiteSportManager
        so all that needs to be specified is the player srid!
        """

        # collect the player srids passed as arguments
        player_srids = []
        for srid in options['player']:
            player_srids.append(srid)

        player_srid = player_srids[0] # get the first one
        print('looking for player:', str(player_srid))

        # find the sports.<sport>.models.Player object
        ssm = SiteSportManager()
        player = None
        site_sport = None # the sport (the string name) of the sport the player was found in
        for sport in SiteSportManager.SPORTS:
            site_sport = ssm.get_site_sport(sport)
            player_class = ssm.get_player_class(site_sport)
            try:
                player = player_class.objects.get(srid=player_srid)
                break
            except player_class.DoesNotExist:
                #self.stdout.write('checked %s for Player object but they werent found'%sport)
                pass

        # hopefully we found the player by now
        if player is None:
            self.stdout.write('player [%s] not found in any sport!' % player_srid)
            return
        # else:
        #     self.stdout.write('player:', str(player))

        # generate the salary for this player specifically, printing out all the player stats
        # objects used and the weighting involved in the calculations for debugging purposes.
        sg = SportSalaryGenerator(sport=site_sport.name, debug_srid=player_srid)
        sg.generate_salaries()
示例#16
0
    def get_player_stats(lineup_player):
        ssm = SiteSportManager()
        # get the player model(s) for the sport used (multiple for MLB)
        player_stats_models = ssm.get_player_stats_class(
            lineup_player.lineup.draft_group.salary_pool.site_sport)

        player_stats = []

        # check every stats model type ( ie: baseball has PlayerStatsHitter & PlayerStatsPitcher)
        for player_stats_model in player_stats_models:
            try:
                player_stats.append(
                    player_stats_model.objects.get(
                        player_id=lineup_player.player_id,
                        srid_game=lineup_player.draft_group_player.game_team.
                        game_srid).to_json())
            except player_stats_model.DoesNotExist:
                pass

        return player_stats
示例#17
0
    def get_pbp_descriptions(self, draft_group, max=15):
        """
        get the most recent pbp descriptions for this draft group

        does not return the full list, but a capped (short) trailing history
        :param draft_group:
        :return:
        """

        # get the distinct games from the gameteam model
        distinct_gameteam_games = self.get_game_teams(
            draft_group=draft_group).distinct('game_srid')
        game_srids = [x.game_srid for x in distinct_gameteam_games]

        # get the sports game_model (ie: sports.<sport>.Game)
        ssm = SiteSportManager()
        pbp_description_model = ssm.get_pbp_description_class(
            sport=draft_group.salary_pool.site_sport)
        # return pbp_description_model.objects.filter( description__srid_game__in=game_srids )[:15]
        return pbp_description_model.objects.filter()[:15]
示例#18
0
    def get_game_boxscores(self, draft_group):
        """
        Return the sports.<sport>.GameBoxscore objects related to the DraftGroup instance.

        This method simply gets the distinct('game_srid') rows
        from the QuerySet returned by get_game_teams().

        :param draft_group:
        :return: QuerySet of sports.<sport>.Game objects
        """

        # get the distinct games from the gameteam model
        distinct_gameteam_games = self.get_game_teams(
            draft_group=draft_group).distinct('game_srid')
        game_srids = [x.game_srid for x in distinct_gameteam_games]

        # get the sports game_model (ie: sports.<sport>.Game)
        ssm = SiteSportManager()
        game_boxscore_model = ssm.get_game_boxscore_class(
            sport=draft_group.salary_pool.site_sport)
        return game_boxscore_model.objects.filter(srid_game__in=game_srids)
示例#19
0
    def get_player_array_from_player_ids_array(player_ids, site_sport):
        """
        Creates and returns an array of :class:`sports.models.Player` objects based
        on the player_ids array.

        :param player_ids: an ordered list of :class:`sports.models.Player` ids
            for the lineup.
        :return: an array of :class:`sports.models.Player` objects

        :raise :class:`lineup.exception.DuplicatePlayerException`: If there are
            duplicate ids in the player_ids list
        """
        ssm = SiteSportManager()
        player_class = ssm.get_player_class(site_sport)

        #
        # Check if there are duplicate players
        if len(set(player_ids)) != len(player_ids):
            raise DuplicatePlayerException()

        players = player_class.objects.filter(pk__in=player_ids)
        return sorted(players, key=lambda player: player_ids.index(player.pk))
示例#20
0
    def create_player_stats_model(self, game_srid, player_srid,
                                  my_player_stats_instance):
        """
        create a new PlayerStats model instance from the fields of the 'mongo_obj'
        :param mongo_obj:
        :return:
        """

        site_sport_manager = SiteSportManager()
        site_sport = site_sport_manager.get_site_sport('nfl')
        player_model_class = site_sport_manager.get_player_class(site_sport)
        game_model_class = site_sport_manager.get_game_class(site_sport)

        try:
            player = player_model_class.objects.get(srid=player_srid)
        except player_model_class.DoesNotExist:
            # if they were never in the database, they wont be in draft group and we should not
            # deal with that here! - Probably means they are defensive players.
            return

        player_stats_model_class = self.get_player_stats_model_class()

        # get new instance
        player_stats = player_stats_model_class()

        # set all properties with these fieldnames to 0
        player_stats.position = player.position  # use the position from their Player object
        player_stats.srid_game = game_srid
        player_stats.game = game_model_class.objects.get(srid=game_srid)
        player_stats.srid_player = player_srid
        player_stats.player = player

        for fieldname, var in my_player_stats_instance.get_vars().items():
            setattr(player_stats, fieldname, var)
            player_stats.save()

        logger.info(
            'Missing PlayerStats model created for player: %s | srid: %s' %
            (player, player_srid))
示例#21
0
    def lineup_players(obj):
        player_display = mark_safe("<ul>")
        sport = obj.draft_group.salary_pool.site_sport
        site_sport_manager = SiteSportManager()
        player_stats_classes = site_sport_manager.get_player_stats_class(sport)
        print(player_stats_classes)

        if obj.draft_group.start >= timezone.now():
            return "Cannot view the players in a lineup until it's draft group has started."

        for player in obj.players.all():
            player_stats = []

            for stats_class in player_stats_classes:
                game_srid = player.draft_group_player.game_team.game_srid
                player_stats_objects = stats_class.objects.filter(
                    srid_player=player.player.srid,
                    srid_game=game_srid
                )
                for player_stats_object in player_stats_objects:
                    player_stats.append(player_stats_object.to_json())

            player_display += format_html(
                "<li>"
                "<strong>Roster Spot:</strong> {}<br />"
                "<strong>sport.models.player:</strong> {}<br />    "
                "<strong>draftgroup.models.player:</strong> {} <br />"
                "<strong>sport.models.player_stats:</strong> {} <br /><br />"
                "</li>",
                player.roster_spot,
                "%s" % player.player,
                "%s" % player.draft_group_player,
                "%s" % player_stats,
            )

        player_display += mark_safe("</ul>")
        return player_display
示例#22
0
    def find_games_within_time_span(site_sport, start, end):
        #
        # we will use the SiteSportManager the model class for player, game
        ssm = SiteSportManager()
        game_model = ssm.get_game_class(site_sport)
        # get all games equal to or greater than start, and less than end.
        games = game_model.objects.filter(start__gte=start,
                                          start__lte=end).order_by('start')

        if len(games) == 0:
            err_msg = 'there are ZERO games in [%s until %s]' % (start, end)
            raise mysite.exceptions.NoGamesInRangeException(err_msg)
        elif len(games) < 2:
            raise NotEnoughGamesException()

        #
        # throw an exception if the specified start time does not coincide with any games
        if game_model.objects.filter(start=start).count() == 0:
            raise NoGamesAtStartTimeException()

        # Keep track of teams that are playing today.
        team_srids = []
        for game in games:
            # make sure we do not encounter the same team multiple times!
            for check_team in [game.away, game.home]:
                if check_team.srid in team_srids:
                    logger.warning("Excluding doubleheader game: %s" % game)
                    # If we find a game that has a team that is already playing today,
                    # exclude the second game.
                    games = games.exclude(pk=game.pk)

            # Add the teams to our list of srids.
            team_srids.append(game.away.srid)
            team_srids.append(game.home.srid)

        return games
示例#23
0
    def create_game(srid=None,
                    status='scheduled',
                    away=None,
                    home=None,
                    site_sport=None,
                    round_start_times=False):
        # site_sport, created = SiteSport.objects.get_or_create(name=sport)

        ssm = SiteSportManager()
        season_model_class = ssm.get_season_class(site_sport)
        dum_srid = '%s' % site_sport
        dum_season_year = 2016
        dum_season_type = 'reg'
        dum_season, created = season_model_class.objects.get_or_create(
            srid=dum_srid,
            season_year=dum_season_year,
            season_type=dum_season_type,
        )

        if srid is None:
            srid = "srid-%s" % int(round(time.time() * 1000)),
        if away is None:
            away = Dummy.create_team(alias='AWAY', site_sport=site_sport)
        if home is None:
            home = Dummy.create_team(alias='HOME', site_sport=site_sport)

        dt_now = timezone.now()
        if round_start_times:
            # zero out the seconds and microseconds!
            dt_now = dt_now.replace(dt_now.year, dt_now.month, dt_now.day,
                                    dt_now.hour, dt_now.minute, 0, 0)

        if site_sport is None:
            game = GameChild()
        else:
            ssm = SiteSportManager()
            game_model = ssm.get_game_class(site_sport)
            game = game_model()

        game.season = dum_season  # cant be None
        game.srid = srid
        game.start = dt_now
        game.status = status

        game.away = away
        game.home = home

        game.save()
        return game
示例#24
0
 def get_player_model_class(self):
     if self.player_model_class is None:
         ssm = SiteSportManager()
         site_sport = ssm.get_site_sport(self.sport)
         self.player_model_class = ssm.get_player_class(site_sport)
     return self.player_model_class
示例#25
0
    def get_lineup_from_id(lineup_id, contest):
        """
        get lineup data we can show to other users, with masked
        out players if the contest has not started yet.

        :param lineup_id:
        :return:
        """

        data = []
        ssm = SiteSportManager()

        #
        # Get the lineup players for a lineup id
        lineup_players = LineupPlayer.objects.filter(
            lineup__pk=lineup_id).order_by('idx').select_related(
                'draft_group_player__game_team')

        #
        # sets the started flag to False if draftgroup has not started
        started = True
        if len(lineup_players
               ) > 0 and not lineup_players[0].lineup.draft_group.is_started():
            started = False

        #
        # get the player model(s) for the sport used (multiple for MLB)
        player_stats_models = ssm.get_player_stats_class(contest.site_sport)

        #
        # add all the players to the data array, but if the contest has not started make the
        # specific player information be an empty array.
        for lineup_player in lineup_players:

            #
            # check every stats model type ( ie: baseball has PlayerStatsHitter & PlayerStatsPitcher)
            category_stats = []
            for player_stats_model in player_stats_models:

                player_stats = None
                #
                # if the player is masked out in the starter map, do not display which player it is
                if not started:
                    continue

                #
                # Get the player stats if the model type applies to the player and they have stats
                try:
                    player_stats = player_stats_model.objects.get(
                        player_id=lineup_player.player_id,
                        srid_game=lineup_player.draft_group_player.game_team.
                        game_srid)
                except player_stats_model.DoesNotExist:
                    player_stats = None
                    pass

                #
                # add the stats to the data field for the given player.
                if player_stats is not None:
                    category_stats.append(player_stats.to_json())

            #
            # add the "category_stats" list  -- ie: the stats for each roster idx
            data.append({
                'started': started,
                'i': lineup_player.idx,
                'data': category_stats,
            })

        # this data is safe to return via the API because
        # the players whos games have not yet started have
        # not been shown!
        return data
示例#26
0
    def setUp(self):
        super().setUp()
        # ensure the default ticket
        TicketManager.create_default_ticket_amounts(verbose=False)
        # add funds to user
        self.user = self.get_basic_user()
        ct = CashTransaction(self.user)
        ct.deposit(100)

        # salary_generator = Dummy.generate_salaries()
        # self.salary_pool = salary_generator.pool
        # start
        #
        #
        self.verbose = True  # set to False to disable print statements

        #
        # The sport we are going to build fake stats for.
        # Lets use nfl, but it doesnt matter what sport we use
        self.sport = 'nfl'

        #
        # Ensure there are Games by using the Dummy to generate fake stats.
        # The ScheduleManager requires that Game objects exist
        # because when it creates scheduled Contest objects
        # it is required to create a draft group.
        self.dummy = Dummy(sport=self.sport)
        self.generator = self.dummy.generate()
        self.salary_pool = self.generator.pool
        self.site_sport = self.dummy.site_sport  # stash the site_sport for easy use

        self.site_sport_manager = SiteSportManager()
        self.game_model = self.site_sport_manager.get_game_class(
            self.site_sport)  # ie: sports.nfl.models.Game
        self.games = self.game_model.objects.all()  # there should be handful now, for today
        if self.games.count() <= 0:
            raise Exception(
                'buyin.tests.BuyinTest - we meant to create games.... but none were created!')
        # end

        # create a simple prize pool
        self.first = 100.0
        self.second = 50.0
        self.third = 25.0
        self.buyin = 10
        cps = CashPrizeStructureCreator(name='test')
        cps.add(1, self.first)
        cps.add(2, self.second)
        cps.add(3, self.third)
        cps.set_buyin(self.buyin)
        cps.save()
        cps.prize_structure.save()

        self.prize_structure = cps.prize_structure
        self.ranks = cps.ranks

        #
        # create the Contest
        # now = timezone.now()
        # start = DfsDateTimeUtil.create(now.date(), time(23,0))
        # end = DfsDateTimeUtil.create(now.date() + timedelta(days=1), time(0,0))
        start = self.games[0].start + timedelta(minutes=5)
        end = self.games[self.games.count() - 1].start  # set 'end' to start of last game
        cc = ContestCreator("test_contest", self.sport, self.prize_structure, start, end)
        self.draft_group2 = DraftGroup()
        self.draft_group2.salary_pool = self.salary_pool
        self.draft_group2.start = start
        self.draft_group2.end = end
        self.draft_group2.save()

        self.contest_pool, created = ContestPoolCreator(
            self.sport,
            self.prize_structure,
            start,
            (end - start).seconds * 60,
            self.draft_group2
        ).get_or_create()
        self.contest = cc.create()
        self.contest.status = Contest.RESERVABLE
        self.contest.save()

        self.draft_group = DraftGroup()
        self.draft_group.salary_pool = self.salary_pool
        self.draft_group.start = start
        self.draft_group.end = end
        self.draft_group.save()
示例#27
0
class BuyinTest(AbstractTest):
    """
    create a basic contest, and use the BuyinManager to buy into it.
    """

    def setUp(self):
        super().setUp()
        # ensure the default ticket
        TicketManager.create_default_ticket_amounts(verbose=False)
        # add funds to user
        self.user = self.get_basic_user()
        ct = CashTransaction(self.user)
        ct.deposit(100)

        # salary_generator = Dummy.generate_salaries()
        # self.salary_pool = salary_generator.pool
        # start
        #
        #
        self.verbose = True  # set to False to disable print statements

        #
        # The sport we are going to build fake stats for.
        # Lets use nfl, but it doesnt matter what sport we use
        self.sport = 'nfl'

        #
        # Ensure there are Games by using the Dummy to generate fake stats.
        # The ScheduleManager requires that Game objects exist
        # because when it creates scheduled Contest objects
        # it is required to create a draft group.
        self.dummy = Dummy(sport=self.sport)
        self.generator = self.dummy.generate()
        self.salary_pool = self.generator.pool
        self.site_sport = self.dummy.site_sport  # stash the site_sport for easy use

        self.site_sport_manager = SiteSportManager()
        self.game_model = self.site_sport_manager.get_game_class(
            self.site_sport)  # ie: sports.nfl.models.Game
        self.games = self.game_model.objects.all()  # there should be handful now, for today
        if self.games.count() <= 0:
            raise Exception(
                'buyin.tests.BuyinTest - we meant to create games.... but none were created!')
        # end

        # create a simple prize pool
        self.first = 100.0
        self.second = 50.0
        self.third = 25.0
        self.buyin = 10
        cps = CashPrizeStructureCreator(name='test')
        cps.add(1, self.first)
        cps.add(2, self.second)
        cps.add(3, self.third)
        cps.set_buyin(self.buyin)
        cps.save()
        cps.prize_structure.save()

        self.prize_structure = cps.prize_structure
        self.ranks = cps.ranks

        #
        # create the Contest
        # now = timezone.now()
        # start = DfsDateTimeUtil.create(now.date(), time(23,0))
        # end = DfsDateTimeUtil.create(now.date() + timedelta(days=1), time(0,0))
        start = self.games[0].start + timedelta(minutes=5)
        end = self.games[self.games.count() - 1].start  # set 'end' to start of last game
        cc = ContestCreator("test_contest", self.sport, self.prize_structure, start, end)
        self.draft_group2 = DraftGroup()
        self.draft_group2.salary_pool = self.salary_pool
        self.draft_group2.start = start
        self.draft_group2.end = end
        self.draft_group2.save()

        self.contest_pool, created = ContestPoolCreator(
            self.sport,
            self.prize_structure,
            start,
            (end - start).seconds * 60,
            self.draft_group2
        ).get_or_create()
        self.contest = cc.create()
        self.contest.status = Contest.RESERVABLE
        self.contest.save()

        self.draft_group = DraftGroup()
        self.draft_group.salary_pool = self.salary_pool
        self.draft_group.start = start
        self.draft_group.end = end
        self.draft_group.save()

    def test_incorrect_contest_type(self):
        bm = BuyinManager(self.user)
        self.assertRaises(mysite.exceptions.IncorrectVariableTypeException,
                          lambda: bm.buyin(0))

    def test_incorrect_lineup_type(self):
        bm = BuyinManager(self.user)
        self.assertRaises(mysite.exceptions.IncorrectVariableTypeException,
                          lambda: bm.buyin(self.contest, 0))

    def test_simple_buyin(self):
        bm = BuyinManager(self.user)
        bm.buyin(self.contest_pool)

    def test_simple_ticket_buyin(self):
        tm = TicketManager(self.user)
        try:
            tm.get_ticket_amount(self.buyin)

        except Exception:
            ta = TicketAmount()
            ta.amount = self.buyin
            ta.save()
        tm.deposit(amount=self.buyin)
        bm = BuyinManager(self.user)
        bm.buyin(self.contest_pool)
        tm.ticket.refresh_from_db()
        self.assertEqual((tm.ticket.consume_transaction is not None), True)

    def test_lineup_no_contest_draft_group(self):
        lineup = Lineup()
        lineup.draft_group = self.draft_group2
        lineup.user = self.user
        lineup.save()
        bm = BuyinManager(self.user)
        contest_pool = self.contest_pool
        contest_pool.draft_group = None
        contest_pool.save()
        self.assertRaises(exceptions.ContestIsNotAcceptingLineupsException,
                          lambda: bm.buyin(contest_pool, lineup))

    def test_lineup_share_draft_group(self):
        lineup = Lineup()
        lineup.draft_group = self.draft_group
        lineup.user = self.user

        bm = BuyinManager(self.user)
        self.assertRaises(exceptions.ContestLineupMismatchedDraftGroupsException,
                          lambda: bm.buyin(self.contest_pool, lineup))

    def test_contest_full(self):
        self.contest_pool.current_entries = 19
        self.contest_pool.entries = 1
        self.contest_pool.save()
        bm = BuyinManager(self.user)
        self.assertRaises(exceptions.ContestIsFullException,
                          lambda: bm.buyin(self.contest_pool))

    # def test_contest_is_in_progress(self):
    #     self.contest.status = self.contest.INPROGRESS
    #     self.contest.save()
    #     self.should_raise_contest_is_in_progress_or_closed_exception()
    #
    # def test_contest_is_cancelled(self):
    #     self.contest.status = self.contest.CANCELLED
    #     self.contest.save()
    #     self.should_raise_contest_is_in_progress_or_closed_exception()
    #
    # def test_contest_is_closed(self):
    #     self.contest.status = self.contest.CLOSED
    #     self.contest.save()
    #     self.should_raise_contest_is_in_progress_or_closed_exception()
    #
    # def test_contest_is_completed(self):
    #     self.contest.status = self.contest.COMPLETED
    #     self.contest.save()
    #     self.should_raise_contest_is_in_progress_or_closed_exception()
    #
    # def should_raise_contest_is_in_progress_or_closed_exception(self):
    #     bm = BuyinManager(self.user)
    #     self.assertRaises(exceptions.ContestIsInProgressOrClosedException,
    #               lambda: bm.buyin(self.contest))

    def test_user_owns_lineup(self):
        lineup = Lineup()
        lineup.draft_group = self.draft_group2
        lineup.user = self.get_admin_user()

        bm = BuyinManager(self.user)
        self.assertRaises(LineupDoesNotMatchUser,
                          lambda: bm.buyin(self.contest_pool, lineup))

    def test_user_submits_past_max_entries(self):
        self.contest_pool.max_entries = 1
        self.contest_pool.entries = 3
        self.contest_pool.save()

        bm = BuyinManager(self.user)
        bm.buyin(self.contest_pool)

        bm = BuyinManager(self.user)
        self.assertRaises(exceptions.ContestMaxEntriesReachedException,
                          lambda: bm.buyin(self.contest_pool))
示例#28
0
 def get_player_model_class(self, sport):
     ssm = SiteSportManager()
     site_sport = ssm.get_site_sport(sport)
     sport_player_model_class = ssm.get_player_class(site_sport)
     return sport_player_model_class
示例#29
0
 def __init__(self, block):
     self.block = block
     self.cutoff = self.block.get_utc_cutoff()
     self.block_prize_structures = BlockPrizeStructure.objects.filter(block=self.block)
     self.site_sport_manager = SiteSportManager()
     self.game_model_class = self.site_sport_manager.get_game_class(self.block.site_sport)
示例#30
0
    def update_final_fantasy_points(self, draft_group_id, scorer_class=None):
        """
        updates the final_fantasy_points for all players in the draft group

        :param draft_group_id:
        :param scorer_class: gives the caller ability to override the scoring class used to calc fantasy points
        :return:
        """

        # get the draft group and then get its players
        draft_group = self.get_draft_group(draft_group_id)
        logger.info("Updating final fantasy points for %s" % draft_group)

        # check if the draft_group has already finalized fantasy_points...
        if draft_group.fantasy_points_finalized is not None:
            err_msg = 'draft_group id: %s' % draft_group_id
            raise FantasyPointsAlreadyFinalizedException(err_msg)

        # get the site sport, and the draft group players
        site_sport = draft_group.salary_pool.site_sport
        players = self.get_players(draft_group)

        # get all the PlayerStats objects for this draft group
        ssm = SiteSportManager()
        # print('ssm.get_score_system_class( %s ):' % str(site_sport))

        if scorer_class is None:
            salary_score_system_class = ssm.get_score_system_class(site_sport)
        else:
            salary_score_system_class = scorer_class

        score_system = salary_score_system_class()
        game_srids = [
            x.game_srid for x in self.get_game_teams(draft_group=draft_group)
        ]
        game_srids = list(
            set(game_srids
                ))  # itll have the same games twice. this removes duplicates

        # get the PlayerStats model(s) for the sport.
        # and get an instance of the sports scoring.classes.<Sport>SalaryScoreSystem
        # to determine which player stats models to use to retrieve the final fantasy_points from!
        for draft_group_player in players:
            # get the sports.<sport>.player  -- we'll need it later
            sport_player = draft_group_player.salary_player.player
            # determine the PlayerStats class to retrieve the fantasy_points from
            player_stats_class = score_system.get_primary_player_stats_class_for_player(
                sport_player)

            try:
                # Find the player's stats for this draft group.
                player_stats = player_stats_class.objects.get(
                    srid_game__in=game_srids, srid_player=sport_player.srid)
            # except player_stats_class.MultipleObjectsReturned as e1:
            #     # print('site_sport:', str(site_sport))
            #     # print('game_srids:', str(game_srids))
            #     # print('sport_player.srid:', str(sport_player.srid))
            #     # raise Exception('testing MultipleObjectsReturned issue')
            #
            #     #
            #     # raise an exception that will let us troubleshoot the draft group range...
            #     # because the draft group probably has too wide of a range
            #     # but it never should have let us create it then!
            #     err_msg = 'original exception[%s]' % str(e1)
            #     err_msg += ''
            #     raise self.StartEndRangeException(err_msg)

            except player_stats_class.DoesNotExist:
                logger.warning("PlayerStats can't be found for: %s" %
                               sport_player)
                logger.info('game_srids: %s' % game_srids)
                logger.info('sport_player.srid: %s' % sport_player.srid)
                player_stats = None
                continue

            # move the current fantasy_points from the player_stats into
            # the draft_group_player and save it!
            logger.info('Setting %s to %s' %
                        (draft_group_player, player_stats))
            draft_group_player.final_fantasy_points = player_stats.fantasy_points
            draft_group_player.save()

        #
        # set the datetime for when we finalized the draft_group players fantasy points
        draft_group.fantasy_points_finalized = timezone.now()
        draft_group.save()
        logger.info("Done updating final fantasy points for %s" % draft_group)