mirror of
https://github.com/inventree/InvenTree.git
synced 2026-11-28 10:34:34 +00:00
Fixes for stale stock (#13369)
* Remove unused settings Remove settings which have had no effect since the legacy user interface was removed (or which were never implemented): - STOCK_SHOW_INSTALLED_ITEMS - PART_SHOW_RELATED - BARCODE_INPUT_DELAY - PLUGIN_UPDATE_CHECK - REPORT_INLINE (user) - LABEL_INLINE (user) Remove them from the settings pages and documentation, and use other boolean user settings in the tests which used LABEL_INLINE as an example. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Respect part creation and duplication settings The PART_COPY_TESTS, PART_CATEGORY_PARAMETERS and PART_CREATE_SUPPLIER settings had no effect since the legacy user interface was removed. The part forms now use them for the defaults of the "copy tests" and "copy category parameters" options, and to show the initial supplier fields. Adds Playwright tests for the create and duplicate part forms. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Enforce expired stock and IPN edit settings The STOCK_ALLOW_EXPIRED_BUILD, STOCK_ALLOW_EXPIRED_SALE and PART_ALLOW_EDIT_IPN settings had no effect since the legacy user interface was removed. - When stock expiry is enabled, expired stock can only be allocated to build orders / sales orders if the corresponding setting permits it. This applies to manual (API) allocation, allocation by serial number, auto-allocation, and new allocations created via the model. Existing allocations of since-expired stock remain editable. - When PART_ALLOW_EDIT_IPN is disabled, the IPN of an existing part cannot be changed via the API, and the IPN field is disabled in the edit form. Adds unit tests for each allocation path and the IPN rule, a Playwright test for the IPN field, and documents the expired stock settings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Additional docs * Update CHANGELOG * Fix playwright test --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ad19adcfea
commit
a44d6da500
25 files changed
+647
-101
No files matched your search
@@ -1693,6 +1693,11 @@ class Build(
|
||||
"""
|
||||
location = kwargs.get('location')
|
||||
exclude_location = kwargs.get('exclude_location')
|
||||
|
||||
# Exclude expired stock (unless it may be used for building)
|
||||
expiry_filter = stock.models.StockItem.allowed_expiry_filter(
|
||||
'STOCK_ALLOW_EXPIRED_BUILD'
|
||||
)
|
||||
substitutes = kwargs.get('substitutes', True)
|
||||
optional_items = kwargs.get('optional_items', False)
|
||||
|
||||
@@ -1742,6 +1747,8 @@ class Build(
|
||||
serial=output.serial,
|
||||
).exclude(Q(serial=None) | Q(serial=''))
|
||||
|
||||
available_stock = available_stock.filter(expiry_filter)
|
||||
|
||||
if location:
|
||||
# Filter only stock items located "below" the specified location
|
||||
sublocations = location.get_descendants(include_self=True)
|
||||
@@ -1824,6 +1831,11 @@ class Build(
|
||||
stock_sort_by = kwargs.get('stock_sort_by', stock.models.STOCK_SORT_DEFAULT)
|
||||
line_ids = kwargs.get('line_ids')
|
||||
|
||||
# Exclude expired stock (unless it may be used for building)
|
||||
expiry_filter = stock.models.StockItem.allowed_expiry_filter(
|
||||
'STOCK_ALLOW_EXPIRED_BUILD'
|
||||
)
|
||||
|
||||
def stock_sort(item, bom_item, variant_parts):
|
||||
if item.part == bom_item.sub_part:
|
||||
return 1
|
||||
@@ -1892,7 +1904,7 @@ class Build(
|
||||
# function below, which inspects item.part for every candidate.
|
||||
available_stock = stock.models.StockItem.objects.select_related(
|
||||
'part'
|
||||
).filter(stock.models.StockItem.IN_STOCK_FILTER)
|
||||
).filter(stock.models.StockItem.IN_STOCK_FILTER, expiry_filter)
|
||||
|
||||
# Filter by list of available parts
|
||||
available_stock = available_stock.filter(part__in=list(available_parts))
|
||||
@@ -2373,6 +2385,13 @@ class BuildItem(InvenTreeMetadataModel):
|
||||
)
|
||||
)
|
||||
|
||||
# Expired stock may only be newly allocated if permitted
|
||||
# (existing allocations of since-expired stock remain editable)
|
||||
if self._state.adding:
|
||||
self.stock_item.check_expired_allowed(
|
||||
'STOCK_ALLOW_EXPIRED_BUILD', field='stock_item'
|
||||
)
|
||||
|
||||
self.check_allocated_quantity(raise_error=raise_error)
|
||||
|
||||
except stock.models.StockItem.DoesNotExist:
|
||||
|
||||
@@ -920,6 +920,9 @@ class BuildAllocationItemSerializer(serializers.Serializer):
|
||||
if not stock_item.in_stock:
|
||||
raise ValidationError(_('Item must be in stock'))
|
||||
|
||||
# Expired stock may only be allocated if permitted
|
||||
stock_item.check_expired_allowed('STOCK_ALLOW_EXPIRED_BUILD')
|
||||
|
||||
return stock_item
|
||||
|
||||
quantity = serializers.DecimalField(
|
||||
|
||||
@@ -377,13 +377,6 @@ SYSTEM_SETTINGS: dict[str, InvenTreeSettingsKeyType] = {
|
||||
'default': 100,
|
||||
'validator': [int, MinValueValidator(1)],
|
||||
},
|
||||
'BARCODE_INPUT_DELAY': {
|
||||
'name': _('Barcode Input Delay'),
|
||||
'description': _('Barcode input processing delay time'),
|
||||
'default': 50,
|
||||
'validator': [int, MinValueValidator(1)],
|
||||
'units': 'ms',
|
||||
},
|
||||
'BARCODE_WEBCAM_SUPPORT': {
|
||||
'name': _('Barcode Webcam Support'),
|
||||
'description': _('Allow barcode scanning via webcam in browser'),
|
||||
@@ -550,12 +543,6 @@ SYSTEM_SETTINGS: dict[str, InvenTreeSettingsKeyType] = {
|
||||
'validator': bool,
|
||||
'requires_restart': True,
|
||||
},
|
||||
'PLUGIN_UPDATE_CHECK': {
|
||||
'name': _('Check for plugin updates'),
|
||||
'description': _('Enable periodic checks for updates to installed plugins'),
|
||||
'default': True,
|
||||
'validator': bool,
|
||||
},
|
||||
# Settings for plugin mixin features
|
||||
'ENABLE_PLUGINS_URL': {
|
||||
'name': _('Enable URL integration'),
|
||||
|
||||
@@ -19,28 +19,12 @@ def label_printer_options():
|
||||
|
||||
|
||||
USER_SETTINGS: dict[str, InvenTreeSettingsKeyType] = {
|
||||
'LABEL_INLINE': {
|
||||
'name': _('Inline label display'),
|
||||
'description': _(
|
||||
'Display PDF labels in the browser, instead of downloading as a file'
|
||||
),
|
||||
'default': True,
|
||||
'validator': bool,
|
||||
},
|
||||
'LABEL_DEFAULT_PRINTER': {
|
||||
'name': _('Default label printer'),
|
||||
'description': _('Configure which label printer should be selected by default'),
|
||||
'default': '',
|
||||
'choices': label_printer_options,
|
||||
},
|
||||
'REPORT_INLINE': {
|
||||
'name': _('Inline report display'),
|
||||
'description': _(
|
||||
'Display PDF reports in the browser, instead of downloading as a file'
|
||||
),
|
||||
'default': False,
|
||||
'validator': bool,
|
||||
},
|
||||
'BARCODE_IN_FORM_FIELDS': {
|
||||
'name': _('Barcode Scanner in Form Fields'),
|
||||
'description': _('Allow barcode scanner input in form fields'),
|
||||
|
||||
@@ -857,7 +857,9 @@ class UserSettingsApiTest(InvenTreeAPITestCase):
|
||||
)
|
||||
|
||||
# Check the detail API endpoint
|
||||
url = reverse('api-user-setting-detail', kwargs={'key': 'LABEL_INLINE'})
|
||||
url = reverse(
|
||||
'api-user-setting-detail', kwargs={'key': 'SEARCH_PREVIEW_SHOW_PARTS'}
|
||||
)
|
||||
self.get(url, expected_code=401)
|
||||
|
||||
def test_user_settings_api_list(self):
|
||||
@@ -900,7 +902,7 @@ class UserSettingsApiTest(InvenTreeAPITestCase):
|
||||
|
||||
def test_user_setting_init(self):
|
||||
"""Test we can retrieve a setting which has not yet been initialized."""
|
||||
key = 'LABEL_INLINE'
|
||||
key = 'SEARCH_PREVIEW_SHOW_PARTS'
|
||||
|
||||
# Ensure it does not actually exist in the database
|
||||
self.assertFalse(InvenTreeUserSetting.objects.filter(key=key).exists())
|
||||
|
||||
@@ -1698,7 +1698,11 @@ class SalesOrder(AuditedOrderMixin, TotalPriceMixin, Order):
|
||||
continue
|
||||
|
||||
available_stock = stock.models.StockItem.objects.filter(
|
||||
stock.models.StockItem.IN_STOCK_FILTER, part=line_item.part
|
||||
stock.models.StockItem.IN_STOCK_FILTER,
|
||||
stock.models.StockItem.allowed_expiry_filter(
|
||||
'STOCK_ALLOW_EXPIRED_SALE'
|
||||
),
|
||||
part=line_item.part,
|
||||
)
|
||||
|
||||
if location:
|
||||
@@ -1841,6 +1845,13 @@ class SalesOrder(AuditedOrderMixin, TotalPriceMixin, Order):
|
||||
serials_unavailable.add(serial)
|
||||
continue
|
||||
|
||||
# Expired stock may only be allocated if permitted
|
||||
try:
|
||||
stock_item.check_expired_allowed('STOCK_ALLOW_EXPIRED_SALE')
|
||||
except ValidationError:
|
||||
serials_unavailable.add(serial)
|
||||
continue
|
||||
|
||||
# Lock the StockItem row, so that concurrent allocation requests are
|
||||
# serialized against each other, and re-validate the unallocated
|
||||
# quantity against the now-current (and now-locked) state
|
||||
@@ -3330,6 +3341,14 @@ class SalesOrderAllocation(models.Model):
|
||||
if self.quantity > self.item.quantity:
|
||||
errors['quantity'] = _('Allocation quantity cannot exceed stock quantity')
|
||||
|
||||
# Expired stock may only be newly allocated if permitted
|
||||
# (existing allocations of since-expired stock remain editable)
|
||||
if self._state.adding:
|
||||
try:
|
||||
self.item.check_expired_allowed('STOCK_ALLOW_EXPIRED_SALE')
|
||||
except ValidationError as exc:
|
||||
errors['item'] = exc.messages
|
||||
|
||||
# Ensure that we do not 'over allocate' a stock item
|
||||
build_allocation_count = self.item.build_allocation_count()
|
||||
sales_allocation_count = self.item.sales_order_allocation_count(
|
||||
|
||||
@@ -1825,6 +1825,9 @@ class SalesOrderShipmentAllocationItemSerializer(serializers.Serializer):
|
||||
'quantity': _('Quantity must be 1 for serialized stock item')
|
||||
})
|
||||
|
||||
# Expired stock may only be allocated if permitted
|
||||
stock_item.check_expired_allowed('STOCK_ALLOW_EXPIRED_SALE', field='stock_item')
|
||||
|
||||
q = normalize(stock_item.unallocated_quantity())
|
||||
|
||||
if quantity > q:
|
||||
|
||||
@@ -27,6 +27,7 @@ import part.helpers as part_helpers
|
||||
import stock.models
|
||||
import users.models
|
||||
import users.permissions
|
||||
from common.settings import get_global_setting
|
||||
from data_exporter.mixins import DataExportSerializerMixin
|
||||
from importer.registry import register_importer
|
||||
from InvenTree.mixins import DataImportExportSerializerMixin
|
||||
@@ -972,6 +973,20 @@ class PartSerializer(
|
||||
allow_blank=False,
|
||||
)
|
||||
|
||||
def validate_IPN(self, value):
|
||||
"""Ensure that the IPN of an existing part can only be changed if permitted."""
|
||||
part = self.instance
|
||||
|
||||
if isinstance(part, Part) and part.pk:
|
||||
if (value or '') != (part.IPN or '') and not get_global_setting(
|
||||
'PART_ALLOW_EDIT_IPN', True, cache=False
|
||||
):
|
||||
raise serializers.ValidationError(
|
||||
_('The IPN of an existing part cannot be changed')
|
||||
)
|
||||
|
||||
return value
|
||||
|
||||
def validate_existing_image(self, img):
|
||||
"""Validate the selected image file."""
|
||||
if not img:
|
||||
|
||||
@@ -124,12 +124,6 @@ SYSTEM_SETTINGS: dict[str, InvenTreeSettingsKeyType] = {
|
||||
'default': False,
|
||||
'validator': bool,
|
||||
},
|
||||
'PART_SHOW_RELATED': {
|
||||
'name': _('Show related parts'),
|
||||
'description': _('Display related parts for a part'),
|
||||
'default': True,
|
||||
'validator': bool,
|
||||
},
|
||||
'PART_CREATE_INITIAL': {
|
||||
'name': _('Initial Stock Data'),
|
||||
'description': _('Allow creation of initial stock when adding a new part'),
|
||||
|
||||
@@ -3879,3 +3879,45 @@ class PartApiPerformanceTest(PartAPITestBase, InvenTreeAPIPerformanceTestCase):
|
||||
url = reverse('api-part-list')
|
||||
response = self.get(url, expected_code=200)
|
||||
self.assertGreater(len(response.data), 13)
|
||||
|
||||
|
||||
class PartIPNEditTest(InvenTreeAPITestCase):
|
||||
"""Tests for the PART_ALLOW_EDIT_IPN setting."""
|
||||
|
||||
roles = ['part.add', 'part.change', 'part.view', 'part_category.view']
|
||||
|
||||
def setUp(self):
|
||||
"""Create a part with an IPN."""
|
||||
super().setUp()
|
||||
self.part = Part.objects.create(name='IPN Widget', IPN='IPN-001')
|
||||
self.url = reverse('api-part-detail', kwargs={'pk': self.part.pk})
|
||||
|
||||
def test_edit_allowed(self):
|
||||
"""The IPN can be changed when permitted (the default)."""
|
||||
set_global_setting('PART_ALLOW_EDIT_IPN', True)
|
||||
|
||||
self.patch(self.url, {'IPN': 'IPN-002'}, expected_code=200)
|
||||
self.part.refresh_from_db()
|
||||
self.assertEqual(self.part.IPN, 'IPN-002')
|
||||
|
||||
def test_edit_blocked(self):
|
||||
"""The IPN of an existing part cannot be changed when not permitted."""
|
||||
set_global_setting('PART_ALLOW_EDIT_IPN', False)
|
||||
|
||||
response = self.patch(self.url, {'IPN': 'IPN-002'}, expected_code=400)
|
||||
self.assertIn('cannot be changed', str(response.data['IPN']))
|
||||
|
||||
self.part.refresh_from_db()
|
||||
self.assertEqual(self.part.IPN, 'IPN-001')
|
||||
|
||||
# Other fields can still be edited, and re-submitting the same IPN is fine
|
||||
self.patch(
|
||||
self.url, {'IPN': 'IPN-001', 'description': 'Updated'}, expected_code=200
|
||||
)
|
||||
|
||||
# A new part can still be created with an IPN
|
||||
self.post(
|
||||
reverse('api-part-list'),
|
||||
{'name': 'IPN Widget 2', 'IPN': 'IPN-003', 'description': 'New part'},
|
||||
expected_code=201,
|
||||
)
|
||||
@@ -693,6 +693,51 @@ class StockItem(
|
||||
& Q(expiry_date__lt=InvenTree.helpers.current_date())
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def allow_expired_stock(setting: str) -> bool:
|
||||
"""Return True if expired stock may be used for a particular purpose.
|
||||
|
||||
Arguments:
|
||||
setting: The global setting which controls whether expired stock may be used
|
||||
(e.g. 'STOCK_ALLOW_EXPIRED_BUILD' or 'STOCK_ALLOW_EXPIRED_SALE')
|
||||
|
||||
Expired stock is always allowed if the stock expiry feature is disabled.
|
||||
"""
|
||||
if not get_global_setting('STOCK_ENABLE_EXPIRY', False):
|
||||
return True
|
||||
|
||||
return bool(get_global_setting(setting, False))
|
||||
|
||||
@classmethod
|
||||
def allowed_expiry_filter(cls, setting: str) -> Q:
|
||||
"""Return a filter which excludes expired stock, if it may not be used for a particular purpose.
|
||||
|
||||
Arguments:
|
||||
setting: The global setting which controls whether expired stock may be used
|
||||
"""
|
||||
if cls.allow_expired_stock(setting):
|
||||
return Q()
|
||||
|
||||
return Q(expiry_date=None) | Q(
|
||||
expiry_date__gte=InvenTree.helpers.current_date()
|
||||
)
|
||||
|
||||
def check_expired_allowed(self, setting: str, field: str | None = None) -> None:
|
||||
"""Raise a ValidationError if this item has expired, and expired stock may not be used.
|
||||
|
||||
Arguments:
|
||||
setting: The global setting which controls whether expired stock may be used
|
||||
field: Optional field name to associate the error with
|
||||
"""
|
||||
expired = (
|
||||
self.expiry_date is not None
|
||||
and self.expiry_date < InvenTree.helpers.current_date()
|
||||
)
|
||||
|
||||
if expired and not StockItem.allow_expired_stock(setting):
|
||||
msg = _('Expired stock cannot be used')
|
||||
raise ValidationError({field: msg} if field else msg)
|
||||
|
||||
@staticmethod
|
||||
def _lock_serial_numbers(part: PartModels.Part, serials: list) -> None:
|
||||
"""Serialize concurrent serial number creation, and re-validate under the lock.
|
||||
|
||||
@@ -70,12 +70,6 @@ SYSTEM_SETTINGS: dict[str, InvenTreeSettingsKeyType] = {
|
||||
'default': '',
|
||||
'validator': common.validators.validate_icon,
|
||||
},
|
||||
'STOCK_SHOW_INSTALLED_ITEMS': {
|
||||
'name': _('Show Installed Stock Items'),
|
||||
'description': _('Display installed stock items in stock tables'),
|
||||
'default': False,
|
||||
'validator': bool,
|
||||
},
|
||||
'STOCK_ENFORCE_BOM_INSTALLATION': {
|
||||
'name': _('Check BOM when installing items'),
|
||||
'description': _(
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
"""Tests for the STOCK_ALLOW_EXPIRED_BUILD and STOCK_ALLOW_EXPIRED_SALE settings.
|
||||
|
||||
When stock expiry is enabled, expired stock may only be allocated to build orders
|
||||
(or sales orders) if the corresponding setting permits it.
|
||||
"""
|
||||
|
||||
from datetime import timedelta
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.urls import reverse
|
||||
|
||||
import InvenTree.helpers
|
||||
from build.models import Build, BuildItem, BuildLine
|
||||
from build.status_codes import BuildStatus
|
||||
from common.settings import set_global_setting
|
||||
from company.models import Company
|
||||
from InvenTree.unit_test import InvenTreeAPITestCase
|
||||
from order.models import (
|
||||
SalesOrder,
|
||||
SalesOrderAllocation,
|
||||
SalesOrderLineItem,
|
||||
SalesOrderShipment,
|
||||
)
|
||||
from part.models import BomItem, Part
|
||||
from stock.models import StockItem, StockLocation
|
||||
|
||||
|
||||
class ExpiredAllocationTestBase(InvenTreeAPITestCase):
|
||||
"""Common data for expired allocation tests."""
|
||||
|
||||
roles = ['build.add', 'build.change', 'sales_order.add', 'sales_order.change']
|
||||
|
||||
@classmethod
|
||||
def setUpTestData(cls):
|
||||
"""Create parts, stock, a build order and a sales order."""
|
||||
super().setUpTestData()
|
||||
|
||||
cls.location = StockLocation.objects.create(name='Expiry Store')
|
||||
|
||||
cls.component = Part.objects.create(
|
||||
name='Expiring Component', component=True, salable=True
|
||||
)
|
||||
|
||||
cls.assembly = Part.objects.create(name='Expiry Assembly', assembly=True)
|
||||
|
||||
BomItem.objects.create(part=cls.assembly, sub_part=cls.component, quantity=1)
|
||||
|
||||
today = InvenTree.helpers.current_date()
|
||||
|
||||
cls.expired = StockItem.objects.create(
|
||||
part=cls.component,
|
||||
quantity=10,
|
||||
location=cls.location,
|
||||
expiry_date=today - timedelta(days=10),
|
||||
)
|
||||
|
||||
cls.customer = Company.objects.create(name='Expiry Customer', is_customer=True)
|
||||
|
||||
def setUp(self):
|
||||
"""Enable stock expiry by default."""
|
||||
super().setUp()
|
||||
self.set_rules(expiry=True, build=False, sale=False)
|
||||
|
||||
def set_rules(self, expiry: bool, build: bool, sale: bool):
|
||||
"""Configure the stock expiry settings."""
|
||||
set_global_setting('STOCK_ENABLE_EXPIRY', expiry)
|
||||
set_global_setting('STOCK_ALLOW_EXPIRED_BUILD', build)
|
||||
set_global_setting('STOCK_ALLOW_EXPIRED_SALE', sale)
|
||||
|
||||
def fresh_stock(self, quantity=10):
|
||||
"""Create a stock item which has not expired."""
|
||||
return StockItem.objects.create(
|
||||
part=self.component,
|
||||
quantity=quantity,
|
||||
location=self.location,
|
||||
expiry_date=InvenTree.helpers.current_date() + timedelta(days=30),
|
||||
)
|
||||
|
||||
|
||||
class BuildExpiredAllocationTest(ExpiredAllocationTestBase):
|
||||
"""Allocation of expired stock to build orders."""
|
||||
|
||||
def setUp(self):
|
||||
"""Create a build order for each test."""
|
||||
super().setUp()
|
||||
|
||||
self.build = Build.objects.create(
|
||||
part=self.assembly,
|
||||
quantity=5,
|
||||
reference='BO-9876',
|
||||
status=BuildStatus.PRODUCTION,
|
||||
)
|
||||
|
||||
self.line = BuildLine.objects.get(build=self.build)
|
||||
|
||||
def allocate(self, item, expected_code):
|
||||
"""Allocate a stock item against the build via the API."""
|
||||
return self.post(
|
||||
reverse('api-build-allocate', kwargs={'pk': self.build.pk}),
|
||||
{
|
||||
'items': [
|
||||
{'build_line': self.line.pk, 'stock_item': item.pk, 'quantity': 1}
|
||||
]
|
||||
},
|
||||
expected_code=expected_code,
|
||||
)
|
||||
|
||||
def test_api_blocked(self):
|
||||
"""Expired stock cannot be allocated when not permitted."""
|
||||
response = self.allocate(self.expired, 400)
|
||||
self.assertIn('Expired stock cannot be used', str(response.data))
|
||||
self.assertFalse(BuildItem.objects.filter(stock_item=self.expired).exists())
|
||||
|
||||
# Stock which has not expired can still be allocated
|
||||
self.allocate(self.fresh_stock(), 201)
|
||||
|
||||
def test_api_allowed(self):
|
||||
"""Expired stock can be allocated when permitted (or when expiry is disabled)."""
|
||||
self.set_rules(expiry=True, build=True, sale=False)
|
||||
self.allocate(self.expired, 201)
|
||||
|
||||
BuildItem.objects.all().delete()
|
||||
|
||||
self.set_rules(expiry=False, build=False, sale=False)
|
||||
self.allocate(self.expired, 201)
|
||||
|
||||
def test_auto_allocate(self):
|
||||
"""Auto-allocation skips expired stock when not permitted."""
|
||||
self.build.auto_allocate_stock()
|
||||
self.assertEqual(self.build.allocated_stock.count(), 0)
|
||||
|
||||
# With fresh stock available, only the fresh stock is allocated
|
||||
fresh = self.fresh_stock()
|
||||
self.build.auto_allocate_stock()
|
||||
self.assertEqual(
|
||||
list(self.build.allocated_stock.values_list('stock_item', flat=True)),
|
||||
[fresh.pk],
|
||||
)
|
||||
|
||||
def test_auto_allocate_allowed(self):
|
||||
"""Auto-allocation uses expired stock when permitted."""
|
||||
self.set_rules(expiry=True, build=True, sale=False)
|
||||
|
||||
self.build.auto_allocate_stock()
|
||||
self.assertEqual(
|
||||
list(self.build.allocated_stock.values_list('stock_item', flat=True)),
|
||||
[self.expired.pk],
|
||||
)
|
||||
|
||||
def test_model_validation(self):
|
||||
"""A new BuildItem cannot allocate expired stock, but existing allocations remain editable."""
|
||||
with self.assertRaises(ValidationError):
|
||||
BuildItem(build_line=self.line, stock_item=self.expired, quantity=1).clean()
|
||||
|
||||
# Allocate while permitted, then disallow
|
||||
self.set_rules(expiry=True, build=True, sale=False)
|
||||
item = BuildItem.objects.create(
|
||||
build_line=self.line, stock_item=self.expired, quantity=1
|
||||
)
|
||||
self.set_rules(expiry=True, build=False, sale=False)
|
||||
|
||||
item.quantity = 2
|
||||
item.clean()
|
||||
item.save()
|
||||
|
||||
|
||||
class SalesOrderExpiredAllocationTest(ExpiredAllocationTestBase):
|
||||
"""Allocation of expired stock to sales orders."""
|
||||
|
||||
def setUp(self):
|
||||
"""Create a sales order for each test."""
|
||||
super().setUp()
|
||||
|
||||
self.order = SalesOrder.objects.create(
|
||||
customer=self.customer, reference='SO-9876'
|
||||
)
|
||||
self.shipment = SalesOrderShipment.objects.create(
|
||||
order=self.order, reference='1'
|
||||
)
|
||||
self.line = SalesOrderLineItem.objects.create(
|
||||
order=self.order, part=self.component, quantity=5
|
||||
)
|
||||
|
||||
def allocate(self, item, expected_code):
|
||||
"""Allocate a stock item against the sales order via the API."""
|
||||
return self.post(
|
||||
reverse('api-so-allocate', kwargs={'pk': self.order.pk}),
|
||||
{
|
||||
'items': [
|
||||
{'line_item': self.line.pk, 'stock_item': item.pk, 'quantity': 1}
|
||||
],
|
||||
'shipment': self.shipment.pk,
|
||||
},
|
||||
expected_code=expected_code,
|
||||
)
|
||||
|
||||
def test_api_blocked(self):
|
||||
"""Expired stock cannot be allocated when not permitted."""
|
||||
response = self.allocate(self.expired, 400)
|
||||
self.assertIn('Expired stock cannot be used', str(response.data))
|
||||
|
||||
self.allocate(self.fresh_stock(), 201)
|
||||
|
||||
def test_api_allowed(self):
|
||||
"""Expired stock can be allocated when permitted (or when expiry is disabled)."""
|
||||
self.set_rules(expiry=True, build=False, sale=True)
|
||||
self.allocate(self.expired, 201)
|
||||
|
||||
SalesOrderAllocation.objects.all().delete()
|
||||
|
||||
self.set_rules(expiry=False, build=False, sale=False)
|
||||
self.allocate(self.expired, 201)
|
||||
|
||||
def test_auto_allocate(self):
|
||||
"""Auto-allocation skips expired stock when not permitted."""
|
||||
self.order.auto_allocate_stock(shipment=self.shipment)
|
||||
self.assertFalse(SalesOrderAllocation.objects.filter(line=self.line).exists())
|
||||
|
||||
self.set_rules(expiry=True, build=False, sale=True)
|
||||
self.order.auto_allocate_stock(shipment=self.shipment)
|
||||
self.assertTrue(
|
||||
SalesOrderAllocation.objects.filter(
|
||||
line=self.line, item=self.expired
|
||||
).exists()
|
||||
)
|
||||
|
||||
def test_serial_allocation(self):
|
||||
"""Expired serialized stock cannot be allocated by serial number when not permitted."""
|
||||
tracked = Part.objects.create(
|
||||
name='Expiring Tracked', salable=True, trackable=True
|
||||
)
|
||||
StockItem.objects.create(
|
||||
part=tracked,
|
||||
quantity=1,
|
||||
serial='EXP-1',
|
||||
location=self.location,
|
||||
expiry_date=InvenTree.helpers.current_date() - timedelta(days=1),
|
||||
)
|
||||
line = SalesOrderLineItem.objects.create(
|
||||
order=self.order, part=tracked, quantity=1
|
||||
)
|
||||
|
||||
with self.assertRaises(ValidationError):
|
||||
self.order.allocate_serial_numbers(line, 1, 'EXP-1', self.shipment)
|
||||
|
||||
self.set_rules(expiry=True, build=False, sale=True)
|
||||
allocations = self.order.allocate_serial_numbers(
|
||||
line, 1, 'EXP-1', self.shipment
|
||||
)
|
||||
self.assertEqual(len(allocations), 1)
|
||||
|
||||
def test_model_validation(self):
|
||||
"""A new allocation cannot use expired stock, but existing allocations remain editable."""
|
||||
with self.assertRaises(ValidationError):
|
||||
SalesOrderAllocation(
|
||||
line=self.line, shipment=self.shipment, item=self.expired, quantity=1
|
||||
).clean()
|
||||
|
||||
self.set_rules(expiry=True, build=False, sale=True)
|
||||
allocation = SalesOrderAllocation.objects.create(
|
||||
line=self.line, shipment=self.shipment, item=self.expired, quantity=1
|
||||
)
|
||||
self.set_rules(expiry=True, build=False, sale=False)
|
||||
|
||||
allocation.quantity = 2
|
||||
allocation.clean()
|
||||
allocation.save()
|
||||
Reference in new issue
Block a user