def put(self, request, ord_uuid): order = self.get_object(ord_uuid) 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)
def orderbeer(self, request, pk=None): user = request.user role = self.get_object() if not role.associatedGame.active: return Response({'detail': 'Game Frozen/Not Active'}, status=status.HTTP_423_LOCKED) if role.playedBy == user: # if not registered for game no access serializd = OrderSerializer(data=request.data) if serializd.is_valid(): roundcompleted = role.associatedGame.rounds_completed currentweek = role.roleweeks.all().filter( number=roundcompleted+1).first() # reverse foreignkey lookup if role.ordered: return Response({'detail': 'Order Already Placed'}, status=status.HTTP_429_TOO_MANY_REQUESTS) currentweek.order_placed = serializd.data['quantity'] currentweek.save() role.ordered = True role.save() return Response({"detail": "Success"}) else: # if not valid input input<=0 return Response(serializd.errors, status=status.HTTP_406_NOT_ACCEPTABLE) else: # if no permission return Response({"detail": "Not Authorized"}, status=status.HTTP_401_UNAUTHORIZED)
def create(self, request): slr = OrderSerializer(data=request.data, context={'request': request}) if slr.is_valid(): slr.save() return Response(slr.data) else: return Response(slr.errors, status=400)
def test_create_delivery_sends_error_email_default_error( self, mock_logger, mock_email): httpretty.register_uri( httpretty.POST, f"{lazona_connector.vars.koiki_host}/rekis/api/altaEnvios", status=200, content_type="text/json", body=json.dumps({ 'respuesta': '102', 'mensaje': 'ERROR', 'envios': [{ 'numPedido': '124', 'respuesta': '102', 'mensaje': '' }] })) serializer = OrderSerializer(data=self.data) self.assertTrue(serializer.is_valid()) order = serializer.validated_data mock_email.send.return_value = True create_or_update_delivery(order) message = mock_email.call_args[0][1] self.assertIn("Missatge d'error no proporcionat", message)
def post(self, request, *args): if not request.user.first_name or not request.user.last_name: content = { "warning": "to make an order user has to register a recipient first" } return HttpResponse(json.dumps(content), status=status.HTTP_304_NOT_MODIFIED) recipient = Recipient.objects.filter( name=request.user.first_name, surname=request.user.last_name).first() if not recipient: content = { "warning": "the recipient doesn't found. try to set up a new one" } return HttpResponse(json.dumps(content), status=status.HTTP_304_NOT_MODIFIED) serializer_class = OrderSerializer( data={ 'delivery_address': request.data['delivery_address'], 'product_set': request.data['product_set'], 'user': request.user.pk, 'recipient': recipient.pk }) if not serializer_class.is_valid(): return Response(status=status.HTTP_400_BAD_REQUEST) serializer_class.save() return Response(serializer_class.data, status=status.HTTP_201_CREATED)
def test_create_delivery_sends_email(self, mock_logger, mock_email): httpretty.register_uri( httpretty.POST, f"{lazona_connector.vars.koiki_host}/rekis/api/altaEnvios", status=200, content_type="text/json", body=json.dumps({ 'respuesta': '101', 'mensaje': 'OK', 'envios': [{ 'numPedido': '123', 'codBarras': 'yyy', 'etiqueta': 'abcd', 'respuesta': '101', 'mensaje': 'OK' }] }), ) serializer = OrderSerializer(data=self.data) self.assertTrue(serializer.is_valid()) order = serializer.validated_data mock_email.send.return_value = True create_or_update_delivery(order) mock_logger.info.assert_called_once_with( "Sending Koiki pdf to vendor with id 6") self.assertIn({"to": ["*****@*****.**"]}, mock_email.call_args) message = mock_email.call_args[0][1] self.assertIn( f"{lazona_connector.vars.wcfmmp_host}/area-privada/orders-details/33", message)
def test_create_delivery_sends_error_email(self, mock_logger, mock_email): httpretty.register_uri( httpretty.POST, f"{lazona_connector.vars.koiki_host}/rekis/api/altaEnvios", status=200, content_type="text/json", body=json.dumps({ 'respuesta': '102', 'mensaje': 'ERROR', 'envios': [{ 'numPedido': '124', 'respuesta': '102', 'mensaje': 'Missing field X' }] })) serializer = OrderSerializer(data=self.data) self.assertTrue(serializer.is_valid()) order = serializer.validated_data mock_email.send.return_value = True create_or_update_delivery(order) mock_logger.info.assert_called_once_with( "Sending Koiki error to admins for order 33") self.assertIn({"to": lazona_connector.vars.error_mail_recipients}, mock_email.call_args) message = mock_email.call_args[0][1] self.assertIn( f"{lazona_connector.vars.wcfmmp_host}/area-privada/orders-details/33", message) self.assertIn("Missing field X", message)
def post(self, request, format=None): serializer = OrderSerializer(data=request.data) if serializer.is_valid(): serializer.save() date = serializer.validated_data.get("date") order_items = serializer.validated_data.get("items") for i in order_items: item = Item.objects.get(pk=i.get("id")) if ItemHistory.objects.filter(date=date, item=item).exists(): item_sold = ItemHistory.objects.get(date=date, item=item) item_sold.amount = F('amount') + i.get("amount") item_sold.save() else: item_sold = ItemHistory.objects.create(date=date, item=item, amount=i.get("amount")) if Composition.objects.filter(item=item).exists(): item_components = list() queryset = Composition.objects.filter(item=item) for entry in queryset: item_components.append((entry.component, entry.amount),) for component in item_components: if ComponentHistory.objects.filter(date=date, component=component[0]).exists(): component_spent = ComponentHistory.objects.get(date=date, component=component[0]) component_spent.amount = F('amount') + (component[1] * i.get("amount")) component_spent.save() else: component_spent = ComponentHistory.objects.create(date=date, component=component[0], amount=(component[1]*i.get("amount"))) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request): serializer = OrderSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response({'error': serializer.errors}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def put(self, request, order_id): order = self.get_object(order_id) serializer = OrderSerializer(instance=order, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response({'error': serializer.errors})
def post(self, request, pk): order = get_object_or_404(Order, pk=pk) serializer = OrderSerializer(order, data=request.data) if not serializer.is_valid(): return Response({'serializer': serializer, 'order': order}) serializer.save() return redirect('order')
def put(self, request, pk=None): order = self.getOrder(pk) serializer = OrderSerializer(instance=order, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(self.serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request): serializer = OrderSerializer(data=request.data) if serializer.is_valid(): order = serializer.validated_data create_or_update_delivery.delay(order) return Response(status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def _single_create(self, user, device, order): if user.id == device.owner.id: order["owner"] = user.id serializer = OrderSerializer(data=order) print serializer print serializer.is_valid() if serializer.is_valid(): return True, serializer else: return False, None else: return False, None
def retry_delivery(self, request, shipment_id): client = APIClient() shipment = Shipment.objects.get(id=shipment_id) response = client.request(f"orders/{shipment.order_id}") serializer = OrderSerializer(data=response.json()) if serializer.is_valid(): order = serializer.validated_data create_or_update_delivery(order, vendor_id=str(shipment.vendor_id)) return HttpResponseRedirect( reverse("admin:api_shipment_change", args=(shipment.id, ))) return HttpResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def create(self, request, *args, **kwargs): user = self.request.user products = self.request.data['products'] amounts = self.request.data['amounts'] customer_id = self.request.data['customer'] owner = self.request.data['owner'] total_price = self.request.data['total_price'] total_tax = self.request.data['total_tax'] order = Order.objects.create(owner=owner, products=products, amounts=amounts, customer_id=customer_id, total_price=total_price, total_tax=total_tax) order_serializer = OrderSerializer(order) sio.emit('create_change_order', { 'data': { 'state': 'created', 'order': order_serializer.data, 'user': { 'email': user.email, 'id': user.id } } }, namespace='/test') return Response(order_serializer.data)
def get(self, request, *args, **kwargs): if not request.user.is_authenticated: return JsonResponse({ 'Status': False, 'Error': 'Log in required' }, status=403) if request.user.type != 'shop': return JsonResponse( { 'Status': False, 'Error': 'Только для магазинов' }, status=403) order = Order.objects.filter( ordered_items__product_info__shop__user_id=request.user.id ).exclude(state='basket').prefetch_related( 'ordered_items__product_info__product__category', 'ordered_items__product_info__product_parameters__parameter' ).select_related('contact').annotate(total_sum=Sum( F('ordered_items__quantity') * F('ordered_items__product_info__price'))).distinct() serializer = OrderSerializer(order, many=True) return Response(serializer.data)
def get(self, request, *args, **kwargs): username = self.kwargs['username'] requested_user = get_object_or_404(User, username=username) permission = is_owner(self.request, username) user_orders = Order.objects.filter(user=requested_user) customer = requested_user.customerprofile if len(user_orders) > 0: order = user_orders.order_by("-timestamp")[0] if not order.paid and order.txn_id is None: pass else: order = Order() else: order = Order() order.timestamp = timezone.now() order.user = requested_user order.shots = customer.outstanding_shots order.videoshots = customer.outstanding_videoshots order.amount = customer.amount_due order.outstanding_amount = customer.amount_due order.paid_amount = 0.0 order.paid = False order.txn_ide = "" order.save() serializer = OrderSerializer(order) return Response(serializer.data, status=status.HTTP_200_OK)
def put(self, request, company_id, pk): try: request.data["company"] = company_id order = Order.objects.get(company_id=company_id, pk=pk) serializer = OrderSerializer(order, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) except ObjectDoesNotExist as a: return JsonResponse( {"detail": "An error occurred on the server" + str(a)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
class UserDataSerializer(serializers.ModelSerializer): users_order = OrderSerializer(many=True) class Meta: model = UserData fields = ('username', 'phone_number', 'address', 'users_order') read_only_fields = ( 'id', 'created_at', ) def create(self, validated_data): username = validated_data.get('username') phone_number = validated_data.get('phone_number') address = validated_data.get('address') user_data = UserData.objects.create(username=username, phone_number=phone_number, address=address) users_orders = validated_data.get('users_order') for users_order in users_orders: product = Product.objects.get(pk=users_order.get('product').pk) Order.objects.create(product=product, quantity=users_order.get('quantity'), user_data=user_data) return user_data
def post(self, request): order = self.model.objects.get(id=request.data.get('orderId')) order.resolved_at = timezone.now() order.save() return Response(OrderSerializer(self.model.objects.all(), many=True).data, status.HTTP_200_OK)
def list(self, request): """ GET (ALL) """ orders_db = Order.objects.all() orders_serializer = OrderSerializer(orders_db, many=True) return Response(orders_serializer.data)
def create(self, request): order_data = request.data order = Order.objects.create(product_name=order_data['product_name'], count = order_data['count'], user = self.request.user) order.save() serializer = OrderSerializer(order) logger.debug(f'Order {serializer.instance} was created') logger.info(f'Order {serializer.instance} was created') return Response(serializer.data)
def test_list(self): self.client.force_login(user=self.user) Order.objects.create(user=self.user, delivery_date=datetime.now()) url = reverse('api:order-list') response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, OrderSerializer(Order.objects.filter(user=self.user), many=True).data)
def get(self, request, pk, format=None): try: order = get_order(pk) except Exception: raise Http404 serializer = OrderSerializer(order) return Response(serializer.data)
def get(self, request, *args, **kwargs): order = Order.objects.filter( user_id=request.user.id).exclude(status='basket').select_related('contact').prefetch_related( 'ordered_items').annotate( total_quantity=Sum('ordered_items__quantity'), total_sum=Sum('ordered_items__total_amount')).distinct() serializer = OrderSerializer(order, many=True) return Response(serializer.data)
def update(self, request, pk): order = Order.objects.get(id=pk) order.product_name = request.data['product_name'] order.count = request.data['count'] order.save() serializer = OrderSerializer(order) logger.debug(f'Order {serializer.instance} was updated') logger.info(f'Order {serializer.instance} was updated') return Response(serializer.data)
def get(self, request, user_id): if request.user.account_type == 3: restaurant = RestaurantOwner.objects.get( user=request.user.id).restaurant orders = Order.objects.filter(restaurant=restaurant, status__gt=4) else: orders = Order.objects.filter(user=user_id) serializer = OrderSerializer(orders, many=True) return Response(serializer.data)
def get(self, request, *args, **kwargs): basket = Order.objects.filter( user_id=request.user.id, status='basket').prefetch_related( 'ordered_items').annotate( total_sum=Sum('ordered_items__total_amount'), total_quantity=Sum('ordered_items__quantity')) serializer = OrderSerializer(basket, many=True) return Response(serializer.data)
def post(self, request: Request): cart_filters = {} if request.user.is_anonymous: cart_filters['user_agent'] = request.META.get('HTTP_USER_AGENT') cart_filters['for_anonymous_user'] = True else: cart_filters['user'] = request.user order_data = OrderSerializer(data=request.data) if order_data.is_valid(): try: make_order(**cart_filters) except CantOrderEmptyCart: return Response(status=status.HTTP_400_BAD_REQUEST, data={'errors': 'Cant make order with empty cart'}) return Response(status=status.HTTP_200_OK) return Response(status=status.HTTP_400_BAD_REQUEST, data={'errors': order_data.errors})
def orders_by_user(request, user_id): try: user = User.objects.get(id=user_id) except User.DoesNotExist as e: return Response({'error': str(e)}) if request.method == 'GET': orders = user.orders.get_users_orders(user_id) serializer = OrderSerializer(orders, many=True) return Response(serializer.data)