async def add_review(id: str, review: ReviewModel = Body(..., embed=True), identity: str = Depends(get_jwt_identity)): try: if Order.objects(orderer=identity, products__product=id, orderStatus__nin=['not placed', 'failed']).count() == 0: raise UnauthorizedError product = Product.objects.get(id=id) review = Review(reviewer=identity, product=id, score=review.score, review=review.review) review.save() product.addReview(review.score) product.save() return review.serialize() except UnauthorizedError: raise UnauthorizedError( detail='User has not purchased this product').http_exception except DoesNotExist: raise SchemaValidationError().http_exception except Exception as e: raise e
async def get_reviews( id: str, page: Optional[int] = None, size: Optional[int] = None, identity: Optional[str] = Depends(get_jwt_identity_optional)): try: reviews = Review.objects(product=id) if page == None: page = 0 size = reviews.count() elif size == None: raise SchemaValidationError allowed = False if identity: allowed = Order.objects(orderer=identity, products__product=id, orderStatus__nin=['not placed', 'failed' ]).count() > 0 return { 'count': reviews.count(), 'reviews': list( map(lambda r: r.serialize(), reviews[page * size:page * size + size])), 'allowed': allowed } except SchemaValidationError: raise SchemaValidationError().http_exception except Exception as e: raise e
async def create_order( order_body: OrderModel, identity: Optional[str] = Depends(get_jwt_identity_optional)): try: products = [] for p in order_body.items: product: Product = Product.objects.get(id=p.id) products.append( CartItem(product=product, qty=p.qty, price=product.price)) order = Order(orderer=identity, orderStatus='not placed', gateway=order_body.gateway, products=products) order.save() return str(order.id) except DoesNotExist: raise SchemaValidationError().http_exception except Exception as e: raise e
def create_order(data): account_id = data.get('account') account = Account.query.filter(Account.email == account_id).one() payment_type = data.get('payment_method') shipping_type = data.get('shipping_method') order = Order(payment_type, shipping_type, account) db.session.add(order) total_price = 0 book_list = data.get('books') for book_entry in book_list: book_id = book_entry['book']['id'] book = Book.query.filter(Book.id == book_id).one() book_order = BookOrder(order, book, book_entry['quantity']) db.session.add(book_order) total_price += book.price * book_entry['quantity'] delete_cart_entry(account_id, book_id) order.price = total_price db.session.commit()
def create_order(self, side, recvWindow, quantity, price=0.): quantity = float(quantity) new_order = api.createOrder( symbol=self.pair, recvWindow=recvWindow, side=side, type='MARKET', quantity="{quantity:0.{precision}f}".format( quantity=quantity, precision=self.get_limit()['baseAssetPrecision']), newOrderRespType='FULL') if 'orderId' in new_order: if side.lower() == 'buy': self.order_id = new_order['orderId'] logger(description= f"Создан ордер на покупку id:{new_order['orderId']} \ price: {price},quantity: {quantity}", log_type='info') order = Order(order_type='buy', pair=self.pair, buy_order_id=new_order['orderId'], buy_amount=quantity, buy_price=price) session.add(order) session.commit() self.update_rate(method='buy') elif side.lower() == 'sell': logger( description=f"Создан ордер на продажу по рынку {new_order}", log_type='info', ) session.query(Order).filter_by( buy_order_id=self.order_id).update({ 'order_type': side.lower(), 'sell_finished': datetime.datetime.utcnow(), 'sell_created': datetime.datetime.utcnow(), 'sell_order_id': new_order['orderId'], 'sell_amount': quantity, 'sell_price': price }) session.commit() self.update_rate(method='sell') else: raise Exception('error order doesn\'t create') return new_order
def results(): # build a request object req = request.get_json(force=True) session = str(req.get('session')).split('/')[-1] order_session = Order(session=session) if Order.objects(session=session) is None: order_session.save() # fetch action from json action = req.get('queryResult').get('action') parameters = req.get('queryResult').get('parameters') if action == 'getting.started': return {'fulfillmentText': 'webhook works'} elif action == 'delivery.product.add' or action == 'delivery.search' or action == 'delivery.order.add': reply = add_products(parameters, session) elif action == 'delivery.product.remove': reply = delete_products(parameters, session) elif action == 'delivery.product.swap': reply = update_products(parameters, session) elif action == 'delivery.order.check': reply = check_order() return reply
async def get_orders(page: Optional[int] = None, size: Optional[int] = None, identity: str = Depends(get_jwt_identity)): try: orders = Order.objects(orderer=identity) total = orders.count() if page == None: page = 0 size = total elif size == None: raise SchemaValidationError orders = orders[page * size:page * size + size] return { 'total': total, 'orders': list(map(lambda o: o.serialize(), orders)) } except SchemaValidationError: raise SchemaValidationError().http_exception except Exception as e: raise e
def submit_order_by_shopcart(token_type,user_info): result={'code':1,'msg':'ok'} try: data=request.get_json() pay_type=data.get('pay_type',0)#0货到付款 1在线支付 use_coupons=data.get('use_coupons',None) get_coupons=data.get('get_coupons',None) buyerAddress=BuyerAddress.query.filter_by(buyer_id=user_info.buyer_id,is_default='1').first() rv=[] if not buyerAddress: raise Exception('user dont have default address') carGrouptList=getOrderCartList(user_info.buyer_id, buyerAddress.address_id) communityId=buyerAddress.community_id community= Community.query.filter_by(community_id=communityId).first() detailAddress='' if community: detailAddress=community.community_name+" "+buyerAddress.detail_address else: detailAddress=buyerAddress.detail_address for order_info in carGrouptList: order=Order() order.order_no=build_order_no() order.shop_id=order_info['shop_id'] order.buyer_id=user_info.buyer_id order.sale_money=order_info['sum_the_shop'] order.freight=order_info['freight'] order.submit_time=datetime.now().strftime('%Y-%m-%d %H:%M:%S') order.address_id=buyerAddress.address_id order.send_address=detailAddress order.receiver=buyerAddress.consignee order.phone=buyerAddress.phone order.remark=data.get('remark','') order.status='0' #已提交 order.pay_type=pay_type get_coupon_money=0 if use_coupons: for use_coupon in use_coupons: if int(use_coupon['shop_id'])==int(order.shop_id): sql='''insert into tb_coupon (CouponType,ShopID,BuyerID,OrderNO,CouponMoney) values(%s,%s,%s,%s,%s)''' db.engine.execute(sql,('1',order.shop_id,user_info.buyer_id,order.order_no,use_coupon['coupon_money'])) order.use_coupon=use_coupon['coupon_money'] if get_coupons: for get_coupon in get_coupons: if int(get_coupon['shop_id']==int(order.shop_id)): get_coupon_money=get_coupon['coupon_money'] order.get_coupon=get_coupon_money if not order.use_coupon: order.use_coupon=0 order.sale_money=float(order.sale_money)-float(order.use_coupon) db.session.add(order) goods_list=getGoodsList(order.shop_id,order.buyer_id) for goods_info in goods_list: purchase=Purchase.query.filter_by(goods_id=goods_info['goods_id']).order_by(Purchase.batch_no).first() quantity=goods_info['quantity'] if purchase: purchase.quantity-=quantity db.session.commit() order_detail=OrderDetail() order_detail.order_no=order.order_no order_detail.goods_id=goods_info['goods_id'] if purchase: order_detail.batch_no=purchase.batch_no order_detail.sale_price=goods_info['sale_price'] order_detail.quantity=quantity order_detail.discount_price=goods_info['discount_price'] db.session.add(order_detail) r_map={} r_map['order_no']=order.order_no r_map['shop_id']=order.shop_id r_map['sale_money']=str(order.sale_money) r_map['use_coupon']=str(order.use_coupon) r_map['get_coupon']=str(order.get_coupon) r_map['freight']=str(order.freight) r_map['has_alipay']=order_info['has_alipay'] r_map['has_online_bank']=order_info['has_online_bank'] rv.append(r_map) message=Message() message.sender_type='3' message.sender_name='系统消息' message.receiver_type='1' #商铺 message.receiver=order_info['shop_id'] message.receiver_name=order_info['shop_name'] message.send_title=r'您有一个新订单:'+order.order_no message.send_content=r'''您有一个新的订单:<a style='text-decoration:underline' href='index.php/Display/OrderDetailPage?OrderNo=".$OrderNo."'>".$OrderNo."</a><br/><div class='date'>点击订单编号查看详细信息!</div> ''' message.send_time=datetime.now() db.session.add(message) db.session.commit() send_email_2_shop(order.shop_id, order.order_no) #删除购物车 delete_cart_sql=''' delete from tb_shoppingcart where BuyerID=%s and IsSelected='1' ''' db.engine.execute(delete_cart_sql,(user_info.buyer_id)) db.session.commit() result['orders']=rv except Exception,e: current_app.logger.exception(e) result['code']=0 result['msg']=e.message
def submit_order(result,user): data=request.get_json() payback_id=int(data['payback_id']) payback=Payback.query.get(payback_id) project_id=int(data['project_id']) amount=int(data['amount']) project=Project.query.get(project_id) delivery_money=data.get('delivery_money',0) address_id=data['address_id'] if project and payback: try: #自动开启事务 order=Order() order.order_no=build_order_no() order.payback_id=payback_id order.buyer_id=int(user.id) order.delivery_money=delivery_money order.status=Order.STATUS_SUBMIT order.total_money=payback.money*amount+delivery_money order.payback_money=payback.money order.address_id=address_id order.amount=amount order.project_id=payback.project_id order.publisher_id=payback.project.publisher_id db.session.add(order) db.session.commit() print order.id order=Order.query.get(order.id) result['order']=order.as_map2() except Exception as e: current_app.logger.exception(e) result['msg']=e.message db.session.rollback()