Prevent allocation of stock against wrong build (#13432)

This commit is contained in:
Oliver authored and GitHub committed 2026-12-02 12:12:02 +11:00
1 parent 7e5521edf2
commit 08d98c2a43
3 files changed
+262 -1

No files matched your search

+28
View File
@@ -1377,6 +1377,8 @@ class Build(
if output.build != self: if output.build != self:
raise ValidationError(_('Build output does not match Build Order')) raise ValidationError(_('Build output does not match Build Order'))
self.check_output_allocations(output)
# If quantity is not specified, assume the entire output quantity # If quantity is not specified, assume the entire output quantity
if quantity is None: if quantity is None:
quantity = output.quantity quantity = output.quantity
@@ -1426,6 +1428,20 @@ class Build(
# Delete allocations # Delete allocations
allocated_items.all().delete() allocated_items.all().delete()
def check_output_allocations(self, output: stock.models.StockItem) -> None:
"""Ensure that all stock allocated to a build output belongs to this build.
Arguments:
output: The StockItem instance (build output) to check
Raises:
ValidationError: If any allocation belongs to a different build
"""
if output.items_to_install.exclude(build_line__build=self).exists():
raise ValidationError(
_('Build output has stock allocated from a different build order')
)
def can_complete_output( def can_complete_output(
self, self,
output: stock.models.StockItem, output: stock.models.StockItem,
@@ -1454,6 +1470,8 @@ class Build(
if output.build != self: if output.build != self:
raise ValidationError(_('Build output does not match Build Order')) raise ValidationError(_('Build output does not match Build Order'))
self.check_output_allocations(output)
prevent_incomplete = get_global_setting( prevent_incomplete = get_global_setting(
'PREVENT_BUILD_COMPLETION_HAVING_INCOMPLETED_TESTS' 'PREVENT_BUILD_COMPLETION_HAVING_INCOMPLETED_TESTS'
) )
@@ -2396,6 +2414,16 @@ class BuildItem(InvenTreeMetadataModel):
) )
) )
# The build output must belong to the same build as the build line
if (
self.install_into
and self.build_line
and self.install_into.build_id != self.build_line.build_id
):
raise ValidationError({
'install_into': _('Build output does not match the parent build')
})
# Expired stock may only be newly allocated if permitted # Expired stock may only be newly allocated if permitted
# (existing allocations of since-expired stock remain editable) # (existing allocations of since-expired stock remain editable)
if self._state.adding: if self._state.adding:
+11 -1
View File
@@ -881,6 +881,10 @@ class BuildAllocationItemSerializer(serializers.Serializer):
"""Check if the parts match.""" """Check if the parts match."""
build = self.context['build'] build = self.context['build']
# The build line must belong to this build
if build_line.build_id != build.pk:
raise ValidationError(_('Build line does not match the parent build'))
# BomItem should point to the same 'part' as the parent build # BomItem should point to the same 'part' as the parent build
if build.part != build_line.bom_item.part: if build.part != build_line.bom_item.part:
# If not, it may be marked as "inherited" from a parent part # If not, it may be marked as "inherited" from a parent part
@@ -945,7 +949,13 @@ class BuildAllocationItemSerializer(serializers.Serializer):
quantity = data['quantity'] quantity = data['quantity']
output = data.get('output', None) output = data.get('output', None)
# build = self.context['build'] build = self.context['build']
# The build output must belong to this build
if output is not None and output.build_id != build.pk:
raise ValidationError({
'output': _('Build output does not match the parent build')
})
# Check that the "stock item" is valid for the referenced "sub_part" # Check that the "stock item" is valid for the referenced "sub_part"
# Fast path: direct part match, avoids querying substitutes / variants below # Fast path: direct part match, avoids querying substitutes / variants below
+223
View File
@@ -3,6 +3,7 @@
from datetime import datetime, timedelta from datetime import datetime, timedelta
from typing import Optional from typing import Optional
import django.core.exceptions as django_exceptions
from django.db import connection from django.db import connection
from django.db.models import F, Sum from django.db.models import F, Sum
from django.test.utils import CaptureQueriesContext from django.test.utils import CaptureQueriesContext
@@ -3595,3 +3596,225 @@ class BuildActionRoleTest(InvenTreeAPITestCase):
# Request now passes the permission check (and fails validation) # Request now passes the permission check (and fails validation)
self.assignRole('build.delete') self.assignRole('build.delete')
self.post(url, {'outputs': []}, expected_code=400) self.post(url, {'outputs': []}, expected_code=400)
class CrossBuildAllocationTest(BuildAPITest):
"""Stock cannot be allocated spanning different build orders."""
def setUp(self):
"""Create two builds of the same tracked assembly."""
super().setUp()
self.assembly = Part.objects.create(
name='Cross Assembly',
description='A tracked assembly',
assembly=True,
trackable=True,
)
self.component = Part.objects.create(
name='Cross Component',
description='A tracked component',
component=True,
trackable=True,
)
BomItem.objects.create(part=self.assembly, sub_part=self.component, quantity=1)
self.b1 = Build.objects.create(
part=self.assembly, reference='BO-7001', quantity=1
)
self.b2 = Build.objects.create(
part=self.assembly, reference='BO-7002', quantity=1
)
self.b1_line = self.b1.build_lines.get()
self.b2_line = self.b2.build_lines.get()
self.b1_output = self.b1.create_build_output(1, serials=['7001']).first()
self.b2_output = self.b2.create_build_output(1, serials=['7002']).first()
self.location = StockLocation.objects.get(pk=1)
self.s1 = StockItem.objects.create(
part=self.component, quantity=1, serial='C-1', location=self.location
)
self.s2 = StockItem.objects.create(
part=self.component, quantity=1, serial='C-2', location=self.location
)
self.n = BuildItem.objects.count()
def test_build_item_api(self):
"""The BuildItem API rejects a build line and output from different builds."""
url = reverse('api-build-item-list')
# B2's line, installed into B1's output
response = self.post(
url,
{
'build_line': self.b2_line.pk,
'stock_item': self.s1.pk,
'install_into': self.b1_output.pk,
'quantity': 1,
},
expected_code=400,
)
self.assertIn(
'Build output does not match the parent build', str(response.data)
)
self.assertEqual(BuildItem.objects.count(), self.n)
# Allocating against the matching build is still allowed
self.post(
url,
{
'build_line': self.b1_line.pk,
'stock_item': self.s1.pk,
'install_into': self.b1_output.pk,
'quantity': 1,
},
expected_code=201,
)
self.assertEqual(BuildItem.objects.count(), self.n + 1)
def test_build_item_model(self):
"""BuildItem model validation rejects a cross-build allocation."""
with self.assertRaises(django_exceptions.ValidationError):
BuildItem.objects.create(
build_line=self.b2_line,
stock_item=self.s1,
install_into=self.b1_output,
quantity=1,
)
self.assertEqual(BuildItem.objects.count(), self.n)
def test_allocate_api(self):
"""The build allocation API rejects lines and outputs from a different build."""
url = reverse('api-build-allocate', kwargs={'pk': self.b1.pk})
# A build line from B2
response = self.post(
url,
{
'items': [
{
'build_line': self.b2_line.pk,
'stock_item': self.s1.pk,
'output': self.b1_output.pk,
'quantity': 1,
}
]
},
expected_code=400,
)
self.assertIn('Build line does not match the parent build', str(response.data))
# An output from B2
response = self.post(
url,
{
'items': [
{
'build_line': self.b1_line.pk,
'stock_item': self.s1.pk,
'output': self.b2_output.pk,
'quantity': 1,
}
]
},
expected_code=400,
)
self.assertIn(
'Build output does not match the parent build', str(response.data)
)
self.assertEqual(BuildItem.objects.count(), self.n)
# Matching line and output is allowed
self.post(
url,
{
'items': [
{
'build_line': self.b1_line.pk,
'stock_item': self.s1.pk,
'output': self.b1_output.pk,
'quantity': 1,
}
]
},
expected_code=201,
)
self.assertEqual(BuildItem.objects.count(), self.n + 1)
def create_legacy_cross_allocation(self):
"""Simulate a cross-build allocation created before validation was added."""
BuildItem.objects.bulk_create([
BuildItem(
build_line=self.b2_line,
stock_item=self.s1,
install_into=self.b1_output,
quantity=1,
),
BuildItem(
build_line=self.b1_line,
stock_item=self.s2,
install_into=self.b1_output,
quantity=1,
),
])
def test_complete_with_cross_allocation(self):
"""A build output with stock allocated from another build cannot be completed."""
self.create_legacy_cross_allocation()
url = reverse('api-build-output-complete', kwargs={'pk': self.b1.pk})
response = self.post(
url,
{'outputs': [{'output': self.b1_output.pk}], 'location': self.location.pk},
expected_code=400,
)
self.assertIn('allocated from a different build order', str(response.data))
# Nothing has been consumed
self.s1.refresh_from_db()
self.b1_output.refresh_from_db()
self.b2_line.refresh_from_db()
self.assertTrue(self.s1.in_stock)
self.assertIsNone(self.s1.consumed_by)
self.assertTrue(self.b1_output.is_building)
self.assertEqual(self.b2_line.consumed, 0)
def test_scrap_with_cross_allocation(self):
"""A build output with stock allocated from another build cannot be scrapped."""
self.create_legacy_cross_allocation()
url = reverse('api-build-output-scrap', kwargs={'pk': self.b1.pk})
response = self.post(
url,
{
'outputs': [{'output': self.b1_output.pk}],
'location': self.location.pk,
'notes': 'Scrap',
},
expected_code=400,
)
self.assertIn('allocated from a different build order', str(response.data))
self.s1.refresh_from_db()
self.b1_output.refresh_from_db()
self.assertTrue(self.s1.in_stock)
self.assertTrue(self.b1_output.is_building)