def order(self, request): if request.method == 'POST': print(request.form) delivery_type = request.form['delivery-type'] try: orders = self.cart_main.getUnique() ordered_products = [] for order in orders: db_product = Product.query.filter( Product.id == order).first() order_amount = self.cart_main.countProduct(order) ordered_products.append( Prod(db_product.name, order_amount, db_product.price)) sum = 0 for product in ordered_products: db_product = Product.query.filter( Product.name == product.name).first() sum = sum + db_product.price * product.amount if product.amount > db_product.amount: raise Exception("Przekroczyłeś produkty w magazynie") for product in ordered_products: db_product = Product.query.filter( Product.name == product.name).first() db_product.amount = db_product.amount - product.amount print(db_product.amount) db_session.add(db_product) db_session.commit() self.cart_main = Cart() return render_template('order_result.html', price=sum, avg_rating=self.avg_rating) except KeyError: print('error1') except Exception as e: self.cart_main = Cart() return render_template( 'template.html', title= "Nie można stworzyć zamówienia, przekroczyłeś liczbę produktów w magazynie", avg_rating=self.avg_rating) return render_template('order_form.html', title='Formularz zamówienia', avg_rating=self.avg_rating)
def close(paydesk_id=None, cart_id=None): try: dbs = db_session() oldCart = dbs.query(Cart).filter(Cart.paydesk_id == paydesk_id, Cart.status == "OPEN").one_or_none() oldCart.status = "CLOSED" msg = { "msgtype": "INFO", "msgid": 0, "text": "Cart closed", "info": "Cart %d closed" % (oldCart.id) } newCart = Cart(paydesk_id=paydesk_id, status="OPEN") ret = dbs.add(newCart) dbs.commit() articles = dbs.query(Article).filter( Article.paydesk_id == paydesk_id, Article.cart_id == newCart.id).order_by( Article.scantime.desc()).all() return { "Msg": msg, "Cart": newCart.dump(), "Articles": [p.dump() for p in articles] }, 200 except Exception as ex: msg = { "msgtype": "INFO", "msgid": 0, "text": "Cart closed", "info": "Cart %d closed" % (oldCart.id) } return {"Msg": msg}, 400
def post() -> Response: """ POST response method for creating user. :return: JSON object """ data = request.get_json() usercart = Cart().save() output = {'id': str(usercart.id)} y = {"cartId": str(usercart.id)} print('usercart') print(usercart.id) print(usercart.products) print('data') print(data) data.update(y) print('data') print(data) post_user = Users(**data) try: post_user.save() except NotUniqueError as exc: return {'message': "Email Id already exits!!"}, 400 output = {'id': str(post_user.id)} return jsonify({'result': output})
def edit(): productid = request.form.get('pid') cartid = request.cookies.get('cart') quantity = request.form.get('qty') cart = Cart() ret = cart.edit((quantity, cartid, productid)) return str(ret)
def add_many(): data = request.get_json() item_input = data['item'] amount_input = data['amount'] user_id = User.get_by_id(get_jwt_identity()) cart = Cart(user=user_id, item=item_input, amount=amount_input) cart_check = Cart.get_or_none(Cart.user == user_id, Cart.item == item_input, Cart.payment_status == False) if item_input == "": return jsonify({ 'message': 'All fields required', 'status': 'failed' }), 400 elif cart_check: cart_check.update(amount=Cart.amount + amount_input, updated_at=datetime.datetime.now()).where( Cart.user_id == user_id, Cart.item_id == item_input, Cart.payment_status == False).execute() return jsonify({ 'message': 'Item already exists, added to amount', 'status': 'success' }), 200 elif cart.save(): return jsonify({ 'message': 'Item added successfully', 'status': 'success' }), 200 else: return jsonify({"message": "Uncaught error", "status": "Failed"}), 400
def _create_cart(self): iphone_silver = Product('Iphone Silver', 'Silver', 999) iphone_black = Product('Iphone Black', 'Black', 899) cart = Cart(self._create_user()) cart.add(iphone_silver, 2) cart.add(iphone_black, 1) return cart
def test_total_product_discounts(self): product = Product(sku='prod-a', name='Producto A') product.set_pricing(country_code='ES', price=50., discount=0.) product.set_pricing(country_code='GB', price=55., discount=0.1) product.set_pricing(country_code='IT', price=55., discount=0.25) cart = Cart() cart.add_item(product=product, quantity=2) self.assertEqual(cart.get_total(country_code='ES'), 100.0) self.assertEqual(cart.get_total(country_code='GB'), 99.0) self.assertEqual(cart.get_total(country_code='IT'), 82.5)
def add_to_cart(self, request): if request.method == 'POST': product_id = request.form['product_id'] amount = request.form['quantity'] product_to_cart = Product.query.filter( Product.id == product_id).first() if product_to_cart is not None: try: self.cart_main.add(product_id, amount) except KeyError: self.cart_main = Cart() self.cart_main.add(product_id, amount) return self.cart()
def index(): id = request.cookies.get('cart') if id != None: cart = Cart() a = cart.getCarts(id) sum = 0 b = [] for i in a: b.append(i[2]*i[4]) for u in b: sum += u return render_template('cart/index.html', arr = a, sum = sum) return redirect("/")
def add(): cart = Cart() id = request.cookies.get('cart') if id == None: id = randomString(16) response = make_response(redirect('/cart')) response.set_cookie('cart', id, max_age= 3600 * 24 * 30) else: response = redirect('/cart') productid = request.form.get('productid') quantity = request.form.get('quantity') cart.add((id, productid, quantity)) return response
def create_cart(item, user): new_cart = Cart(user_id=item['user_id'], item_id=item['id'], date_created=datetime.utcnow(), last_modified=datetime.utcnow()) try: new_cart.save() message = 'Cart saved successfully' return message, 200 except Exception as e: return str(e), 400 return 'Cart created and items added' # Test code - remove later
def new_cart(): current_user = User.get_by_id(get_jwt_identity()) if current_user: name = request.form.get("name") ingredient = Ingredient.get(name=name) quantity = request.form.get("quantity") amount = int(quantity)*ingredient.price cart = Cart(quantity=quantity, amount=amount, user_id = current_user.id, ingredient_id = ingredient.id) if cart.save(): return jsonify({"message" : "Ingredient has been successfully added into cart!"}) else: return jsonify({"message": "Ingredient exists in cart already!"}) else: return error
def test_total_voucher(self): product_a = Product(sku='prod-a', name='Producto A') product_a.set_pricing(country_code='ES', price=50., discount=0.1) product_b = Product(sku='prod-b', name='Producto B') product_b.set_pricing(country_code='ES', price=20., discount=0.) cart = Cart() cart.apply_voucher(code='promo5', amount=5., min_amount=90.) cart.add_item(product=product_a, quantity=1) cart.add_item(product=product_b, quantity=1) self.assertEqual(cart.get_total(country_code='ES'), 65.0) cart.add_item(product=product_a, quantity=1) self.assertEqual(cart.get_total(country_code='ES'), 105.0)
def opencart(paydesk_id=None): try: msg = { "msgtype": "ERROR", "msgid": 2, "text": "Attempt to open cart", "info": "unexpected error" } if paydesk_id is None: raise Exception_InvalidPaydesk() dbs = db_session() cart = dbs.query(Cart).filter(Cart.paydesk_id == paydesk_id, Cart.status == "OPEN").one_or_none() if cart == None: cart = Cart(paydesk_id=paydesk_id, status="OPEN") ret = dbs.add(cart) dbs.commit() msg = { "msgtype": "INFO", "msgid": 0, "text": "Cart created", "info": "Cart %d created" % (cart.id) } else: msg = { "msgtype": "INFO", "msgid": 1, "text": "Cart re-opend", "info": "Cart %d reopend" % (cart.id) } articles = dbs.query(Article).filter( Article.paydesk_id == paydesk_id, Article.cart_id == cart.id).order_by( Article.scantime.desc()).all() return { "Msg": msg, "Cart": cart.dump(), "Articles": [p.dump() for p in articles] }, 200 except Exception as ex: msg = { "msgtype": "ERROR", "msgid": 0, "text": "Severe Error", "info": "" } return msg, 400
def handle_message_server(event): # 從event裡面取得用戶id user_id = event.source.user_id # 從event裡面取得reply_token reply_token = event.reply_token # 從資料庫取得送出postback的用戶資料 query = User.query.filter_by(id=user_id).first() # 從event裡面取得用戶傳來的訊息 message_text = str(event.message.text).lower() # 建立一個購物車物件 cart = Cart(user_id=user_id) # 綁webhook if reply_token == '00000000000000000000000000000000': return 'ok' line_bot_api_server.reply_message(reply_token, TextSendMessage(text=message_text))
def generate_output(self): articles = Articles(data=self.input_data.get('articles', [])) delivery = DeliveryFee(data=self.input_data.get('delivery_fees', [])) discount = Discount(data=self.input_data.get('discounts', [])) checkout_list = [] for cart_data in self.input_data.get('carts', []): cart = Cart(cart_id=cart_data.get('id'), items=cart_data.get('items'), articles=articles, delivery=delivery, discount=discount) checkout_list.append({'id': cart.id, 'total': cart.total}) return {'carts': checkout_list}
def my_cart(): user_data = session.get('user_data', None) user=json.loads(user_data) logged_in = session.get('logged_in', False) username = user['username'] if request.method=="POST": try: product_id = request.form.get('product_id') quantity = request.form.get('quantity') product = Product.get_product(connection, product_id) if product_id and quantity: total = float(product.price) * float(quantity) if 'mycart' in session: if username in session['mycart']: if product_id in session['mycart'][username]: flash("This item is already in your cart!") return redirect(request.referrer) else: session['mycart'][username][product_id] = {'name': product.name, 'price': product.price, 'quantity':quantity,'total':total} flash("Item added to cart!") return redirect(request.referrer) else: session['mycart'][username] = { product_id:{'name': product.name, 'price': product.price, 'quantity':quantity,'total':total} } flash("Item added to cart!") return redirect(request.referrer) else: session['mycart'] = { username:{ product_id:{'name': product.name, 'price': product.price, 'quantity':quantity,'total':total} } } flash("Item added to cart!") return redirect(request.referrer) except Exception as e: print(e) finally: return redirect(request.referrer) else: prods = [] if not 'mycart' in session or not username in session['mycart']: return render_template("module_home/mycart.html",logged_in=logged_in,prods=prods,user=user,total=None) else: cart_products = session['mycart'][username] total = 0 if cart_products: for k, v in cart_products.items(): total = total + float(v['total']) prods.append(Cart(k,v['name'],v['quantity'],v['price'],v['total'])) return render_template("module_home/mycart.html",logged_in=logged_in,prods=prods,user=user, total=total)
def test_quantity_discount(self): product_a = Product(sku='prod-a', name='Producto A') product_a.set_pricing( country_code='ES', price=50., discount=0.1, quantity_discount=[ {'min_quantity': 3, 'discount': 45., 'is_percent': False} ] ) product_b = Product(sku='prod-b', name='Producto B') product_b.set_pricing( country_code='ES', price=1.5, discount=0., quantity_discount=[ {'min_quantity': 10, 'discount': 5., 'is_percent': False}, {'min_quantity': 50, 'discount': 0.1, 'is_percent': True}, {'min_quantity': 200, 'discount': 0.2, 'is_percent': True} ] ) cart = Cart() cart.apply_voucher(code='promo100', amount=100., min_amount=200.) cart.add_item(product=product_a, quantity=1) cart.add_item(product=product_b, quantity=1) self.assertEqual(cart.get_total(country_code='ES'), 46.5) cart.add_item(product=product_a, quantity=2) cart.add_item(product=product_b, quantity=8) self.assertEqual(cart.get_total(country_code='ES'), 103.5) cart.add_item(product=product_b, quantity=1) self.assertEqual(cart.get_total(country_code='ES'), 100.0) cart.add_item(product=product_b, quantity=50) self.assertEqual(cart.get_total(country_code='ES'), 171.0) cart.add_item(product=product_a, quantity=1) cart.add_item(product=product_b, quantity=50) self.assertEqual(cart.get_total(country_code='ES'), 183.5) cart.add_item(product=product_a, quantity=2) cart.add_item(product=product_b, quantity=90) self.assertEqual(cart.get_total(country_code='ES'), 365.0)
def test__calculate_items_total(): articles = Articles(data=ARTICLES_DATA) delivery = DeliveryFee(data=DELIVERY_DATA) discount = Discount(data=[]) items = [ { 'article_id': 1, 'quantity': 6 }, { 'article_id': 2, 'quantity': 2 }, ] cart = Cart(cart_id=1, items=items, articles=articles, delivery=delivery, discount=discount) assert cart._calculate_items_total() == 100 * 6 + 200 * 2
def test_total_with_delivery_fee(): articles = Articles(data=ARTICLES_DATA) delivery = DeliveryFee(data=DELIVERY_DATA) discount = Discount(data=[]) items = [ { 'article_id': 1, 'quantity': 6 }, { 'article_id': 2, 'quantity': 2 }, ] cart = Cart(cart_id=1, items=items, articles=articles, delivery=delivery, discount=discount) assert cart.total == (100 * 6 + 200 * 2) + 400
def test__apply_delivery_fee(): articles = Articles(data=ARTICLES_DATA) delivery = DeliveryFee(data=DELIVERY_DATA) discount = Discount(data=[]) items = [ { 'article_id': 1, 'quantity': 6 }, { 'article_id': 2, 'quantity': 2 }, ] cart = Cart(cart_id=1, items=items, articles=articles, delivery=delivery, discount=discount) cart_price = 1000 assert cart._apply_delivery_fee(price=cart_price) == cart_price + 400
def save_order(): user_data = session.get('user_data', None) user=json.loads(user_data) username = user['username'] prods = [] if request.method == "POST": total = request.form.get('total') now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") print(now) if Order.insert_order(connection,Order(0,username,now,total)): cart_products = session['mycart'][username] if cart_products: for k, v in cart_products.items(): prods.append(Cart(k,v['name'],v['quantity'],v['price'],v['total'])) for prod in prods: OrderDetails.insert_order_details(connection,OrderDetails(0,0,prod.id_product,prod.quantity,prod.total)) UserProductRating.insert_product_notrated(connection,UserProductRating(username,prod.id_product,0,0)) flash('Order Saved Successfully!') session.modified = True session['mycart'].pop(username) return redirect(url_for(".my_cart")) else: flash("Error saving order, try again later.") return redirect(request.referrer)
def _create_empty_cart(slug: str) -> Cart: return Cart(slug=slug)
def delete(): productid = request.form.get('pid') cartid = request.cookies.get('cart') cart = Cart() cart.delete((cartid, productid)) return redirect("/cart")
class Controller: avg_rating = db_session.query( func.avg(ShopRatings.rating).label('average')).first().average cart_main = Cart() def __init__(self): init_db() def reset(self): self.cart_main = Cart() return render_template('template.html', title="Strona główna", avg_rating=self.avg_rating) def home(self): return render_template('template.html', title="Strona główna", avg_rating=self.avg_rating) def cart(self): try: orders = self.cart_main.getUnique() print(orders) ordered_products = [] for order in orders: db_product = Product.query.filter(Product.id == order).first() order_amount = self.cart_main.countProduct(order) ordered_products.append( Prod(db_product.name, order_amount, db_product.price)) sum = 0 for product in ordered_products: db_product = Product.query.filter( Product.name == product.name).first() sum = sum + db_product.price * product.amount return render_template('cart.html', products=ordered_products, title="Koszyk", price=sum, avg_rating=self.avg_rating) except KeyError: return render_template('cart.html', products=[], title="Koszyk", avg_rating=self.avg_rating) return render_template('cart.html', products=[], title="Koszyk", avg_rating=self.avg_rating) def catalog(self): categories = Category.query.all() return render_template('browse_categories.html', categories=categories, title='Kategorie', avg_rating=self.avg_rating) def order_form(self): return render_template('order_form.html', title='Formularz zamówienia', avg_rating=self.avg_rating) def order(self, request): if request.method == 'POST': print(request.form) delivery_type = request.form['delivery-type'] try: orders = self.cart_main.getUnique() ordered_products = [] for order in orders: db_product = Product.query.filter( Product.id == order).first() order_amount = self.cart_main.countProduct(order) ordered_products.append( Prod(db_product.name, order_amount, db_product.price)) sum = 0 for product in ordered_products: db_product = Product.query.filter( Product.name == product.name).first() sum = sum + db_product.price * product.amount if product.amount > db_product.amount: raise Exception("Przekroczyłeś produkty w magazynie") for product in ordered_products: db_product = Product.query.filter( Product.name == product.name).first() db_product.amount = db_product.amount - product.amount print(db_product.amount) db_session.add(db_product) db_session.commit() self.cart_main = Cart() return render_template('order_result.html', price=sum, avg_rating=self.avg_rating) except KeyError: print('error1') except Exception as e: self.cart_main = Cart() return render_template( 'template.html', title= "Nie można stworzyć zamówienia, przekroczyłeś liczbę produktów w magazynie", avg_rating=self.avg_rating) return render_template('order_form.html', title='Formularz zamówienia', avg_rating=self.avg_rating) def category(self, category_id): prod_in_category = Product.query.filter( Product.category == category_id).all() category_name = Category.query.filter( Category.id == category_id).first().name return render_template('browse_category.html', products=prod_in_category, title=f'Kategoria {category_name}', avg_rating=self.avg_rating) def product(self, product_id): product = Product.query.filter(Product.id == product_id).first() return render_template('browse_product.html', product=product, title=f'{product.name}', avg_rating=self.avg_rating) def add_to_cart(self, request): if request.method == 'POST': product_id = request.form['product_id'] amount = request.form['quantity'] product_to_cart = Product.query.filter( Product.id == product_id).first() if product_to_cart is not None: try: self.cart_main.add(product_id, amount) except KeyError: self.cart_main = Cart() self.cart_main.add(product_id, amount) return self.cart() def rate(self, request): rating = request.form.get('rate') ratingText = request.form.get('text') ratingText = None if ratingText == '' else ratingText db_session.add(ShopRatings(rating, ratingText)) db_session.commit() self.avg_rating = db_session.query( func.avg(ShopRatings.rating).label('average')).first().average return jsonify(status='success')
def reset(self): self.cart_main = Cart() return render_template('template.html', title="Strona główna", avg_rating=self.avg_rating)
def handle_message(event): # 從event裡面取得用戶id user_id = event.source.user_id # 從event裡面取得reply_token reply_token = event.reply_token # 從資料庫取得送出postback的用戶資料 query = User.query.filter_by(id=user_id).first() # 從event裡面取得用戶傳來的訊息 message_text = str(event.message.text).lower() # 建立一個購物車物件 cart = Cart(user_id=user_id) # 綁webhook if reply_token == '00000000000000000000000000000000': return 'ok' # 如果正在註冊中 if query.is_signup: if check_cellphone(event.message.text): line_bot_api.push_message(user_id, TextSendMessage('恭喜註冊成功!')) line_bot_api.link_rich_menu_to_user(user_id, richmenu_list.RichMenu_ID.richmenu_04) query.is_member = True query.is_signup = False query.phone_number = event.message.text db_session.commit() return else: line_bot_api.push_message(user_id, AllMessage.error_cellphone_format()) if query.is_member: if query.edit_user_name: print('編輯使用者中') query.user_name_custom = message_text query.edit_user_name = False db_session.commit() line_bot_api.push_message(user_id, TextSendMessage(text='設定完成')) return elif query.edit_home_address: print('編輯住家中') query.home_address = message_text query.edit_home_address = False db_session.commit() line_bot_api.push_message(user_id, TextSendMessage(text='設定完成')) return elif query.edit_company_address: print('編輯公司中') query.company_address = message_text query.edit_company_address = False db_session.commit() line_bot_api.push_message(user_id, TextSendMessage(text='設定完成')) return # 編輯使用者名稱 if message_text == '編輯使用者名稱': query.edit_user_name = True query.edit_home_address = False query.edit_company_address = False db_session.commit() line_bot_api.reply_message(event.reply_token, AllMessage.edit_user_name()) return # 編輯住家 elif message_text == '編輯住家': query.edit_user_name = False query.edit_home_address = True query.edit_company_address = False db_session.commit() line_bot_api.reply_message(event.reply_token, AllMessage.edit_home_address()) return # 編輯公司 elif message_text == '編輯公司': query.edit_user_name = False query.edit_home_address = False query.edit_company_address = True db_session.commit() line_bot_api.reply_message(event.reply_token, AllMessage.edit_company_address()) return # 購物車相關 if "數量為:" in message_text: product_name = message_text.split(',')[0] num_item = message_text.rsplit(':')[1] product = db_session.query(Products).filter(Products.name.ilike(product_name)).first() if product: cart.add(product=product_name, num=num_item) confirm_template = ConfirmTemplate( text='{},數量為:{}?'.format(product_name, num_item), actions=[ PostbackAction(label='繼續選購', text='繼續選購', data='當日外帶'), PostbackAction(label='確認訂單', text='確認訂單', data='確認訂單') ]) line_bot_api.reply_message(reply_token, TemplateSendMessage(alt_text='還需要加購嗎?', template=confirm_template)) else: line_bot_api.reply_message(reply_token, TextSendMessage(text="抱歉,我們沒有賣{}".format(product_name))) # 功能列表 if message_text == "功能列表": line_bot_api.reply_message(reply_token, AllMessage.Menu_client(user_id)) return # 變成管理員的通關密碼 if message_text in ["霹靂卡霹靂拉拉波波莉娜貝貝魯多", "AI戰神"]: query.is_manager = True line_bot_api.reply_message(reply_token, TextSendMessage(text="恭喜你成為管理員了")) return
def _create(): cart = CartController._read() if not cart: cart = Cart() return cart
def handler_postback(event): # 把postback裡面的資料轉成字典 data = dict(parse_qsl(event.postback.data)) # 再取出action裡面的值 action = data.get('action') # 從event裡面取得用戶id user_id = event.source.user_id # 從event裡面取得reply_token reply_token = event.reply_token # 建立一個購物車物件 cart = Cart(user_id=user_id) # 從資料庫取得送出postback的用戶資料 query = User.query.filter_by(id=user_id).first() print(event.postback.data) # 點擊加入會員 if event.postback.data in ['join_us', '加入會員']: # 資料庫該使用者狀態改為註冊中 # Updata data print('註冊中') query.is_signup = True db_session.commit() line_bot_api.link_rich_menu_to_user(user_id, richmenu_list.RichMenu_ID.richmenu_02) line_bot_api.push_message(user_id, AllMessage.sign_cellphone()) # 點擊取消輸入之類的 elif event.postback.data in ['exit']: query.is_signup = False query.edit_user_name = False query.edit_home_address = False query.edit_company_address = False db_session.commit() if not query.is_member: line_bot_api.link_rich_menu_to_user(user_id, richmenu_list.RichMenu_ID.richmenu_01) line_bot_api.push_message(user_id, TextSendMessage(text='好的,歡迎您再來找我聊聊天喔!')) # 點擊會員中心 elif event.postback.data in ['會員中心']: line_bot_api.reply_message(reply_token, TextSendMessage(text='這是專屬於你的會員中心', sender=Sender( name='會員中心管理員結衣', icon_url='https://i.imgur.com/S7SHmup.png' ))) line_bot_api.push_message(user_id, AllMessage.member_center(query)) # 觸發點餐相關事件 elif event.postback.data in ['當日外帶', 'add', '點餐']: # 先跳出選擇內用外帶 line_bot_api.reply_message(reply_token, TemplateSendMessage(alt_text="請問您要內用還是外帶呢?", sender=Sender( name='服務員結衣', icon_url='https://i.imgur.com/S7SHmup.png' ), template=ConfirmTemplate( text="請問您要內用還是外帶呢?", actions=[ PostbackAction( label="內用", text="內用", data="here" ), PostbackAction( label="外帶", text="外帶", data="out" ) ] ))) # 外帶事件 elif event.postback.data in ['out']: line_bot_api.reply_message(reply_token, Products.list_all()) # 內用事件 elif event.postback.data in ['here']: line_bot_api.reply_message(reply_token, TemplateSendMessage(alt_text="請掃描桌上的QRCODE", sender=Sender( name='服務員結衣', icon_url='https://i.imgur.com/S7SHmup.png' ), template=ButtonsTemplate( text='請掃描桌上的QRCode點餐', actions=[ URIAction( type='uri', label='點我掃描', uri="https://liff.line.me/1654280234-Wabazm3B" ) ] ))) # 觸發確認訂單事件 elif event.postback.data in ['待補', '確認訂單']: if cart.bucket(): line_bot_api.reply_message(reply_token, cart.display()) else: line_bot_api.reply_message(reply_token, TextSendMessage(text='你的購物車目前沒東西喔')) # 觸發清空購物車事件 elif event.postback.data in ['Empty Cart']: cart.reset() line_bot_api.reply_message(reply_token, TextSendMessage(text="你的購物車已經被清空了")) # 如果action為check則執行結帳動作 elif action == 'checkout': if not cart.bucket(): line_bot_api.reply_message(reply_token, TextSendMessage(text='你的購物車是空的')) return 'OK' # 透過uuid來建立訂單id,它可以幫我們建立一個獨一無二的值 order_id = uuid.uuid4().hex # 訂單總金額 total = 0 # 訂單內容物的陣列 items = [] for product_name, num in cart.bucket().items(): product = db_session.query(Products).filter(Products.name.ilike(product_name)).first() print(product.id) item = Items(product_id=product.id, product_name=product.name, product_price=product.price, order_id=order_id, quantity=num) items.append(item) total += product.price * int(num) cart.reset() line_pay = LinePay() # 傳送這些資訊過去他會回我們一個json # 自己試試看把info印出來或是用postman看看裡面的結構 info = line_pay.pay(product_name='OrderBot 點吧', amount=total, order_id=order_id, product_image_url=Config.STORE_IMAGE_URL) # 從info裡面擷取付款連結跟transactionid pay_web_url = info['paymentUrl']['web'] transaction_id = info['transactionId'] # 產生訂單 order = Orders(id=order_id, transaction_id=transaction_id, is_pay=False, amount=total, user_id=user_id) db_session.add(order) for item in items: db_session.add(item) db_session.commit() message = TemplateSendMessage( alt_text='差一點點就完成訂購囉~', template=ButtonsTemplate( text='差一點點就完成訂購囉~', actions=[ URIAction(label='Pay NT${}'.format(order.amount), uri='{liff_url}?redirect_url={url}'.format( liff_url=Config.LIFF_URL, url=pay_web_url)) ])) line_bot_api.reply_message(reply_token, message) # 訂單管理 elif event.postback.data in ['訂單管理']: line_bot_api.reply_message(reply_token, Booking.list_all_user(user_id)) # 取消訂單 elif '取消訂位' in event.postback.data: line_bot_api.reply_message(reply_token, TextSendMessage(text="您的訂單已取消", sender=Sender( name='會員中心管理員結衣', icon_url='https://i.imgur.com/S7SHmup.png' ))) book_id = str(event.postback.data)[4:] db_session.query(Booking).filter_by(id=book_id).first().is_confirm = -2 db_session.commit() return 'OK'
from models.cart import Cart from models.CartItem import CartItem from db.db import inventory cart = Cart() def fetch_cart_payload(): cart_result = list(map(lambda x: x.json(), cart.items)) if cart_result: return {'Items': cart_result} return "Cart is Empty" def add_item(item_name): inv_items = [item for item in inventory if item.name == item_name] cart_items = [item for item in cart.items if item.name == item_name] if len(cart_items) < 1: cart.items.append(CartItem(item_name, inv_items[0].price, 1)) else: cart_items[0].quantity += 1 def remove_item(item_name): cart_items = [item for item in cart.items if item.name == item_name][0] if cart_items.quantity > 1: cart_items.quantity -= 1 else: index = cart.items.index(cart_items) del cart.items[index]