Esempio n. 1
0
def bids():
    if request.method == 'GET':
        bids = Bid.query.all()
        return BidSchema().jsonify(bids, many=True)
    if request.method == 'POST':
        form = BidForm()

        if form.validate():
            bid = Bid(**request.form.to_dict())

            bid.usd_value = int(bid.amount) * int(bid.rate)

            if will_oversubscribe(bid):
                bid.status = 'Waitlisted'

            try:
                db.session.add(bid)
                db.session.commit()
            except IntegrityError:
                db.session.rollback()
                data = {'errors': {'name': 'You\'ve already bidded.'}}
                return make_response(jsonify(data), 400)

            return BidSchema().jsonify(bid)
        else:
            return make_response(jsonify({'errors': form.errors}), 400)
Esempio n. 2
0
def bids_view(per_page=None,
              start='',
              end='',
              direction=FirestorePage.NEXT_PAGE):
    if per_page is None or direction not in [
            FirestorePage.NEXT_PAGE, FirestorePage.PREV_PAGE
    ]:
        bids = Bid.order_by(('bid_order', Bid.ORDER_DESCENDING))
        if not bids[0].is_bid_complete(Game.read().user_count):
            bids = bids[1:]
        for bid in bids:
            bid.bid_map.sort(key=lambda item: item['username'])
        return bids
    page = FirestorePage(per_page)
    if start:
        page.current_start = Bid.read(start)
    if end:
        page.current_end = Bid.read(end)
    page.want = direction
    page = Bid.order_by(('bid_order', Bid.ORDER_DESCENDING), page=page)
    if len(page.items) == 0:
        return None
    if not page.items[0].is_bid_complete(Game.read().user_count):
        page.items = page.items[1:]
    for bid in page.items:
        bid.bid_map.sort(key=lambda item: item['username'])
    return page
Esempio n. 3
0
 def setUp(self) -> None:
     self.app = create_app(TestConfig)
     self.app_context = self.app.app_context()
     self.app_context.push()
     User.delete_all()
     Player.delete_all()
     Game.delete_all()
     Bid.delete_all()
Esempio n. 4
0
 def upload_players(self):
     # Index   0        1         2       3         4           5        6         7         8        9
     hdr = [
         'name', 'country', 'type', 'tags', 'bid_order', 'matches', 'runs',
         'catches', 'balls', 'wickets'
     ]
     if self.data_list[0] != hdr:
         return self.ERROR_INVALID_HEADER
     Player.delete_all()
     Bid.delete_all()
     Player.init_batch()
     for player_row in self.data_list[1:]:
         player_row.reverse()
         player = Player(player_row.pop().strip())
         player.country = player_row.pop().strip()
         country = Country(player.country)
         player.rank = country.rank
         player.color = country.color
         player.bg_color = country.bg_color
         player.country_code = country.code
         player.type = player_row.pop().strip()
         tags = [
             tag.strip().lower() for tag in player_row.pop().split(';')
             if len(tag) > 0
         ]
         tags.append(player.country.lower())
         tags.append(player.country_code.lower())
         if player.type.lower() not in tags:
             tags.append(player.type.lower())
         player.tags = tags
         try:
             player.bid_order = int(player_row.pop())
         except ValueError:
             pass
         try:
             player.matches = int(player_row.pop())
         except ValueError:
             pass
         try:
             player.runs = int(player_row.pop())
         except ValueError:
             pass
         try:
             player.catches = int(player_row.pop())
         except ValueError:
             pass
         try:
             player.balls = int(player_row.pop())
         except ValueError:
             pass
         try:
             player.wickets = int(player_row.pop())
         except ValueError:
             pass
         player.update_batch()
     Player.commit_batch()
     Game.init_game()
     return self.SUCCESS
Esempio n. 5
0
def invite_bid():
    available_players = available_players_view()
    if not available_players:
        return Bid.ERROR_NO_MORE_PLAYERS
    transaction = Bid.get_transaction()
    bid_result = invite_bid_transaction(transaction, available_players[0])
    if bid_result != Bid.SUCCESS:
        return bid_result
    bid = Bid.query_first(player_name=available_players[0].name)
    if not bid:
        return Bid.ERROR_SYSTEM
    return bid
Esempio n. 6
0
 def __call__(self):
     data = dict()
     # Game
     data['game'] = list()
     game = Game.read()
     if game:
         data['game'].append(game.to_dict())
     # User
     data['user'] = list()
     users = User.get_all()
     for user in users:
         user_dict = user.to_dict()
         data['user'].append(user_dict)
     # Player
     data['player'] = list()
     players = Player.get_all()
     for player in players:
         data['player'].append(player.to_dict())
     # Bid
     data['bid'] = list()
     bids = Bid.get_all()
     for bid in bids:
         data['bid'].append(bid.to_dict())
     # Write to the file
     with open(self.file_name, 'w') as json_file:
         json.dump(data,
                   json_file,
                   ensure_ascii=False,
                   sort_keys=True,
                   indent=4)
Esempio n. 7
0
def accept_bid(bid, user, amount=Bid.PASS):
    transaction = Bid.get_transaction()
    bid_result = accept_bid_transaction(transaction, bid, user, amount)
    if bid_result <= 0:
        return bid_result
    bid.refresh()
    game = Game.read()
    if not bid.is_bid_complete(game.user_count):
        return Bid.SUCCESS
    # Determine Winner
    player = Player.query_first(name=bid.player_name)
    winning_bid = max(bid.bid_map, key=lambda bid_dict: bid_dict['amount'])
    if winning_bid['amount'] < 1:
        purchase_player_transaction(transaction, player)
    else:
        winning_bids = [
            bid_dict for bid_dict in bid.bid_map
            if bid_dict['amount'] == winning_bid['amount']
        ]
        if len(winning_bids) > 1:
            winning_index = random.randrange(0, len(winning_bids))
            winning_bid = winning_bids[winning_index]
        winner = User.query_first(username=winning_bid['username'])
        purchase_player_transaction(transaction, player, winner,
                                    winning_bid['amount'])
        bid.winner = winning_bid['username']
        bid.winning_price = winning_bid['amount']
        bid.update()
    # Invite another bid
    return invite_bid()
Esempio n. 8
0
def invite_bid_transaction(transaction, player):
    player_ref, player_snapshot = player.get_doc(transaction)
    game = Game.read()
    if not game:
        game = Game.init_game()
    game_ref, game_snapshot = game.get_doc(transaction)
    # Validate
    if not player_snapshot or player_snapshot.get(
            'status') != Player.AVAILABLE:
        return Bid.ERROR_PLAYER_NOT_AVAILABLE
    if game_snapshot.get('bid_in_progress'):
        return Bid.ERROR_BID_IN_PROGRESS
    bid = Bid(player_snapshot.get('name'))
    # Creation not in transaction is fine since it will only create the bid once
    bid = bid.create()
    player_updates = {'status': Player.BIDDING}
    game_updates = {
        'bid_in_progress': True,
        'user_to_bid': game_snapshot.get('user_count'),
        'player_in_bidding': player_snapshot.get('name'),
        'users_to_bid': [user.username for user in User.get_all()]
    }
    # Auto bid for zero balance
    zero_balance_users = User.query(balance=0)
    if zero_balance_users:
        bid_ref, bid_snapshot = bid.get_doc(transaction)
        bid_updates = {
            'bid_map': bid_snapshot.get('bid_map'),
        }
        for user in zero_balance_users:
            zero_bid = {
                'username': user.username,
                'amount': Bid.NO_BALANCE,
            }
            bid_updates['bid_map'].append(zero_bid),
            game_updates['user_to_bid'] -= 1
            game_updates['users_to_bid'].remove(user.username)
        transaction.update(bid_ref, bid_updates)
    transaction.update(player_ref, player_updates)
    transaction.update(game_ref, game_updates)
    return Bid.SUCCESS
Esempio n. 9
0
    def bid_on_item():
        """Check whether user is logged in or not"""
        auth_header = request.headers.get('Authorization')
        access_token = auth_header.split(" ")[1]

        if access_token:
            #Attempt to decode the token and get the user_id
            user_id = User.decode_token(access_token)
            if not isinstance(user_id, str):
                #User is authenticated

                if request.method == 'POST':
                    bid_amount = float(request.data.get('bid_amount', ''))
                    bid_on_item = int(request.data.get('bid_on_item', ''))
                    if bid_amount and bid_on_item:
                        placed_bid = Bid(placed_by=user_id,
                                         bid_amount=bid_amount,
                                         bid_on_item=bid_on_item)
                        placed_bid.save()
                        item = Item.query.filter_by(
                            item_id=placed_bid.bid_on_item).first()
                        response = jsonify({
                            'status': 'bid successfully placed',
                            'bid_id': placed_bid.bid_id,
                            'bid_amount': placed_bid.bid_amount,
                            'placed_on': item.name,
                        })
                        return make_response(response), 201
                else:
                    response = jsonify({
                        'status':
                        'send a POST request with bid_amount and bid_on_item as form data to place bid'
                    })
                    return make_response(response), 200
            else:
                #User is not legit
                message = user_id
                response = {'message': message}
                return make_response(jsonify(response)), 401
Esempio n. 10
0
 def upload_all(cls, file_name='wc.json'):
     try:
         with open(file_name) as json_file:
             data = json.load(json_file)
     except FileNotFoundError:
         return cls.ERROR_FILE_NOT_FOUND
     # Load User data
     if 'user' in data:
         User.delete_all()
         User.init_batch()
         for user_dict in data['user']:
             user = User.from_dict(user_dict)
             if not user:
                 continue
             user.update_batch()
         User.commit_batch()
     # Load Game
     if 'game' in data:
         game_dict = next((game for game in data['game']), None)
         if game_dict:
             game = Game.from_dict(game_dict)
             if game:
                 Game.delete_all()
                 game.create()
     # Load Player
     if 'player' in data:
         Player.delete_all()
         Player.init_batch()
         for player_dict in data['player']:
             player = Player.from_dict(player_dict)
             if not player:
                 continue
             player.update_batch()
         Player.commit_batch()
     # Load Bid
     if 'bid' in data:
         Bid.delete_all()
         Bid.init_batch()
         for bid_dict in data['bid']:
             bid = Bid.from_dict(bid_dict)
             if not bid:
                 continue
             bid.update_batch()
         Bid.commit_batch()
     return cls.SUCCESS
Esempio n. 11
0
def new_player():
    bids = Bid.query.filter_by(active=1)
    if bids.count() > 0:
        flash('Alredy an auction in action')
        return redirect(url_for('index'))
    players = Player.query.filter_by(assigned=0)
    rand = random.randrange(0, players.count())
    rand_player = players[rand]
    rand_player.assigned = 1
    bid = Bid(bid=0, active=1, user_id=-1, player_id=rand_player.id)
    db.session.add(rand_player)
    db.session.add(bid)
    db.session.commit()
    str_new_bid = r'<li class="list-group-item d-flex justify-content-between align-items-center">    <span> ' + str(
        bid.player.name) + r' </span>    <span>' + str(
            bid.player.surname
        ) + r'</span>    <span> ' + str(
            bid.user.name
        ) + r' </span>    <span class="badge badge-primary badge-pill">' + str(
            bid.bid) + r'</span>    <span>' + str(bid.time) + r'</span></li>'
    socketio.emit('new_player', {'data': str_new_bid}, namespace='/test')
    return redirect(url_for('index'))
Esempio n. 12
0
 def test_auto_bid(self):
     users = User.get_all()
     self.assertEqual(9, len(users))
     game = Game.read()
     self.assertIsNotNone(game)
     self.assertEqual(9, game.user_count)
     self.assertEqual(150, game.player_count)
     self.assertEqual(150, game.player_to_bid)
     self.assertFalse(game.bid_in_progress)
     invite_bid()
     game.refresh()
     while game.bid_in_progress:
         bid = Bid.query_first(player_name=game.player_in_bidding)
         for user in users:
             user.refresh()
             if user.balance > 0:
                 sbp = game.avg_player_bid
                 amount = randrange(sbp - 20, sbp + 20)
                 if user.balance < amount:
                     amount = user.balance
                 accept_bid(bid, user, amount)
         game.refresh()
     self.assertEqual(0, game.player_to_bid)
Esempio n. 13
0
def index():
    form = BiddingForm()
    yourBids = Bid.query.filter_by(user_id=current_user.username).all()
    allVegetables = Vegi.query.all()
    if request.method == 'POST':
        if form.validate_on_submit():
            if Vegi.query.filter_by(
                    vegetable=form.vegetable.data).first() is None:
                flash('VERBOTEN!! (vegi not found)')
                return redirect(url_for('index'))
            if current_user.get_money() < form.amount.data:
                flash('VERBOTEN!! (not enough izhk)')
                return redirect(url_for('index'))
            prevBid = Bid.query.filter_by(
                vegetable=form.vegetable.data).first()
            if prevBid is not None:
                current_user.set_money(current_user.get_money() +
                                       prevBid.get_amount())
                current_user.set_money(current_user.get_money() -
                                       form.amount.data)
                prevBid.set_amount(form.amount.data)
                db.session.commit()
            else:
                myBid = Bid(amount=form.amount.data,
                            vegetable=form.vegetable.data,
                            user_id=current_user.username)
                current_user.set_money(current_user.get_money() -
                                       form.amount.data)
                db.session.add(myBid)
                db.session.commit()
            flash('Crangrats! Your bid is placed!')

    return render_template('index.html',
                           title='Home',
                           form=form,
                           yourBids=yourBids,
                           allVegetables=allVegetables)
Esempio n. 14
0
def auction(auction_id):
    auction = Auction.query.filter_by(id=auction_id).first_or_404()
    users = auction.users.order_by(db.func.lower(User.username))
    lot = auction.current_lot()
    if auction not in current_user.auctions:
        flash("You are not an authorized member of that auction.")
        return redirect(url_for("index"))
    balances = (auction.balances.join(User).order_by(
        db.func.lower(User.username)))
    if not lot:
        return render_template("auction.html",
                               title=f"Auction {auction_id}",
                               auction=auction,
                               users=users,
                               balances=balances,
                               lot=None)
    advance_form = AdvanceForm()
    advance_form.auction_id.data = auction_id
    close_bidding_form = CloseBiddingForm()
    waiting_on = lot.waiting_on()
    if (current_user == auction.creator) and not waiting_on:
        if advance_form.submit_advance.data and advance_form.validate():
            lot.record_winner()
            if lot.content:
                auction.pool.remove_from_pool(lot.content)
            if not auction.is_complete():
                requested_lot = advance_form.next_lot.data
                if requested_lot:
                    try:
                        num_cards = int(requested_lot)
                        auction.add_lot(size=num_cards)
                    except ValueError:
                        auction.add_lot(card=advance_form.next_lot.data)
                else:
                    auction.add_lot(size=auction.default_lot)
            db.session.commit()
            emit("next lot", {"auction.id": auction.id},
                 namespace=None,
                 broadcast=True)
            if auction.is_complete():
                return render_template("auction.html",
                                       title=f"Auction {auction_id}",
                                       auction=auction,
                                       users=users,
                                       lot=None)
        if advance_form.submit_reset.data:
            lot.reset()
            db.session.commit()
            emit("reset", {"auction.id": auction.id},
                 namespace=None,
                 broadcast=True)
    if (current_user == auction.creator) and waiting_on:
        if close_bidding_form.submit_close.data:
            for user in waiting_on:
                bid = Bid(bidder=user, lot=auction.current_lot(), amount=0)
                db.session.add(bid)
            db.session.commit()
            skipped = ", ".join([user.username for user in waiting_on])
            flash(f"Proceeding without {skipped}.")
            emit("some bidders skipped", {"auction.id": auction.id},
                 namespace=None,
                 broadcast=True)
    bid_form = BidForm()
    bid_form.auction_id.data = auction_id
    bid_form.lot_id.data = auction.current_lot().id
    if bid_form.validate_on_submit() and bid_form.submit_bid.data:
        if bid_form.lot_id.data != auction.current_lot().id or not waiting_on:
            # Don't take bids if user wasn't looking at current lot for some
            # reason, or if the bid was somehow submitted on a completed lot.
            # Not sure if the first part is actually working as implemented.
            return redirect(url_for("auction", auction_id=auction_id))
        amount = bid_form.amount.data
        if not amount:
            amount = 0
        bid = Bid(bidder=current_user,
                  lot=auction.current_lot(),
                  amount=amount)
        db.session.add(bid)
        db.session.commit()
        emit("a bid", {"auction.id": auction.id},
             namespace=None,
             broadcast=True)
        flash(f"Bid of {amount} recorded.")
        return redirect(url_for("auction", auction_id=auction_id))
    lot = auction.current_lot()
    waiting_on = lot.waiting_on()
    if waiting_on and current_user not in waiting_on:
        names = ", ".join([user.username for user in waiting_on])
        flash(f"Waiting on {names}.")
    return render_template("auction.html",
                           title=f"Auction {auction_id}",
                           auction=auction,
                           users=users,
                           balances=balances,
                           lot=lot,
                           waiting_on=waiting_on,
                           bid_form=bid_form,
                           advance_form=advance_form,
                           close_bidding_form=close_bidding_form)
Esempio n. 15
0
def index():
    form = None
    bids = Bid.query.filter_by(active=1).order_by(Bid.time.desc())
    if current_user.is_anonymous:
        return render_template('index.html', title='Main screen', bids=bids)
    player_id = None
    max_bid = 1
    if bids.count() > 0:
        player_id = bids[0].player_id
        max_bid = bids[0].bid + 1
    form = BidForm(bid=max_bid,
                   user_id=current_user.get_id(),
                   player_id=player_id)
    if form.validate_on_submit():
        latest_bid = Bid.query.filter_by(active=1).order_by(
            Bid.time.desc()).first()
        user = User.query.filter_by(id=form.user_id.data).first()
        if form.bid.data <= user.money:
            sql = """select CURRENT_TIMESTAMP from users"""  #stupido hack
            result = db.engine.execute(sql)
            names = []
            for row in result:
                names.append(row[0])
            #flash('latest bid time ' + str(latest_bid.time) + '  current time ' + names[0])
            #datetime_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')   2018-06-25 14:03:39
            datetime_object = datetime.strptime(names[0], '%Y-%m-%d %H:%M:%S')
            #flash('differenza ' + str(datetime_object - latest_bid.time))
            if (datetime_object - latest_bid.time).total_seconds() < 31:
                if form.bid.data > latest_bid.bid:
                    #flash('ultimo user id ' + str(latest_bid.user_id) + '  il tuo invece ' + str(form.user_id.data) + '  la espressione ' + form.user_id.data != latest_bid.user_id)
                    if int(form.user_id.data) != int(latest_bid.user_id):
                        new_bid = Bid(bid=form.bid.data,
                                      active=1,
                                      user_id=form.user_id.data,
                                      player_id=form.player_id.data)
                        db.session.add(new_bid)
                        db.session.commit()
                        #flash('Good luck on your bid')
                        latest_bid = Bid.query.filter_by(active=1).order_by(
                            Bid.time.desc()).first()
                        str_new_bid = r'<li class="list-group-item d-flex justify-content-between align-items-center">    <span> ' + str(
                            latest_bid.player.name
                        ) + r' </span>    <span>' + str(
                            latest_bid.player.surname
                        ) + r'</span>    <span> ' + str(
                            latest_bid.user.name
                        ) + r' </span>    <span class="badge badge-primary badge-pill">' + str(
                            latest_bid.bid) + r'</span>    <span>' + str(
                                latest_bid.time) + r'</span></li>'
                        socketio.emit('my_response', {'data': str_new_bid},
                                      namespace='/test')
                    else:
                        flash('You are already the best bidder')
                else:
                    flash('You must offer more')
            else:
                flash('Too late :(')
        else:
            flash('Not enough money')
    return render_template('index.html',
                           title='Main screen',
                           bids=bids,
                           form=form)
Esempio n. 16
0
    def test_bid(self):
        # Setup players, users and game in db
        player_list = [
            {
                'name': 'Rohit Sharma',
                'bid_order': 2
            },
            {
                'name': 'Shikhar Dhawan',
                'bid_order': 4
            },
            {
                'name': 'Virat Kohli',
                'bid_order': 1
            },
            {
                'name': 'Hardik Pandya',
                'bid_order': 3
            },
            {
                'name': 'Jasprit Bumrah',
                'bid_order': 5
            },
        ]
        user_list = [
            {
                'username': '******',
                'name': 'Nayan'
            },
            {
                'username': '******',
                'name': 'Pranay'
            },
            {
                'username': '******',
                'name': 'Shraddha'
            },
            {
                'username': '******',
                'name': 'Raj'
            },
        ]
        for player in player_list:
            Player.from_dict(player).create()
        for user in user_list:
            User.from_dict(user).create()
        game = Game.init_game()

        # Invite bid and check
        bid = invite_bid()
        game.refresh()
        self.assertIsInstance(bid, Bid)
        self.assertEqual('Virat Kohli', game.player_in_bidding)
        self.assertEqual(4, game.user_to_bid)
        self.assertEqual(5, game.player_to_bid)
        self.assertEqual(Player.BIDDING,
                         Player.query_first(name='Virat Kohli').status)
        self.assertTrue(game.bid_in_progress)
        self.assertEqual(1, bid.bid_order)

        # One Bid on 1st player
        bid_result = accept_bid(bid, User.query_first(username='******'), 1500)
        bid.refresh()
        game.refresh()
        self.assertEqual(Bid.SUCCESS, bid_result)
        self.assertNotIn('nz', game.users_to_bid)
        self.assertTrue(bid.has_bid('nz'))
        self.assertEqual(3, game.user_to_bid)
        self.assertIn({'username': '******', 'amount': 1500}, bid.bid_map)

        # Two more bid on 1st player
        bid_result = accept_bid(bid, User.query_first(username='******'), 1200)
        bid.refresh()
        game.refresh()
        self.assertEqual(Bid.SUCCESS, bid_result)
        bid_result = accept_bid(bid, User.query_first(username='******'), 1550)
        bid.refresh()
        game.refresh()
        self.assertEqual(Bid.SUCCESS, bid_result)
        self.assertIn('sa', game.users_to_bid)
        self.assertEqual(1, game.user_to_bid)
        self.assertFalse(bid.is_bid_complete(game.user_count))
        self.assertEqual(Bid.SUCCESS, bid_result)
        self.assertFalse(bid.has_bid('sa'))

        # Last player and check winner
        bid_result = accept_bid(bid, User.query_first(username='******'), 1350)
        bid.refresh()
        game.refresh()
        self.assertEqual('RG', game.last_winner)
        self.assertEqual('Virat Kohli', game.last_player)
        self.assertEqual(1550, game.last_price)
        self.assertEqual(Player.PURCHASED,
                         Player.query_first(name='Virat Kohli').status)
        self.assertEqual('rg',
                         Player.query_first(name='Virat Kohli').owner_username)
        self.assertEqual('rg', bid.winner)
        self.assertEqual(1550, bid.winning_price)

        # Check if the next player is properly invited for bid
        bid = bid_result
        self.assertIsInstance(bid, Bid)
        self.assertEqual('Rohit Sharma', game.player_in_bidding)
        self.assertEqual(4, game.user_to_bid)
        self.assertEqual(4, game.player_to_bid)
        self.assertEqual(Player.BIDDING,
                         Player.query_first(name='Rohit Sharma').status)
        self.assertTrue(game.bid_in_progress)
        self.assertEqual(2, bid.bid_order)

        # Pass the player
        bid_result = accept_bid(bid, User.query_first(username='******'), Bid.PASS)
        game.refresh()
        bid.refresh()
        self.assertEqual(Bid.SUCCESS, bid_result)
        bid_result = accept_bid(bid, User.query_first(username='******'))
        game.refresh()
        bid.refresh()
        self.assertEqual(Bid.SUCCESS, bid_result)
        bid_result = accept_bid(bid, User.query_first(username='******'), Bid.PASS)
        game.refresh()
        bid.refresh()
        self.assertEqual(Bid.SUCCESS, bid_result)
        self.assertEqual(1, game.user_to_bid)
        bid_result = accept_bid(bid, User.query_first(username='******'))
        game.refresh()
        bid.refresh()
        self.assertIsInstance(bid_result, Bid)
        self.assertEqual('Unsold', game.last_winner)
        self.assertEqual('Rohit Sharma', game.last_player)
        self.assertEqual(0, game.last_price)
        self.assertEqual(Player.UNSOLD,
                         Player.query_first(name='Rohit Sharma').status)
        self.assertIsNone(
            Player.query_first(name='Rohit Sharma').owner_username)
        self.assertIsNone(bid.winner)
        self.assertEqual(0, bid.winning_price)

        # Check next player
        bid = bid_result
        self.assertEqual('Hardik Pandya', game.player_in_bidding)
        self.assertEqual(4, game.user_to_bid)
        self.assertEqual(3, game.player_to_bid)
        self.assertEqual(Player.BIDDING,
                         Player.query_first(name='Hardik Pandya').status)
        self.assertTrue(game.bid_in_progress)
        self.assertEqual(3, bid.bid_order)

        # Check accept bid errors
        self.assertEqual(Bid.ERROR_INVALID_AMOUNT, accept_bid(bid, None, 0))
        self.assertEqual(Bid.ERROR_SYSTEM, accept_bid(bid, None))
        test_user = User(name='Nayan', username='******')
        test_user.username = None
        self.assertEqual(Bid.ERROR_SYSTEM, accept_bid(bid, test_user))
        test_user.username = '******'
        self.assertEqual(Bid.ERROR_SYSTEM, accept_bid(None, test_user))
        test_bid = Bid('No Player')
        self.assertEqual(Bid.ERROR_SYSTEM, accept_bid(test_bid, test_user))
        test_bid = Bid.read(bid.doc_id)
        test_bid.player_name = 'Invalid Player'
        self.assertEqual(Bid.ERROR_PLAYER_NOT_FOUND,
                         accept_bid(test_bid, test_user))
        test_bid.player_name = 'Rohit Sharma'
        self.assertEqual(Bid.ERROR_PLAYER_NOT_INVITED_TO_BID,
                         accept_bid(test_bid, test_user))
        self.assertEqual(Bid.ERROR_NO_BALANCE,
                         accept_bid(bid, test_user, User.INITIAL_BUDGET + 100))
        self.assertEqual(Bid.SUCCESS, accept_bid(bid, test_user))
        self.assertEqual(Bid.ERROR_ALREADY_BID, accept_bid(bid, test_user))

        # Let other players bid
        bid_result = accept_bid(bid, User.query_first(username='******'), 2000)
        self.assertEqual(Bid.SUCCESS, bid_result)
        bid_result = accept_bid(bid, User.query_first(username='******'), 2100)
        self.assertEqual(Bid.SUCCESS, bid_result)
        bid_result = accept_bid(bid, User.query_first(username='******'), 10000)
        self.assertIsInstance(bid_result, Bid)
        self.assertEqual(
            'sa',
            Player.query_first(name=bid.player_name).owner_username)

        # Bid for next player and check the auto zero bid for 'sa'
        bid = bid_result
        bid_result = accept_bid(bid, User.query_first(username='******'), 2000)
        self.assertEqual(Bid.SUCCESS, bid_result)
        bid_result = accept_bid(bid, User.query_first(username='******'), 2600)
        self.assertEqual(Bid.SUCCESS, bid_result)
        bid_result = accept_bid(bid, User.query_first(username='******'), 2700)
        self.assertIsInstance(bid_result, Bid)
        self.assertEqual(
            'rg',
            Player.query_first(name=bid.player_name).owner_username)
        self.assertEqual(2, User.query_first(username='******').player_count)
        self.assertTrue(bid.has_bid('sa'))
        self.assertEqual(Bid.NO_BALANCE, [
            bd['amount'] for bd in bid.bid_map if bd['username'] == 'sa'
        ][0])

        # Bid for next player and check for a tie
        bid = bid_result
        bid_result = accept_bid(bid, User.query_first(username='******'), 5000)
        self.assertEqual(Bid.SUCCESS, bid_result)
        bid_result = accept_bid(bid, User.query_first(username='******'), 5000)
        self.assertEqual(Bid.SUCCESS, bid_result)
        bid_result = accept_bid(bid, User.query_first(username='******'), 5000)
        self.assertEqual(Bid.ERROR_NO_MORE_PLAYERS, bid_result)
        self.assertIn(
            Player.query_first(name=bid.player_name).owner_username,
            ['nz', 'pp', 'rg'])
        game.refresh()
        self.assertEqual(0, game.player_to_bid)
        self.assertIsNone(game.player_in_bidding)
        self.assertFalse(game.bid_in_progress)
        self.assertEqual(0, game.user_to_bid)

        # Check bids view
        bids = bids_view()
        self.assertEqual(5, len(bids))
        self.assertEqual('Jasprit Bumrah', bids[0].player_name)
        test_usernames = ['nz', 'pp', 'rg', 'sa']
        db_usernames = [bd['username'] for bd in bids[0].bid_map]
        self.assertListEqual(test_usernames, db_usernames)

        # Check paginated bids view
        page = bids_view(3)
        page = bids_view(page.per_page, end=page.current_end.doc_id)
        self.assertEqual('Rohit Sharma', page.items[0].player_name)
        db_usernames = [bd['username'] for bd in page.items[0].bid_map]
        self.assertListEqual(test_usernames, db_usernames)
Esempio n. 17
0
def item(id):

    # Buscando o item
    item = Item.query.filter_by(id=id).first_or_404()

    # buscando a melhor oferta neste item
    best_bid = Bid.query.filter_by(item=item, best_bid=True).first()
    if best_bid == None:
        item.best_bid = None
        print(item.best_bid)
    else:
        item.best_bid = best_bid

    # se a data limite já estiver passado o sistema atualiza os dados.
    if datetime.now() > item.expires_in:
        item.finished_off=True
        db.session.commit()

    # Item não encontrado.
    if item is None:
        flash("Item {} não encontrado".format(item_id))
        return redirect(url_for('index'))

    # Formulário.
    form = BidRegisterForm()

    # formulário enviado.
    if form.validate_on_submit():
        
        # caso o usuário seja o dono do item.
        if item.owner.id == current_user.id:
            flash("Desculpe, você não pode dar lances no seu próprio item.")
            return redirect(url_for('item', id=item.id))
        
        """ Tratamento de erros | -------------------------------------------"""
        # 01 - caso já tenha passado do período de lances abertos.
        now = datetime.utcnow()
        if now > item.expires_in:
            flash("Desculpe, o período de lances deste item já passou.")
            return redirect(url_for('item', id=item.id))

        # 02 - caso o preço do lance seja menor que o valor estipulado pelo dono.
        min_value = item.initial_price
        bid_value = form.value.data
        if min_value > bid_value:
            flash("O valor do lance deve ser maior que preço mínimo.")
            return redirect(url_for('item', id=item.id))

        # 03 - caso o lance seja menor que o maior já feito.
        for bid in item.bids:
            if bid.value > bid_value:
                flash("O valor do lance deve ser maior que os lances já feitos.")
                return redirect(url_for('item', id=item.id))


        # Setando False na antiga melhor oferta
        if best_bid is not None:
            best_bid.best_bid = False
            db.session.commit()
        
        # Salvando o novo lance na base de dados.
        bid = Bid(
            value=form.value.data,
            item=item,
            author=current_user,
            best_bid=True
        )

        db.session.add(bid)
        db.session.commit()


        flash("Parabéns! Novo lance feito cadastrado com sucesso.")
        return redirect(url_for('item', id=item.id))
    
    return render_template('item.html', form=form, item=item)