def test_orders_inserts(self): self.test_users_inserts() i1 = Item(title='Acabaxi', description='A great abacaxi. Very big.', price=5, restaurant_id=1) i2 = Item(title='Banana', description='A great bannanana. Very big.', price=3, restaurant_id=1) db.session.add(i1) db.session.add(i2) o1 = Order() db.session.add(o1) db.session.flush() db.session.refresh(o1) db.session.refresh(i1) db.session.refresh(i2) o1.orderitems.append( OrderItem(order_id=o1.id, item_id=i1.id, quantity=2)) o1.orderitems.append( OrderItem(order_id=o1.id, item_id=i2.id, quantity=1)) db.session.commit() retrieved = Order.find_by_id(o1.id) self.assertEquals(retrieved.total_price(), 2 * i1.price + i2.price)
def sell_stock(self, quantity, brand): stock = Stock.query.filter(Stock.brand == brand).one_or_none() stock_infos = Stock.get_stock_infos_by_user_id(brand, self.id) if not stock_infos or (quantity > stock_infos.get('user_quantity')): return False else: Order.create_sell_order(quantity=quantity, user_id=self.id, stock_id=stock.id) self.funds += stock.price * quantity return True
def buy_stock(self, quantity, brand): stock = Stock.query.filter(Stock.brand == brand).one_or_none() if not stock or quantity < 0 or (stock.quantity < quantity or quantity * stock.price > self.funds): return False else: Order.create_buy_order(quantity=quantity, user_id=self.id, stock_id=stock.id) self.funds -= stock.price * quantity return True
def post(self): """ creates an order """ self.reqparse.add_argument('items', location='json', type=dict, action='append') data = self.reqparse.parse_args() try: order = Order() order.created_by = current_identity.id order.state = ORDER_PENDING rest = get_current_restaurant() order.restaurant_id = rest.id db.session.add(order) db.session.flush() for item in data['items']: order_item = OrderItem(order_id=order.id, item_id=int(item['id']), quantity=int(item['quantity'])) dbitem = Item.find_by_id(item['id']) if dbitem.restaurant_id != order.restaurant_id: raise IntegrityError db.session.add(order_item) db.session.commit() send_email('New Order on Pystro!', [mng.email for mng in rest.managers], 'Nice!') return order.serializable(), 201 except IntegrityError as e: db.session.rollback() return "Integrity error: " + str(e), 400
def patch(self): """ pays an order """ try: self.reqparse.add_argument('order_id', type=int, location='json') data = self.reqparse.parse_args() order = Order.find_by_id(data['id']) if order.state != ORDER_PENDING: return "Order is not pending", 203 order.state = ORDER_PAID db.session.add(order) db.session.commit() return order.serializable(), 200 except IntegrityError as e: db.session.rollback() return "Integrity error: " + str(e), 400
def get(self): return Order.find_by_restaurant_id(get_current_restaurant().id)