diff --git a/src/backend/InvenTree/stock/serializers.py b/src/backend/InvenTree/stock/serializers.py index 5162feb194..27d7a0468d 100644 --- a/src/backend/InvenTree/stock/serializers.py +++ b/src/backend/InvenTree/stock/serializers.py @@ -43,6 +43,7 @@ from InvenTree.serializers import ( TreePathSerializer, ) from InvenTree.tasks import batch_offload_tasks +from order.status_codes import SalesOrderStatusGroups, TransferOrderStatusGroups from plugin.base.event.events import batch_events from users.serializers import UserSerializer @@ -548,13 +549,26 @@ class StockItemSerializer( 'consumed_by', ) - # Annotate the queryset with the total allocated to sales orders + # Annotate the queryset with the total allocated quantity + # Note: this must match the calculation in StockItem.allocation_count() queryset = queryset.annotate( allocated=Coalesce( - SubquerySum('sales_order_allocations__quantity'), Decimal(0) + SubquerySum( + 'sales_order_allocations__quantity', + filter=Q( + line__order__status__in=SalesOrderStatusGroups.OPEN, + shipment__shipment_date=None, + ), + ), + Decimal(0), + ) + + Coalesce( + SubquerySum( + 'transfer_order_allocations__quantity', + filter=Q(line__order__status__in=TransferOrderStatusGroups.OPEN), + ), + Decimal(0), ) - # For now, stock allocated to a transfer order will not impact its availability - # + Coalesce(SubquerySum('transfer_order_allocations__quantity'), Decimal(0)) + Coalesce(SubquerySum('allocations__quantity'), Decimal(0)) ) @@ -799,6 +813,11 @@ class SerializeStockItemSerializer(serializers.Serializer): if not item.part.trackable: raise ValidationError(_('Serial numbers cannot be assigned to this part')) + # Serialized items are taken from the source item, which retains its allocations + validate_allocation_boundary( + data['quantity'], item.quantity, item.allocation_count() + ) + # Ensure the serial numbers are valid! quantity = data['quantity'] serial_numbers = data['serial_numbers'] @@ -930,6 +949,11 @@ class InstallStockItemSerializer(serializers.Serializer): 'quantity': _('Quantity to install must not exceed available quantity') }) + # Installed stock is no longer available, so must not be allocated + validate_allocation_boundary( + quantity, stock_item.quantity, stock_item.allocation_count() + ) + return data def save(self): @@ -1181,6 +1205,11 @@ class DisassembleStockItemSerializer(serializers.Serializer): if not item.in_stock: raise ValidationError(_('Stock item is unavailable')) + # Disassembled stock is taken from the item, which retains its allocations + validate_allocation_boundary( + data['quantity'], item.quantity, item.allocation_count() + ) + items = data.get('items', []) if len(items) == 0: @@ -1793,6 +1822,53 @@ class StockMergeSerializer(serializers.Serializer): ) +def validate_allocation_boundary( + quantity, item_quantity, allocated, allow_entire: bool = False +) -> None: + """Ensure that an operation does not take stock which is allocated. + + Allocations remain attached to the original stock item when it is split or reduced, + so an operation which takes part of an allocated item must not take more than + the unallocated quantity - otherwise the remaining allocations are left short. + + Arguments: + quantity: The quantity to be taken from the stock item + item_quantity: The (current) quantity of the stock item + allocated: The total quantity allocated against the stock item + allow_entire: If True, taking the entire item is permitted + (e.g. a transfer, where the allocations move with the item) + + Raises: + ValidationError: Against the 'quantity' field, if the allocation boundary is crossed + """ + if allocated <= 0: + return + + item_quantity = Decimal(item_quantity) + + if allow_entire and quantity >= item_quantity: + return + + unallocated = max(item_quantity - Decimal(allocated), Decimal(0)) + + if quantity <= unallocated: + return + + unallocated = InvenTree.helpers.normalize(unallocated) + + if allow_entire: + msg = _( + 'Stock item is allocated: move the entire quantity, ' + 'or no more than the unallocated quantity ({unallocated})' + ).format(unallocated=unallocated) + else: + msg = _( + 'Stock item is allocated: quantity must not exceed the unallocated quantity ({unallocated})' + ).format(unallocated=unallocated) + + raise ValidationError({'quantity': msg}) + + class StockAdjustmentItemSerializer(serializers.Serializer): """Serializer for a single StockItem within a stock adjustment request. @@ -1819,9 +1895,48 @@ class StockAdjustmentItemSerializer(serializers.Serializer): # Either True / False / None self.require_in_stock = kwargs.pop('require_in_stock', True) self.require_non_zero = kwargs.pop('require_non_zero', False) + self.check_allocations = kwargs.pop('check_allocations', False) super().__init__(*args, **kwargs) + def validate(self, data): + """Validate a single stock adjustment row.""" + data = super().validate(data) + + if self.check_allocations: + self.check_row_allocations(data['pk'], data['quantity']) + + return data + + def check_row_allocations(self, stock_item: StockItem, quantity) -> None: + """Prevent a partial move from splitting stock across an allocation boundary. + + Allocated quantities are bulk-fetched by the parent serializer into the + '_stock_allocated' context cache. The remaining quantity of each item is + tracked in the '_stock_remaining' context cache, as the same item may + appear in multiple rows. + """ + allocated_cache = self.context.get('_stock_allocated') + + if allocated_cache is None: + allocated = stock_item.allocation_count() + else: + allocated = allocated_cache.get(stock_item.pk, Decimal(0)) + + if allocated <= 0: + return + + remaining = self.context.setdefault('_stock_remaining', {}) + item_qty = remaining.get(stock_item.pk, Decimal(stock_item.quantity)) + + validate_allocation_boundary(quantity, item_qty, allocated, allow_entire=True) + + # A partial move splits off unallocated stock, reducing the remaining quantity. + # A full move relocates the entire item, which retains its quantity + # (and allocations), so any subsequent row is still checked against it. + if quantity < item_qty: + remaining[stock_item.pk] = item_qty - quantity + pk = PrefetchedPrimaryKeyRelatedField( cache_key='_stockitems', queryset=StockItem.objects.all(), @@ -1933,6 +2048,13 @@ class StockAdjustmentSerializer(serializers.Serializer): ) } + if getattr(self.fields['items'].child, 'check_allocations', False): + # Bulk-fetch allocated quantities for the per-row allocation boundary check + self.context['_stock_allocated'] = StockItem.bulk_allocation_count( + self.context.get('_stockitems', {}).values() + ) + self.context['_stock_remaining'] = {} + return super().to_internal_value(data) def validate(self, data): @@ -2085,7 +2207,9 @@ class StockTransferSerializer(StockAdjustmentSerializer): fields = ['items', 'notes', 'location'] - items = StockAdjustmentItemSerializer(many=True, require_non_zero=True) + items = StockAdjustmentItemSerializer( + many=True, require_non_zero=True, check_allocations=True + ) location = serializers.PrimaryKeyRelatedField( queryset=StockLocation.objects.filter(), diff --git a/src/backend/InvenTree/stock/test_api.py b/src/backend/InvenTree/stock/test_api.py index a9e0ad1eef..c701b28476 100644 --- a/src/backend/InvenTree/stock/test_api.py +++ b/src/backend/InvenTree/stock/test_api.py @@ -61,6 +61,23 @@ class StockAPITestCase(InvenTreeAPITestCase): 'part.view', ] + def allocate_to_sales_order(self, item: StockItem, quantity): + """Allocate a quantity of the provided stock item against an open sales order.""" + n = order.models.SalesOrder.objects.count() + 1 + + customer = company.models.Company.objects.create( + name=f'Allocation Customer {n}', is_customer=True + ) + so = order.models.SalesOrder.objects.create( + customer=customer, reference=f'SO-ALLOC-{n}' + ) + line = order.models.SalesOrderLineItem.objects.create( + order=so, part=item.part, quantity=quantity + ) + return order.models.SalesOrderAllocation.objects.create( + line=line, item=item, quantity=quantity + ) + class StockLocationTest(StockAPITestCase): """Series of API tests for the StockLocation API.""" @@ -1168,6 +1185,87 @@ class StockItemListTest(StockAPITestCase): self.assertGreaterEqual(len(data), 2500) + def test_allocated_quantity(self): + """The 'allocated' API field must match StockItem.allocation_count(). + + Only active allocations are counted: + - Build order allocations + - Sales order allocations against open orders, which are not yet shipped + - Transfer order allocations against open orders + """ + from order.status_codes import SalesOrderStatus, TransferOrderStatus + + assembly = Part.objects.create( + name='AQ Assembly', description='Allocated quantity test', assembly=True + ) + component = Part.objects.create( + name='AQ Component', + description='Allocated quantity test', + component=True, + salable=True, + ) + part.models.BomItem.objects.create( + part=assembly, sub_part=component, quantity=1 + ) + + item = StockItem.objects.create(part=component, quantity=100, location_id=1) + + url = reverse('api-stock-detail', kwargs={'pk': item.pk}) + + def check(expected): + self.assertEqual(item.allocation_count(), expected) + self.assertEqual(self.get(url).data['allocated'], expected) + + response = self.get(reverse('api-stock-list'), {'part': component.pk}) + self.assertEqual(response.data[0]['allocated'], expected) + + check(0) + + # Build order allocation + bo = build.models.Build.objects.create(part=assembly, quantity=10) + build.models.BuildItem.objects.create( + stock_item=item, build_line=bo.build_lines.first(), quantity=1 + ) + check(1) + + # Open sales order allocation + self.allocate_to_sales_order(item, 2) + check(3) + + # Sales order allocation against a shipped shipment is not counted + allocation = self.allocate_to_sales_order(item, 4) + allocation.shipment = order.models.SalesOrderShipment.objects.create( + order=allocation.line.order, + reference='AQ-1', + shipment_date=datetime.now().date(), + ) + allocation.save() + check(3) + + # Sales order allocation against a closed order is not counted + allocation = self.allocate_to_sales_order(item, 8) + allocation.line.order.status = SalesOrderStatus.CANCELLED.value + allocation.line.order.save() + check(3) + + # Open transfer order allocation + for idx, (to_status, quantity) in enumerate([ + (TransferOrderStatus.ISSUED, 16), + (TransferOrderStatus.CANCELLED, 32), + ]): + to = order.models.TransferOrder.objects.create( + reference=f'TO-AQ-{idx}', status=to_status.value + ) + line = order.models.TransferOrderLineItem.objects.create( + order=to, part=component, quantity=quantity + ) + order.models.TransferOrderAllocation.objects.create( + line=line, item=item, quantity=quantity + ) + + # Only the open transfer order is counted + check(19) + def test_filter_by_allocated(self): """Test that we can filter by "allocated" status. @@ -1919,6 +2017,34 @@ class StockItemTest(StockAPITestCase): for new_item in new_items: self.assertIsNotNone(new_item.creation_date) + def test_serialize_allocated(self): + """Serialization must not take stock which is allocated.""" + # Stock item 100: part 25 (trackable), quantity 10 + item = StockItem.objects.get(pk=100) + self.allocate_to_sales_order(item, 4) + + url = reverse('api-stock-item-serialize', kwargs={'pk': item.pk}) + + response = self.post( + url, + {'quantity': 7, 'serial_numbers': '911-917', 'destination': 1}, + expected_code=400, + ) + self.assertIn( + 'must not exceed the unallocated quantity (6)', + str(response.data['quantity']), + ) + + self.post( + url, + {'quantity': 6, 'serial_numbers': '911-916', 'destination': 1}, + expected_code=201, + ) + + item.refresh_from_db() + self.assertEqual(item.quantity, 4) + self.assertEqual(item.allocation_count(), 4) + def test_bulk_serialize_benchmark(self): """Benchmark: measure the number of DB queries required to serialize 100 stock items at once.""" InvenTreeSetting.set_setting('ENABLE_PLUGINS_EVENTS', True, change_user=None) @@ -2418,6 +2544,42 @@ class StockItemTest(StockAPITestCase): self.assertIsNone(sub_item.belongs_to) self.assertEqual(sub_item.location.pk, 1) + def test_install_allocated(self): + """Installation must not take stock which is allocated.""" + parent = StockItem.objects.create( + part=part.models.Part.objects.get(pk=100), serial='ALLOC-1', quantity=1 + ) + sub_part = part.models.Part.objects.get(pk=50) + + url = reverse('api-stock-item-install', kwargs={'pk': parent.pk}) + + # Partially allocated item: install up to the unallocated quantity + sub_item = StockItem.objects.create(part=sub_part, quantity=10, location_id=1) + self.allocate_to_sales_order(sub_item, 4) + + response = self.post( + url, {'stock_item': sub_item.pk, 'quantity': 7}, expected_code=400 + ) + self.assertIn( + 'must not exceed the unallocated quantity (6)', + str(response.data['quantity']), + ) + + self.post(url, {'stock_item': sub_item.pk, 'quantity': 6}, expected_code=201) + + sub_item.refresh_from_db() + self.assertEqual(sub_item.quantity, 4) + self.assertIsNone(sub_item.belongs_to) + + # Fully allocated (serialized) item cannot be installed + serialized = StockItem.objects.create( + part=sub_part, serial='ALLOC-2', quantity=1, location_id=1 + ) + self.allocate_to_sales_order(serialized, 1) + + response = self.post(url, {'stock_item': serialized.pk}, expected_code=400) + self.assertIn('unallocated quantity (0)', str(response.data['quantity'])) + def test_return_from_customer(self): """Test that we can return a StockItem from a customer, via the API.""" # Assign item to customer @@ -2765,6 +2927,29 @@ class StockItemDisassembleTest(StockAPITestCase): self.assertIn('Duplicate BOM items provided', str(response.data)) + def test_disassemble_allocated(self): + """Disassembly must not take stock which is allocated.""" + self.allocate_to_sales_order(self.item, 4) + + response = self.post( + self.url, + {'items': [{'bom_item': 1, 'quantity': 70}], 'quantity': 7}, + expected_code=400, + ) + self.assertIn( + 'must not exceed the unallocated quantity (6)', + str(response.data['quantity']), + ) + + self.post( + self.url, + {'items': [{'bom_item': 1, 'quantity': 60}], 'quantity': 6}, + expected_code=201, + ) + + self.item.refresh_from_db() + self.assertEqual(self.item.quantity, 4) + def test_consumable_and_virtual_excluded(self): """Consumable BOM lines, and lines pointing to a virtual part, cannot be disassembled.""" # BOM line marked as consumable directly @@ -3382,6 +3567,91 @@ class StocktakeTest(StockAPITestCase): entry = stock_events(item, event_type=StockHistoryCode.STOCK_UPDATE).last() self.assertEqual(entry.additional_data['deltas']['quantity'], 10) + def test_transfer_allocated(self): + """A partial transfer must not split stock across an allocation boundary. + + An allocated item can be transferred in full (allocations move with it), + or partially up to the unallocated quantity - but not in between. + """ + assembly = Part.objects.create( + name='TA Assembly', description='Transfer allocation test', assembly=True + ) + component = Part.objects.create( + name='TA Component', description='Transfer allocation test', component=True + ) + part.models.BomItem.objects.create( + part=assembly, sub_part=component, quantity=1 + ) + bo = build.models.Build.objects.create(part=assembly, quantity=10) + build_line = bo.build_lines.first() + + location = StockLocation.objects.get(pk=5) + + item = StockItem.objects.create(part=component, location=location, quantity=10) + other = StockItem.objects.create(part=component, location=location, quantity=10) + + allocation = build.models.BuildItem.objects.create( + stock_item=item, build_line=build_line, quantity=4 + ) + + url = reverse('api-stock-transfer') + + def transfer(*rows, expected_code=201): + return self.post( + url, + {'items': [{'pk': pk, 'quantity': q} for pk, q in rows], 'location': 1}, + expected_code=expected_code, + ) + + # Crossing the allocation boundary is rejected - error is on the offending row + for q in [7, 9]: + response = transfer((other.pk, 1), (item.pk, q), expected_code=400) + errors = response.data['items'] + self.assertNotIn(0, errors) + self.assertIn('unallocated quantity (6)', str(errors[1]['quantity'])) + + # Repeated rows which cumulatively cross the boundary are also rejected + response = transfer((item.pk, 4), (item.pk, 3), expected_code=400) + errors = response.data['items'] + self.assertNotIn(0, errors) + self.assertIn('unallocated quantity (2)', str(errors[1]['quantity'])) + + # A full move relocates the entire item - a later row is still checked against it + response = transfer((item.pk, 10), (item.pk, 7), expected_code=400) + errors = response.data['items'] + self.assertNotIn(0, errors) + self.assertIn('unallocated quantity (6)', str(errors[1]['quantity'])) + + item.refresh_from_db() + self.assertEqual(item.quantity, 10) + self.assertEqual(item.location.pk, 5) + + # Transfer of the unallocated quantity is allowed - allocated stock stays put + transfer((item.pk, 6)) + + item.refresh_from_db() + self.assertEqual(item.quantity, 4) + self.assertEqual(item.location.pk, 5) + + allocation.refresh_from_db() + self.assertEqual(allocation.stock_item, item) + + # Now fully allocated: any partial transfer is rejected + transfer((item.pk, 1), expected_code=400) + + # Transfer of the entire item is allowed - allocation moves with it + transfer((item.pk, 4)) + + item.refresh_from_db() + self.assertEqual(item.quantity, 4) + self.assertEqual(item.location.pk, 1) + + allocation.refresh_from_db() + self.assertEqual(allocation.stock_item, item) + + # Partial transfer of an unallocated item is unaffected + transfer((other.pk, 3)) + def test_count_with_location(self): """Test that the stock count endpoint correctly handles the optional location field.""" url = reverse('api-stock-count') diff --git a/src/frontend/src/pages/stock/StockDetail.tsx b/src/frontend/src/pages/stock/StockDetail.tsx index 375e708db8..cd6904cae8 100644 --- a/src/frontend/src/pages/stock/StockDetail.tsx +++ b/src/frontend/src/pages/stock/StockDetail.tsx @@ -621,9 +621,23 @@ export default function StockDetail() { }, [id, stockitem, part, user, stockAdjustActions.menuActions]); const stockBadges: ReactNode[] = useMemo(() => { - let available = (stockitem?.quantity ?? 0) - (stockitem?.allocated ?? 0); + const quantity: number = stockitem?.quantity ?? 0; + const allocated: number = stockitem?.allocated ?? 0; + + let available = quantity - allocated; available = Math.max(0, available); + // Tolerance for comparing (decimal) quantities + const epsilon = 1e-6; + + const isAllocated: boolean = allocated > epsilon; + const overAllocated: boolean = + isAllocated && allocated > quantity + epsilon; + const fullyAllocated: boolean = + isAllocated && !overAllocated && allocated >= quantity - epsilon; + + const allocatedTooltip = `${t`Allocated Quantity`}: ${formatDecimal(allocated)} / ${formatDecimal(quantity)}`; + return instanceQuery.isLoading ? [] : [ @@ -658,6 +672,27 @@ export default function StockDetail() { } key='available' />, + , + , + , { await page.getByRole('button', { name: 'Submit' }).click(); + // Initially - quantity too high for available stock await page - .getByText('Number of unique serial numbers (51) must match quantity (100)') + .getByText( + 'Stock item is allocated: quantity must not exceed the unallocated quantity' + ) + .waitFor(); + + // Reduce quantity and re-submit + await page.getByRole('textbox', { name: 'number-field-quantity' }).fill('90'); + await page.getByRole('button', { name: 'Submit' }).click(); + + await page + .getByText('Number of unique serial numbers (51) must match quantity (90)') .waitFor(); await page @@ -322,7 +333,7 @@ test('Stock - Serialize', async ({ browser }) => { await page.getByRole('button', { name: 'Submit' }).click(); await page - .getByText('Number of unique serial numbers (3) must match quantity (100)') + .getByText('Number of unique serial numbers (3) must match quantity (90)') .waitFor(); await page.getByRole('button', { name: 'Cancel' }).click();