Handle internal django errors when receiving purchase order items via the API

(cherry picked from commit 9355c68024)
This commit is contained in:
Oliver 2021-10-03 00:21:06 +10:00
parent 16dcd8adf6
commit 6d448d8475
2 changed files with 26 additions and 10 deletions

View File

@ -8,11 +8,13 @@ from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.conf.urls import url, include
from django.db import transaction
from django.core.exceptions import ValidationError as DjangoValidationError
from django_filters import rest_framework as rest_filters
from rest_framework import generics
from rest_framework import filters, status
from rest_framework.response import Response
from rest_framework import serializers
from rest_framework.serializers import ValidationError
@ -243,11 +245,12 @@ class POReceive(generics.CreateAPIView):
pk = self.kwargs.get('pk', None)
if pk is None:
return None
else:
order = PurchaseOrder.objects.get(pk=self.kwargs['pk'])
return order
try:
order = PurchaseOrder.objects.get(pk=pk)
except (PurchaseOrder.DoesNotExist, ValueError):
raise ValidationError(_("Matching purchase order does not exist"))
return order
def create(self, request, *args, **kwargs):
@ -259,9 +262,14 @@ class POReceive(generics.CreateAPIView):
serializer.is_valid(raise_exception=True)
# Receive the line items
self.receive_items(serializer)
try:
self.receive_items(serializer)
except DjangoValidationError as exc:
# Re-throw a django error as a DRF error
raise ValidationError(detail=serializers.as_serializer_error(exc))
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
@transaction.atomic

View File

@ -418,16 +418,24 @@ class PurchaseOrder(Order):
barcode = ''
if not self.status == PurchaseOrderStatus.PLACED:
raise ValidationError({"status": _("Lines can only be received against an order marked as 'Placed'")})
raise ValidationError({
"status": _("Lines can only be received against an order marked as 'Placed'")
})
try:
if not (quantity % 1 == 0):
raise ValidationError({"quantity": _("Quantity must be an integer")})
raise ValidationError({
"quantity": _("Quantity must be an integer")
})
if quantity < 0:
raise ValidationError({"quantity": _("Quantity must be a positive number")})
raise ValidationError({
"quantity": _("Quantity must be a positive number")
})
quantity = int(quantity)
except (ValueError, TypeError):
raise ValidationError({"quantity": _("Invalid quantity provided")})
raise ValidationError({
"quantity": _("Invalid quantity provided")
})
# Create a new stock item
if line.part and quantity > 0: