From 3b666503a8d97cad928dfeea49c5a97dd6c0344d Mon Sep 17 00:00:00 2001 From: Oliver Date: Wed, 2 Dec 2026 14:46:52 +1100 Subject: [PATCH] [barcode] Additional validation for sales order allocation via barcode (#13430) * [barcode] Additional validation for sales order allocation via barcode - Line item must match sales order - Quantity must be greater than zero * Bump API version --- .../InvenTree/InvenTree/api_version.py | 5 +- .../InvenTree/plugin/base/barcodes/api.py | 16 ++- .../plugin/base/barcodes/serializers.py | 17 ++- .../plugin/base/barcodes/test_barcode.py | 112 ++++++++++++++++++ 4 files changed, 145 insertions(+), 5 deletions(-) diff --git a/src/backend/InvenTree/InvenTree/api_version.py b/src/backend/InvenTree/InvenTree/api_version.py index 4a40c5722c..ffe5fd2709 100644 --- a/src/backend/InvenTree/InvenTree/api_version.py +++ b/src/backend/InvenTree/InvenTree/api_version.py @@ -1,11 +1,14 @@ """InvenTree API version information.""" # InvenTree API version -INVENTREE_API_VERSION = 587 +INVENTREE_API_VERSION = 588 """Increment this API version number whenever there is a significant change to the API that any clients need to know about.""" INVENTREE_API_TEXT = """ +v588 -> 2026-12-01 : https://github.com/inventree/InvenTree/pull/13430 + - The "quantity" field for the barcode sales order allocation endpoint must be greater than zero + v587 -> 2026-11-30 : https://github.com/inventree/InvenTree/pull/13418 - "tags" fields are now reported with the "tags" type (instead of "list") in OPTIONS responses - "tags" fields can now be imported via the data importer (as a comma-separated list) diff --git a/src/backend/InvenTree/plugin/base/barcodes/api.py b/src/backend/InvenTree/plugin/base/barcodes/api.py index c9b8ea8630..7968682917 100644 --- a/src/backend/InvenTree/plugin/base/barcodes/api.py +++ b/src/backend/InvenTree/plugin/base/barcodes/api.py @@ -1,5 +1,6 @@ """API endpoints for barcode plugins.""" +from django.core.exceptions import ValidationError as DjangoValidationError from django.db import transaction from django.db.models import F from django.urls import include, path @@ -720,6 +721,10 @@ class BarcodeSOAllocate(BarcodeView): # Next, check if a line-item is provided (optional field) if line_item := kwargs.get('line'): + # The provided line item must belong to the provided sales order + if line_item.order != sales_order: + raise ValidationError(_('Line item does not match sales order')) + return line_item # If not provided, we need to find the correct line item @@ -846,14 +851,21 @@ class BarcodeSOAllocate(BarcodeView): elif all( x is not None for x in [line_item, sales_order, shipment, quantity] ): - order.models.SalesOrderAllocation.objects.create( + allocation = order.models.SalesOrderAllocation( line=line_item, shipment=shipment, item=stock_item, quantity=quantity, ) - response['success'] = _('Stock item allocated to sales order') + # Run full model validation before saving + try: + allocation.full_clean() + except DjangoValidationError as exc: + response['error'] = ' '.join(str(m) for m in exc.messages) + else: + allocation.save() + response['success'] = _('Stock item allocated to sales order') else: response['error'] = _('Not enough information') diff --git a/src/backend/InvenTree/plugin/base/barcodes/serializers.py b/src/backend/InvenTree/plugin/base/barcodes/serializers.py index 63a65199fe..0698afe265 100644 --- a/src/backend/InvenTree/plugin/base/barcodes/serializers.py +++ b/src/backend/InvenTree/plugin/base/barcodes/serializers.py @@ -243,6 +243,19 @@ class BarcodeSOAllocateSerializer(BarcodeSerializer): return shipment - quantity = serializers.IntegerField( - required=False, help_text=_('Quantity to allocate') + quantity = serializers.DecimalField( + max_digits=15, + decimal_places=5, + required=False, + help_text=_('Quantity to allocate'), ) + + def validate_quantity(self, quantity): + """Ensure that the provided quantity is greater than zero. + + Fractional quantities (e.g. 0.5) are permitted. + """ + if quantity is not None and quantity <= 0: + raise ValidationError(_('Quantity must be greater than zero')) + + return quantity diff --git a/src/backend/InvenTree/plugin/base/barcodes/test_barcode.py b/src/backend/InvenTree/plugin/base/barcodes/test_barcode.py index fa4866ad56..a7bc325379 100644 --- a/src/backend/InvenTree/plugin/base/barcodes/test_barcode.py +++ b/src/backend/InvenTree/plugin/base/barcodes/test_barcode.py @@ -649,3 +649,115 @@ class SOAllocateTest(InvenTreeAPITestCase): self.line_item.refresh_from_db() self.assertEqual(self.line_item.allocated_quantity(), 10) self.assertTrue(self.line_item.is_fully_allocated()) + + def allocations(self, line=None): + """Return the allocations against the provided line item (default: the test line).""" + line = line or self.line_item + return order.models.SalesOrderAllocation.objects.filter(line=line) + + def test_invalid_quantity(self): + """Zero or negative allocation quantities are rejected, and nothing is saved.""" + for qty in [-2, -0.5, 0]: + response = self.postBarcode( + self.stock_item.format_barcode(), + sales_order=self.sales_order.pk, + line=self.line_item.pk, + shipment=self.shipment.pk, + quantity=qty, + expected_code=400, + ) + + self.assertIn('Quantity must be greater than zero', str(response)) + + self.assertEqual(self.allocations().count(), 0) + + # Stock availability is unaffected + self.stock_item.refresh_from_db() + self.assertEqual(self.stock_item.unallocated_quantity(), 100) + + def test_fractional_quantity(self): + """Fractional quantities greater than zero accepted.""" + response = self.postBarcode( + self.stock_item.format_barcode(), + sales_order=self.sales_order.pk, + line=self.line_item.pk, + shipment=self.shipment.pk, + quantity=0.5, + expected_code=200, + ) + + self.assertIn('Stock item allocated', str(response['success'])) + + allocations = self.allocations() + self.assertEqual(allocations.count(), 1) + self.assertEqual(float(allocations.first().quantity), 0.5) + + def test_line_from_other_order(self): + """A line belonging to a different order is rejected.""" + other_order = order.models.SalesOrder.objects.create(customer=self.customer) + + other_line = order.models.SalesOrderLineItem.objects.create( + order=other_order, part=self.part, quantity=10 + ) + + # Shipment belonging to the first order + response = self.postBarcode( + self.stock_item.format_barcode(), + sales_order=self.sales_order.pk, + line=other_line.pk, + shipment=self.shipment.pk, + quantity=1, + expected_code=400, + ) + + self.assertIn('Line item does not match sales order', str(response['error'])) + + # Shipment determined automatically + response = self.postBarcode( + self.stock_item.format_barcode(), + sales_order=self.sales_order.pk, + line=other_line.pk, + quantity=1, + expected_code=400, + ) + + self.assertIn('Line item does not match sales order', str(response['error'])) + + self.assertEqual(self.allocations(other_line).count(), 0) + self.assertEqual(self.allocations().count(), 0) + + def test_model_validation(self): + """Allocation is validated against the model before save.""" + import datetime + + set_global_setting('STOCK_ENABLE_EXPIRY', True) + set_global_setting('STOCK_ALLOW_EXPIRED_SALE', False) + + self.stock_item.expiry_date = datetime.date(2000, 1, 1) + self.stock_item.save() + + response = self.postBarcode( + self.stock_item.format_barcode(), + sales_order=self.sales_order.pk, + line=self.line_item.pk, + shipment=self.shipment.pk, + quantity=1, + expected_code=400, + ) + + self.assertIn('Expired stock cannot be used', str(response['error'])) + self.assertEqual(self.allocations().count(), 0) + + # Allow expired stock to be sold - the allocation should now succeed + set_global_setting('STOCK_ALLOW_EXPIRED_SALE', True) + + self.postBarcode( + self.stock_item.format_barcode(), + sales_order=self.sales_order.pk, + line=self.line_item.pk, + shipment=self.shipment.pk, + quantity=1, + expected_code=200, + ) + + self.assertEqual(self.allocations().count(), 1)