def create(request): body = json.loads(request.body.decode('utf-8')) print(body) order = Order( **{ 'trader_ip': body['ip'], 'order_id': body['order_id'], 'product_code': body['code'], 's_b': body['s_b'], 'price': body['price'], 'type': body['type'], 'status': 'created', 'amount': body['amount'], 'remain': body['amount'] }) # first: save to db order.save() # second: judge the type of the order if order.type == 'market': execute_market_order(order) elif order.type == 'limit': execute_limit_order(order) elif order.type == 'stop': execute_stop_order(order) elif order.type == 'cancel': execute_cancel_order(order) # third: return OK return HttpResponse(status=200)
def post(self, request): serializer = self.serializer(data=request.data) if not serializer.is_valid(): raise BadRequest(serializer.errors) quantity = serializer.validated_data.get('quantity') with transaction.atomic(): try: order = Order( customer_id=serializer.validated_data.get('customer_id')) order.save() order_detail = OrderDetail( quantity=quantity, product_id=serializer.validated_data.get('product_id'), order_id=order.id) order_detail.save() invoice = Invoice(order_id=order.id, amount=(quantity * order_detail.product.price)) invoice.save() except Exception as ex: raise BadRequest(ex) return Response(data={ "status": "SUCCESS", "invoice_number": invoice.id })
def create(request): body = json.loads(request.body.decode('utf-8')) print(body) order = Order(**{ 'trader_ip': body['ip'], 'order_id': body['order_id'], 'product_code': body['code'], 's_b': body['s_b'], 'price': body['price'], 'type': body['type'], 'status': 'created', 'amount': body['amount'], 'remain': body['amount'] }) # first: save to db order.save() # second: judge the type of the order if order.type == 'market': execute_market_order(order) elif order.type == 'limit': execute_limit_order(order) elif order.type == 'stop': execute_stop_order(order) elif order.type == 'cancel': execute_cancel_order(order) # third: return OK return HttpResponse(status=200)
def create(self, validated_data): order_data = copy.deepcopy(validated_data) del order_data['items'] item_list_data = validated_data['items'] order = Order(**order_data) order.save() for item_data in item_list_data: order_item = OrderItem(**item_data) order_item.order = order order_item.save() return order
def post_order(request): key = request.GET.get('key') menus = request.GET.get('menus') prices = request.GET.get('prices') counts = request.GET.get('counts') order = Order(key=key, menus=menus, prices=prices, counts=counts) order.save() t = Timer(random.uniform(10.0, 20.0), change_status_order, [order]) t.start() return HttpResponse(serializers.serialize('json', [ order, ]), content_type='application/json')
def post(self, request): restaurant = Restaurant.objects.get(pk=request.data['restaurantId']) ordered_extras = [] order = Order(user=request.user, restaurant=restaurant, order_cost=request.data['orderCost'], delivery_address=request.data['deliveryAddress']) order.save() for dish in request.data['orderedItems']: ordered_dish = Dish.objects.get(pk=dish['dishId']) ordered_dish_instance = OrderedDish(dish=ordered_dish, order=order) ordered_dish_instance.save() ordered_extras.extend(list(map(lambda x, d=ordered_dish_instance: OrderedExtra( extra=Extra.objects.get(pk=x), dish=d), dish['orderedExtras']))) OrderedExtra.objects.bulk_create(ordered_extras) serializer = OrderSerializer(order) return Response(serializer.data)
def create(self, validated_data): data = validated_data.get('data') if not data: raise ValidationError({'validation_error': 'empty request'}) orders = [Order(**item) for item in data] return Order.objects.bulk_create(orders)
def route_order_create(buyer_id, seller_id, line_items): order = Order(buyer_id=buyer_id, seller_id=seller_id, line_items=[]) total = 0 for li in line_items: product = Product.query.filter(Product.id == li['product_id']).first() total += li['quantity'] * product.price item = LineItem(product=product, order=order, quantity=li['quantity'], unit_price=li['quantity'] * product.price) order.line_items.append(item) order.total = total db.session.add(order) db.session.commit() db.session.refresh(order) return order
def payment_result(params): calculated_signature = get_signature(params) existing_signature = params["signature"] # allow testing only if enabled globally testing = params["testing"] == "1" and __testing_mode if testing or existing_signature == calculated_signature: try: form = ModulTxnForm(params) if form.errors: logging.error( f"Modulbank Txn couldn't be validated: {form.errors.as_data()}" ) return 500 else: # save txn (should it be one txn with set_paid?) txn: ModulTxn = form.save() # then pay an order order = Order.set_paid_by(txn) # if everything was fine - send application send_application(order) return 200 except Exception as e: logging.error(e, exc_info=True) return 500 else: logging.warning( f"Incorrect signature value: Expected {calculated_signature} but got {existing_signature}" ) return 401
def post(self, request, pk='r'): rest_id = request.session['id'] customer_lat = request.data['lat'] customer_long = request.data['long'] order_price = request.data['price'] driver_id = find_driver(rest_id) order_obj = Order( restaurant_id=rest_id, driver_id=driver_id, customer_lat=customer_lat, customer_long=customer_long, order_price=order_price, status='S1', ) order_obj.save() return Response(None, status=200)
def get_order_history(request): user = request.auth.user customer = Customer.objects.get(id=user.id) if customer.basket_free: basket_list = BasketListModel.objects.filter( user=customer).order_by('basket_group_id') orders = [] for basket_group in basket_list: basket_products = Basket.objects.filter( basket_group_id=basket_group.basket_group_id, user=customer) total_price = 0 products = [] for basket in basket_products: products.append(basket.product) total_price += basket.product.price * basket.quantity order = Order(products=products, basket_group=basket_group, total_price=total_price) orders.append(order) serializer = OrderSerializer(orders, many=True) return Response(serializer.data) else: basket_list = BasketListModel.objects.filter( user=customer).order_by('basket_group_id') basket_group_it = basket_list[len(basket_list) - 2].basket_group_id basket_group = basket_list[len(basket_list) - 2] orders = [] for it in range(1, basket_group_it + 1): basket_products = Basket.objects.filter(basket_group_id=it, user=customer) total_price = 0 products = [] for basket in basket_products: products.append(basket.product) total_price += basket.product.price * basket.quantity order = Order(products=products, basket_group=basket_group, total_price=total_price) orders.append(order) serializer = OrderSerializer(orders, many=True) return Response(serializer.data)
def add_order(): email = request.json["mail"] order_items = request.json["items"] user_id = request.json["user"] new_order = Order(email, datetime.datetime.now()) if user_id: new_order.user = user_id db.session.add(new_order) db.session.commit() for item in order_items: instance = OrderItem(item["id"], new_order.id, item["quantity"]) db.session.add(instance) db.session.commit() return order_schema.dump(new_order)
def add_product(request, customer_id): # get current cart from cache if current cart does not exist, make a new one jsonObj = json.loads(request.body) product_id = jsonObj['product_id'] quantity = jsonObj['quantity'] product = Product.objects.filter(id=product_id)[0] if quantity > product.inventory: data = { "error": "not enough inventory"} else: orderList = Order.objects.filter(customer_id=customer_id, status=0) if orderList: cart = orderList[0] else: current_customer = Customer.objects.filter(id=customer_id)[0] cart = Order(status=0, customer_id=current_customer) # check request object for item cart.total_cost = cart.total_cost + (product.unit_cost * quantity) cart.save() order_detail = OrderDetail(order_id=cart, product_id=product, quantity=quantity) order_detail.save() data = serializers.serialize("json", [order_detail,]) return JsonResponse(data, safe=False)
def order(self, request, pk=None): """Permet de créer une commande. Il faut envoyer un dictionaire dont la valeur "billets" correspondt à un tableau contenat les billest """ clean_old_orders.delay() # On récupère l'évenement en s'assurant au passage que l'utilisateur a le droit d'y accéder event = Event.for_user(request.user).get(id=pk) # On récupère le client lié à l'user client = request.user.client # On récupère la commande en cours si il en existe une, sinon on la crée order = client.orders.filter(event=event, status__lt=Order.STATUS_PAYMENT, created_at__gt=timezone.now() - timedelta(minutes=20)).first() or \ Order(event=event, client=client, status=Order.STATUS_SELECT_PRODUCT) order.save() if request.method == 'GET': return Response(OrderSerializer(order).data) # On place le status en sélection de produit order.status = order.STATUS_SELECT_PRODUCT order.save() order.billets.all().delete() # Si il y a un champ billets dans les données renvoyées if "billets" in request.data: # Pour chaque billet dans l'array de billets for billet in request.data['billets']: # Si le billet est update if "id" not in billet: billet_data = BilletSerializer(data=billet, context={"order": order.id}) if billet_data.is_valid(): billet_data.validated_data['order'] = order billet = billet_data.create(billet_data.validated_data) billet.save() ok = order.is_valid() # Si la commande ne répond pas aux règles if not ok: order.destroy_all() return Response("NIQUE TA MERE ESSAYE PAS DE GRUGER", status=400) order.status = order.STATUS_SELECT_PARTICIPANT order.save() return Response(OrderSerializer(order).data)
def create(self, client, order): if not client: name = None if self.data.source == 'facebook': facebook_user = FacebookService.get_user_info( self.data.sender_id) if facebook_user['first_name'] and facebook_user['last_name']: name = facebook_user['first_name'] + " " + facebook_user[ 'last_name'] client = Client(token=self.data.sender_id, source=self.data.source, name=name) client.save() if order: # TODO ask to client if he wants to clear items pass else: order = Order(client=client) order.save() return None
def post(): order_data = request.json result = OrderDao().load(order_data) if result.errors: return result.errors, 400 order = Order.create(customer_name=result.data['customer_name'], customer_email=result.data['customer_email']) comment_list = [] for comment in result.data['comments']: comment_list.append(Comment(text=comment, order_id=order.id)) Comment.bulk_create(comment_list) return order_data, 200
def make_purchase(order_id: str): order, order_items = Order.get_with_items(order_id) @dataclass(init=True) class ModulReceiptItem: name: str quantity: int price: int sno: str = "usn_income" payment_object: str = "service" payment_method: str = "advance" vat: str = "none" def to_receipt_item(oi: OrderItem): return ModulReceiptItem(str(oi), oi.quantity, oi.price) def randomStr(size: int): ''.join(random.choice(string.ascii_letters) for x in range(size)) receipt_items = map(lambda oi: dataclasses.asdict(to_receipt_item(oi)), order_items) txn_params = { "salt": randomStr(32), "merchant": settings.PAYMENT_MERCHANT_ID, "receipt_contact": '*****@*****.**', "testing": 1 if __testing_mode else 0, "order_id": order.id, "receipt_items": json.dumps(list(receipt_items)), "amount": order.amount, "client_phone": order.phone, "client_email": order.email, "callback_url": "{}/api/payment_result".format(__host), "description": "Заказ №{}".format(order.id), "unix_timestamp": int(time()), "success_url": "{}/success-page?pg_order_id={}".format(__host, order.id) } # make signature afterwards signature = get_signature(txn_params) txn_params["signature"] = signature resp = requests.post(__api_url, data=txn_params, allow_redirects=False) return resp
def get_queryset(self): base = Billet.objects.filter( order__event__organizer__membership__user=self.request.user) | Billet.objects.filter( order__event__membership__user=self.request.user) if 'status' in self.request.GET: status = self.request.GET.get('status', '') base = base.filter(order__in=Order.accountable_orders(), canceled=False) if status == 'accountable': pass elif status == 'validated': base = base.filter(order__in=Order.objects.filter(status=Order.STATUS_VALIDATED)) if 'event' in self.request.GET: event = self.request.GET.get('event', '') event = self.allowed_events().get(id=event) base = base.filter(order__event=event) if 'products' in self.request.GET: products = self.products_for_order() base = base.filter(product__in=products) return base
def newOrder(): values = request.json neworder = Order(OrderTypeID= values["OrderTypeID"], OrderDate= values["OrderDate"], State= values["State"], PayState= values["PayState"], TotalQuantity= values["TotalQuantity"], EstimatedTime= 20, Notes= values["Notes"], SubTotal= values["SubTotal"], Discount= values["Discount"], Tax= values["Tax"], Total= values["Total"], ClientName= values["ClientName"]) db.session.add(neworder) db.session.commit() cart = values["Cart"] print(cart) for i in cart: neworderdetail = OrderDetail(OrderID= neworder.OrderID, ProductID= i["ProductID"], Quantity= i["Quantity"], SubTotal= i["SubTotal"], Discount=i["Discount"], Tax= i["Tax"], Total= i["Total"]) db.session.add(neworderdetail) db.session.commit() response_body = { "status": "OK", "NewOrderID": neworder.OrderID } status_code = 200 return jsonify(response_body),200
def get_queryset(self): base = Answer.objects.filter(question__in=Question.objects.filter( Q(option__event__organizer__membership__user=self.request.user) | Q(product__event__organizer__membership__user=self.request.user) | Q(option__event__membership__user=self.request.user) | Q(product__event__membership__user=self.request.user))) if 'question' in self.request.GET: question = self.request.GET.get('question', '') base = base.filter(question=question) if 'status' in self.request.GET: status = self.request.GET.get('status', '') if status == 'accountable': base = base.filter(order__in=Order.accountable_orders()) elif status == 'validated': base = base.filter(order__status=Order.STATUS_VALIDATED) elif status == 'any': base = base else: if self.action == 'list': base = base.filter(order__status=Order.STATUS_VALIDATED) return base
def get_queryset(self): base = Order.objects.filter( event__organizer__membership__user=self.request.user) | Order.objects.filter( event__membership__user=self.request.user) if 'status' in self.request.GET: status = self.request.GET.get('status', '') if status == 'accountable': base = base.filter(id__in=Order.accountable_orders()) elif status == 'validated': base = base.filter(status=Order.STATUS_VALIDATED) elif status == 'any': base = base else: if self.action == 'list': base = base.filter(status=Order.STATUS_VALIDATED) if 'search' in self.request.GET: search = self.request.GET.get('search', '').split(' ') for word in search: base = base.filter(Q(client__first_name__icontains=word) | Q(client__last_name__icontains=word) | Q(client__email__icontains=word) | Q(transaction__mercanet__transactionReference=word)) base = base.order_by('created_at').reverse() return base
def insert_user_order(request): if request.method == 'POST': try: token = request.headers.get('token') token = Token.objects.filter(token=token) if token.exists(): user = token[0].user info = loads(request.body.decode('utf-8')) time = info['datetime'] if not RestaurantInfo.objects.first().open: return my_response( False, 'The restaurant is closed, Please try later', {}) if not check_allow_record_order(time): return my_response( False, 'Maximum order is recorded for the restaurant time period, Please try again in a few minutes', {}) total_price = info['totalPrice'] description = info['description'] address = info['addressId'] del_time = info['deliveryTime'] order_type = info['orderType'] ser_charge = info['serviceCharge'] delivery_cost = info['deliveryCost'] pay_type = info['paymentType'] tr_id = random.randint(100000, 100000000) order = Order( user=user, track_id=str(tr_id), datetime=time, total_price=total_price, description=description, address_id=address, delivery_time=del_time, order_type=order_type, service_charge=ser_charge, delivery_cost=delivery_cost, payment_type=pay_type, ) order.save() foods = info['foods'] for f in foods: of = OrderFood(food_size_id=f['foodSizeId'], order=order, number=f['number']) of.save() ts = f['types'] for t in ts: OrderType(order_food=of, food_type_id=t).save() food_options = f['foodOptions'] for op_size_id in food_options: OrderOption(order_food=of, option_size_id=op_size_id).save() options = info['options'] for o in options: of = OrderFood(food_size_id=o['optionSizeId'], order=order, number=o['number']) of.save() notif_to_admin(orderId=order.order_id, title='order', message='you have a order with trackId: ' + str(order.track_id)) return my_response(True, 'success', order.to_json()) else: return my_response(False, 'invalid token', {}) except Exception as e: return my_response( False, 'error in insert order, check body send, ' + str(e), {}) else: return my_response(False, 'invalid method', {})
def clean_old_orders(): deleted, _ = Order.objects.exclude( id__in=Order.accountable_orders()).delete() return deleted
def get_AllOrders(): return jsonify(Order.getAllOrders()), 200
def create_order(request): user_id = request.query_params.get("user_id") if user_id == None: user_id = uuid.uuid4() response = requests.get( "http://basket-web:8004/basket/createOrder/?user_id=%d" % int(user_id)).json() # response = requests.get("http://127.0.0.1:8002/basket/createOrder/?user_id=%d" % int(user_id)).json() queryBefore = Order.objects.all().count() order = Order() order.user_id = user_id order.total_amount = 0 order.save() queryset = Order.objects.filter(user_id=user_id).order_by('-order_id') order_serializer = OrderSerializer(queryset, many=True) prices = 0.0 for i in range(len(response)): order_item = OrderItem() order_item.order_id = Order.objects.filter( order_id=order_serializer.data[0]['order_id']).first() order_item.catalog_item_id = response[i]['catalog_item_id'] order_item.quantity = response[i]["quantity"] order_item.price = requests.get( "http://catalog-web:8002/product/basket/?prod_id=%d" % order_item.catalog_item_id).json()[0]['price'] # order_item.price = requests.get("http://127.0.0.1:8003/product/basket/?prod_id=%d" % order_item.catalog_item_id).json()[0]['price'] print(order_item.price) prices += (order_item.price * order_item.quantity) order_item.save() order = Order.objects.filter(order_id=order_serializer.data[0]['order_id']) order.update(total_amount=prices) print(order.first().total_amount) order.first().save() queryAfter = Order.objects.all().count() if (queryAfter == queryBefore + 1): return Response({'success': True}, status=200) else: return Response({'success': False}, status=200)