Exemplo n.º 1
0
 def post(self, request):
     serializer = OrderSerializer(data=request.data,
                                  context={'request': request})
     serializer.is_valid(raise_exception=True)
     order = serializer.save()
     return Response({
         'msg': '提交成功',
         'order_id': order.id
     },
                     status=status.HTTP_200_OK)
Exemplo n.º 2
0
 def create(self, request, **kwargs):
     data = request.data
     table_key = data.get('table')
     queryset = Order.objects.filter(table=table_key,
                                     status='In progress').first()
     if queryset is not None:
         return Response(status=status.HTTP_400_BAD_REQUEST)
     serializer = OrderSerializer(data=data)
     serializer.is_valid(raise_exception=True)
     serializer.save()
     return Response(serializer.data, status=status.HTTP_201_CREATED)
Exemplo n.º 3
0
    def partial_update(self, request, pk=None, **kwargs):
        order = self.__get_active_order(pk)

        if order is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        serializer = OrderSerializer(instance=order,
                                     data=request.data,
                                     partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(status=status.HTTP_200_OK)
Exemplo n.º 4
0
def execute_payment(request):
    result = CaptureOrder().capture_order(request.data['order_id'])
    # get shopping cart & scp
    shopping_cart = ShoppingCart.objects.get(
        pk=uuid.UUID(request.data['shopping_cart_id']))
    shopping_cart_products = shopping_cart.shopping_cart_products.all().values(
        'product', 'message', 'return_address', 'recipient_address', 'color',
        'font')
    scp = list(shopping_cart_products)
    email = request.data['email']
    if not email:
        return Response(data="A valid email address is required.",
                        status=status.HTTP_400_BAD_REQUEST)
    # create order with sc data
    order = OrderSerializer(data={'email': email, 'order_products_set': scp})
    order.is_valid(raise_exception=True)
    order.save()

    shopping_cart.delete()
    del request.session['cart_id']

    request.session['order_id'] = order.data['id']

    total = decimal.Decimal(
        order.data['stamp_cost']) + order.data['total_price']['price__sum']
    receipt_message = loader.render_to_string('orders/order.html', {
        "order": order.data,
        "total": total
    })
    send_mail('Your Thin Gifts Order',
              'Thank you for your recent order.',
              '*****@*****.**', [email, '*****@*****.**'],
              html_message=receipt_message,
              fail_silently=False)

    print_message = loader.render_to_string('orders/print-info.html', {
        "order": order.data,
        "total": total
    })

    send_mail('Print Details for Order',
              'Print Details for Order',
              '*****@*****.**',
              ['*****@*****.**', '*****@*****.**'],
              html_message=print_message,
              fail_silently=False)

    return Response(order.data)
def ConfirmOrder(request, format=None):

    if request.method == 'GET':

        try:
            order = orderMaster.objects.all()

        except product.DoesNotExist:
            raise Response(status=404)

        serializer = OrderSerializer(order, many=True)

        return Response(serializer.data)

    if request.method == 'POST':

        try:
            cart = cartItem.objects.filter(user=request.user)

        except product.DoesNotExist:
            raise Response(status=404)

        serializer = OrderSerializer(data=request.data, partial=True)
        if serializer.is_valid():
            data = {}
            master = serializer.save(user=request.user)
            data['success'] = True
            data['masterID'] = master.id
            return Response(data)
        return Response(status=400)
def ChangeStatus(request, orderID, format=None):

    if request.method == 'PATCH':

        try:
            master = orderMaster.objects.get(id=orderID)
        except product.DoesNotExist:
            raise Response(status=404)
        print(master)
        print(request.data)
        # master.status = x
        # master.save()
        # return JsonResponse(
        #     {
        #         'success':True
        #     }
        # )
        serializer = OrderSerializer(master, data=request.data, partial=True)

        if serializer.is_valid():

            data = {}
            #print(serializer.status )
            b = serializer.save()
            # b = serializer.update(master, request.data)

            print(b)
            data['success'] = True
            #data['data'] = b
            return Response(data)
        return Response(status=400)
Exemplo n.º 7
0
Arquivo: views.py Projeto: jtuz/parrot
    def post(self, request, format=None):
        serializer = OrderSerializer(data=request)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 8
0
    def create(self, request, *args, **kwargs):
        if "items" in request.data:
            buffer = get_lines_items(request.data["items"])
            request.data["items"] = []

        else:
            return Response({"error": "empty orders"})
        _o = OrderSerializer(data=request.data)

        if _o.is_valid():
            order = _o.save()
            order.items.add(*buffer)
            if not self.make_payment(order):
                order.delete()
                return Response({
                    "success": False,
                    "message": "Not enough Balance"
                })
            goods = []
            for item in order.items.all():
                if item.product.require_manual_activation:
                    print(f"ORDER {order.id} STATUS Require manual activation")
                    order.status = 1
                    _o = OrderSerializer(order)
                    headers = self.get_success_headers(_o.data)
                    return Response(_o.data,
                                    status=status.HTTP_201_CREATED,
                                    headers=headers)

                gds = Good.objects.filter(
                    product=item.product,
                    status="UNUSED").all()[:item.quantity]

                if not gds:

                    if gds.count() == 0:
                        print("product not in stock")
                    else:
                        print("there is not enough goods")

                    order.status = 0
                    order.save()
                    _o = OrderSerializer(order)
                    headers = self.get_success_headers(_o.data)
                    return Response(_o.data,
                                    status=status.HTTP_201_CREATED,
                                    headers=headers)
                for good in gds:
                    good.status = "SENT"
                    good.save()
                    goods.append(good.id)
            order.goods.set(goods)
            order.status = 2
            order.save()
            _o = OrderSerializer(order)
            headers = self.get_success_headers(_o.data)
            return Response(_o.data,
                            status=status.HTTP_201_CREATED,
                            headers=headers)
        return Response(_o.errors)
Exemplo n.º 9
0
 def post(self, request, format=None):
     pk = request.data['id']
     order = self.get_order(pk)
     serializer = OrderSerializer(order, data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 10
0
    def post(request):
        """Create new order for an account"""
        try:
            account_name = request.query_params.get('account')
            account = _get_account_(account_name)
        except AccountNotFound as err:
            return Response(
                data={'error': str(err)},
                status=status.HTTP_404_NOT_FOUND,
            )

        client = bitmex(
            test=BITMEX_TEST_MODE,
            api_key=account.api_key,
            api_secret=account.api_secret,
        )
        try:
            # FIXME: it always raises error:
            #  "Account has insufficient Available Balance"
            result, _ = client.Order.Order_new(
                symbol=request.data['symbol'],
                orderQty=request.data['volume'],
                side=request.data['side'],
                ordType='Market',
            ).result()
        except HTTPUnauthorized as err:
            return Response(
                data={'error': str(err)},
                status=status.HTTP_401_UNAUTHORIZED,
            )
        except HTTPNotFound as err:
            return Response(
                data={'error': str(err)},
                status=status.HTTP_404_NOT_FOUND,
            )
        except HTTPBadRequest as err:
            return Response(
                data={'error': str(err)},
                status=status.HTTP_400_BAD_REQUEST,
            )
        except KeyError as err:
            return Response(
                data={'error': f'Missed mandatory field {err}'},
                status=status.HTTP_400_BAD_REQUEST,
            )

        serializer = OrderSerializer(
            data={
                **request.data,
                'order_id': result.get('orderID'),
                'price': result.get('price'),
                'account': account.id,
            }
        )
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 11
0
 def create(self, request):
     serializer = OrderSerializer(data=request.data,
                                  context={'request': request})
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     else:
         return Response(serializer.errors,
                         status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 12
0
def orders_api(request):
    if request.method == 'GET':
        orders = Order.objects.all()
        serializer = OrderSerializer(orders, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = OrderSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 13
0
 def update(self, request, pk):
     order = get_object_or_404(Order, id=pk)
     if order.status == 'created':
         serializer = OrderSerializer(order, data=request.data)
         if serializer.is_valid():
             serializer.save()
             return Response(serializer.data, status=status.HTTP_200_OK)
     else:
         message = 'Вы не можете редактировать заказ в обработке/доставленный заказ/отмененный заказ'
         return Response({"data": f"{message}"},
                         status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 14
0
 def post(self, request, *args, **kwargs):
     try:
         data = JSONParser().parse(request)
         print(data, type(data))
         data['customer'] = request.user.id
         serializer = OrderSerializer(data=data)
         if serializer.is_valid():
             serializer.save()
         else:
             return Response({'status': 'error', 'message': serializer.errors}, status=400)
         return Response({'status': 'success', 'data': serializer.data}, status=200)
     except Exception as e:
         return Response({'status': 'error', 'errors': str(e)}, status=400)
Exemplo n.º 15
0
def PostOrders(request):
    # GET list of products, POST a new product, DELETE all products
    if request.method == 'GET':
        orders = BaseOrder.objects.all()
        orders_serializer = OrderSerializer(orders, many=True)
        return JsonResponse(orders_serializer.data, safe=False)
        # 'safe=False' for objects serialization

    if request.method == 'POST':
        orders_data = JSONParser().parse(request)
        orders_serializer = OrderSerializer(data=orders_data)
        if orders_serializer.is_valid():
            orders_serializer.save()
            return JsonResponse(orders_serializer.data,
                                status=status.HTTP_201_CREATED)
        return JsonResponse(orders_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 16
0
def update_orders(request, id, *args, **kwargs):
    try:
        order = request.user.orders.get(id=id)
    except ObjectDoesNotExist:
        return Response({'errors': {
            'order': ['Does not exist.']
        }},
                        status=status.HTTP_400_BAD_REQUEST)
    ser = OrderSerializer(order,
                          data=request.data,
                          context={
                              'request': request,
                          })
    if ser.is_valid():
        updated_order = ser.save()
        return Response(ser.data, status=status.HTTP_200_OK)
    return Response(
        {"errors": ser.errors},
        status=status.HTTP_400_BAD_REQUEST,
    )
Exemplo n.º 17
0
 def post(self, request, *args, **kwargs):
     cart = Cart(request.session)
     serializer = OrderSerializer(data=request.data)
     if serializer.is_valid():
         order = serializer.save()
         for item in cart.items:
             instance = OrderItem(
                 order=order,
                 product=item.product,
                 price=item.price,
                 quantity=item.quantity
             )
             instance.save()
         cart.clear()
         UserOrderNotification.apply_async((order.pk,), countdown=10)
         AdminOrderNotification.apply_async((order.pk,), countdown=10)
         return Response(
             status=status.HTTP_201_CREATED
         )
     else:
         return Response(
             status=status.HTTP_422_UNPROCESSABLE_ENTITY
         )
Exemplo n.º 18
0
def Order_detail(request, pk):
    try:
        orders = Orders.objects.get(pk=pk)
    except Stock.DoesNotExist:
        return JsonResponse({'message': 'The stock does not exist'},
                            status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        Order_serializer = OrderSerializer(orders)
        return JsonResponse(Order_serializer.data)

    elif request.method == 'PUT':
        Order_data = JSONParser().parse(request)
        print(Order_data)
        quantity1 = Order_data['quantity']
        statusobj = OrderStatus.objects.get(abbv__iexact='RQEDI')
        obj2 = Orders.objects.get(id=pk)
        obj2.quantity = quantity1
        obj2.status = statusobj
        obj2.save()

        Order_serializer = OrderSerializer(orders, data=Order_data)
        if Order_serializer.is_valid():
            # Stock_serializer.save()
            return JsonResponse(Order_serializer.data)
        return JsonResponse(Order_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        statusobj = OrderStatus.objects.get(abbv__iexact='RQDEL')
        obj2 = Orders.objects.get(id=pk)
        obj2.status = statusobj
        obj2.save()

        return JsonResponse({'message': 'Stock was deleted successfully!'},
                            status=status.HTTP_204_NO_CONTENT)
Exemplo n.º 19
0
 def post(self,request):
     data = request.data
     serializer = OrderSerializer(data=data,context={'request':request})
     serializer.is_valid()
     serializer.save()
     return Response(serializer.data)
Exemplo n.º 20
0
 def post(self, request, format=None):
     serializer = OrderSerializer(data=request.data)
     if serializer.is_valid():
         serializer.save()
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 21
0
 def _create_order(self, content):
     serializer = OrderSerializer(data=content)
     serializer.is_valid(raise_exception=True)
     order = serializer.create(serializer.validated_data)
     return order
Exemplo n.º 22
0
 def create(self):
     serializer = OrderSerializer(data=self.request.data,
                                  context=self.serializer_context)
     serializer.is_valid(raise_exception=True)
     serializer.save()
     return serializer.data