def partial_update(self, request, pk=None): order = Order.objects.all().get(id=pk) seller_id = order.seller_id user_id = order.user_id car_id = order.car_id car = Car.objects.all().get(id=car_id) buyer = User.objects.all().get(id=user_id) buyer.balance = buyer.balance - car.price buyer_serializer = UserSerializer(buyer, data=model_to_dict(buyer), partial=True) buyer_serializer.is_valid(raise_exception=True) buyer_serializer.save() seller = User.objects.all().get(id=seller_id) seller.balance = seller.balance + car.price seller_serializer = UserSerializer(seller, data=model_to_dict(seller), partial=True) seller_serializer.is_valid(raise_exception=True) seller_serializer.save() order.status = 1 serializer = OrderSerializer(order, data=model_to_dict(order), partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data)
def orders(request): try: orders = Order.objects.all() except Order.DoesNotExist as e: return Response({'error': str(e)}) if request.method == 'GET': serializer = OrderSerializer(orders, many=True) return Response(serializer.data) elif request.method == 'PUT': serializer = OrderSerializer(instance=orders, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response({'error': serializer.errors}) 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({'error': serializer.errors}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) elif request.method == 'DELETE': orders.delete() return Response({'deleted': True})
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 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 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 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 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 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, 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, *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 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 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 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 post(self, request, *args, **kwargs): serializer = OrderSerializer(data=request.data) # order_tg = 'hell' if serializer.is_valid(): question = serializer.save() tgapi(question) serializer = OrderSerializer(question) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
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 patch(self, request, pk): order = self.get_object(pk) if request.user.account_type == 2: data_to_edit = {'status': request.data["status"], 'delivery': request.data["delivery"]} serializer = OrderSerializer( order, data=data_to_edit, partial=True) else: 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)
def create(self, request): order = request.data order["create_date"] = date.today() car_id = order["car"] user_id = order["user"] seller_id = order["seller"] if user_id is None or car_id is None: return Response(status=status.HTTP_400_BAD_REQUEST) # update car car = Car.objects.all().get(id=car_id) if car is None: return Response(status=status.HTTP_404_NOT_FOUND) if car.status == 1: return Response(status=status.HTTP_404_NOT_FOUND) # update user user = User.objects.all().get(id=user_id) if user is None: return Response(status=status.HTTP_404_NOT_FOUND) if user.balance < car.price: return Response(status=status.HTTP_406_NOT_ACCEPTABLE) car.status = 1 serializer_car = CarSerializer(car, data={}, partial=True) serializer_car.is_valid(raise_exception=True) serializer_car.save() # user.balance = user.balance - car.price # serializer_user = UserSerializer(user, data={}, partial=True) # serializer_user.is_valid(raise_exception=True) # serializer_user.save() serializer = OrderSerializer(data=order) serializer.is_valid(raise_exception=True) serializer.save() return Response(status=status.HTTP_201_CREATED)
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)
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) elif request.method == 'POST': request_body = json.loads(request.body) serializer = OrderSerializer(data=request_body) 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 orders_list(request): permission_classes = (IsAuthenticated) 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({'error': serializer.errors}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) elif request.method == 'DELETE': orders = Order.objects.all() orders.delete()
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 test_create_shipment_successful_multiple_koiki_methods( self, 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", }, { "numPedido": "124", "codBarras": "ttt", "etiqueta": "abc2", "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) self.assertEqual(Shipment.objects.all().count(), 2) shipment_koiki = Shipment.objects.filter(vendor_id=6).first() self.assertEqual(shipment_koiki.order_id, 33) self.assertEqual(shipment_koiki.method, ShipmentMethod.KOIKI) shipment_local = Shipment.objects.filter(vendor_id=7).first() self.assertEqual(shipment_local.order_id, 33) self.assertEqual(shipment_local.method, ShipmentMethod.KOIKI)
def test_failure(self, mock_client): client = MagicMock() vendor = MagicMock() delivery = Delivery( { "respuesta": "102", "mensaje": "ERROR IN THE RECEIVED DATA", "numPedido": "test", "order_id": 33, }, vendor, ) client.create_delivery.return_value = [delivery] mock_client.return_value = client serializer = OrderSerializer(data=self.data) self.assertTrue(serializer.is_valid()) order = serializer.validated_data create_or_update_delivery(order) self.assertTrue(delivery._is_errored())
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 test_delivery_successful(self, mock_client, mock_success_email, mock_print_pdf): client = MagicMock(name="client") vendor = MagicMock() delivery = Delivery( { "respuesta": "101", "numPedido": "test", "order_id": 33, "codBarras": "CODBAR33" }, vendor, ) client.create_delivery.return_value = [delivery] mock_print_pdf.return_value = "pdf_barcodes/test.pdf" mock_client.return_value = client self.assertEqual(delivery.get_data_val("barcode"), "CODBAR33") serializer = OrderSerializer(data=self.data) self.assertTrue(serializer.is_valid()) order = serializer.validated_data create_or_update_delivery(order) mock_success_email.assert_called_once()
def post(self, request, format=None): if isinstance(request.data, list): # request having multiple object serializer = OrderSerializer(data=request.data, many=True) # get the current hour when the request has been hit now = datetime.datetime.now() current_hour = int(now.hour) current_min = int(now.minute) # current_hour = 6 # current_min = 2 if (0 <= current_hour < 6) or 13 < current_hour < 16 or current_hour == 24 or ( current_hour == 13 and current_min > 0) or (current_hour == 23 and current_min > 0): return Response( { "Time": "wrong order timing, please order between 6-9,9-13,16-19,19-23" }, status=status.HTTP_400_BAD_REQUEST) if serializer.is_valid(): slot_weight = self.check_per_slot_100kg(request.data) if slot_weight: vehicle_limit_pending_per_day = ( self.check_vehicle_per_day_limit_exceeded())[0] if vehicle_limit_pending_per_day: # List of [truck, bike, scooter] vehicle_limit_pending_list_per_day = ( self.check_vehicle_per_day_limit_exceeded())[1] weight = request.data weight = sorted(weight, key=lambda we: we['order_weight'], reverse=True) current_slot_list = self.slot_list( current_hour, current_min) if current_slot_list == [6, 9]: # order_assignment(self, weight, truckAvailable, bikeAvailable, scooterAvailable): # return truck, scooter, bike if weight[0]['order_weight'] > 50: return Response( { "order_weight": "Since Truck is not available maximum weight that can be handle by scooter i.e 50 and request is exceeding that" }, status=status.HTTP_400_BAD_REQUEST) truck, scooter, bike = self.order_assignment( request.data, False, True, True) elif current_slot_list == [9, 13]: truck, scooter, bike = self.order_assignment( request.data, True, True, True) elif current_slot_list == [16, 19]: truck, scooter, bike = self.order_assignment( request.data, True, True, True) elif current_slot_list == [19, 24]: truck, scooter, bike = self.order_assignment( request.data, True, False, False) bike_delivery_partners = DeliveryPartner.objects.filter( is_available=True, vehicle_type="Bike").values('delivery_partner_id') bike_delivery_partners_list = [] if bike_delivery_partners: for i in bike_delivery_partners: bike_delivery_partners_list.append( i['delivery_partner_id']) scooter_delivery_partners = DeliveryPartner.objects.filter( is_available=True, vehicle_type="Scooter").values( 'delivery_partner_id') scooter_delivery_partners_list = [] if scooter_delivery_partners: for i in scooter_delivery_partners: scooter_delivery_partners_list.append( i['delivery_partner_id']) truck_delivery_partners = DeliveryPartner.objects.filter( is_available=True, vehicle_type="Truck").values('delivery_partner_id') truck_delivery_partners_list = [] if truck_delivery_partners: for i in truck_delivery_partners: truck_delivery_partners_list.append( i['delivery_partner_id']) assign_data = [] if truck != [] or truck != [[]]: if not truck_delivery_partners: return Response( { "delivery partner": "Delivery boy is not available for Truck today" }, status=status.HTTP_400_BAD_REQUEST) for truck_list_iterator in truck: current_truck_dic = {'vehicle_type': "Truck"} if not truck_delivery_partners_list: return Response( { "delivery partner": "Delivery boy is not available for Truck today" }, status=status.HTTP_400_BAD_REQUEST) else: current_truck_dic[ "delivery_partner_id"] = truck_delivery_partners_list[ 0] truck_delivery_partners_list.pop(0) current_truck_dic[ 'list_order_ids_assigned'] = truck_list_iterator assign_data.append(current_truck_dic) if scooter != [] or scooter != [[]]: if not scooter_delivery_partners: return Response( { "delivery partner": "Delivery boy is not available for Truck today" }, status=status.HTTP_400_BAD_REQUEST) for scooter_list_iterator in scooter: current_scooter_dic = {} current_scooter_dic['vehicle_type'] = "Scooter" if not scooter_delivery_partners_list: return Response( { "delivery partner": "Delivery boy is not available for Scooter today" }, status=status.HTTP_400_BAD_REQUEST) else: current_scooter_dic[ "delivery_partner_id"] = scooter_delivery_partners_list[ 0] scooter_delivery_partners_list.pop(0) current_scooter_dic[ 'list_order_ids_assigned'] = scooter_list_iterator assign_data.append(current_scooter_dic) if bike != [] or bike != [[]]: if not bike_delivery_partners: return Response( { "delivery partner": "Delivery boy is not available for Bike today" }, status=status.HTTP_400_BAD_REQUEST) for bike_list_iterator in bike: current_bike_dic = {} current_bike_dic['vehicle_type'] = "Bike" if not bike_delivery_partners_list: return Response( { "delivery partner": "Delivery boy is not available for Bike today" }, status=status.HTTP_400_BAD_REQUEST) else: current_bike_dic[ "delivery_partner_id"] = bike_delivery_partners_list[ 0] bike_delivery_partners_list.pop(0) current_bike_dic[ 'list_order_ids_assigned'] = bike_list_iterator assign_data.append(current_bike_dic) print("assigned data", assign_data) # example # assign_data = [ # { # "vehicle_type":"Scooter", # "delivery_partner_id":15, # "list_order_ids_assigned": [11], # } # ] assign_serializer = AssignedOrderSerializer( data=assign_data, many=True) if assign_serializer.is_valid(): serializer.save() assign_serializer.save() return Response(assign_data, status=status.HTTP_201_CREATED) else: return Response( { "vehicle_limit": "vehicle limit exceeded for today" }, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response( {"slot_weight": "weight exceeded for this slot"}, status=status.HTTP_400_BAD_REQUEST) else: # if orderid already exist return Response( { "order": "Request is expecting a list of object. For example - [{order_id: 1, order_weight:30}]" }, status=status.HTTP_400_BAD_REQUEST) return Response(status=status.HTTP_400_BAD_REQUEST)
def orderUpdate(request, id): order = Order.objects.get(id=id) serializer = OrderSerializer(instance=order, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data)
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(serializer.errors, status=status.HTTP_400_BAD_REQUEST)