From 0ccac09962b5adad621aaba21b9812ac9afd5201 Mon Sep 17 00:00:00 2001
From: Oliver Walters <oliver.henry.walters@gmail.com>
Date: Sat, 16 May 2020 09:06:39 +1000
Subject: [PATCH] Auto-fill serial numbers for the SerializeStock form

---
 InvenTree/stock/forms.py | 25 +++++++++++++++++++++++--
 InvenTree/stock/views.py |  9 +++++++++
 2 files changed, 32 insertions(+), 2 deletions(-)

diff --git a/InvenTree/stock/forms.py b/InvenTree/stock/forms.py
index 0286054766..3eb3c1018b 100644
--- a/InvenTree/stock/forms.py
+++ b/InvenTree/stock/forms.py
@@ -9,6 +9,9 @@ from django import forms
 from django.forms.utils import ErrorDict
 from django.utils.translation import ugettext as _
 
+from crispy_forms.layout import Field, Layout
+from crispy_forms.bootstrap import PrependedText
+
 from mptt.fields import TreeNodeChoiceField
 
 from InvenTree.helpers import GetExportFormats
@@ -95,11 +98,29 @@ class SerializeStockForm(HelperForm):
     def __init__(self, *args, **kwargs):
 
         # Extract the stock item
-        stock_item = kwargs.pop('item')
+        item = kwargs.pop('item')
 
         super().__init__(*args, **kwargs)
 
-        # TODO - Pre-fill the serial numbers!
+        # Pre-calculate what the serial numbers should be!
+        sn = item.part.get_next_serial_number()
+
+        if item.quantity >= 2:
+            sn = "{n}-{m}".format(n=sn, m=int(sn+item.quantity-1))
+        else:
+            sn = str(sn)
+
+        # TODO - Refactor this? Should not have to specify Field('field') for each field...
+        self.helper.layout = Layout(
+            Field('quantity'),
+            Field(PrependedText(
+                'serial_numbers',
+                '#',
+                placeholder=sn
+            )),
+            Field('destination'),
+            Field('note'),
+        )
 
     class Meta:
         model = StockItem
diff --git a/InvenTree/stock/views.py b/InvenTree/stock/views.py
index b94036f66e..13ec701c10 100644
--- a/InvenTree/stock/views.py
+++ b/InvenTree/stock/views.py
@@ -774,7 +774,16 @@ class StockItemSerialize(AjaxUpdateView):
 
         item = self.get_object()
 
+        # Pre-calculate what the serial numbers should be!
+        sn = item.part.get_next_serial_number()
+
+        if item.quantity >= 2:
+            sn = "{n}-{m}".format(n=sn, m=int(sn+item.quantity-1))
+        else:
+            sn = str(sn)
+
         initials['quantity'] = item.quantity
+        initials['serial_numbers'] = sn
         initials['destination'] = item.location.pk
 
         return initials