class TestPeerShop(TestCase): def setUp(self): user = User.objects.create_user('test', '', 'test') self.item = Item( user=user, image=PROJECT_PATH + '/test/IMG_0699.JPG', thumb=PROJECT_PATH + '/test/IMG_0699_thumbnail.JPG', title='keyboard', description='kkk', price=10 ) super(Item, self.item).save() user2 = User.objects.create_user('test2', '', 'test2') self.bid = Bid( bidUser=user2, bidPrice=10, itemUser=user, item=self.item, status='-' ) self.bid.save() def test_views_integration(self): c = Client() response = c.get(reverse('peerShop:main')) assert response.status_code == 200 assert 'PeerShop' in response.content response = c.get(reverse('peerShop:bid-list')) assert response.status_code == 200 assert 'PeerShop' in response.content response = c.get(reverse('peerShop:shop', args=('test',))) assert response.status_code == 200 assert 'PeerShop' in response.content response = c.get(reverse('peerShop:item-detail', args=(self.item.id,))) assert response.status_code == 200 assert self.item.title in response.content def test_login_view(self): c = Client() assert c.login(username='******', password='******') response = c.get(reverse('peerShop:shop', args=('test',))) assert response.status_code == 200 assert 'PeerShop' in response.content def test_bid_delete(self): c = Client() assert c.login(username='******', password='******') response = c.post( reverse('peerShop:bid-delete', args=(self.bid.id,)), ) assert response.status_code == 200 assert 'Deleted' in response.content, response.content assert not Bid.objects.filter(id=self.bid.id).exists()
def justify_developer_choice(demand_id): """ The '/bid/<demand_id>/justify-developer' route is where the client fills out a form to explain his/her reason for choosing a developer who did not offer the lowest bid. """ bids = Bid.get_bids_for_demand(demand_id) bids_info = [] bidders_info = {} for bid in bids: info = Bid.get_info(bid) bids_info.append(info) if info['developer_username'] not in bidders_info: username = info['developer_username'] bidders_info[username] = User.get_user_info(username) bidders_info[username]['lowest_bid'] = info['bid_amount'] form = JustifyDeveloperChoiceForm() if request.method == 'POST': if form.validate(): Demand.choose_developer( demand_id, session['chosen_developer'], session['username'], bidders_info[session['chosen_developer']]['lowest_bid'], form.reason.data) return render_template("developer_chosen.html") else: return render_template("justify_developer_choice.html", demand_id=demand_id, form=form) if request.method == 'GET': return render_template("justify_developer_choice.html", demand_id=demand_id, form=form)
def bidding(request, user_id, auction_id): auction = get_object_or_404(Auction, pk=auction_id) # bids = Bid.objects.filter(id=auction_id) if request == "POST": bid = Bid() bid.bidder = user_id bid.bid_amount = request.POST['bid_amount'] bid.save() return render(request, 'auction_detail.html', {'bid': bid}) return render(request, 'bidding.html', {{'auction': auction}})
def choose_developer(demand_id): """ The '/bid/<demand_id>/choose-developer' route directs a client to a page where he/she can select the developer he/she wants to hire to implement the system that was demanded. """ demand_info = Demand.get_info(demand_id) bids = Bid.get_bids_for_demand(demand_id) bids_info = [] bidders_info = {} for bid in bids: info = Bid.get_info(bid) bids_info.append(info) if info['developer_username'] not in bidders_info: username = info['developer_username'] bidders_info[username] = User.get_user_info(username) bidders_info[username]['lowest_bid'] = info['bid_amount'] rating = Developer.get_info(username)['avg_rating'] # round rating to the nearest 0.5 rating = round(0.5 * round(float(rating) / 0.5), 1) bidders_info[username]['full_stars'] = int(rating) bidders_info[username]['has_half_star'] = rating % 1 == .5 if request.method == 'POST': chosen_developer = request.form['developer'] session['chosen_developer'] = request.form['developer'] # if the chosen developer had the lowest bid, # update the demand's chosen developer if chosen_developer == bids_info[0]['developer_username']: # updates the table, notifies the developer, and also starts the transaction request Demand.choose_developer(demand_id, chosen_developer, session['username'], bids_info[0]['bid_amount']) return render_template("developer_chosen.html") # if the chosen developer did not have the lowest bid, # the client must provide a reason for choosing this developer else: return redirect( url_for('justify_developer_choice', demand_id=demand_id)) if request.method == 'GET': return render_template("choose_developer.html", demand_id=demand_id, bidders_info=bidders_info)
def validate_bid_amount(form, field, demand_id): """ Custom validator for BidForm. Validates if bid_amount is less than the lowest bid, if there is any. Also validates that bid_amount is a positive number. """ bids = Bid.get_bids_for_demand(demand_id) if len(bids) > 0: lowest_bid_amount = Bid.get_info(bids[0]).bid_amount if float(field.data) >= float(lowest_bid_amount): print(field.data) raise ValidationError( 'Bid must be lower than the currently lowest bid.')
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, 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 my_projects(): """ The '/dashboard/projects' route directs a user to view their projects. """ if 'username' in session: if not session['type_of_user'] == "user": return render_template("access_denied.html") user_type = User.get_user_info(session['username'])['type_of_user'] current = list( Demand.get_info(x) for x in Demand.get_current_projects(session['username'])) mid = [] completed = [] if user_type == "developer": bids_by_username = Bid.get_bids_by_username(session['username']) temp = [] for i in bids_by_username: info = Bid.get_info(i)['demand_id'] if info not in temp: temp.append(info) mid = list(Demand.get_info(y) for y in temp) completed = list( Demand.get_info(x) for x in Developer.get_past_projects(session['username'])) else: temp = (Demand.get_info(x) for x in Demand.get_filtered_demands( None, None, session['username'], None, None, None, True)) for demand in temp: if demand['chosen_developer_username'] is np.nan: mid.append(demand) completed = list( Demand.get_info(x) for x in Client.get_past_projects(session['username'])) return render_template("myProjects.html", user_type=user_type, current=current, mid=mid, completed=completed) else: return redirect(url_for('login'))
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 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 make_bid(args): listing_id = args['listing_id'] bidder_email = args['bidder_email'] bid_amount = args['bid_amount'] listing = Listing.objects.filter(listing_id=listing_id) bidder_profile = Profile.objects.get(email=bidder_email) if len(listing) == 0: return False, ERROR_NO_SUCH_LISTING bids = Bid.objects.filter(listing_id=listing_id) bid_id = str(listing_id) + str(len(bids)) bid = Bid(listing_id=listing_id, bid_id=bid_id, bidder_email=bidder_email, amount=bid_amount, status=0) bid.save() recent_bids = json.loads(str(bidder_profile.recent_bids)) if len(recent_bids) == NUM_RECENT_BIDS: del recent_bids[0] recent_bids.append(listing_id) bidder_profile.__dict__['recent_bids'] = json.dumps(recent_bids) bidder_profile.save() listing = listing[0] listing_bids = json.loads(listing.bids) listing_bids.append(bid_id) listing.__dict__['bids'] = json.dumps(listing_bids) listing.save() owner = Profile.objects.get(profile_id=listing.profile_id) locale.setlocale(locale.LC_ALL, '') notification_title = 'Someone made a bid!' notification_description = '%s made a bid of %s!' % (bidder_email, locale.currency(float(bid_amount))) extras = {'bid_id' : bid_id} notification.create(notification_title, notification_description, owner.email, owner.password, extras) return True, None
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 setUp(self): user = User.objects.create_user('test', '', 'test') self.item = Item( user=user, image=PROJECT_PATH + '/test/IMG_0699.JPG', thumb=PROJECT_PATH + '/test/IMG_0699_thumbnail.JPG', title='keyboard', description='kkk', price=10 ) super(Item, self.item).save() user2 = User.objects.create_user('test2', '', 'test2') self.bid = Bid( bidUser=user2, bidPrice=10, itemUser=user, item=self.item, status='-' ) self.bid.save()
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)
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 bid(request, nfl_id): u = request.user allow_bids = u.is_authenticated() and (not settings.LOCK_BIDS) and util.is_1_waiver_period() if allow_bids: p = Player.objects.get(nfl_id=nfl_id) team = Team.objects.get(owner=u) roster = Player.objects.filter(dflteam=team).order_by("position") if request.method == "POST": val = int(request.POST.get("bidvalue")) if val < 0: val = 0 if val > team.account: val = team.account pk_to_drop = request.POST.get("Drop") dropee = Player.objects.get(pk=pk_to_drop) priority = int(request.POST.get("Priority")) # priority can not be the same as any other unprocessed bids with same drop same_drop = Bid.objects.filter(team=team).filter(processed=False).filter(drop=dropee) other_prios = [] for sd in same_drop: other_prios.append(sd.priority) while priority in other_prios: priority += 1 b = Bid(team=team, amount=val, player=p, drop=dropee, priority=priority) b.save() # if bid-sum is larger than account, all bids must have unique prio bidsum = Bid.objects.filter(team=team).filter(processed=False).aggregate(Sum("amount")) if bidsum["amount__sum"] > team.account: active_bids = Bid.objects.filter(team=team).filter(processed=False).order_by("priority", "date") count = 0 for b in active_bids: count += 1 b.priority = count b.save() return HttpResponseRedirect("/team") else: return render(request, "bid.html", {"player": p, "roster": roster, "team": team}) else: return HttpResponseRedirect("/")
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')
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 place_bid(self, request, **kwargs): """ The game's active player makes a new high bid """ game = kwargs[DEC_KEYS.GAME] new_bid = Bid.create(request.count, request.rank) game_logic.place_bid(game, new_bid) return message_types.VoidMessage()
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)