[bug] fixes for batch code generation (#13375)

- Improve template validation
- Ensure generated batch code fits within field length
- Fix docs
This commit is contained in:
Oliver authored and GitHub committed 2026-11-26 14:04:43 +11:00
1 parent a44d6da500
commit e309531322
6 files changed
+114 -7

No files matched your search

+5 -1
View File
@@ -22,7 +22,11 @@ Multiple stock items may share the same batch code without restriction, even acr
#### Generating Batch Codes
Batch codes can be generated automatically based on a provided pattern. The default pattern simply uses the current date-code as the batch number, however this can be customized within a certain scope.
Batch codes can be generated automatically based on a provided pattern, using the `STOCK_BATCH_CODE_TEMPLATE` setting. By default this pattern is empty, and no batch code is generated. The pattern uses the Django template language, and can make use of the context variables listed below.
For example, the pattern `{% raw %}B{{ year }}-{{ week }}{% endraw %}` would generate a batch code such as `B2024-51`.
If the pattern is invalid, it cannot be saved. If an error occurs while a batch code is being generated, the error is logged and no batch code is assigned. Generated batch codes are truncated to a maximum of 100 characters.
{{ image("stock/batch_code_template.png", title="Batch code pattern") }}
+18 -3
View File
@@ -10,6 +10,9 @@ import common.models
import InvenTree.exceptions
import InvenTree.helpers
# Maximum length of the StockItem.batch field
BATCH_CODE_MAX_LENGTH = 100
def generate_batch_code(**kwargs):
"""Generate a default 'batch code' for a new StockItem.
@@ -71,11 +74,23 @@ def generate_batch_code(**kwargs):
return batch
# If we get to this point, no plugin was able to generate a new batch code
batch_template = common.models.InvenTreeSetting.get_setting(
'STOCK_BATCH_CODE_TEMPLATE', ''
batch_template = str(
common.models.InvenTreeSetting.get_setting('STOCK_BATCH_CODE_TEMPLATE', '')
or ''
)
return Template(batch_template).render(Context(context))
if not batch_template.strip():
return ''
try:
batch = Template(batch_template).render(Context(context))
except Exception:
# An invalid template must not prevent stock items from being created
InvenTree.exceptions.log_error('generate_batch_code')
return ''
# Ensure the generated value fits within the StockItem.batch field
return batch.strip()[:BATCH_CODE_MAX_LENGTH]
def generate_serial_number(part=None, quantity=1, **kwargs) -> Optional[str]:
+2 -2
View File
@@ -60,7 +60,7 @@ from order.status_codes import SalesOrderStatusGroups, TransferOrderStatusGroups
from part import models as PartModels
from plugin.events import trigger_event
from stock.events import StockEvents
from stock.generators import generate_batch_code
from stock.generators import BATCH_CODE_MAX_LENGTH, generate_batch_code
from stock.status_codes import StockHistoryCode, StockStatus, StockStatusGroups
from users.models import Owner
@@ -1342,7 +1342,7 @@ class StockItem(
batch = models.CharField(
verbose_name=_('Batch Code'),
max_length=100,
max_length=BATCH_CODE_MAX_LENGTH,
blank=True,
null=True,
help_text=_('Batch code for this stock item'),
@@ -3,6 +3,7 @@
from django.utils.translation import gettext_lazy as _
import common.validators
import stock.validators
from common.setting.type import InvenTreeSettingsKeyType, SettingFlag
SYSTEM_SETTINGS: dict[str, InvenTreeSettingsKeyType] = {
@@ -26,8 +27,11 @@ SYSTEM_SETTINGS: dict[str, InvenTreeSettingsKeyType] = {
},
'STOCK_BATCH_CODE_TEMPLATE': {
'name': _('Batch Code Template'),
'description': _('Template for generating default batch codes for stock items'),
'description': _(
'Template for generating default batch codes for stock items (leave blank to disable)'
),
'default': '',
'validator': stock.validators.validate_batch_code_template,
},
'STOCK_ENABLE_EXPIRY': {
'name': _('Stock Expiry'),
+58
View File
@@ -6,6 +6,7 @@ from decimal import Decimal
from unittest import mock
from django.contrib.auth import get_user_model
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.db import connection, transaction
from django.db.models import Sum
@@ -16,10 +17,12 @@ from django_q.models import OrmQ
from djmoney.money import Money
from rest_framework.test import APIClient
import InvenTree.helpers
from audit.helpers import write_batched
from audit.models import AuditLogEntry
from build.models import Build
from common.models import InvenTreeSetting
from common.settings import set_global_setting
from company.models import Company
from InvenTree.unit_test import (
AdminTestCase,
@@ -31,6 +34,7 @@ from order.models import SalesOrder
from part.models import Part, PartTestTemplate
from plugin.base.event.events import batch_events
from stock.events import StockEvents
from stock.generators import generate_batch_code
from stock.status_codes import StockHistoryCode, StockStatus
from .models import StockItem, StockItemTestResult, StockLocation, StockLocationType
@@ -1421,6 +1425,60 @@ class StockBarcodeTest(StockTestBase):
plugin.set_setting('INTERNAL_BARCODE_FORMAT', 'short')
class StockBatchCodeTest(StockTestBase):
"""Tests for the STOCK_BATCH_CODE_TEMPLATE setting and batch code generation."""
def create_item(self):
"""Create a new StockItem, using the default batch code."""
return StockItem.objects.create(
part=Part.objects.get(pk=1), location=StockLocation.objects.get(pk=1)
)
def test_invalid_template_rejected(self):
"""Templates which cannot be compiled cannot be saved."""
for template in ['{% if year %}', '{{ year|notafilter }}', '{% notatag %}']:
with self.assertRaises(ValidationError):
set_global_setting('STOCK_BATCH_CODE_TEMPLATE', template)
# Valid (and empty) templates can be saved
set_global_setting('STOCK_BATCH_CODE_TEMPLATE', 'B{{ year }}')
set_global_setting('STOCK_BATCH_CODE_TEMPLATE', '')
def test_default_batch_code(self):
"""Test batch code generation from the template."""
# Default: no batch code
self.assertEqual(generate_batch_code(), '')
self.assertEqual(self.create_item().batch, '')
set_global_setting('STOCK_BATCH_CODE_TEMPLATE', 'B{{ year }}-{{ week }}')
now = InvenTree.helpers.current_time()
item = self.create_item()
self.assertEqual(item.batch, f'B{now.year}-{now.isocalendar()[1]}')
# Generated values are truncated to fit the batch field
set_global_setting('STOCK_BATCH_CODE_TEMPLATE', 'X' * 150)
item = self.create_item()
self.assertEqual(item.batch, 'X' * 100)
def test_template_errors(self):
"""Errors in the batch code template must not prevent stock creation."""
# A template which compiles, but fails when rendered
set_global_setting(
'STOCK_BATCH_CODE_TEMPLATE', '{% include "missing_template.html" %}'
)
self.assertEqual(generate_batch_code(), '')
self.assertEqual(self.create_item().batch, '')
# A malformed template stored in the database (bypassing validation)
InvenTreeSetting.objects.filter(key='STOCK_BATCH_CODE_TEMPLATE').update(
value='{% if year %}'
)
cache.clear()
self.assertEqual(generate_batch_code(), '')
self.assertEqual(self.create_item().batch, '')
class VariantTest(StockTestBase):
"""Tests for calculation stock counts against templates / variants."""
+26
View File
@@ -0,0 +1,26 @@
"""Validators for the stock app."""
from django.core.exceptions import ValidationError
from django.template import Template, TemplateSyntaxError
from django.utils.translation import gettext_lazy as _
def validate_batch_code_template(value):
"""Validate that the STOCK_BATCH_CODE_TEMPLATE setting is a valid template.
An empty value is allowed (no batch code is generated by default).
Note: The template is only compiled here, not rendered,
as the rendering context depends on the data supplied at generation time.
"""
template = str(value or '')
if not template.strip():
return
try:
Template(template)
except TemplateSyntaxError as exc:
raise ValidationError({
'value': _('Invalid batch code template: {error}').format(error=exc)
})