def objects() -> List[Order]: _ = list() _.append( Order( id="o-1", user_id="u-12345", product_ids=["p-67890"], status=OrderStatus.SHIPPED, eta=4, )) _.append( Order( id="o-2", user_id="u-12345", product_ids=["p-33333"], status=OrderStatus.PROCESSING, eta=7, )) _.append( Order( id="o-3", user_id="u-67890", product_ids=["p-11111"], status=OrderStatus.PROCESSING, eta=3, )) _.append( Order( id="o-4", user_id="u-67890", product_ids=["p-27182"], status=OrderStatus.DELIVERED, eta=-2, )) return _
def get(self): tCode = re.sub(r'\W', '', self.request.get('code')).lower() tOrderId = self.request.get('id') logging.debug(tCode) tOrder = Order() #tOrder.orderVerificationCode tOrderQuery = Order().all() tOrderQuery.filter('orderVerificationCode', tCode) if (tOrderId): tOrderQuery.filter('orderTransactionId', tOrderId) tOrderList = tOrderQuery.fetch(limit=1) logging.debug(str(tOrderList)) tSave = False if tOrderList is not None: try: tOrder = tOrderList[0] tOrder.orderIsVerified = True tSave = True except: if len(tOrderList) > 0: tOrder = tOrderList tOrder.orderIsVerified = True tSave = True if tSave: try: tOrder.put() except: pass
def test_bakery(self): vs = Product("Vegemite Scroll", "VS5", {3: 6.99, 5: 8.99}) mb = Product("Blueberry Muffin", "MB11", {2: 9.95, 5: 16.95, 8: 24.95}) cf = Product("Croissant", "CF", {3: 5.95, 5: 9.95, 9: 16.99}) bakery = Bakery([vs, mb, cf]) # test get product by code test_code = "VS5" self.assertEqual(bakery.get_product("VS5").code, test_code) self.assertRaises(KeyError, bakery.get_product, "not_exist_code") # init order for test order = Order({"VS5": "10", "WRONG_CODE": 14, "CF": 13}) # input format test bakery.process_order(order) self.assertTrue(order.get_product("WRONG_CODE")["total_price"] is None) # test single product order order = Order({"VS5": 10}) bakery.process_order(order) self.assertEqual(order.get_product("VS5")["packs"], {5: 2}) # test combined products order order = Order({"VS5": 10, "MB11": 14, "CF": 13}) bakery.process_order(order) self.assertEqual(order.get_product("VS5")["packs"], {5: 2}) self.assertEqual(order.get_product("VS5")["remainder"], 0) self.assertEqual(order.get_product("MB11")["packs"], {8: 1, 2: 3}) self.assertEqual(order.get_product("MB11")["remainder"], 0) self.assertEqual(order.get_product("CF")["remainder"], 0) self.assertEqual(order.get_product("CF")["packs"], {5: 2, 3: 1})
def post(self): tIpLookup = IpLookup() tIpStore = IpInfo() tIp = str(self.request.get('ip')) tTransactionId = str(self.request.get('transid')) tIpInfo = {} #logging.debug("Scraping Ip: " + tIp) if (tIp != None and len(tIp) > 0): tIpInfo = tIpLookup.IpInfoScraper(tIp) else: tIpInfo = {} tIpInfo['country'] = "" tIpInfo['host'] = "" tIpInfo['state'] = "" tIpInfo['isp'] = "" tIpInfo['proxy'] = "" tIpInfo['type'] = "" tIpStore.ip = tIp tIpStore.ipCountry = tIpInfo['country'] tIpStore.ipHost = tIpInfo['host'] tIpStore.ipState = tIpInfo['state'] tIpStore.ipIsp = tIpInfo['isp'] tIpStore.ipProxy = tIpInfo['proxy'] tIpStore.ipType = tIpInfo['type'] tIpStore.ipOrder = tTransactionId tIpKey = tIpStore.put() #logging.debug("Stored IP: " + tIp + " at Key " + str(tIpKey)) tOrder = Order() tOrderQuery = Order().all() #logging.debug("Transaction Id: " + tTransactionId) tOrderQuery.filter("orderTransactionId", tTransactionId) tOrder = tOrderQuery.fetch(1)[0] tMobilePhone = tOrder.orderMobileNumber tCustomerKey = tOrder.orderCustomer tOrderKey = str(tOrder.key()) #logging.debug("IP Address Mobile Number " + str(tMobilePhone)) if (tMobilePhone != None and len(tMobilePhone) > 0): taskqueue.add(url="/phonelookup", countdown=1, params={ "order": tOrderKey, "customer": tCustomerKey, "ipcountry": tIpStore.ipCountry })
def order(service_id): new_order = Order(service_id=service_id, user_id=session['user_id'], time=datetime.now().strftime("%I:%M%p %d-%B-%Y"), is_accepted=False) new_order.save() return render_template('base.html', result='Da Gui Yeu Cau')
def add_to_cart(): from datetime import datetime date_create_order = datetime.now() time_order = '00:00' order = Order.query.filter_by(user_id=current_user.id, status='pending').first() if not order: order = Order(user_id=current_user.id, status='pending', created_at=date_create_order, address='www', time=time_order) order.new_order(order) id = request.form['food_id'] food = Food.query.get(id) if food: #logic- add dish to cart food_order = FoodOrder(order_id=order.id, food_id=food.id, count=1, price=food.price) food_order.new_food_order(food_order) return jsonify(food.name) else: requestJson = jsonify("Ошибка! Блюдо не найдено") requestJson.status_code = 401 return requestJson
def order(ordered): if "user_id" in session: order = Order(userid=session["user_id"], serviceid=ordered, is_accepted=False) order.save() return render_template('order.html') else: return redirect(url_for('sign_in'))
def order(service_id): new_order = Order(service_id=service_id, user_id=session['user_id'], time_order=datetime.now().strftime("%I:%M %p"), is_accepted=False) new_order.save() return "Send request"
def post(self): data = request.get_json() validation_result = self.validate_input_data(data) if not validation_result[0]: try: return { "validation_error": self.convert_orders_ids_to_response( list( map(lambda x: {"id": x[Order.id_str]}, validation_result[1]))) }, 400 except KeyError: return {"validation_error": dict()}, 400 added_orders = list() for key in data: for order in data[key]: new_order = Order(order[Order.id_str], order[Order.weight_str], order[Order.region_str], order[Order.delivery_hours_str]) added_orders.append(new_order) db.insert_orders(added_orders) return self.convert_orders_ids_to_response( list(map(lambda x: x.get_json_id(), added_orders))), 201
def create_order(user_id, fullname, email, phone, address, guide_info, total_price, total_quantity, item_list): found_order = Order.objects(user_id=user_id, status="Chờ duyệt") if found_order: return False order_time = unix_time_millis() # prep_time = order_time + 5*60*1000 # bake_time = prep_time + 20*60*1000 status = "Chờ duyệt" new_order = Order( user_id=user_id, fullname=fullname, email=email, phone=phone, address=address, guide_info=guide_info, total_price=total_price, total_quantity=total_quantity, status=status, order_time=order_time, # prep_time=prep_time, # bake_time=bake_time, item_list=item_list ) new_order.save() return True
def post(self): try: openid = self.get_argument("openid", None) product_id = self.get_argument("product_id", None) if not openid or not product_id: return self.response(code=10002, msg='参数错误') phone = random_str(11) product = self.session.query(Product).filter( Product.id == product_id).first() fee = float(product.price) out_trade_no = order_num(phone) order = Order(product_id=product_id, product_name=product.name, product_description=product.description, total_fee=float(product.price), create_ts=datetime.datetime.now(), user_openid=openid, pay_status=1, out_trade_no=out_trade_no) self.session.add(order) self.session.flush() orderid = order.id pay_data = request_prepayment(openid, int(fee * 100), out_trade_no, orderid) if pay_data['return_code'] == 'FAIL': return self.response(code=10003, msg=pay_data["return_msg"]) if pay_data['result_code'] == 'FAIL': return self.response(code=10003, msg="%s:%s" % (pay_data['errcode'], pay_data['errmsg'])) self.session.commit() sign_data = dict() sign_data['appId'] = options.AppID sign_data['timeStamp'] = str(int(time.time())) sign_data['nonceStr'] = random_str(16) sign_data['package'] = 'prepay_id=' + pay_data['prepay_id'] sign_data['signType'] = 'MD5' sign = get_sign(sign_data) return_data = { 'appId': sign_data['appId'], 'timeStamp': sign_data['timeStamp'], 'nonceStr': sign_data['nonceStr'], 'package': sign_data['package'], 'signType': sign_data['signType'], 'paySign': sign } return self.response(data=return_data, code=10001, msg='success') except Exception as e: self.logger.error(str(e)) print(traceback.print_exc()) self.session.rollback() return self.response(code=10000, msg='服务端异常') finally: self.session.remove()
def record_order(order_data): """ This methods pick the data from the user request and save it into the database :param order_data: :return: receipt for the order saved """ new_order = Order() pizza_query = db.session.query(Pizza).join(SizeReference) topping_query = db.session.query(Topping).join(ToppingReference).join( ToppingTypeSize).join(SizeReference) for unique_request in order_data: request_list = unique_request.split("-") pizza_size = request_list[0].strip(" ").capitalize() pizza_obj = pizza_query.filter( SizeReference.name == pizza_size).first() new_user_request = UserRequest(pizza_id=pizza_obj.id) topping_list = request_list[-1].split( ",") if len(request_list) > 1 else [] topping_list = list(filter(lambda x: x != "", topping_list)) for topping in topping_list: topping_name = topping.strip(" ").capitalize() topping_obj = topping_query.filter( ToppingReference.name == topping_name).filter( SizeReference.name == pizza_size).first() new_user_request.toppings.append(topping_obj) new_order.user_requests.append(new_user_request) db.session.add(new_order) db.session.commit() new_receipt = Receipt(order_id=new_order.id) db.session.add(new_receipt) db.session.commit() return new_receipt
def order(service_id): new_order = Order(service_id=service_id, time=time, accepted=accepted, user_id=user_id) new_order.save() return "sent"
def order(service_id): order = Order(user_id=session['id'], service_id=service_id, time=datetime.now(), is_accepted=False) order.save() return render_template('order.html')
def update(self, *args): try: order: Order = Order() if len(args) is 0: raise Exception('Invalid arguments') if isinstance(args[0], int) or isinstance(int(args[0]), int): order.fill() order.id = args[0] values = order.getValues().split(',') old_values = self.getById(args[0]).getValues().split(',') keys = order.getKeys().split(',') for i in range(len(keys)): if values[i] == 'null': order.__setattr__(keys[i], old_values[i]) if isinstance(args[0], Order): order = args[0] if not order.isFull(): raise Exception('Invalid input') queryStr = '' keys = order.getKeys().split(',') values = order.getValues().split(',') for i in range(len(keys)): queryStr += keys[i] + ' = ' + values[i] + ', ' self.db.cursor.execute(f'Update "Order" Set {queryStr[:-2]} Where id = {order.id}') self.db.connect.commit() return True except Exception as err: print("Update error! ", err) return False
def _add_orders(self, quantity, product_id, user_id, ): """ Метод заполнения заказа """ # получаем список всех product_id all_id_product = self.select_all_product_id() # если данные есть в списке, обновляем таблицы заказа и продуктов if product_id in all_id_product: quantity_order = self.select_order_quantity(product_id) quantity_order += 1 self.update_order_value(product_id, 'quantity', quantity_order) quantity_product = self.select_single_product_quantity( product_id) quantity_product -= 1 self.update_product_value(product_id, 'quantity', quantity_product) return # если данных нет, создаем новый объект заказа else: order = Order(quantity=quantity, product_id=product_id, user_id=user_id, data=datetime.now()) quantity_product = self.select_single_product_quantity(product_id) quantity_product -= 1 self.update_product_value(product_id, 'quantity', quantity_product) self._session.add(order) self._session.commit() self.close()
def sell(self, **kwargs): order = Order(currency=self.exchange.currency, asset=self.exchange.asset, symbol=self.exchange.get_symbol(), side=Order.SELL, test=self.test, **kwargs) self.order(order)
def create_order(order_type=Order.NORMAL_TYPE): return Order(name=cfaker.first_name(), number=cfaker.pydecimal(), owner=a_customer_user.id, type=order_type, ordered_products=[an_ordered_product], delivery=a_delivery_user.id, delivery_rated=False, owner_rated=False).save()
def buy(self, **kwargs): order = Order(currency=self.exchange.currency, asset=self.exchange.asset, symbol=self.exchange.get_symbol(), type=Order.TYPE_LIMIT, side=Order.BUY, test=self.test, **kwargs) self.order(order)
def sent(profile_id): sent = Order( account_id = session['id'], service_id = profile_id, time = datetime.now(), is_accepted = False ) sent.save() return render_template('sent.html')
def add_order(source_id, locate_source, orders, status): o = Order(id=create_id_order(), source_id=source_id, locate_source=locate_source, orders=orders, status=status) db.session.add(o) db.session.commit() return '''
def servicerequest(): all_service = Service.objects() users = User.objects() order = Order( #service_id = service.id, #user_id = user.id, time=str(datetime.now()), is_accepted=False) order.save() return "Đã gửi yêu cầu"
def order(): new_order = Order( service_id = session['service_id'], user_id = session['user_id'], time = datetime.datetime.now(), is_accept = False ) new_order.save() return "Đã yêu cầu dịch vụ"
def create_order(self): db = get_db() db_order = Order( customer_id=self.user_id, order_date=datetime.now(), order_status="pending", ) db.add(db_order) db.commit() return OrderFullResponse.from_orm(db_order)
def order(service_id): new_order = Order( service_id = service_id, user_id = session['user_id'], time = datetime.datetime.now(), is_accepted = False ) new_order.save() return "Đã gửi yêu cầu"
def create_order(): """ Create a new order by placing products and client --- parameters: - in: header name: authorization required: true schema: type: string - in: query name: shop required: true schema: type: object parameters: id: type: integer - in: query name: total required: true schema: type: integer responses: 200: description: Successfully created the order schema: type: object parameters: message: type: string example: Success """ user = request.user shop = storage.get(User, user).shops[0] in_order = request.get_json() order = Order() order.date = str(datetime.utcnow()) order.description = json.dumps(in_order['shop']) order.total = in_order['total'] order.shop = shop.id order.origin = 'admin' client = storage.get(Client, shop.client) if client: order.client = client.id else: client = Client() client.username = shop.title client.email = storage.get(User, user).username client.phone = shop.phone order.client = client.id client.save() order.save() print() return jsonify(message='Success')
def createNewOrder(self, weight, size, loginCostumer, loginExecutor, price, adressPickup, adressDelivery, timePickup, timeDelivery, description): self.lastOrderId += 1 order = Order(self.lastOrderId, weight, size, loginCostumer, loginExecutor, price, "created", adressPickup, adressDelivery, timePickup, timeDelivery, description) jsonString = json.dumps(order) with open("Order" + str(order.id) + ".txt", "w") as text_file: text_file.write(jsonString) return order
def order(service_id): new_order = Order(service_id=service_id, user_id=session['user_id'], date_time=datetime.datetime.now(), is_accepted=False) new_order.save() service = Service.objects.with_id(service_id) if service is not None: return "Đã gửi yêu cầu" else: return "Service is not found!"
def order(service_id): if session.get('user_login'): service = Service.objects.with_id(service_id) order = Order(service_name=service.name, user_id=session['account'], time=datetime.now(), is_accepted=False) order.save() return redirect(url_for('search')) else: return redirect(url_for("login"))
def order(service_id): if request.method == "GET": service = Service.objects().with_id(service_id) new_order = Order( service_id=service_id, service_name=service.name, user_id=session['user_id'], user_name=User.objects().get(id=session['user_id']).fullname, time=str(datetime.datetime.now()), is_accepted=False) new_order.save() return "Đã gửi yêu cầu"