Esempio n. 1
0
 def __init__(self, session):
     self.session = session
     self.games = NFLGameManager(self.session)
     self.teams = NFLTeamManager(self.session)
     self.odds = NFLOddsManager(self.session)
     self.accounts = AccountingManager(self.session)
     # FIXME: put this in config or database
     self.max_bet = 500
Esempio n. 2
0
class UserManagementViewer(AdminViewer):
    def __init__(self, request):
        super(UserManagementViewer, self).__init__(request)
        prepare_main_data(self.request)
        self.users = UserManager(self.request.db)
        self.accounts = AccountingManager(self.request.db)
        self._dispatch_table = dict(
            list=self.list_users,
            add=self.add_user,
            delete=self.delete_user,
            confirmdelete=self.confirm_delete_user,
            view=self.view_user,
            listgroups=self.list_groups,
            viewgroup=self.view_group,
        )
        self.context = self.request.matchdict['context']
        self._view = self.context
        self.dispatch()

    def list_users(self):
        users = self.users.user_query().all()
        template = 'trumpet:templates/user-list.mako'
        env = dict(users=users)
        self.layout.content = self.render(template, env)
        #self.layout.resources.manage_images.need()
        self.layout.resources.manage_users.need()

    def add_user(self):
        schema = AddUserSchema()
        form = deform.Form(schema, buttons=('submit', ))
        self.layout.resources.deform_auto_need(form)
        if 'submit' in self.request.POST:
            controls = self.request.POST.items()
            self.layout.subheader = 'User Submitted'
            try:
                data = form.validate(controls)
            except deform.ValidationFailure, e:
                self.layout.content = e.render()
                return
            name = data['name']
            password = data['password']
            confirm = data['confirm']
            if password == confirm:
                user = self.users.add_user(name, password)
                self.accounts.add_user_account(user)
                content = '<p>User %s added.</p>' % user.username
                self.layout.content = content
            else:
                self.layout.content = 'password mismatch'
            return
        rendered = form.render()
        self.layout.content = rendered
        self.layout.subheader = 'Add a user'
Esempio n. 3
0
class UserManagementViewer(AdminViewer):
    def __init__(self, request):
        super(UserManagementViewer, self).__init__(request)
        prepare_main_data(self.request)
        self.users = UserManager(self.request.db)
        self.accounts = AccountingManager(self.request.db)
        self._dispatch_table = dict(
            list=self.list_users,
            add=self.add_user,
            delete=self.delete_user,
            confirmdelete=self.confirm_delete_user,
            view=self.view_user,
            listgroups=self.list_groups,
            viewgroup=self.view_group,)
        self.context = self.request.matchdict['context']
        self._view = self.context
        self.dispatch()
        
    def list_users(self):
        users = self.users.user_query().all()
        template = 'trumpet:templates/user-list.mako'
        env = dict(users=users)
        self.layout.content = self.render(template, env)
        #self.layout.resources.manage_images.need()
        self.layout.resources.manage_users.need()
        
    def add_user(self):
        schema = AddUserSchema()
        form = deform.Form(schema, buttons=('submit',))
        self.layout.resources.deform_auto_need(form)
        if 'submit' in self.request.POST:
            controls = self.request.POST.items()
            self.layout.subheader = 'User Submitted'
            try:
                data = form.validate(controls)
            except deform.ValidationFailure, e:
                self.layout.content = e.render()
                return
            name = data['name']
            password = data['password']
            confirm = data['confirm']
            if password == confirm:
                user = self.users.add_user(name, password)
                self.accounts.add_user_account(user)
                content = '<p>User %s added.</p>' % user.username
                self.layout.content = content
            else:
                self.layout.content = 'password mismatch'
            return
        rendered = form.render()
        self.layout.content = rendered
        self.layout.subheader = 'Add a user'
Esempio n. 4
0
    def __init__(self, request):
        super(BetsViewer, self).__init__(request)
        #self.layout.main_menu = make_main_menu(self.request).render()
        #self.layout.ctx_menu = make_ctx_menu(self.request).output()
        make_context_menu(self.request)
        
        self.accounts = AccountingManager(self.request.db)
        
        self.teams = NFLTeamManager(self.request.db)
        self.games = NFLGameManager(self.request.db)
        self.odds = NFLOddsManager(self.request.db)
        self.bets = BetsManager(self.request.db)
        
        settings = self.get_app_settings()
        url = settings['vignewton.nfl.odds.url']
        self.odds.oddscache.set_url(url)
        
        self.context = self.request.matchdict['context']
        # make dispatch table
        self._cntxt_meth = dict(
            main=self.main_view,
            allpending=self.view_all_pending_bets,
            allclosed=self.view_all_closed_bets,
            )

        if self.context in self._cntxt_meth:
            self._cntxt_meth[self.context]()
        else:
            msg = 'Undefined Context: %s' % self.context
            self.layout.content = '<b>%s</b>' % msg
Esempio n. 5
0
 def __init__(self, request):
     super(UserManagementViewer, self).__init__(request)
     prepare_main_data(self.request)
     self.users = UserManager(self.request.db)
     self.accounts = AccountingManager(self.request.db)
     self._dispatch_table = dict(
         list=self.list_users,
         add=self.add_user,
         delete=self.delete_user,
         confirmdelete=self.confirm_delete_user,
         view=self.view_user,
         listgroups=self.list_groups,
         viewgroup=self.view_group,
     )
     self.context = self.request.matchdict['context']
     self._view = self.context
     self.dispatch()
Esempio n. 6
0
 def __init__(self, session):
     self.session = session
     self.games = NFLGameManager(self.session)
     self.teams = NFLTeamManager(self.session)
     self.odds = NFLOddsManager(self.session)
     self.accounts = AccountingManager(self.session)
     # FIXME: put this in config or database
     self.max_bet = 500
Esempio n. 7
0
def setup(env):
    request = env['request']
    db = request.db
    env['db'] = db
    settings = env['registry'].settings

    url = settings['vignewton.nfl.schedule.url']
    env['url'] = url
    odds_url = settings['vignewton.nfl.odds.url']
    from vignewton.managers.nflgames import NFLTeamManager
    tm = NFLTeamManager(db)
    env['tm'] = tm
    from vignewton.managers.odds import NFLOddsManager
    om = NFLOddsManager(db)
    env['om'] = om
    om.oddscache.set_url(odds_url)
    if not om.get_current_odds():
        filename = 'testdata/o.pickle'
        if not os.path.isfile(filename):
            om.update_current_odds()
        else:
            om.populate_from_pickle(filename)
    from vignewton.managers.nflgames import NFLGameManager
    gm = NFLGameManager(db)
    env['gm'] = gm
    gm.set_schedule_url(url)
    update_game_schedule = False
    if update_game_schedule:
        update_games(gm)
    env['ug'] = update_games
    from vignewton.managers.accounting import AccountingManager
    am = AccountingManager(db)
    am.initialize_bets_manager()
    env['am'] = am
    #env['games'] = om.oddscache.get_latest()[0].content
    #env['bg'] = env['games'][-3]
    from vignewton.managers.util import determine_max_bet
    env['dmb'] = determine_max_bet
    env['game'] = gm.query().get(125)
    backup_cache(gm, om)
    from vignewton.managers.bets import BetsManager
    bm = BetsManager(db)
    env['bm'] = bm
    from vignewton.managers.util import chop_ical_nflgame_desc
    env['cind'] = chop_ical_nflgame_desc
    env['g'] = gm.get(131)
Esempio n. 8
0
def setup(env):
    request = env['request']
    db = request.db
    env['db'] = db
    settings = env['registry'].settings
    
    url = settings['vignewton.nfl.schedule.url']
    env['url'] = url
    odds_url = settings['vignewton.nfl.odds.url']
    from vignewton.managers.nflgames import NFLTeamManager
    tm = NFLTeamManager(db)
    env['tm'] = tm
    from vignewton.managers.odds import NFLOddsManager
    om = NFLOddsManager(db)
    env['om'] = om
    om.oddscache.set_url(odds_url)
    if not om.get_current_odds():
        filename = 'testdata/o.pickle'
        if not os.path.isfile(filename):
            om.update_current_odds()
        else:
            om.populate_from_pickle(filename)
    from vignewton.managers.nflgames import NFLGameManager
    gm = NFLGameManager(db)
    env['gm'] = gm
    gm.set_schedule_url(url)
    update_game_schedule = False
    if update_game_schedule:
        update_games(gm)
    env['ug'] = update_games
    from vignewton.managers.accounting import AccountingManager
    am = AccountingManager(db)
    am.initialize_bets_manager()
    env['am'] = am
    #env['games'] = om.oddscache.get_latest()[0].content
    #env['bg'] = env['games'][-3]
    from vignewton.managers.util import determine_max_bet
    env['dmb'] = determine_max_bet
    env['game'] = gm.query().get(125)
    backup_cache(gm, om)
    from vignewton.managers.bets import BetsManager
    bm = BetsManager(db)
    env['bm'] = bm
    from vignewton.managers.util import chop_ical_nflgame_desc
    env['cind'] = chop_ical_nflgame_desc
    env['g'] = gm.get(131)
Esempio n. 9
0
def populate_accounting_tables(session):
    db = session
    try:
        with transaction.manager:
            for ttype in TRANSACTION_TYPES:
                x = TransactionType()
                x.name = ttype
                db.add(x)
    except IntegrityError:
        transaction.abort()
            
    try:
        from vignewton.managers.accounting import AccountingManager
        am = AccountingManager(db)
        for acct in ['Cash', 'Wagers', 'JuiceInsurance', 'InTheWild']:
            am.add_account('%s_Account' % acct)
    except IntegrityError:
        transaction.abort()
Esempio n. 10
0
 def __init__(self, request):
     super(UserManagementViewer, self).__init__(request)
     prepare_main_data(self.request)
     self.users = UserManager(self.request.db)
     self.accounts = AccountingManager(self.request.db)
     self._dispatch_table = dict(
         list=self.list_users,
         add=self.add_user,
         delete=self.delete_user,
         confirmdelete=self.confirm_delete_user,
         view=self.view_user,
         listgroups=self.list_groups,
         viewgroup=self.view_group,)
     self.context = self.request.matchdict['context']
     self._view = self.context
     self.dispatch()
Esempio n. 11
0
class BetsManager(object):
    def __init__(self, session):
        self.session = session
        self.games = NFLGameManager(self.session)
        self.teams = NFLTeamManager(self.session)
        self.odds = NFLOddsManager(self.session)
        self.accounts = AccountingManager(self.session)
        # FIXME: put this in config or database
        self.max_bet = 500
        
        
    def query(self):
        return self.session.query(UserBet)

    def get(self, bet_id):
        return self.query().get(bet_id)

    def get_current_bet(self, user_id):
        q = self.session.query(CurrentBet)
        return q.get(user_id)

    def _get_odds(self, game_id):
        odds = self.odds.get_odds(game_id)
        return odds

    def _copy_current_odds(self, bet, odds):
        for field in ['favored_id', 'underdog_id', 'total',
                      'spread']:
            setattr(bet, field, getattr(odds, field))

    def _check_amount(self, user_id, amount):
        if amount % 10 != 0:
            raise BetNotInTensError, "Bad amount %d" % amount
        if amount < 10:
            raise MinimumBetError, "Bet must be at least ten: %d" % amount
        if amount > self.max_bet:
            msg = "Bet must be no more than %d: amount %d"
            raise MaximumBetError, msg % (self.max_bet, amount)
        acct = self.accounts.get(user_id)
        balance = acct.balance.balance
        max_bet = determine_max_bet(balance)
        if amount > max_bet:
            juice_insurance = amount / 10
            total = amount + juice_insurance
            msg = "Total needed %d, current balance %d" % (total, balance)
            raise InsufficientFundsError, msg
        return True

    def check_bet_amount(self, user_id, amount):
        return self._check_amount(user_id, amount)
    
    # pick is either an NFLTeam object, 'over', or 'under'
    def request_bet(self, user_id, game_id, amount, bettype, pick):
        # here we sanitize the bettype and
        # amount arguments
        if bettype not in ['line', 'underover']:
            raise RuntimeError, "Bad bettype %s:" % bettype
        # check amount
        # self.accounts.check_bet_amount(user_id, amount)
        self._check_amount(user_id, amount)
        if self.get_current_bet(user_id) is not None:
            raise UnconfirmedBetExistsError, "Betting in progress"
        with transaction.manager:
            now = datetime.now()
            curbet = CurrentBet()
            curbet.user_id = user_id
            curbet.game_id = game_id
            curbet.created = now
            curbet.amount = amount
            curbet.bet_type = bettype
            if bettype == 'line':
                # the pick is a team
                curbet.team_id = pick.id
            else:
                # the pick is under/over
                curbet.underover = pick
            self.session.add(curbet)
        return self.session.merge(curbet)

    def show_requested_bet(self, user_id):
        current = self.get_current_bet(user_id)
        if current is None:
            raise NoCurrentBetError, "No current bet"
        odds = self._get_odds(current.game_id)
        odata = self.odds.get_data(odds)
        return current, odata
    
    def cancel_requested_bet(self, user_id):
        with transaction.manager:
            q = self.session.query(CurrentBet)
            q = q.filter_by(user_id=user_id)
            q.delete()
            
    def place_requested_bet(self, user_id):
        current, odata = self.show_requested_bet(user_id)
        game_id = current.game_id
        amount = current.amount
        bettype = current.bet_type
        underover = current.underover
        team_id = current.team_id
        account = self.accounts.get(user_id)
        txn = self.accounts.place_bet(account.id, amount)
        with transaction.manager:
            now = datetime.now()
            bet = UserBet()
            bet.user_id = user_id
            bet.game_id = current.game_id
            bet.txn_id = txn.id
            bet.created = current.created
            bet.amount = current.amount
            bet.bet_type = current.bet_type
            bet.underover = current.underover
            bet.team_id = current.team_id
            for field in odata:
                setattr(bet, field, odata[field])
            self.session.add(bet)
            dq = self.session.query(CurrentBet).filter_by(user_id=user_id)
            dq.delete()
        return self.session.merge(bet)
    

    def get_bets(self, user_id=None, game_id=None):
        pass

    def get_game_bets(self, game_id):
        q = self.query()
        q = q.filter_by(game_id=game_id)
        return q.all()
    

    def get_user_bets(self, user_id, game_id=None):
        q = self.query()
        q = q.filter_by(user_id=user_id)
        if game_id is not None:
            q = q.filter_by(game_id=game_id)
        return q.all()

    def get_user_closed_bets(self, user_id, game_id=None):
        q = self.session.query(ClosedBet)
        q = q.filter_by(user_id=user_id)
        if game_id is not None:
            q = q.filter_by(game_id=game_id)
        return q.all()
        
    def _get_score(self, bet):
        "returns score as favored, underdog"
        game = bet.game
        score = game.score
        if bet.favored_id == game.away_id:
            favored_score = score.away_score
        elif bet.favored_id == game.home_id:
            favored_score = score.home_score
        else:
            raise RuntimeError, "Team/score mismatch game %d" % game.id
        if bet.underdog_id == game.away_id:
            underdog_score = score.away_score
        elif bet.underdog_id == game.home_id:
            underdog_score = score.home_score
        else:
            raise RuntimeError, "Team/score mismatch game %d" % game.id
        return favored_score, underdog_score
    
    
    def _determine_bet(self, bet_id):
        bet = self.query().get(bet_id)
        if bet is None:
            raise RuntimeError, "Bad bet id %d" % bet_id
        if bet.game.score is None:
            return
        fscore, uscore = self._get_score(bet)
        result = determine_bet(bet, fscore, uscore)
        acct = self.accounts.get(bet.user_id)
        if result == 'push':
            txn = self.accounts.push_bet(acct.id, bet.amount)
        elif result == 'win':
            txn = self.accounts.win_bet(acct.id, bet.amount)
        elif result == 'lose':
            txn = self.accounts.lose_bet(bet.amount)
        else:
            raise RuntimeError, "bad result %s" % result
        with transaction.manager:
            cb = make_closed_bet(bet, result, txn)
            self.session.add(cb)
            self.session.delete(bet)
        return self.session.merge(cb)
    
    def determine_bet(self, bet_id):
        return self._determine_bet(bet_id)

    def determine_bets(self):
        closed = list()
        for bet in self.get_all_bets():
            cb = self.determine_bet(bet.id)
            closed.append(cb)
        return closed
    
    def get_all_bets(self):
        return self.query().all()

    def get_all_closed_bets(self):
        return self.session.query(ClosedBet).all()
Esempio n. 12
0
class BetsManager(object):
    def __init__(self, session):
        self.session = session
        self.games = NFLGameManager(self.session)
        self.teams = NFLTeamManager(self.session)
        self.odds = NFLOddsManager(self.session)
        self.accounts = AccountingManager(self.session)
        # FIXME: put this in config or database
        self.max_bet = 500

    def query(self):
        return self.session.query(UserBet)

    def get(self, bet_id):
        return self.query().get(bet_id)

    def get_current_bet(self, user_id):
        q = self.session.query(CurrentBet)
        return q.get(user_id)

    def _get_odds(self, game_id):
        odds = self.odds.get_odds(game_id)
        return odds

    def _copy_current_odds(self, bet, odds):
        for field in ['favored_id', 'underdog_id', 'total', 'spread']:
            setattr(bet, field, getattr(odds, field))

    def _check_amount(self, user_id, amount):
        if amount % 10 != 0:
            raise BetNotInTensError, "Bad amount %d" % amount
        if amount < 10:
            raise MinimumBetError, "Bet must be at least ten: %d" % amount
        if amount > self.max_bet:
            msg = "Bet must be no more than %d: amount %d"
            raise MaximumBetError, msg % (self.max_bet, amount)
        acct = self.accounts.get(user_id)
        balance = acct.balance.balance
        max_bet = determine_max_bet(balance)
        if amount > max_bet:
            juice_insurance = amount / 10
            total = amount + juice_insurance
            msg = "Total needed %d, current balance %d" % (total, balance)
            raise InsufficientFundsError, msg
        return True

    def check_bet_amount(self, user_id, amount):
        return self._check_amount(user_id, amount)

    # pick is either an NFLTeam object, 'over', or 'under'
    def request_bet(self, user_id, game_id, amount, bettype, pick):
        # here we sanitize the bettype and
        # amount arguments
        if bettype not in ['line', 'underover']:
            raise RuntimeError, "Bad bettype %s:" % bettype
        # check amount
        # self.accounts.check_bet_amount(user_id, amount)
        self._check_amount(user_id, amount)
        if self.get_current_bet(user_id) is not None:
            raise UnconfirmedBetExistsError, "Betting in progress"
        with transaction.manager:
            now = datetime.now()
            curbet = CurrentBet()
            curbet.user_id = user_id
            curbet.game_id = game_id
            curbet.created = now
            curbet.amount = amount
            curbet.bet_type = bettype
            if bettype == 'line':
                # the pick is a team
                curbet.team_id = pick.id
            else:
                # the pick is under/over
                curbet.underover = pick
            self.session.add(curbet)
        return self.session.merge(curbet)

    def show_requested_bet(self, user_id):
        current = self.get_current_bet(user_id)
        if current is None:
            raise NoCurrentBetError, "No current bet"
        odds = self._get_odds(current.game_id)
        odata = self.odds.get_data(odds)
        return current, odata

    def cancel_requested_bet(self, user_id):
        with transaction.manager:
            q = self.session.query(CurrentBet)
            q = q.filter_by(user_id=user_id)
            q.delete()

    def place_requested_bet(self, user_id):
        current, odata = self.show_requested_bet(user_id)
        game_id = current.game_id
        amount = current.amount
        bettype = current.bet_type
        underover = current.underover
        team_id = current.team_id
        account = self.accounts.get(user_id)
        txn = self.accounts.place_bet(account.id, amount)
        with transaction.manager:
            now = datetime.now()
            bet = UserBet()
            bet.user_id = user_id
            bet.game_id = current.game_id
            bet.txn_id = txn.id
            bet.created = current.created
            bet.amount = current.amount
            bet.bet_type = current.bet_type
            bet.underover = current.underover
            bet.team_id = current.team_id
            for field in odata:
                setattr(bet, field, odata[field])
            self.session.add(bet)
            dq = self.session.query(CurrentBet).filter_by(user_id=user_id)
            dq.delete()
        return self.session.merge(bet)

    def get_bets(self, user_id=None, game_id=None):
        pass

    def get_game_bets(self, game_id):
        q = self.query()
        q = q.filter_by(game_id=game_id)
        return q.all()

    def get_user_bets(self, user_id, game_id=None):
        q = self.query()
        q = q.filter_by(user_id=user_id)
        if game_id is not None:
            q = q.filter_by(game_id=game_id)
        return q.all()

    def get_user_closed_bets(self, user_id, game_id=None):
        q = self.session.query(ClosedBet)
        q = q.filter_by(user_id=user_id)
        if game_id is not None:
            q = q.filter_by(game_id=game_id)
        return q.all()

    def _get_score(self, bet):
        "returns score as favored, underdog"
        game = bet.game
        score = game.score
        if bet.favored_id == game.away_id:
            favored_score = score.away_score
        elif bet.favored_id == game.home_id:
            favored_score = score.home_score
        else:
            raise RuntimeError, "Team/score mismatch game %d" % game.id
        if bet.underdog_id == game.away_id:
            underdog_score = score.away_score
        elif bet.underdog_id == game.home_id:
            underdog_score = score.home_score
        else:
            raise RuntimeError, "Team/score mismatch game %d" % game.id
        return favored_score, underdog_score

    def _determine_bet(self, bet_id):
        bet = self.query().get(bet_id)
        if bet is None:
            raise RuntimeError, "Bad bet id %d" % bet_id
        if bet.game.score is None:
            return
        fscore, uscore = self._get_score(bet)
        result = determine_bet(bet, fscore, uscore)
        acct = self.accounts.get(bet.user_id)
        if result == 'push':
            txn = self.accounts.push_bet(acct.id, bet.amount)
        elif result == 'win':
            txn = self.accounts.win_bet(acct.id, bet.amount)
        elif result == 'lose':
            txn = self.accounts.lose_bet(bet.amount)
        else:
            raise RuntimeError, "bad result %s" % result
        with transaction.manager:
            cb = make_closed_bet(bet, result, txn)
            self.session.add(cb)
            self.session.delete(bet)
        return self.session.merge(cb)

    def determine_bet(self, bet_id):
        return self._determine_bet(bet_id)

    def determine_bets(self):
        closed = list()
        for bet in self.get_all_bets():
            cb = self.determine_bet(bet.id)
            closed.append(cb)
        return closed

    def get_all_bets(self):
        return self.query().all()

    def get_all_closed_bets(self):
        return self.session.query(ClosedBet).all()