def setUp(self): ''' Set up method that will run before every Test ''' self.user_ = User(username = '******',password = '******', email = '*****@*****.**') self.new_orders = Orders(pizza_name='vegan pizza',pizza_size="large",price="1000",user = self.user_Stan)
def submit_order(): order = Orders() order.time = datetime.datetime.now() restaurant_id = session['restaurant_id'] for item in request.args.getlist('array[]'): menuItem = MenuItem.query.filter_by(name=item).first() freq = menuItem.frequency if freq is None: menuItem.frequency = 1 else: menuItem.frequency += 1 item_id = menuItem.id for paired_item in request.args.getlist('array[]'): if item != paired_item: paired_item_id = MenuItem.query.filter_by(name=paired_item).first().id suggestionPair = Suggestions.query.filter_by(current_id=item_id, next_id=paired_item_id).first() if suggestionPair is not None: new_weight = suggestionPair.weight + 1 suggestionPair.weight = new_weight order.items.append(menuItem) db.session.add(order) restaurant = Restaurant.query.get(restaurant_id) restaurant.orders.append(order) db.session.commit() order_id = Orders.query.filter_by(time=order.time).first().id print(order_id) return jsonify({'order_id':order_id, 'success':True}), 200, {'ContentType':'application/json'}
class OrdersTest(unittest.TestCase): ''' Test Class to test the behaviour of the class ''' def setUp(self): ''' Set up method that will run before every Test ''' self.user_ = User(username = '******',password = '******', email = '*****@*****.**') self.new_orders = Orders(pizza_name='vegan pizza',pizza_size="large",price="1000",user = self.user_Stan) def tearDown(self): Orders.query.delete() User.query.delete() def test_instance(self): self.assertTrue(isinstance(self.new_orders, Orders)) # We then check if the values of variables are correctly being placed. def test_check_instance_variables(self): self.assertEquals(self.new_orders.pizza_name,'vegan pizza') self.assertEquals(self.new_orders.pizza_size,'large') self.assertEquals(self.new_orders.price,'1000') self.assertEquals(self.new_pitch.user,self.user_Stan) def test_save_product(self): self.new_orders.save_orders() self.assertTrue(len(Orders.query.all())>0)
def add_order(): form = OrderForm() choice = [] # users = User.query.all() # for u in users: # label = u.name # value = u.username # choice.append((value,label)) # form.buyer.choices = choice form.update_choices() if form.validate_on_submit(): order_status = dict(form.order_status.choices).get( form.order_status.data) buyer = User.query.filter_by(username=form.buyer.data).first() order = Orders(amount=form.amount.data, order_status=order_status, buyer=buyer) db.session.add(order) db.session.commit() message = "*{}'s* Taobao order of SGD *{}* has been added.".format( order.buyer.name, order.amount) #message = '*' + buyer_name + '*' + ' has added a Taobao order of SGD ' + '*' + str(amount) + '*' + ' successfully. \n*Order Status:* ' + status api_result = sendtelegram(message) flash("Order added.", "success") if api_result is True: flash("Sent telegram message successfully", 'success') else: flash("Error sending telegram message", 'danger') return redirect(url_for('add_order')) return render_template('add_order.html', form=form)
def submitorder(): if not session.get('cmail'): return redirect(request.url_root) if request.method == "GET": tprice = request.args.get("tprice") items = request.args.get("items") rid = request.args.get("rid") elif request.method == "POST": tprice = request.form['tprice'] items = request.form["items"] rid = request.form['rid'] cmail = session['cmail'] customer = Customer.query.filter(Customer.cmail == cmail).first() restadmin = Restadmin.query.filter(Restadmin.rid == rid).first() rid = restadmin.rid ostatus = "pending" orders = Orders(cid=customer.cid, rid=rid, items=items, tprice=tprice, ostatus=ostatus) if orders: db.session.add(orders) db.session.commit() # return redirect(url_for('userorders')) return render_template('lastpage.html') return render_template('payment.html')
def menu(): menu_type = request.args.get("ordertype", 1, type=int) if menu_type == 1: today = date.today().strftime("%A") elif menu_type == 0: today = "Daily" else: return redirect(url_for('logout')) items = Items.query.filter_by(item_nature=today).all() form = ChoiceMenu() form.foodoption.choices = [(itm.itemid, itm.itemname) for itm in items] if form.validate_on_submit(): alreadyorderd = Orders.query.filter_by( item_id=form.foodoption.data, e_id=current_user.emp_id).first() if alreadyorderd is None: orders = Orders(item_id=form.foodoption.data, e_id=current_user.emp_id, quantity=form.quantity.data, order_date=datetime_from_utc_to_local()) db.session.add(orders) db.session.commit() return redirect(url_for('menu')) alreadyorderd.quantity += form.quantity.data db.session.commit() return redirect(url_for('menu')) return render_template( "menu.html", form=form, disabletime=datetime_from_utc_to_local().timetuple())
def order(): orders = Orders.objects(opareteUser=current_user.realname) drugs = {} for x in orders: for y in x.buyDetail: drugs[y] = Commodity.objects(id=ObjectId(y)).first().name return render_template('doctor/order.html', orders=orders, bought=drugs)
def payment(): items = Items.query.filter(Items.id.in_(session['cart'])).all() itemsList = listToString(session['cart']) cost = getCartTotalCost(items) invoice_no = getInvoiceNumber() # stripe payment stuff #customer = stripe.Customer.create(email=current_user.email,source=request.form['stripeToken']) #charge = stripe.Charge.create(customer=customer.id, amount=cost*100, currency='usd', description='A payment for '+invoice_no) # add to orders Database order = Orders(user_id=current_user.id, invoice_no=invoice_no, comment=remove_tags(request.form['specialRequest']), cost=cost, item_id=itemsList) try: db.session.add(order) db.session.commit() except Exception as e: print("\n FAILED entry: {}\n".format(json.dumps(order))) print(e) # Update to items inventory Database for item in session['cart']: u = db.session.query(Items).get(item) if u.inventory > 0: u.inventory -= 1 db.session.commit() session['cart'] = [] return render_template('thankyou.html', title='Order Placed', receipt=invoice_no)
def customize_product(product): form = CustomizeForm() if request.method == "POST" and form.validate(): user = User.query.filter_by(username=current_user.username).first() if not user: return render_template("403.html"), 403 order = Orders( order_name=form.order_name.data, order_desc=form.order_description.data, author=user, ) db.session.add(order) db.session.commit() files = request.files.getlist(form.order_reference.name) if len(files) != 0: attachments = [] for file in files: attachments.append(file.stream.read()) else: attachments = None send_mail( form.order_name.data, current_user.email, ["*****@*****.**"], f"Client Email: {current_user.email}\ndescription of project: {form.order_description.data}", None, attachments, ) return redirect("/success") return render_template( "customize_product.html", title=product, form=form, )
def makeOrder(): """ Make Order This route takes a list of product(s) and creates a zinc order. TODO: define input format in comment """ try: # gets post request data = request.get_json() # Posts to zinc to create order as per POST data = http.post( f"{zinc}/orders", data=json.dumps({ "retailer": "aliexpress", "products": data['products'], "max_price": 1000, # Change in future "shipping_address": data['shipping'], "billing_address": data['billing'], "shipping": data['shipping_params'], "is_gift": True, "payment_method": data['payment'], "retailer_credentials": retailer_credentials, "shipping_method": data['shipping_method'] }), auth=(api_key)).json() # Creates an order object from response db.session.add(Orders(code=data['order'], )) return "Success", 200 except: return "Invalid json format", 500
def cart_order(): if request.method == 'POST': user_id = session.get('user_id', 0) # 获取用户id # 添加订单 orders = Orders(user_id=user_id, recevie_name=request.form.get('recevie_name'), recevie_tel=request.form.get('recevie_tel'), recevie_address=request.form.get('recevie_address'), remark=request.form.get('remark')) db.session.add(orders) # 添加数据 db.session.commit() # 提交数据 # 添加订单详情 cart = Cart.query.filter_by(user_id=user_id).all() object = [] for item in cart: object.append( OrdersDetail( order_id=orders.id, goods_id=item.goods_id, number=item.number, )) db.session.add_all(object) # 更改购物车状态 Cart.query.filter_by(user_id=user_id).update({'user_id': 0}) db.session.commit() return redirect(url_for('home.index'))
def voice(): if current_user.user_type != "admin": flash("Only Admins may place orders.") return redirect(url_for('index')) form = VoiceOrderForm() if form.validate_on_submit(): product_name, SKUs = voice_order() if product_name == False: flash("Your order '{}' did not follow the expected format. Your order should start with 'place an order for'".format(SKUs)) return redirect(url_for('voice')) product = InventoryItems.query.filter_by(item_name=product_name).first() if product == None: flash("We could not find product {}. Please ensure your product matches our inventory.".format(product_name)) return redirect(url_for('voice')) order = Orders(user_id=current_user.id, supplier_id=product.supplier_id, order_ETA=datetime.utcnow().date() + timedelta(days=product.lead_time)) db.session.add(order) db.session.commit() inv_in_order = InventoryInOrder(order_id=order.id, SKUs=SKUs, inventory_id=product.id) db.session.add(inv_in_order) db.session.commit() send_order(order.id) flash('Placed an order for {} SKUs of {}. Pending supplier confirmation.'.format(inv_in_order.SKUs, product.item_name)) return redirect(url_for('index')) return render_template('voice.html', title='Voice Order', form=form)
def partner(comp_name, comp_hash): company = Company.query.filter_by(company_hash=comp_hash).first() submenu = Submenu.query.filter_by(company_id=company.id).all() for menu in submenu: menu.show_order = 0 for n in range(0, len(submenu)): menu.show_order = str(n) menu.hash_order = menu.submenu_hash + menu.show_order orders_form = OrderListForm() if orders_form.validate_on_submit(): food_id_list = request.form.getlist('order_food_id') food_hash_list = request.form.getlist('order_food_hash') qty_list = request.form.getlist('order_quantity') for i in range( 0, len(food_hash_list) ): #dont set price here so it will be updated for future price change before checkout--set price in checkout list = Orders(food_item_hash=food_hash_list[i], quantity=qty_list[i], food_item_id=food_id_list[i], user_id=current_user.id, company_id=company.id) db.session.add(list) db.session.commit() return redirect(url_for('checkout', username=current_user.username)) return render_template('partner.html', company=company, submenu=submenu, orders_form=orders_form)
def dashboard_old(request, **kwargs): user = request.user user_detail = UserDetails.objects.get_or_create(user=user) user_detail = user_detail[0] if user_detail.user_type == "Tutor": return redirect("tutor-dashboard") details = Orders.objects.filter(user=user) labs = LabOrders.objects.filter(user=user) if request.method == 'POST': desc = request.POST.get('desc') reference_material = request.FILES['reference_material'] assignment = request.FILES['assignment'] deadline = request.POST.get('deadline') subject = request.POST.get('subject') order = Orders(user=user, status='Awaiting Confirmation', desc=desc, reference_material=reference_material, assignment=assignment, deadline=deadline, subject=subject) order.save() id = order.pk id += 1000 order.order_id = f'TC-HW-{id}' order.save() print("Order successful, order id : {}".format(order.order_id)) send_message(request, "Order successful, order id : {}".format(order.order_id)) c = { 'user': user.username, 'order_id': order.order_id, 'subject': order.subject, 'deadline': deadline, } email = user.email order_id = order.order_id email_msg = render_to_string('order.txt', c) mail = EmailMessage( subject=f'Order Created - {order_id}', body=email_msg, from_email='TutorChamps Student Support <*****@*****.**>', to=[email, '*****@*****.**']) mail.send() serializers = OrderSerializers(order) return JsonResponse(serializers.data) print(details) _context = { 'details': details, 'user': user, 'user_detail': user_detail, 'labs': labs, 'ordered': False } if "order" in kwargs.keys(): if kwargs["order"] == "order-successful": _context["ordered"] = True print(_context["ordered"]) return render(request, 'dash_board.html', _context)
def editorders(order_id): order = Orders().query.filter_by(id=order_id).first() itemName = Items.query.filter_by(itemid=order.item_id).first() form = ChoiceMenu() form.foodoption.choices = [(order.item_id, itemName.itemname)] if form.validate_on_submit(): order.item_id = form.foodoption.data order.quantity = form.quantity.data order.order_date = datetime_from_utc_to_local() db.session.commit() return redirect(url_for("Myorders")) elif request.method == "GET": form.foodoption.choices = [(order.item_id, itemName.itemname)] form.quantity.data = order.quantity return render_template( "menu.html", form=form, disabletime=datetime_from_utc_to_local().timetuple())
def deploy(make_menu=False, seed=False): """Run deployment tasks.""" from flask_migrate import upgrade from app.models import Pies, User, Orders # migrate database to latest revision upgrade() # if deploying for the first time, create the pie menu if make_menu: # build the menu of pies Pies.add_menu() # seed the database with data if seed: # create fake users so there's some data in the DB User.generate_fake(200) # create some orders too Orders.generate_orders(600)
def buy(id): data = queryId(Goods, id) order = Orders(username=current_user.username, goodsname=data.goodsname, address=current_user.address, account_price=data.goods_price) db.session.add(order) db.session.commit() data = queryId(Goods, id) return render_template('home/pay.html', content=data)
def select_single(request): if request.is_ajax(): operator = Operators.login_required(request) if operator is None: # Operators.set_redirect_field_name(request, request.path) # return redirect(reverse("operators_signin")) return HttpResponse('signin', content_type='text/plain') else: auth_permissions = Operators.get_auth_permissions(operator) action = request.POST['action'] id = request.POST['id'] if action != '' and id is not None: if action == 'delete': if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values( ): try: model = Order_Items.objects.get(order_item_id=id) order = Orders.objects.get( order_id=model.orders_order_id) Order_Items.delete_order_item( request, model, operator) Orders.update_grand_total(request, order, operator) messages.success(request, 'Item removed successfully.') except (TypeError, ValueError, OverflowError, Order_Items.DoesNotExist): return HttpResponseBadRequest( 'Bad Request', content_type='text/plain') else: return HttpResponseForbidden('Forbidden', content_type='text/plain') return HttpResponse('success', content_type='text/plain') else: return HttpResponseBadRequest('Bad Request', content_type='text/plain') else: return HttpResponseForbidden('Forbidden', content_type='text/plain')
def productrcsv(): f = request.files['Orders'] if not f: return "No file" stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None) csv_input = list(csv.DictReader(stream)) for row in csv_input: x = datetime.strptime(row['purchaseDate'], '%d/%m/%Y').date() us = Orders(o_id=row['id'], totalPrice=row['totalPrice'], date_of_purchase=x) db.session.add(us) db.session.commit() return "done"
def create_order(): data = request.get_json() or {} if 'order_items' not in data: return bad_request('must include order_items') if len(data['order_items']) < 1: return bad_request('must include order_items') order = Orders() order.from_dict(data, new_order=True) db.session.add(order) # db.session.commit() item_id = 1 for item in data['order_items']: order_item = Order_items() # order_item.order_id = order.order_id order_item.item_id = item_id item_id += 1 order_item.from_dict(item, new_item=True) order.order_items.append(order_item) db.session.commit() response = jsonify(order.to_dict()) response.status_code = 201 response.headers['Location'] = url_for('api.get_orders', id=order.order_id) return response
def entro(form, orders_id=None, orders=None): if form.validate_on_submit(): if orders_id == None: orders = Orders(client_id=klient_id, product_id=product_id, adds_id=adds_id, finish_id=finish_id, head_id=head_id, writing_id=writing_id, info=form.info.data) else: form.populate_obj(orders) db.session.commit() else: errors = form.errors
def post(self, module): token = request.headers.get("x-access-token") token_data = jwt.decode(token, app.config['SECRET_KEY']) json_data = request.json if not json_data: return {"message": "not json"}, 400 orders = json_data.get('orders') for i in range(0, len(orders)): if orders[i] is None: continue order = orders[i].get('product') donor = Donor.query.get(order.get('donor_id')) beneficiary_username = token_data.get("username") beneficiary = Beneficiary.query.filter_by( username=beneficiary_username).first() if not beneficiary: return { 'message': 'beneficiary not found', 'username': beneficiary_username, "error": 1 }, 400 listing = Listings.query.get(order.get('listing_id')) quantity = orders[i].get('quantity') if quantity < 0: return { 'message': 'listing quantity less than 0', "error": 1 }, 400 listing.quantity -= int(quantity) if listing.quantity < 0: return {'message': 'quantity more than stock', "error": 1}, 400 o = Orders(donor=donor, beneficiary_id=beneficiary.id, listing=listing, quantity=quantity, module=json_data.get('module'), time_stamp=json_data.get('time_stamp')) db.session.add(o) db.session.commit() send_mail(to_email=donor.email, donor=donor, beneficiary=beneficiary, listing=listing) return { "message": "Your order has been placed and email has been sent", "error": 0 }, 200
def asignment_order(request): user = request.user uname = user.username user = User.objects.get(username=uname) if request.method == 'POST': desc = request.POST.get('desc') assignment = request.FILES['files'] subject = request.POST.get('subject') deadline = request.POST.get('deadline') Orders(user=user, desc=desc, assignment=assignment, subject=subject, deadline=deadline, status='Awaiting Confirmation').save() return redirect('old-user')
def order(): flag, total_amount, time_taken = 0, 0, 0 t = time_correction() if request.method == 'POST': dishes = Quantity.query.filter_by(customer=current_user).all() for dish in dishes: if dish.quantity != 0: if flag == 0: flash("Your order is:") recent_order = RecentOrders( customer=current_user, timestamp=(datetime.now() - timedelta(minutes=330))) history = History(customer=current_user, timestamp=(datetime.now() - timedelta(minutes=330)), recent_order=recent_order) db.session.add(recent_order) db.session.add(history) flag = 1 time_taken += int(dish.dish.timetaken) * int(dish.quantity) total_amount += int(dish.dish.amount) * int(dish.quantity) order = Orders(history=history, quantity=dish.quantity, dish=dish.dish) db.session.add(order) flash("{} {} Rs.{}".format(dish.quantity, dish.dish.dishname, dish.quantity * dish.dish.amount)) flash("Total amount is Rs.{}".format(total_amount)) dish.quantity = 0 if flag == 0: flash("Please select a dish.") else: user_email = current_user.email Thread(target=notification, args=(app, t + time_taken, user_email)).start() recent_order.timestamp += timedelta(minutes=(t + time_taken)) history.total_amount = total_amount app.config['WAIT_TIME'] += time_taken db.session.commit() return redirect(url_for('index'))
def addOrders(): if request.method == "POST": # store order data from form cid = request.form.get('customer_id') order_date = datetime.strptime(request.form.get('order_date'), '%Y-%m-%d') rname = request.form.get('recipe') units = request.form.get('units') batch_code = request.form.get('batch_code') con = db_connect() cur = con.cursor() cur.execute( 'SELECT bar_weight, version_number FROM recipes WHERE rname =:rname AND approved=1', {'rname': rname}) row = cur.fetchall() results = serialize(cur, row) # calculate batch size unitWeight = results[0]['bar_weight'] batchSize = unitWeight * int(units) # get recipe version number version_number = results[0]['version_number'] # add into database order = Orders(customer_id=cid, order_date=order_date, rname=rname, recipe_version_number=version_number, units=units, batch_size=batchSize, batch_code=batch_code) db.session.add(order) db.session.commit() return redirect(url_for('orders.viewOrders'))
def live_session_orders(request): user = request.user user_detail = UserDetails.objects.get_or_create(user=user) user_detail = user_detail[0] if request.method == 'POST': desc = request.POST.get('desc') assignment = request.FILES['assignment'] deadline = request.POST.get('deadline') duration = request.POST.get('Duration') subject = request.POST.get('subject') reference_material = request.FILES['reference_material'] order = Orders(user=user, status='Awaiting Confirmation', desc=desc, assignment=assignment, deadline=deadline, subject=subject, duration=duration, reference_material=reference_material) order.save() id = order.pk id += 1000 order.order_id = f'TC-LS-{id}' order.save() serializers = OrderSerializers(order) c = { 'user': user.username, 'order_id': order.order_id, 'subject': order.subject, 'deadline': deadline, } email = user.email order_id = order.order_id email_msg = render_to_string('order.txt', c) mail = EmailMessage( subject=f'Order Created - {order_id}', body=email_msg, from_email='TutorChamps Students Support <*****@*****.**>', to=[email, '*****@*****.**']) mail.send() return JsonResponse(serializers.data)
def group_order(gid): form = OrderForm() if form.validate_on_submit(): order = Orders(username=form.username.data, groupId=gid, orderName=form.orderName.data, quantity=form.quantity.data, size=form.size.data) db.session.add(order) db.session.commit() order_details = Grouporder.query.get(gid) total_friends_expected = order_details.n_friends order_till_now = Orders.query.filter_by(groupId=gid) if total_friends_expected == order_till_now.count(): email_to_list = [order_details.username] email_from = '*****@*****.**' email.send_email( email_from, email_to_list, "Order status ", render_template('returnStatus.html', order=order_till_now)) flash('Your order placed Successfully {}'.format(form.username.data)) return redirect('/index') return render_template('orderForm.html', form=form)
def pemesanan(): if "username" in session: product = Product.query.filter_by(id=idp).first() else: return redirect(url_for('login')) if request.method == "POST": nama = request.form.get("nama") warna = request.form.get("warna") kertas = request.form.get("kertas") catatan = request.form.get("catatan") files = request.files['file'] if files: filename = secure_filename(files.filename) files.save( os.path.join(app.config['UPLOAD_FOLDER'] + "files", filename)) orders = Orders(nama=nama, warna=warna, kertas=kertas, catatan=catatan, file=filename) db.session.add(orders) db.session.commit() return render_template("pemesanan.html", product=product)
def submit_order(): #从表单中去除数据添加到Orders模型对象中 orders = Orders() #生成订单id,规则:当前时间+一位随机数 n = random.randint(0, 9) d = datetime.datetime.today() orderid = str(int(d.timestamp() * 1e6)) + str(n) orders.id = orderid orders.orderdate = d.strftime('%Y-%m-%d %H:%M:%S') orders.status = 1 #1 待付款 0 已付款 db.session.add(orders) # 购物车里有的数据:物品id,物品名称,商品价格,商品数量 cart = session['cart'] total = 0.0 for item in cart: quantity = request.form['quantity_' + str(item[0])] try: quantity = int(quantity) except: quantity = 0 #小计 subtotal = item[2] * quantity total = total + subtotal order_line_item = OrderLineItem() order_line_item.quantity = quantity order_line_item.goodsid = item[0] order_line_item.orderid = orderid order_line_item.subtotal = subtotal db.session.add(order_line_item) orders.total = total #提交事务 db.session.commit() #清空购物车 session.pop('cart', None) return render_template('order_finish.html', orderid=orderid)
def payForm(): brand = request.args.get('brand', default = 'BRAND', type = str) model = request.args.get('model', default = 'MODEL', type = str) rentStart = request.args.get('rentStartDate', default=datetime.datetime.today(), type = None) rentEnd = request.args.get('rentDateEnd', default=datetime.datetime.today()+timedelta(days=1), type = None) rentDays = request.args.get('rentDays', type = int) rentCost = request.args.get('rentCost') itemId = request.args.get('itemId', default = 'item_id', type = str) bikeID = request.args.get('bike_id', default = 'bike_id', type = str) rentStartDate = str(rentStart.day) + "/" + str(rentStart.month) + "/" + str(rentStart.year) rentEndDate = rentEnd[8:] + "/" + rentEnd[5:7] + "/" + rentEnd[0:4] data = Bike_Types.query.filter(and_(Bike_Types.brand == brand, Bike_Types.model == model)).first() image = data.image cards = Payment_Methods.query.filter_by(user_id=current_user.id).all() cardForm = SelectPaymentForm() for card in cards: card_num = card.card_number.split("##cardname=") newChoice = (str(card.id), "**** " + card_num[1]) cardForm.paymentChoice.choices.append(newChoice) if cardForm.validate_on_submit(): # Save order in database datetimeStart = datetime.datetime.strptime(rentStartDate, '%d/%m/%Y') datetimeEnd = datetime.datetime.strptime(rentEndDate, '%d/%m/%Y') order = Orders(total_price=rentCost, user_id=current_user.id) db.session.add(order) db.session.commit() rental = Rented_Bikes(start_date=datetimeStart, end_date=datetimeEnd, bike_id=itemId, price=rentCost, order_id=order.id) db.session.add(rental) user = Users.query.filter_by(id=current_user.id).first() user.times_rented += 1 bike = Bikes.query.filter_by(id=itemId).first() bike.times_rented += 1 bike.days_used += rentDays bike_type = Bike_Types.query.filter_by(id=bikeID).first() bike_type.times_rented += 1 db.session.commit() qr(current_user.email, brand, model, bikeID, rentStartDate, rentEndDate, rentCost) flash('Order made successfully.', 'success') return redirect(url_for('account')) form = PaymentForm() if form.validate_on_submit(): # Save payment method, if selected if(form.save.data == True): date = form.expDate.data.split("/") month_hash = bcrypt.generate_password_hash(date[0]).decode('utf-8') year_hash = bcrypt.generate_password_hash(date[1]).decode('utf-8') card_num_pre_hash = bcrypt.generate_password_hash(form.cardNumber.data).decode('utf-8') card_num_hash = card_num_pre_hash + "##cardname=" + form.cardNumber.data[-4:] cvv_hash = bcrypt.generate_password_hash(form.cvv.data).decode('utf-8') payment = Payment_Methods(card_number=card_num_hash, cvv=cvv_hash, expiration_month=month_hash, expiration_year=year_hash, user_id=current_user.id) db.session.add(payment) db.session.commit() # Save order in database datetimeStart = datetime.datetime.strptime(rentStartDate, '%d/%m/%Y') datetimeEnd = datetime.datetime.strptime(rentEndDate, '%d/%m/%Y') order = Orders(total_price=rentCost, user_id=current_user.id) db.session.add(order) db.session.commit() rental = Rented_Bikes(start_date=datetimeStart, end_date=datetimeEnd, bike_id=itemId, price=rentCost, order_id=order.id) db.session.add(rental) user = Users.query.filter_by(id=current_user.id).first() user.times_rented += 1 bike = Bikes.query.filter_by(id=itemId).first() bike.times_rented += 1 bike.days_used += rentDays bike_type = Bike_Types.query.filter_by(id=bikeID).first() bike_type.times_rented += 1 db.session.commit() qr(form.email.data, brand, model, bikeID, rentStartDate, rentEndDate, rentCost) flash('Order made successfully.', 'success') return redirect(url_for('account')) email = current_user.email form.email.default = email form.process() return render_template("payment.html", number_of_cards=len(cards), cardForm=cardForm, form=form, data=data, image=image, rentCost=rentCost, rentDays=rentDays, rentStart=rentStartDate, rentEnd=rentEndDate) # Save order in database datetimeStart = datetime.datetime.strptime(rentStartDate, '%d/%m/%Y') datetimeEnd = datetime.datetime.strptime(rentEndDate, '%d/%m/%Y') order = Orders(total_price=rentCost, user_id=current_user.id) db.session.add(order) db.session.commit() rental = Rented_Bikes(start_date=datetimeStart, end_date=datetimeEnd, bike_id=itemId, price=rentCost, order_id=order.id) db.session.add(rental) user = Users.query.filter_by(id=current_user.id).first() user.times_rented += 1 bike = Bikes.query.filter_by(id=itemId).first() bike.times_rented += 1 bike.days_used += rentDays bike_type = Bike_Types.query.filter_by(id=bikeID).first() bike_type.times_rented += 1 db.session.commit() qr(current_user.email, brand, model, bikeID, rentStartDate, rentEndDate, rentCost) flash('Order made successfully.', 'success') return redirect(url_for('account'))
def post(self, user_id): """ [{ question_id:1, answer_id:1, answer:"548645658", questionnaire_id:1, }] :param user_id: :return: """ content_type = request.headers.get("Content-Type") if "son" not in content_type: return CommonJsonRet(400, False, "Incorrect Content-Type", {})() questionnaire = Questionnaire.query.filter( Questionnaire.is_delete == 0).order_by(desc( Questionnaire.id)).first() if not questionnaire: return CommonJsonRet(404, False, "Questionnaire not found", {})() # 过期时间问题 if questionnaire.end_at < time.time(): return CommonJsonRet(404, False, "Questionnaire Expired", {})() questionnaire_data = QuestionnaireData.query.filter( QuestionnaireData.user_id == user_id, QuestionnaireData.questionnaire_id == questionnaire.id).first() if questionnaire_data: return CommonJsonRet(400, False, "User Has Been Participated ", {})() res_data = request.json print(res_data) item_list = [] for res_datum in res_data: if isinstance(res_datum.get("answer_id"), list): if res_datum.get("answer_id"): for answer_id in set(res_datum.get("answer_id")): questionnaire_data = QuestionnaireData( question_id=res_datum.get("question_id"), answer_id=answer_id, answer=res_datum.get("answer") if res_datum.get("answer") else "", questionnaire_id=questionnaire.id, user_id=user_id, ) item_list.append(questionnaire_data) else: questionnaire_data = QuestionnaireData( question_id=res_datum.get("question_id"), answer_id=-1, answer=res_datum.get("answer") if res_datum.get("answer") else "", questionnaire_id=questionnaire.id, user_id=user_id, ) item_list.append(questionnaire_data) elif isinstance(res_datum.get("answer_id"), int): questionnaire_data = QuestionnaireData( question_id=res_datum.get("question_id"), answer_id=res_datum.get("answer_id"), answer=res_datum.get("answer") if res_datum.get("answer") else "", questionnaire_id=questionnaire.id, user_id=user_id, ) item_list.append(questionnaire_data) else: return CommonJsonRet(400, False, "Error answer_id type", {})() account = Accounts.query.filter(Accounts.user_id == user_id).first() cat = int(time.time()) account.available = account.available + 50000 order_num = get_order_code() order_desc = f"Questionnaire points" pt = PointTrace( user_id=user_id, create_at=cat, points=50000, desc=order_desc, title=order_desc, way=order_desc, order_num=order_num, current=account.available, ) item_list.append(pt) order = Orders( user_id=user_id, order_num=order_num, create_at=cat, pay_time=cat, number=50000, source="Questionnaire points", desc=order_desc, ) item_list.append(order) db.session.bulk_save_objects(item_list) db.session.commit() db.session.close() return CommonJsonRet(200, True, "success", {})()