From 314cec5ad0ec9f51949bf9f6038cae8e0d839f25 Mon Sep 17 00:00:00 2001
From: Oliver Walters <oliver.henry.walters@gmail.com>
Date: Tue, 26 Apr 2022 20:18:33 +1000
Subject: [PATCH] Generate default batch code for stock items

---
 InvenTree/stock/models.py | 29 ++++++++++++++++++++++++++++-
 1 file changed, 28 insertions(+), 1 deletion(-)

diff --git a/InvenTree/stock/models.py b/InvenTree/stock/models.py
index fa343e9a9c..750b4df217 100644
--- a/InvenTree/stock/models.py
+++ b/InvenTree/stock/models.py
@@ -8,6 +8,8 @@ from __future__ import unicode_literals
 
 import os
 
+from jinja2 import Template
+
 from django.utils.translation import gettext_lazy as _
 from django.core.exceptions import ValidationError, FieldError
 from django.urls import reverse
@@ -213,6 +215,30 @@ class StockItemManager(TreeManager):
         )
 
 
+def generate_batch_code():
+    """
+    Generate a default 'batch code' for a new StockItem.
+
+    This uses the value of the 'STOCK_BATCH_CODE_TEMPLATE' setting (if configured),
+    which can be passed through a simple template.
+    """
+
+    batch_template = common.models.InvenTreeSetting.get_setting('STOCK_BATCH_CODE_TEMPLATE', '')
+
+    now = datetime.now()
+
+    context = {
+        'date': now,
+        'year': now.year,
+        'month': now.month,
+        'day': now.day,
+        'hour': now.minute,
+        'minute': now.minute,
+    }
+
+    return Template(batch_template).render(context)
+
+
 class StockItem(MPTTModel):
     """
     A StockItem object represents a quantity of physical instances of a part.
@@ -644,7 +670,8 @@ class StockItem(MPTTModel):
     batch = models.CharField(
         verbose_name=_('Batch Code'),
         max_length=100, blank=True, null=True,
-        help_text=_('Batch code for this stock item')
+        help_text=_('Batch code for this stock item'),
+        default=generate_batch_code,
     )
 
     quantity = models.DecimalField(