def post(self): try: data = json.loads(request.data) chef_id = data.get("chefId") user_id = data.get("userId") arrival_ts = data.get("arrivalDateTimeStamp") # items with meal_id and quantity ordered_items = data.get("orderedItems") order = Order(chef_id, user_id, arrival_ts) order.save() for item in ordered_items: ojmt_obj = OrderJoinMealItem(order.id, item.get("id"), item.get("quantity")) ojmt_obj.save() total_amount_dollars = compute_total(ordered_items) intent = stripe.PaymentIntent.create(amount=int( total_amount_dollars * 100), currency='usd') return jsonify({ 'clientSecret': intent['client_secret'], 'totalAmount': total_amount_dollars, 'orderId': order.id }) except Exception: return custom_json_response( {'error': 'problem getting clientSecret'}, 403)
def trade(self, today: datetime, context: Context) -> List[Order]: assert isinstance(today, datetime) window = 10.0 previous = today - timedelta(days=window) iso = previous.strftime("%Y-%m-%d") test = self.data["AAPL"].get_single_price(previous, flexible=True) rolling_test = self.data["AAPL"].get_rolling_average(previous, today) test2 = self.data["AAPL"].check_date_range(previous, today, flexible=True) curr = self.AlpacaData.get_bars_data("AAPL", timeframe='15Min', start=today, end=today, limit=5) curr_data = curr["AAPL"].at[ curr["AAPL"].index[-1], 'close'] # getting most recent closing price if test < curr_data: # buy self.orders.append(Order("buy", "AAPL", 1)) else: # sell self.orders.append(Order("sell", "AAPL", 1)) return self.orders
def post_order(): """ header Authorization: Token Authentication_user_token { "event_key": "y37jsnks", "drinks": [{ "mixer_type": "coke", "alcohol_type": "rhum", "double": True }], } """ if request.content_type != JSON_MIME_TYPE: return json_error('Invalid Content Type', 'Invalid Content Type', 400) if g.get('current_user', None) is None: return json_error('No user found might have been a machine token', status=401) data = request.json event = Event.find(data.get('event_key')) if event is None: return json_error('Event not found', 'Event not found', 404) drinks = [ Drink(drink.get('mixer_type'), drink.get('alcohol_type'), drink.get('double')) for drink in data.get('drinks') ] # total_price = Order.get_price_from_drinks(drinks) # TODO process transation, for now assume the trasaction always passes new_order = Order(g.current_user._id, drinks, payed=True) new_order.create() event.add_new_order(new_order) g.current_user.add_order(new_order) return json_response(json.dumps(new_order.to_dict()), status=200)
def seed_db(): from models.Item import Item from models.User import User from models.Order import Order from models.OrderShipping import OrderShipping from main import bcrypt from faker import Faker import random faker = Faker() for i in range(3): user = User() user.email = f"test{i}@test.com" user.password = bcrypt.generate_password_hash("123456").decode("utf-8") db.session.add(user) admin = User() admin.email = "*****@*****.**" admin.password = bcrypt.generate_password_hash("123456").decode("utf-8") admin.admin = True db.session.add(admin) db.session.commit() for i in range(10): item = Item() item.name = faker.currency_name() item.description = faker.paragraph(nb_sentences=3) item.price = 53.25 db.session.add(item) db.session.commit() ordershipping = [] for i in range(5): shipping = OrderShipping() shipping.first_name = faker.first_name() shipping.last_name = faker.last_name() shipping.address = faker.street_address() shipping.state = faker.city() shipping.zip_code = faker.postcode() db.session.add(shipping) ordershipping.append(shipping) db.session.commit() orders = [] for i in range(5): order = Order() order.shipping_id = random.choice(ordershipping).id db.session.add(order) orders.append(order) db.session.commit() print("Tables seeded.")
def test_instantiation(self): try: Order('buy', "GMC", 2) Order('sell', 'RKT', notional=1500.00) Order("buy", "AMC", notional=1000.00) except AssertionError: self.fail() else: self.assertTrue(True)
def test_return_good_orders(self): orders = [ Order('buy', 'AAPL', 2), Order('sell', 'GMC', notional=2000.00), Order('buy', 'GOOG', 3.5), ] new_orders = self.o_r.backtest_orders(orders) self.assertTrue(orders == new_orders)
def test_reduce_multiples3(self): orders = [ Order('buy', 'AAPL', 2), Order('buy', 'AAPL', 1), Order('sell', 'AAPL', 5) ] resultant = Order('sell', "AAPL", 2) filtered = self.o_r.backtest_orders(orders) self.assertTrue(resultant == filtered[0])
def get(self): id = get_jwt_identity().get("id") chefOrders = Order.get_order_by_chefId(id) userOrders = Order.get_order_by_userId(id) data = { "chefOrders": order_schema.dump(chefOrders, many=True), "userOrders": order_schema.dump(userOrders, many=True) } return data
def cancel_order(self, order_id): """ this method delete the order that match this order_id from the 'orders' table in db and delete the meeting from the schedule of each participant that invited to this meeting. only the user taht create this order can cancel it :param order_id: """ if Order.who_create_order(order_id) == self.email: Order.delete_order(order_id) Schedule.delete_order(order_id)
def add_order(): if (request.form['client']): now = datetime.now() order = Order(now.strftime("%y-%m-%d %H:%M:%S"), request.form['obs'], request.form['client']) ret = order.insert() if ret == 'Pedido cadastrado com sucesso!': return jsonify({'order_id': order.id}) else: return jsonify({'message': ret}) return jsonify({'message': 'O parâmetro ID do cliente é obrigatório'})
def seed_db(): from main import bcrypt from models.Menu import Menu from models.User import User from models.Order import Order from faker import Faker import random faker = Faker() users = [] menus = [] for i in range(10): user = User() user.email = faker.email() user.password = bcrypt.generate_password_hash("123456").decode("utf-8") user.first_name = faker.first_name() user.last_name = faker.last_name() user.admin = faker.boolean(chance_of_getting_true=50) users.append(user) db.session.add(user) print(f"{i} users created") db.session.commit() for i in range(10): menu = Menu() menu.title = faker.color_name() menu.price = faker.random_number(digits=2) menu.vegetarian = faker.boolean(chance_of_getting_true=50) menus.append(menu) db.session.add(menu) print(f"{i} book record(s) created") db.session.commit() for i in range(10): order = Order() order.menu_id = random.choice(menus).id order.user_id = random.choice(users).id order.test = "test" db.session.add(order) print(f"{i} order created") db.session.commit() print("Tables seeded")
def cancel_meeting(self, meeting_id): """ this user won't come to this meeting so the user decide to cancel it :param meeting_id: """ order_id = Schedule.cancel_meeting(meeting_id) if Order.who_create_order(order_id) == self.email: return self.cancel_order(order_id) if order_id is not None: Order.participant_cancel(self.email, order_id) meetings = Schedule.get_by_order(order_id) for m in meetings: m.remove_participants(self.email)
def make_order_info(self, prompt, customer_known): """Býr til tóma pöntun og sendir pöntunina í gegnum ferlið að búa til allar upplýsingar um hana""" price_repo = PriceRepository() new_order = Order() for step in range(1, 5): if customer_known and (step == 1): new_order.set_customer(customer_known) else: choice = new_order.change_info(str(step), self.__car_service, self.__customer_service, prompt, price_repo) if choice == "t": return "t" elif choice == "h": return "h" price_repo = PriceRepository() price = calc_price(new_order, price_repo) new_order.set_price(price) print_header(prompt) print(new_order) print("="*70) continue_q = input("\nEr allt rétt? (j/n) ").lower() if continue_q != "j": self.change_order_info(new_order, prompt) print_header(prompt) payment_complete = take_payment(new_order.get_order_price()) if type(payment_complete) == str: return "h" print_header(prompt) print("Pöntun skráð.") sleep(2.5) self.__order_repo.add_order(new_order) return new_order
def order_create(): # create new order order_fields = order_schema.load(request.json) shipping_id = request.args["shipping_id"] shipping_id = OrderShipping.query.filter_by(id=shipping_id).first() new_order = Order() new_order.date_ordered = order_fields["date_ordered"] new_order.shipped = order_fields["shipped"] shipping_id.orders.append(new_order) db.session.commit() return jsonify(order_schema.dump(new_order))
def machine_post_order_completed(event_key): """ header Authorization: Token Authentication_machine_token """ if g.get('current_machine', None) is None: return json_error('No machine found might have been a user token', status=401) if g.current_machine.selected_order is None: return json_error('Machine has no order to finsih', 'Machine has no order to finish', 403) order = Order.find_by_id(g.current_machine.selected_order) if order is None: return json_error('Order not found', 'Order not found', 404) if order.machine_id is None: return json_error('Order does not have machine id, it should have one', 'Order does not have machine_id', 403) event = Event.find(event_key) if event is None: return json_error('Event not found', 'Event not found', 404) try: event.machine_finished_order(order) except Order_Process_Exception: return json_error( 'Order: ' + str(order._id) + ' was not found in the new_orders of event: ' + str(event._id), 'Order was not found in event new order', 404) g.current_machine.set_selected_order_done() order.set_done() return json_response(json.dumps(order.to_dict()), status=200)
def machine_get_order(event_key, order_key): """ header Authorization: Token Authentication_machine_token """ if g.get('current_machine', None) is None: return json_error('No machine found might have been a user token', status=401) if g.current_machine.selected_order is not None: return json_error('Machine has not finished its selected order', 'Machine not finished selected order', 403) order = Order.find(order_key) if order is None: return json_error('Order not found', 'Order not found', 404) if order.machine_id is not None: return json_error('Order already has an associated machine', 'Order already has an associated machine', 403) event = Event.find(event_key) if event is None: return json_error('Event not found', 'Event not found', 404) try: event.machine_get_order(order) except Order_Process_Exception: return json_error( 'Order: ' + str(order._id) + ' was not found in the new_orders of event: ' + str(event._id), 'Order was not found in event new order', 404) g.current_machine.set_selected_order(order) order.assigne_machine(g.current_machine._id) return json_response(json.dumps(order.to_dict()), status=200)
def get(self): user_info = self.session['index_user'].to_json() data = json.loads(self.get_argument('data')) trade_no = sec_pass(str(int(time.time()))) # 交易号 # 加入订单 save_data = { "TRADE_NO": trade_no, "UserID": user_info.get('UserID'), "OrderTotalPrice": data.get('totalprice'), "OrderPayType": 1, "OrderStatus": False, "OrderSendAddress": data.get('address') } try: product_list = [] for i, x in enumerate(data.get('all_data')): # 删除购物车信息 session.query(ShopCart).filter( ShopCart.ShopCartID == x['shopcartid']).delete() # 修改商品信息 session.query(Product).filter( Product.ProductID == x['productid']).update({ "ProductBuyNum": Product.ProductBuyNum + int(x['num']) }) product_list.append(str(x['productid'])) save_data['ProductID'] = ','.join(product_list) session.add(Order(**save_data)) session.commit() except Exception, e: session.rollback()
def test_condense3(self): orders = [ ("buy", "GMC", 2.5), ("buy", 'GMC', 3.0, 'limit', 0.0, 'day', 150.0), ] objs = [Order(*o) for o in orders] self.assertFalse(objs[0].condensable(objs[1]))
def test_condense2(self): orders = [ ("buy", "GMC", 2.5), ("sell", 'GMC', 3.0), ] objs = [Order(*o) for o in orders] self.assertTrue(objs[0].condensable(objs[1]))
def delete_product_order(): if (request.form['order_id'] and request.form['product_id']): order_p = OrderProduct() order_p.pedidos_id = request.form['order_id'] order_p.produtos_id = request.form['product_id'] ret = order_p.delete() if (request.form['from'] and request.form['from'] == 'add-page'): order = Order() order.id = request.form['order_id'] order.delete() return jsonify({'message': ret}) return jsonify({ 'message': 'O parâmetro ID do pedido e ID do produto são obrigatórios' })
def put(self, id): req_body = request.get_json() order = Order.get_by_id(id) order.fulfill(req_body.get("clientSecret")) notifyUser(order.chefId, f'User {order.userId} has sent you an order') return custom_json_response({"message": "order created"}, 201)
def delete_user(self, user_email): user = User.get_by_email(user_email) if user is not None and user.company == self.company: if Order.remove_user(user_email): Friends.remove_user(user_email) Schedule.remove_user(user_email) Database.remove('users', {'email': user_email}) return True return False
def index(): order = Order() user_id = request.args.get('user', None) client = Client() clients = client.getAll() if session.get('user_grupo', '') != 'user': if user_id: orders = order.getByUser(user_id) else: orders = order.getAll() else: orders = order.getByUser(session.get('user_id', '')) return render_template('order.html', orders=orders, clients=clients, user_id=user_id), 200
def delete(order_id): order = Order.get(id=order_id) if not order: abort(404) order.delete() db.commit() return '', 204
def order_create(storeId, customerID): order_fields = order_schema.load(request.json) new_order = Order() new_order.order_placed = order_fields["order_placed"] cart = order_fields["cart"] for item in cart: item_query = Product.query.filter_by(id=item).first() new_order.orders_products.append(item_query) db.session.commit() new_order.customer_id = customerID customer = Customer.query.filter_by(id=customerID).first() if not customer: return abort(400, description="Incorrect customer") customer.order.append(new_order) db.session.commit() return jsonify(order_schema.dump(new_order))
def show(order_id): # This will serialize our data schema = OrderSchema() # This gets a order by ID order = Order.get(id=order_id) # If we can't find a order, send a 404 response if not order: abort(404) # otherwise, send back the order data as JSON return schema.dumps(order)
def add(): title = 'Cadastrar Pedido' form = OrderForm() form.cliente.data = session.get('user_id', '') if request.form: form = OrderForm(request.form) if form.validate_on_submit(): if form.order_id.data: order = Order() ret = order.get(form.order_id.data) order.observacao = form.observacao.data order.clientes_id = form.cliente.data ret = order.update() flash(ret, 'info') return redirect(url_for('order.index')) else: flash('É necessário ao menos um produto para cadastrar um pedido.', 'danger') return render_template('order_form.html', form=form, title=title, mode='add', pageOrigin='add-page'), 200
def delete(id): order = Order() ret = order.get(id) if not order.id: flash(ret, 'info') return redirect(url_for('order.index')) if session.get('user_grupo', '') == 'user': if order.clientes_id != session.get('user_id', ''): flash('Você não tem permissão para acessar este recurso.', 'info') return redirect(url_for('order.index')) if request.method == 'POST': order_p = OrderProduct() order_p.deleteByPedido(id) ret = order.delete() flash(ret, 'info') return redirect(url_for('order.index')) title = 'Deseja realmente deletar o pedido ' + str(order.id) + '?' return render_template('order_delete.html', orderId=id, title=title), 200
def delete(id): client = Client() ret = client.get(id) if not client.id: flash(ret, 'info') return redirect(url_for('client.index')) order = Order() has = order.hasByUser(session.get('user_id')) if has: flash( 'O usuário não pode ser deletado pois existe algum pedido relacionado à ele.', 'info') return redirect(url_for('client.index')) if request.method == 'POST': ret = client.delete() flash(ret, 'info') return redirect(url_for('client.index')) title = 'Deseja realmente deletar o usuário ' + client.nome + '?' return render_template('client_delete.html', clientId=id, title=title), 200
async def createOrder(request): try: body = await request.json() except Exception: raise ClientException('No body, use {} if no filter option specified') body = validateCreateOrderBody(body) createInfo = Order.CreateInfo( address = body['address'], name = body['name'], surname = body['surname'], products = body['products'], shippingPrice = SHIPPING_PRICE, userId = request.user.id if request.user is not None else None ) orderId = await orderRepository.createOrder(createInfo) return web.json_response({ 'id': orderId })