def test_one(): joao = User(name='Joao') jose = User(name='Jose') maria = User(name='Maria') auction = Auction("Playstation 3 Novo") auction.register_bid(Bid(joao, 300.0)) auction.register_bid(Bid(jose, 400.0)) auction.register_bid(Bid(maria, 250.0)) appraiser = Appraiser() appraiser.appraise(auction) expected_biggest = 400.0 expected_smallest = 250.0 assert expected_biggest == appraiser.biggest_bid assert expected_smallest == expected_smallest
def bid(request, id): if request.method == "POST"\ and len(Auction.objects.filter(id=id)) > 0\ and request.user is not Auction.objects.get(id=id).seller\ and not Auction.objects.get(id=id).resolved\ and not Auction.objects.get(id=id).banned: getcontext().prec = 2 auction = Auction.objects.get(id=id) bid = Bid() bid.auction = auction bid.bidder = request.user price = Decimal(request.POST["price"]) bids = Bid.objects.filter(auction_id=auction).order_by("price") if len(bids) > 0 and bids.last().bidder.id is request.user.id: messages.add_message(request, messages.ERROR, "You already have the highest bid!") if request.POST.get("next") is not None: return redirect(request.POST.get("next")) else: return HttpResponseRedirect('/auction/' + id + '/') if len(bids) > 0 and price > bids.last().price and price.as_tuple( ).exponent == -2: bid.price = price elif price >= auction.priceMin and price.as_tuple().exponent == -2: bid.price = price else: messages.add_message( request, messages.ERROR, "The bid must exceed the minimum price or the highest bid, whichever is higher, " "by at least 0.01 (always use 2 decimals).") if request.POST.get("next") is not None: return redirect(request.POST.get("next")) else: return HttpResponseRedirect('/auction/' + id + '/') bid.time = datetime.now() if auction.a_hash != Auction.objects.get(id=id).a_hash: messages.add_message( request, messages.ERROR, "The auction has either been edited or a new bid has been made since last time the " "page was loaded. Please try bidding again.") return redirect('/auction/' + id + '/') bid.save() auction.a_hash = hash(auction.name + auction.description + str(auction.due) + str( Bid.objects.filter(auction_id=id).order_by( "price").first().price) + salt) auction.save() # auction.new_bid_notify() update_session_stats(request, "bid") messages.add_message(request, messages.INFO, "Bid created") return redirect(request.POST.get("next"))
def project_view(request, project_id): """ Renders an individual project page, where users can ask questions, look at asked questions/responses, and submit a bid. """ proj = Project.objects.get(id=int(project_id)) bid_success = False if request.method == "POST": # User submitted a bid on this project form = BidSubmissionForm(request.POST) if form.is_valid(): team_members = form.cleaned_data["team_members"] description = form.cleaned_data["description"] section = Section.objects.get(students__id=request.user.id) new_bid = Bid(team_members=team_members, description=description, project=proj, is_approved=False, student=request.user) new_bid.save() request.user.profile.bids.add(new_bid) bid_success = True # TODO notify the user on the UI that the bid was submitted new_notification = Notification( recipient=request.user, subject="Bid Submitted", text="You submitted a bid on '{}' with team members {}.\ If the bid is awarded, you will be \ notified here.".format( proj.name, team_members)) new_notification.save() bid_on = request.user.profile.bids.filter(project=proj).exists() form = BidSubmissionForm() questions = Question.objects.filter(project__id=proj.id) question_form = QuestionForm() context = { "project": proj, "form": form, "bid_success": bid_success, # For showing a message that the bid was successfully saved "question_form": question_form, "questions": questions, "bid_on": bid_on } return render(request, "project.html", context)
def bid(request, auction_id): """ Allows a user to bid on a particular item """ if request.method != 'POST': return JsonResponse({'error': 'Must be called with post'}, status=405) auctions = Auction.objects.filter(id=auction_id) if len(auctions) == 0: return JsonResponse({'error': 'That auction does not exist'}, status=404) auction = auctions[0] if pytz.utc.localize(datetime.now()) > auction.expires: return JsonResponse({'error': 'This auction has ended'}) try: bid_amount = price_to_cents(request.POST.get('bprice')) except (TypeError, ValueError) as err: print err return JsonResponse({'error': "Invalid input for bid amount"}, status=400) try: with transaction.atomic(): bids = Bid.objects.filter(auction=auction).order_by('-bid_amount') if (len(bids) > 0 and bids[0].bid_amount >= bid_amount) or ( auction.list_price > bid_amount): return JsonResponse( {'error': "Entered amount is lower than current bid"}) bid = Bid() bid.bidder = request.user bid.auction = auction bid.bid_amount = bid_amount bid.save() auction.cur_price = bid_amount auction.save() AUCTIONEER.bid(auction, bid) except IntegrityError as err: print err return JsonResponse({'error': "You've already been outbid"}) return JsonResponse({'success': "You're the highest bidder"})
def resolve_bet(txn, bidder, outcome, price, amount, yes_dir): matching_bids = [ b for b in outcome.bids if b.yes_bid != yes_dir and b.price >= 100 - price ] matching_bids = list( sorted(matching_bids, key=lambda b: (-b.price, b.bid_id))) while matching_bids and amount: bid = matching_bids.pop(0) shares_matched = min(amount, bid.amount) amount -= shares_matched c1 = Contract(outcome=outcome, bidder=bidder, price=100 - bid.price, amount=shares_matched, yes_contract=yes_dir) c2 = Contract(outcome=outcome, bidder=bid.bidder, price=bid.price, amount=shares_matched, yes_contract=not yes_dir) if shares_matched == bid.amount: txn.delete(bid) else: bid.amount -= shares_matched txn.add(c1) txn.add(c2) if amount: existing = txn.query(Bid).filter_by(bidder=bidder, outcome=outcome, price=price, yes_bid=yes_dir).first() if existing: existing.amount += amount else: bid = Bid(outcome=outcome, bidder=bidder, price=price, amount=amount, yes_bid=yes_dir) txn.add(bid)
def bidInfo(demand_id): """ The '/bid/<demand_id>' route directs a user to the page with complete specifications for the demand. """ demand_info = Demand.get_info(demand_id) client_info = User.get_user_info(demand_info['client_username']) bids = Bid.get_bids_for_demand(demand_id) bids_info = [] bidders_info = {} if (len(bids) > 0): lowest_bid = Bid.get_info(bids[0])['bid_amount'] else: lowest_bid = 'None' for bid in bids: info = Bid.get_info(bid) bids_info.append(info) if info['developer_username'] not in bidders_info: bidders_info[info['developer_username']] = User.get_user_info( info['developer_username']) form = BidForm() if request.method == 'POST': if form.validate(): Bid(demand_id, session['username'], form.bid_amount.data) return redirect(url_for('bidInfo', demand_id=demand_id)) else: return redirect(url_for('bidInfo', demand_id=demand_id)) elif request.method == 'GET': return render_template("bidPage.html", demand_info=demand_info, client_info=client_info, bids_info=bids_info, bidders_info=bidders_info, lowest_bid=lowest_bid, form=form, demand_id=demand_id)
def single_auction(): username = session['username'] user = User.query.filter_by(username=username).first() if request.method == 'POST': amount = request.form['bid_amount'] item_id = request.form['item_id'] owner_id = user.id new_bid = Bid(amount, item_id, owner_id) db.session.add(new_bid) db.session.commit() item = Item.query.get(item_id) flash("Success you placed a bid") return render_template('auction.html', item=item) item_id = request.args.get('id') item = Item.query.get(item_id) return render_template('auction.html', item=item)
guest_3 = User(username="******", password="******") db.session.add(guest_1) db.session.add(guest_2) db.session.add(guest_3) db.session.commit() print(User.query.all()) # When delete: # db.session.delete(User.query.filter_by(username='******').first) # Step 2: 1 user auction a baseball # The below line gets an error if we don't delete the prior database. ######### item_1 = Item(name="baseball", description='ABC', owner=guest_1) # guest_1 auctions item_1 db.session.add(item_1) db.session.commit() print(Item.query.all()) ######### # Step 3: 2 user place bids on the baseball bid1 = Bid(price=100, payer=guest_2, item=item_1) bid2 = Bid(price=200, payer=guest_3, item=item_1) db.session.add(bid1) db.session.add(bid2) db.session.commit() print(Bid.query.all()) # Step 4: Find the highest bid on baseball highest_bid = Bid.query.filter_by(item_id=1).order_by(Bid.price)[-1] # Step 5: Update the item_1 with the highest price item_1.bid = highest_bid db.session.commit() print(item_1.bid)
def create_bid(request, bid_id): if request.method == 'GET': data = {} if bid_id: # When editing a bid bid = Bid.objects.get(id=bid_id) data = bid.as_dict() data['bid_id'] = bid_id return render(request, 'new_bid_form.html', data) if request.method == 'POST': data = request.POST if not bid_id: # Create a new database Bid bid = Bid() else: # When editing bid = Bid.objects.get(id=bid_id) # Delete Respondents group Respondent.objects.filter(bid__id=bid_id).delete() # Delete Deliverables Deliverable.objects.filter(bid__id=bid_id).delete() bid.create_from_dict(data, request.user) bid.save() nbr_group = int(data.get("saved_groups", '0')) i = 0 while (i < nbr_group): respondent = Respondent() respondent.create_from_dict(data, request.user, bid, str(i)) respondent.save() methodology = Methodology() methodology.create_from_dict(data, request.user, respondent, str(i)) methodology.save() i += 1 # Create / Save Deliverables if quantity is not null deliverables = { 'english_to_english': 'Transcripts from English to English', 'french_to_english': 'Transcripts from French to English', 'content_analysis': 'Content Analysis', 'topline_report': 'Topline report', 'full_report': 'Full Report', 'summary_report': 'Summary Report', 'discussion_guide_design': 'Discussion Guide Design', 'screener_design': 'Screener Design', 'other_deliverable': data.get('other_deliverable', '') } for key in deliverables.keys(): qty = data.get(key + '_qty', '') name = key if key == 'other_deliverable': name = deliverables[key] if qty != '': x = int(qty) deliverable = Deliverable() deliverable.create_from_dict(data, request.user, bid, key, x, name) deliverable.save() return HttpResponseRedirect('/crc/list_bids')
import json from flask import Flask, request, Response from models import User, Item, Bid app = Flask(__name__) items = Item() for i in range(6): items.add({'title': 'item %d' % i}) users = User() users.add({'name': 'Taweel'}) bids = Bid() @app.route('/api/v1/items/<int:item_id>/bid/', methods=['POST']) def record_bid(item_id): # check if id exists item = items.get(item_id) if not item: abort(404) user_id = request.json.get('user_id', 0) amount = request.json.get('amount', 0) bids.add({'item_id': item_id, 'user_id': user_id, 'amount': amount}) return Response(status=201) @app.route('/api/v1/items/<int:item_id>/bids/', methods=['GET']) def get_all_item_bids(item_id): # check if id exists item = items.get(item_id)