コード例 #1
0
    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
        })
コード例 #2
0
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)
コード例 #3
0
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)
コード例 #4
0
 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
コード例 #5
0
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')
コード例 #6
0
 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)
コード例 #7
0
 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)
コード例 #8
0
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)
コード例 #9
0
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)
コード例 #10
0
    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
コード例 #11
0
ファイル: views.py プロジェクト: HosseinGEEK/Pizza
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', {})