blob: da98455b5cbeea05b3e4c8fe1441bdca4c320f4a [file] [log] [blame]
Rohit Waghchauree6143ab2023-03-13 14:51:43 +05301from collections import defaultdict
2from typing import List
Rohit Waghchauref1b59662023-03-06 12:08:28 +05303
Rohit Waghchauree6143ab2023-03-13 14:51:43 +05304import frappe
5from frappe import _, bold
6from frappe.model.naming import make_autoname
Rohit Waghchaure86da3062023-03-20 14:15:34 +05307from frappe.query_builder.functions import CombineDatetime, Sum
Rohit Waghchauref968f0f2023-06-14 23:22:22 +05308from frappe.utils import cint, flt, get_link_to_form, now, nowtime, today
Rohit Waghchauree6143ab2023-03-13 14:51:43 +05309
10from erpnext.stock.deprecated_serial_batch import (
11 DeprecatedBatchNoValuation,
12 DeprecatedSerialNoValuation,
13)
Rohit Waghchauref1b59662023-03-06 12:08:28 +053014from erpnext.stock.valuation import round_off_if_near_zero
15
16
17class SerialBatchBundle:
18 def __init__(self, **kwargs):
Rohit Waghchauree6143ab2023-03-13 14:51:43 +053019 for key, value in kwargs.items():
Rohit Waghchauref1b59662023-03-06 12:08:28 +053020 setattr(self, key, value)
21
22 self.set_item_details()
Rohit Waghchauree6143ab2023-03-13 14:51:43 +053023 self.process_serial_and_batch_bundle()
24 if self.sle.is_cancelled:
25 self.delink_serial_and_batch_bundle()
26
27 self.post_process()
Rohit Waghchauref1b59662023-03-06 12:08:28 +053028
29 def process_serial_and_batch_bundle(self):
30 if self.item_details.has_serial_no:
Rohit Waghchauree6143ab2023-03-13 14:51:43 +053031 self.process_serial_no()
Rohit Waghchauref1b59662023-03-06 12:08:28 +053032 elif self.item_details.has_batch_no:
Rohit Waghchauree6143ab2023-03-13 14:51:43 +053033 self.process_batch_no()
Rohit Waghchauref1b59662023-03-06 12:08:28 +053034
35 def set_item_details(self):
36 fields = [
37 "has_batch_no",
38 "has_serial_no",
39 "item_name",
40 "item_group",
41 "serial_no_series",
42 "create_new_batch",
43 "batch_number_series",
44 ]
45
46 self.item_details = frappe.get_cached_value("Item", self.sle.item_code, fields, as_dict=1)
47
48 def process_serial_no(self):
49 if (
50 not self.sle.is_cancelled
51 and not self.sle.serial_and_batch_bundle
Rohit Waghchauref1b59662023-03-06 12:08:28 +053052 and self.item_details.has_serial_no == 1
Rohit Waghchauref1b59662023-03-06 12:08:28 +053053 ):
Rohit Waghchauree6143ab2023-03-13 14:51:43 +053054 self.make_serial_batch_no_bundle()
55 elif not self.sle.is_cancelled:
56 self.validate_item_and_warehouse()
Rohit Waghchauref1b59662023-03-06 12:08:28 +053057
Rohit Waghchauree6143ab2023-03-13 14:51:43 +053058 def make_serial_batch_no_bundle(self):
Rohit Waghchaure648efca2023-03-28 12:16:27 +053059 self.validate_item()
Rohit Waghchauree6143ab2023-03-13 14:51:43 +053060
Rohit Waghchaure648efca2023-03-28 12:16:27 +053061 sn_doc = SerialBatchCreation(
62 {
63 "item_code": self.item_code,
64 "warehouse": self.warehouse,
65 "posting_date": self.sle.posting_date,
66 "posting_time": self.sle.posting_time,
67 "voucher_type": self.sle.voucher_type,
68 "voucher_no": self.sle.voucher_no,
69 "voucher_detail_no": self.sle.voucher_detail_no,
Rohit Waghchaurec2d74612023-03-29 11:40:36 +053070 "qty": self.sle.actual_qty,
Rohit Waghchaure648efca2023-03-28 12:16:27 +053071 "avg_rate": self.sle.incoming_rate,
72 "total_amount": flt(self.sle.actual_qty) * flt(self.sle.incoming_rate),
73 "type_of_transaction": "Inward" if self.sle.actual_qty > 0 else "Outward",
74 "company": self.company,
75 "is_rejected": self.is_rejected_entry(),
76 }
77 ).make_serial_and_batch_bundle()
Rohit Waghchauref1b59662023-03-06 12:08:28 +053078
Rohit Waghchauree6143ab2023-03-13 14:51:43 +053079 self.set_serial_and_batch_bundle(sn_doc)
Rohit Waghchauref1b59662023-03-06 12:08:28 +053080
Rohit Waghchaure42b22942023-05-27 19:18:03 +053081 def validate_actual_qty(self, sn_doc):
Rohit Waghchauref968f0f2023-06-14 23:22:22 +053082 link = get_link_to_form("Serial and Batch Bundle", sn_doc.name)
83
84 condition = {
85 "Inward": self.sle.actual_qty > 0,
86 "Outward": self.sle.actual_qty < 0,
87 }.get(sn_doc.type_of_transaction)
88
89 if not condition:
90 correct_type = "Inward"
91 if sn_doc.type_of_transaction == "Inward":
92 correct_type = "Outward"
93
94 msg = f"The type of transaction of Serial and Batch Bundle {link} is {bold(sn_doc.type_of_transaction)} but as per the Actual Qty {self.sle.actual_qty} for the item {bold(self.sle.item_code)} in the {self.sle.voucher_type} {self.sle.voucher_no} the type of transaction should be {bold(correct_type)}"
95 frappe.throw(_(msg), title=_("Incorrect Type of Transaction"))
96
Rohit Waghchaure42b22942023-05-27 19:18:03 +053097 precision = sn_doc.precision("total_qty")
98 if flt(sn_doc.total_qty, precision) != flt(self.sle.actual_qty, precision):
Rohit Waghchauref968f0f2023-06-14 23:22:22 +053099 msg = f"Total qty {flt(sn_doc.total_qty, precision)} of Serial and Batch Bundle {link} is not equal to Actual Qty {flt(self.sle.actual_qty, precision)} in the {self.sle.voucher_type} {self.sle.voucher_no}"
Rohit Waghchaure42b22942023-05-27 19:18:03 +0530100 frappe.throw(_(msg))
101
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530102 def validate_item(self):
103 msg = ""
104 if self.sle.actual_qty > 0:
105 if not self.item_details.has_batch_no and not self.item_details.has_serial_no:
106 msg = f"Item {self.item_code} is not a batch or serial no item"
107
108 if self.item_details.has_serial_no and not self.item_details.serial_no_series:
109 msg += f". If you want auto pick serial bundle, then kindly set Serial No Series in Item {self.item_code}"
110
111 if (
112 self.item_details.has_batch_no
113 and not self.item_details.batch_number_series
114 and not frappe.db.get_single_value("Stock Settings", "naming_series_prefix")
115 ):
116 msg += f". If you want auto pick batch bundle, then kindly set Batch Number Series in Item {self.item_code}"
117
118 elif self.sle.actual_qty < 0:
119 if not frappe.db.get_single_value(
120 "Stock Settings", "auto_create_serial_and_batch_bundle_for_outward"
121 ):
122 msg += ". If you want auto pick serial/batch bundle, then kindly enable 'Auto Create Serial and Batch Bundle' in Stock Settings."
123
124 if msg:
125 error_msg = (
126 f"Serial and Batch Bundle not set for item {self.item_code} in warehouse {self.warehouse}."
127 + msg
128 )
129 frappe.throw(_(error_msg))
130
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530131 def set_serial_and_batch_bundle(self, sn_doc):
rohitwaghchaure3e77c0b2023-11-14 19:27:41 +0530132 self.sle.db_set(
133 {"serial_and_batch_bundle": sn_doc.name, "auto_created_serial_and_batch_bundle": 1}
134 )
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530135
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530136 if sn_doc.is_rejected:
137 frappe.db.set_value(
138 self.child_doctype, self.sle.voucher_detail_no, "rejected_serial_and_batch_bundle", sn_doc.name
139 )
140 else:
141 frappe.db.set_value(
142 self.child_doctype, self.sle.voucher_detail_no, "serial_and_batch_bundle", sn_doc.name
143 )
144
145 @property
146 def child_doctype(self):
147 child_doctype = self.sle.voucher_type + " Item"
rohitwaghchaure3e77c0b2023-11-14 19:27:41 +0530148
149 if (
150 self.sle.voucher_type == "Subcontracting Receipt" and self.sle.dependant_sle_voucher_detail_no
151 ):
152 child_doctype = "Subcontracting Receipt Supplied Item"
153
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530154 if self.sle.voucher_type == "Stock Entry":
155 child_doctype = "Stock Entry Detail"
156
Rohit Waghchaure26b39ac2023-04-06 01:36:18 +0530157 if self.sle.voucher_type == "Asset Capitalization":
158 child_doctype = "Asset Capitalization Stock Item"
159
160 if self.sle.voucher_type == "Asset Repair":
161 child_doctype = "Asset Repair Consumed Item"
162
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530163 return child_doctype
164
165 def is_rejected_entry(self):
166 return is_rejected(self.sle.voucher_type, self.sle.voucher_detail_no, self.sle.warehouse)
167
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530168 def process_batch_no(self):
169 if (
170 not self.sle.is_cancelled
171 and not self.sle.serial_and_batch_bundle
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530172 and self.item_details.has_batch_no == 1
173 and self.item_details.create_new_batch
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530174 ):
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530175 self.make_serial_batch_no_bundle()
176 elif not self.sle.is_cancelled:
177 self.validate_item_and_warehouse()
178
179 def validate_item_and_warehouse(self):
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530180 if self.sle.serial_and_batch_bundle and not frappe.db.exists(
181 "Serial and Batch Bundle",
182 {
183 "name": self.sle.serial_and_batch_bundle,
184 "item_code": self.item_code,
185 "warehouse": self.warehouse,
186 "voucher_no": self.sle.voucher_no,
187 },
188 ):
189 msg = f"""
190 The Serial and Batch Bundle
191 {bold(self.sle.serial_and_batch_bundle)}
192 does not belong to Item {bold(self.item_code)}
193 or Warehouse {bold(self.warehouse)}
194 or {self.sle.voucher_type} no {bold(self.sle.voucher_no)}
195 """
196
197 frappe.throw(_(msg))
198
199 def delink_serial_and_batch_bundle(self):
200 update_values = {
201 "serial_and_batch_bundle": "",
202 }
203
204 if is_rejected(self.sle.voucher_type, self.sle.voucher_detail_no, self.sle.warehouse):
205 update_values["rejected_serial_and_batch_bundle"] = ""
206
207 frappe.db.set_value(self.child_doctype, self.sle.voucher_detail_no, update_values)
208
209 frappe.db.set_value(
210 "Serial and Batch Bundle",
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530211 {"voucher_no": self.sle.voucher_no, "voucher_type": self.sle.voucher_type},
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530212 {"is_cancelled": 1, "voucher_no": ""},
213 )
214
Rohit Waghchauref79f2a32023-04-04 11:50:38 +0530215 if self.sle.serial_and_batch_bundle:
216 frappe.get_cached_doc(
217 "Serial and Batch Bundle", self.sle.serial_and_batch_bundle
218 ).validate_serial_and_batch_inventory()
219
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530220 def post_process(self):
Rohit Waghchaure674bd3e2023-03-17 16:42:59 +0530221 if not self.sle.serial_and_batch_bundle:
222 return
223
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530224 docstatus = frappe.get_cached_value(
225 "Serial and Batch Bundle", self.sle.serial_and_batch_bundle, "docstatus"
226 )
227
228 if docstatus != 1:
229 self.submit_serial_and_batch_bundle()
230
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530231 if self.item_details.has_serial_no == 1:
232 self.set_warehouse_and_status_in_serial_nos()
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530233
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530234 if (
235 self.sle.actual_qty > 0
236 and self.item_details.has_serial_no == 1
237 and self.item_details.has_batch_no == 1
238 ):
239 self.set_batch_no_in_serial_nos()
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530240
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530241 if self.item_details.has_batch_no == 1:
242 self.update_batch_qty()
243
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530244 def submit_serial_and_batch_bundle(self):
245 doc = frappe.get_doc("Serial and Batch Bundle", self.sle.serial_and_batch_bundle)
Rohit Waghchaure42b22942023-05-27 19:18:03 +0530246 self.validate_actual_qty(doc)
247
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530248 doc.flags.ignore_voucher_validation = True
249 doc.submit()
250
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530251 def set_warehouse_and_status_in_serial_nos(self):
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530252 serial_nos = get_serial_nos(self.sle.serial_and_batch_bundle)
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530253 warehouse = self.warehouse if self.sle.actual_qty > 0 else None
254
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530255 if not serial_nos:
256 return
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530257
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530258 sn_table = frappe.qb.DocType("Serial No")
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530259 (
260 frappe.qb.update(sn_table)
261 .set(sn_table.warehouse, warehouse)
262 .set(sn_table.status, "Active" if warehouse else "Inactive")
263 .where(sn_table.name.isin(serial_nos))
264 ).run()
265
266 def set_batch_no_in_serial_nos(self):
Rohit Waghchaure5bb31732023-03-21 10:54:41 +0530267 entries = frappe.get_all(
268 "Serial and Batch Entry",
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530269 fields=["serial_no", "batch_no"],
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530270 filters={"parent": self.sle.serial_and_batch_bundle},
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530271 )
272
273 batch_serial_nos = {}
Rohit Waghchaure5bb31732023-03-21 10:54:41 +0530274 for ledger in entries:
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530275 batch_serial_nos.setdefault(ledger.batch_no, []).append(ledger.serial_no)
276
277 for batch_no, serial_nos in batch_serial_nos.items():
278 sn_table = frappe.qb.DocType("Serial No")
279 (
280 frappe.qb.update(sn_table)
281 .set(sn_table.batch_no, batch_no)
282 .where(sn_table.name.isin(serial_nos))
283 ).run()
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530284
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530285 def update_batch_qty(self):
286 from erpnext.stock.doctype.batch.batch import get_available_batches
287
288 batches = get_batch_nos(self.sle.serial_and_batch_bundle)
289
290 batches_qty = get_available_batches(
291 frappe._dict(
292 {"item_code": self.item_code, "warehouse": self.warehouse, "batch_no": list(batches.keys())}
293 )
294 )
295
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530296 for batch_no in batches:
297 frappe.db.set_value("Batch", batch_no, "batch_qty", batches_qty.get(batch_no, 0))
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530298
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530299
Rohit Waghchaure74ab20f2023-04-03 12:26:12 +0530300def get_serial_nos(serial_and_batch_bundle, serial_nos=None):
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530301 if not serial_and_batch_bundle:
302 return []
303
304 filters = {"parent": serial_and_batch_bundle, "serial_no": ("is", "set")}
Rohit Waghchauref8bf4aa2023-04-02 13:13:42 +0530305 if isinstance(serial_and_batch_bundle, list):
306 filters = {"parent": ("in", serial_and_batch_bundle)}
307
Rohit Waghchaure74ab20f2023-04-03 12:26:12 +0530308 if serial_nos:
309 filters["serial_no"] = ("in", serial_nos)
310
Rohit Waghchaure5bb31732023-03-21 10:54:41 +0530311 entries = frappe.get_all("Serial and Batch Entry", fields=["serial_no"], filters=filters)
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530312 if not entries:
313 return []
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530314
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530315 return [d.serial_no for d in entries if d.serial_no]
316
317
318def get_serial_nos_from_bundle(serial_and_batch_bundle, serial_nos=None):
319 return get_serial_nos(serial_and_batch_bundle, serial_nos=serial_nos)
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530320
321
Rohit Waghchaurebb954512023-06-02 00:11:43 +0530322def get_serial_or_batch_nos(bundle):
Rohit Waghchaure9cf645e2023-06-26 16:00:53 +0530323 # For print format
324
325 bundle_data = frappe.get_cached_value(
326 "Serial and Batch Bundle", bundle, ["has_serial_no", "has_batch_no"], as_dict=True
327 )
328
329 fields = []
330 if bundle_data.has_serial_no:
331 fields.append("serial_no")
332
333 if bundle_data.has_batch_no:
334 fields.extend(["batch_no", "qty"])
335
336 data = frappe.get_all("Serial and Batch Entry", fields=fields, filters={"parent": bundle})
337
338 if bundle_data.has_serial_no and not bundle_data.has_batch_no:
339 return ", ".join([d.serial_no for d in data])
340
341 elif bundle_data.has_batch_no:
342 html = "<table class= 'table table-borderless' style='margin-top: 0px;margin-bottom: 0px;'>"
343 for d in data:
344 if d.serial_no:
345 html += f"<tr><td>{d.batch_no}</th><th>{d.serial_no}</th ><th>{abs(d.qty)}</th></tr>"
346 else:
347 html += f"<tr><td>{d.batch_no}</td><td>{abs(d.qty)}</td></tr>"
348
349 html += "</table>"
350
351 return html
Rohit Waghchaurebb954512023-06-02 00:11:43 +0530352
353
Rohit Waghchaure46704642023-03-23 11:41:20 +0530354class SerialNoValuation(DeprecatedSerialNoValuation):
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530355 def __init__(self, **kwargs):
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530356 for key, value in kwargs.items():
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530357 setattr(self, key, value)
358
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530359 self.calculate_stock_value_change()
360 self.calculate_valuation_rate()
361
362 def calculate_stock_value_change(self):
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530363 if flt(self.sle.actual_qty) > 0:
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530364 self.stock_value_change = frappe.get_cached_value(
365 "Serial and Batch Bundle", self.sle.serial_and_batch_bundle, "total_amount"
366 )
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530367
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530368 else:
Rohit Waghchaure5bb31732023-03-21 10:54:41 +0530369 entries = self.get_serial_no_ledgers()
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530370
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530371 self.serial_no_incoming_rate = defaultdict(float)
372 self.stock_value_change = 0.0
373
Rohit Waghchaure5bb31732023-03-21 10:54:41 +0530374 for ledger in entries:
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530375 self.stock_value_change += ledger.incoming_rate
376 self.serial_no_incoming_rate[ledger.serial_no] += ledger.incoming_rate
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530377
378 self.calculate_stock_value_from_deprecarated_ledgers()
379
380 def get_serial_no_ledgers(self):
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530381 serial_nos = self.get_serial_nos()
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530382 bundle = frappe.qb.DocType("Serial and Batch Bundle")
383 bundle_child = frappe.qb.DocType("Serial and Batch Entry")
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530384
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530385 query = (
386 frappe.qb.from_(bundle)
387 .inner_join(bundle_child)
388 .on(bundle.name == bundle_child.parent)
389 .select(
390 bundle.name,
391 bundle_child.serial_no,
392 (bundle_child.incoming_rate * bundle_child.qty).as_("incoming_rate"),
393 )
394 .where(
395 (bundle.is_cancelled == 0)
396 & (bundle.docstatus == 1)
397 & (bundle_child.serial_no.isin(serial_nos))
Rohit Waghchauref8bf4aa2023-04-02 13:13:42 +0530398 & (bundle.type_of_transaction.isin(["Inward", "Outward"]))
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530399 & (bundle.item_code == self.sle.item_code)
400 & (bundle_child.warehouse == self.sle.warehouse)
401 )
402 .orderby(bundle.posting_date, bundle.posting_time, bundle.creation)
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530403 )
404
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530405 # Important to exclude the current voucher
Rohit Waghchauref8bf4aa2023-04-02 13:13:42 +0530406 if self.sle.voucher_no:
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530407 query = query.where(bundle.voucher_no != self.sle.voucher_no)
408
409 if self.sle.posting_date:
410 if self.sle.posting_time is None:
411 self.sle.posting_time = nowtime()
412
413 timestamp_condition = CombineDatetime(
414 bundle.posting_date, bundle.posting_time
415 ) <= CombineDatetime(self.sle.posting_date, self.sle.posting_time)
416
417 query = query.where(timestamp_condition)
418
419 return query.run(as_dict=True)
420
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530421 def get_serial_nos(self):
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530422 if self.sle.get("serial_nos"):
423 return self.sle.serial_nos
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530424
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530425 return get_serial_nos(self.sle.serial_and_batch_bundle)
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530426
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530427 def calculate_valuation_rate(self):
428 if not hasattr(self, "wh_data"):
429 return
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530430
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530431 new_stock_qty = self.wh_data.qty_after_transaction + self.sle.actual_qty
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530432
433 if new_stock_qty > 0:
434 new_stock_value = (
435 self.wh_data.qty_after_transaction * self.wh_data.valuation_rate
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530436 ) + self.stock_value_change
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530437 if new_stock_value >= 0:
438 # calculate new valuation rate only if stock value is positive
439 # else it remains the same as that of previous entry
440 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
441
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530442 if (
443 not self.wh_data.valuation_rate and self.sle.voucher_detail_no and not self.is_rejected_entry()
444 ):
445 allow_zero_rate = self.sle_self.check_if_allow_zero_valuation_rate(
446 self.sle.voucher_type, self.sle.voucher_detail_no
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530447 )
448 if not allow_zero_rate:
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530449 self.wh_data.valuation_rate = self.sle_self.get_fallback_rate(self.sle)
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530450
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530451 self.wh_data.qty_after_transaction += self.sle.actual_qty
452 self.wh_data.stock_value = flt(self.wh_data.qty_after_transaction) * flt(
453 self.wh_data.valuation_rate
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530454 )
455
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530456 def is_rejected_entry(self):
457 return is_rejected(self.sle.voucher_type, self.sle.voucher_detail_no, self.sle.warehouse)
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530458
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530459 def get_incoming_rate(self):
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530460 return abs(flt(self.stock_value_change) / flt(self.sle.actual_qty))
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530461
Rohit Waghchauref8bf4aa2023-04-02 13:13:42 +0530462 def get_incoming_rate_of_serial_no(self, serial_no):
463 return self.serial_no_incoming_rate.get(serial_no, 0.0)
464
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530465
466def is_rejected(voucher_type, voucher_detail_no, warehouse):
467 if voucher_type in ["Purchase Receipt", "Purchase Invoice"]:
468 return warehouse == frappe.get_cached_value(
469 voucher_type + " Item", voucher_detail_no, "rejected_warehouse"
470 )
471
472 return False
473
474
Rohit Waghchaure46704642023-03-23 11:41:20 +0530475class BatchNoValuation(DeprecatedBatchNoValuation):
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530476 def __init__(self, **kwargs):
477 for key, value in kwargs.items():
478 setattr(self, key, value)
479
480 self.batch_nos = self.get_batch_nos()
Rohit Waghchauref704eb72023-03-30 11:32:39 +0530481 self.prepare_batches()
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530482 self.calculate_avg_rate()
483 self.calculate_valuation_rate()
484
485 def calculate_avg_rate(self):
Rohit Waghchaurec2d74612023-03-29 11:40:36 +0530486 if flt(self.sle.actual_qty) > 0:
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530487 self.stock_value_change = frappe.get_cached_value(
488 "Serial and Batch Bundle", self.sle.serial_and_batch_bundle, "total_amount"
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530489 )
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530490 else:
Rohit Waghchaure5bb31732023-03-21 10:54:41 +0530491 entries = self.get_batch_no_ledgers()
Rohit Waghchaure40ab3bd2023-06-01 16:08:49 +0530492 self.stock_value_change = 0.0
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530493 self.batch_avg_rate = defaultdict(float)
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530494 self.available_qty = defaultdict(float)
Rohit Waghchauref704eb72023-03-30 11:32:39 +0530495 self.stock_value_differece = defaultdict(float)
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530496
Rohit Waghchaure5bb31732023-03-21 10:54:41 +0530497 for ledger in entries:
Rohit Waghchauref704eb72023-03-30 11:32:39 +0530498 self.stock_value_differece[ledger.batch_no] += flt(ledger.incoming_rate)
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530499 self.available_qty[ledger.batch_no] += flt(ledger.qty)
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530500
501 self.calculate_avg_rate_from_deprecarated_ledgers()
Rohit Waghchaure40ab3bd2023-06-01 16:08:49 +0530502 self.calculate_avg_rate_for_non_batchwise_valuation()
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530503 self.set_stock_value_difference()
504
505 def get_batch_no_ledgers(self) -> List[dict]:
Rohit Waghchauref704eb72023-03-30 11:32:39 +0530506 if not self.batchwise_valuation_batches:
507 return []
508
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530509 parent = frappe.qb.DocType("Serial and Batch Bundle")
Rohit Waghchaure5bb31732023-03-21 10:54:41 +0530510 child = frappe.qb.DocType("Serial and Batch Entry")
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530511
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530512 timestamp_condition = ""
513 if self.sle.posting_date and self.sle.posting_time:
514 timestamp_condition = CombineDatetime(
515 parent.posting_date, parent.posting_time
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530516 ) <= CombineDatetime(self.sle.posting_date, self.sle.posting_time)
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530517
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530518 query = (
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530519 frappe.qb.from_(parent)
520 .inner_join(child)
521 .on(parent.name == child.parent)
522 .select(
523 child.batch_no,
524 Sum(child.stock_value_difference).as_("incoming_rate"),
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530525 Sum(child.qty).as_("qty"),
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530526 )
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530527 .where(
Rohit Waghchauref704eb72023-03-30 11:32:39 +0530528 (child.batch_no.isin(self.batchwise_valuation_batches))
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530529 & (parent.warehouse == self.sle.warehouse)
530 & (parent.item_code == self.sle.item_code)
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530531 & (parent.docstatus == 1)
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530532 & (parent.is_cancelled == 0)
Rohit Waghchauref8bf4aa2023-04-02 13:13:42 +0530533 & (parent.type_of_transaction.isin(["Inward", "Outward"]))
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530534 )
535 .groupby(child.batch_no)
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530536 )
537
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530538 # Important to exclude the current voucher
539 if self.sle.voucher_no:
540 query = query.where(parent.voucher_no != self.sle.voucher_no)
Rohit Waghchaurec2d74612023-03-29 11:40:36 +0530541
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530542 if timestamp_condition:
Rohit Waghchaurec2d74612023-03-29 11:40:36 +0530543 query = query.where(timestamp_condition)
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530544
545 return query.run(as_dict=True)
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530546
Rohit Waghchauref704eb72023-03-30 11:32:39 +0530547 def prepare_batches(self):
548 self.batches = self.batch_nos
549 if isinstance(self.batch_nos, dict):
550 self.batches = list(self.batch_nos.keys())
551
552 self.batchwise_valuation_batches = []
553 self.non_batchwise_valuation_batches = []
554
555 batches = frappe.get_all(
556 "Batch", filters={"name": ("in", self.batches), "use_batchwise_valuation": 1}, fields=["name"]
557 )
558
559 for batch in batches:
560 self.batchwise_valuation_batches.append(batch.name)
561
562 self.non_batchwise_valuation_batches = list(
563 set(self.batches) - set(self.batchwise_valuation_batches)
564 )
565
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530566 def get_batch_nos(self) -> list:
567 if self.sle.get("batch_nos"):
568 return self.sle.batch_nos
569
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530570 return get_batch_nos(self.sle.serial_and_batch_bundle)
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530571
572 def set_stock_value_difference(self):
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530573 for batch_no, ledger in self.batch_nos.items():
Rohit Waghchaure40ab3bd2023-06-01 16:08:49 +0530574 if batch_no in self.non_batchwise_valuation_batches:
575 continue
576
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530577 if not self.available_qty[batch_no]:
578 continue
579
Rohit Waghchauref704eb72023-03-30 11:32:39 +0530580 self.batch_avg_rate[batch_no] = (
581 self.stock_value_differece[batch_no] / self.available_qty[batch_no]
582 )
583
584 # New Stock Value Difference
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530585 stock_value_change = self.batch_avg_rate[batch_no] * ledger.qty
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530586 self.stock_value_change += stock_value_change
Rohit Waghchaure40ab3bd2023-06-01 16:08:49 +0530587
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530588 frappe.db.set_value(
Rohit Waghchaure40ab3bd2023-06-01 16:08:49 +0530589 "Serial and Batch Entry",
590 ledger.name,
591 {
592 "stock_value_difference": stock_value_change,
593 "incoming_rate": self.batch_avg_rate[batch_no],
594 },
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530595 )
596
597 def calculate_valuation_rate(self):
598 if not hasattr(self, "wh_data"):
599 return
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530600
601 self.wh_data.stock_value = round_off_if_near_zero(
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530602 self.wh_data.stock_value + self.stock_value_change
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530603 )
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530604
Rohit Waghchaurec2d74612023-03-29 11:40:36 +0530605 self.wh_data.qty_after_transaction += self.sle.actual_qty
Rohit Waghchauref1b59662023-03-06 12:08:28 +0530606 if self.wh_data.qty_after_transaction:
607 self.wh_data.valuation_rate = self.wh_data.stock_value / self.wh_data.qty_after_transaction
608
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530609 def get_incoming_rate(self):
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530610 if not self.sle.actual_qty:
611 self.sle.actual_qty = self.get_actual_qty()
612
Rohit Waghchaure5ddd55a2023-03-16 12:58:48 +0530613 return abs(flt(self.stock_value_change) / flt(self.sle.actual_qty))
Rohit Waghchaure16f26fb2023-03-20 22:56:06 +0530614
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530615 def get_actual_qty(self):
616 total_qty = 0.0
617 for batch_no in self.available_qty:
618 total_qty += self.available_qty[batch_no]
619
620 return total_qty
621
Rohit Waghchaure16f26fb2023-03-20 22:56:06 +0530622
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530623def get_batch_nos(serial_and_batch_bundle):
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530624 if not serial_and_batch_bundle:
625 return frappe._dict({})
626
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530627 entries = frappe.get_all(
628 "Serial and Batch Entry",
629 fields=["batch_no", "qty", "name"],
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530630 filters={"parent": serial_and_batch_bundle, "batch_no": ("is", "set")},
Rohit Waghchaurec2d74612023-03-29 11:40:36 +0530631 order_by="idx",
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530632 )
633
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530634 if not entries:
635 return frappe._dict({})
636
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530637 return {d.batch_no: d for d in entries}
638
639
Rohit Waghchaure16f26fb2023-03-20 22:56:06 +0530640def get_empty_batches_based_work_order(work_order, item_code):
Rohit Waghchaure46704642023-03-23 11:41:20 +0530641 batches = get_batches_from_work_order(work_order, item_code)
Rohit Waghchaure16f26fb2023-03-20 22:56:06 +0530642 if not batches:
643 return batches
644
Rohit Waghchaure46704642023-03-23 11:41:20 +0530645 entries = get_batches_from_stock_entries(work_order, item_code)
Rohit Waghchaure16f26fb2023-03-20 22:56:06 +0530646 if not entries:
647 return batches
648
649 ids = [d.serial_and_batch_bundle for d in entries if d.serial_and_batch_bundle]
650 if ids:
651 set_batch_details_from_package(ids, batches)
652
653 # Will be deprecated in v16
654 for d in entries:
655 if not d.batch_no:
656 continue
657
658 batches[d.batch_no] -= d.qty
659
660 return batches
661
662
Rohit Waghchaure46704642023-03-23 11:41:20 +0530663def get_batches_from_work_order(work_order, item_code):
Rohit Waghchaure16f26fb2023-03-20 22:56:06 +0530664 return frappe._dict(
665 frappe.get_all(
Rohit Waghchaure46704642023-03-23 11:41:20 +0530666 "Batch",
667 fields=["name", "qty_to_produce"],
668 filters={"reference_name": work_order, "item": item_code},
669 as_list=1,
Rohit Waghchaure16f26fb2023-03-20 22:56:06 +0530670 )
671 )
672
673
Rohit Waghchaure46704642023-03-23 11:41:20 +0530674def get_batches_from_stock_entries(work_order, item_code):
Rohit Waghchaure16f26fb2023-03-20 22:56:06 +0530675 entries = frappe.get_all(
676 "Stock Entry",
677 filters={"work_order": work_order, "docstatus": 1, "purpose": "Manufacture"},
678 fields=["name"],
679 )
680
681 return frappe.get_all(
682 "Stock Entry Detail",
683 fields=["batch_no", "qty", "serial_and_batch_bundle"],
684 filters={
685 "parent": ("in", [d.name for d in entries]),
686 "is_finished_item": 1,
Rohit Waghchaure46704642023-03-23 11:41:20 +0530687 "item_code": item_code,
Rohit Waghchaure16f26fb2023-03-20 22:56:06 +0530688 },
689 )
690
691
692def set_batch_details_from_package(ids, batches):
693 entries = frappe.get_all(
Rohit Waghchaure5bb31732023-03-21 10:54:41 +0530694 "Serial and Batch Entry",
Rohit Waghchaure16f26fb2023-03-20 22:56:06 +0530695 filters={"parent": ("in", ids), "is_outward": 0},
696 fields=["batch_no", "qty"],
697 )
698
699 for d in entries:
700 batches[d.batch_no] -= d.qty
Rohit Waghchaure46704642023-03-23 11:41:20 +0530701
702
703class SerialBatchCreation:
704 def __init__(self, args):
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530705 self.set(args)
706 self.set_item_details()
Rohit Waghchaure9b728452023-03-28 14:03:59 +0530707 self.set_other_details()
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530708
709 def set(self, args):
710 self.__dict__ = {}
Rohit Waghchaure46704642023-03-23 11:41:20 +0530711 for key, value in args.items():
712 setattr(self, key, value)
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530713 self.__dict__[key] = value
714
715 def get(self, key):
716 return self.__dict__.get(key)
717
718 def set_item_details(self):
719 fields = [
720 "has_batch_no",
721 "has_serial_no",
722 "item_name",
723 "item_group",
724 "serial_no_series",
725 "create_new_batch",
726 "batch_number_series",
727 "description",
728 ]
729
730 item_details = frappe.get_cached_value("Item", self.item_code, fields, as_dict=1)
731 for key, value in item_details.items():
732 setattr(self, key, value)
733
734 self.__dict__.update(item_details)
Rohit Waghchaure46704642023-03-23 11:41:20 +0530735
Rohit Waghchaure9b728452023-03-28 14:03:59 +0530736 def set_other_details(self):
737 if not self.get("posting_date"):
738 setattr(self, "posting_date", today())
739 self.__dict__["posting_date"] = self.posting_date
740
Rohit Waghchaurec2d74612023-03-29 11:40:36 +0530741 if not self.get("actual_qty"):
742 qty = self.get("qty") or self.get("total_qty")
743
744 setattr(self, "actual_qty", qty)
745 self.__dict__["actual_qty"] = self.actual_qty
746
Rohit Waghchaure46704642023-03-23 11:41:20 +0530747 def duplicate_package(self):
748 if not self.serial_and_batch_bundle:
749 return
750
751 id = self.serial_and_batch_bundle
752 package = frappe.get_doc("Serial and Batch Bundle", id)
753 new_package = frappe.copy_doc(package)
Rohit Waghchauref8bf4aa2023-04-02 13:13:42 +0530754
755 if self.get("returned_serial_nos"):
756 self.remove_returned_serial_nos(new_package)
757
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530758 new_package.docstatus = 0
Rohit Waghchaure46704642023-03-23 11:41:20 +0530759 new_package.type_of_transaction = self.type_of_transaction
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530760 new_package.returned_against = self.get("returned_against")
Rohit Waghchaure46704642023-03-23 11:41:20 +0530761 new_package.save()
762
763 self.serial_and_batch_bundle = new_package.name
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530764
Rohit Waghchauref8bf4aa2023-04-02 13:13:42 +0530765 def remove_returned_serial_nos(self, package):
766 remove_list = []
767 for d in package.entries:
768 if d.serial_no in self.returned_serial_nos:
769 remove_list.append(d)
770
771 for d in remove_list:
772 package.remove(d)
773
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530774 def make_serial_and_batch_bundle(self):
775 doc = frappe.new_doc("Serial and Batch Bundle")
776 valid_columns = doc.meta.get_valid_columns()
777 for key, value in self.__dict__.items():
778 if key in valid_columns:
779 doc.set(key, value)
780
781 if self.type_of_transaction == "Outward":
782 self.set_auto_serial_batch_entries_for_outward()
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530783 elif self.type_of_transaction == "Inward":
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530784 self.set_auto_serial_batch_entries_for_inward()
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530785 self.add_serial_nos_for_batch_item()
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530786
787 self.set_serial_batch_entries(doc)
Rohit Waghchauref8bf4aa2023-04-02 13:13:42 +0530788 if not doc.get("entries"):
789 return frappe._dict({})
790
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530791 doc.save()
Rohit Waghchauredcb04622023-06-05 16:56:29 +0530792 self.validate_qty(doc)
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530793
794 if not hasattr(self, "do_not_submit") or not self.do_not_submit:
Rohit Waghchaurec2d74612023-03-29 11:40:36 +0530795 doc.flags.ignore_voucher_validation = True
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530796 doc.submit()
797
798 return doc
799
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530800 def add_serial_nos_for_batch_item(self):
801 if not (self.has_serial_no and self.has_batch_no):
802 return
803
804 if not self.get("serial_nos") and self.get("batches"):
805 batches = list(self.get("batches").keys())
806 if len(batches) == 1:
807 self.batch_no = batches[0]
808 self.serial_nos = self.get_auto_created_serial_nos()
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530809
Rohit Waghchaure74ab20f2023-04-03 12:26:12 +0530810 def update_serial_and_batch_entries(self):
811 doc = frappe.get_doc("Serial and Batch Bundle", self.serial_and_batch_bundle)
812 doc.type_of_transaction = self.type_of_transaction
813 doc.set("entries", [])
814 self.set_auto_serial_batch_entries_for_outward()
815 self.set_serial_batch_entries(doc)
816 if not doc.get("entries"):
817 return frappe._dict({})
818
819 doc.save()
820 return doc
821
Rohit Waghchauredcb04622023-06-05 16:56:29 +0530822 def validate_qty(self, doc):
823 if doc.type_of_transaction == "Outward":
824 precision = doc.precision("total_qty")
825
826 total_qty = abs(flt(doc.total_qty, precision))
827 required_qty = abs(flt(self.actual_qty, precision))
828
829 if required_qty - total_qty > 0:
830 msg = f"For the item {bold(doc.item_code)}, the Avaliable qty {bold(total_qty)} is less than the Required Qty {bold(required_qty)} in the warehouse {bold(doc.warehouse)}. Please add sufficient qty in the warehouse."
831 frappe.throw(msg, title=_("Insufficient Stock"))
832
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530833 def set_auto_serial_batch_entries_for_outward(self):
834 from erpnext.stock.doctype.batch.batch import get_available_batches
835 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos_for_outward
836
837 kwargs = frappe._dict(
838 {
839 "item_code": self.item_code,
840 "warehouse": self.warehouse,
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530841 "qty": abs(self.actual_qty) if self.actual_qty else 0,
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530842 "based_on": frappe.db.get_single_value("Stock Settings", "pick_serial_and_batch_based_on"),
843 }
844 )
845
Rohit Waghchaure74ab20f2023-04-03 12:26:12 +0530846 if self.get("ignore_serial_nos"):
847 kwargs["ignore_serial_nos"] = self.ignore_serial_nos
848
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530849 if self.has_serial_no and not self.get("serial_nos"):
850 self.serial_nos = get_serial_nos_for_outward(kwargs)
Rohit Waghchaure9b728452023-03-28 14:03:59 +0530851 elif not self.has_serial_no and self.has_batch_no and not self.get("batches"):
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530852 self.batches = get_available_batches(kwargs)
853
854 def set_auto_serial_batch_entries_for_inward(self):
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530855 if (self.get("batches") and self.has_batch_no) or (
856 self.get("serial_nos") and self.has_serial_no
857 ):
858 return
859
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530860 self.batch_no = None
861 if self.has_batch_no:
862 self.batch_no = self.create_batch()
863
864 if self.has_serial_no:
865 self.serial_nos = self.get_auto_created_serial_nos()
866 else:
Rohit Waghchaurec2d74612023-03-29 11:40:36 +0530867 self.batches = frappe._dict({self.batch_no: abs(self.actual_qty)})
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530868
869 def set_serial_batch_entries(self, doc):
870 if self.get("serial_nos"):
871 serial_no_wise_batch = frappe._dict({})
872 if self.has_batch_no:
s-aga-r2d8363a2023-09-02 11:02:24 +0530873 serial_no_wise_batch = get_serial_nos_batch(self.serial_nos)
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530874
875 qty = -1 if self.type_of_transaction == "Outward" else 1
876 for serial_no in self.serial_nos:
877 doc.append(
878 "entries",
879 {
880 "serial_no": serial_no,
881 "qty": qty,
882 "batch_no": serial_no_wise_batch.get(serial_no) or self.get("batch_no"),
883 "incoming_rate": self.get("incoming_rate"),
884 },
885 )
886
Rohit Waghchauree88c5d62023-04-05 20:03:44 +0530887 elif self.get("batches"):
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530888 for batch_no, batch_qty in self.batches.items():
889 doc.append(
890 "entries",
891 {
892 "batch_no": batch_no,
893 "qty": batch_qty * (-1 if self.type_of_transaction == "Outward" else 1),
894 "incoming_rate": self.get("incoming_rate"),
895 },
896 )
897
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530898 def create_batch(self):
899 from erpnext.stock.doctype.batch.batch import make_batch
900
901 return make_batch(
902 frappe._dict(
903 {
Rohit Waghchaurec2d74612023-03-29 11:40:36 +0530904 "item": self.get("item_code"),
905 "reference_doctype": self.get("voucher_type"),
906 "reference_name": self.get("voucher_no"),
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530907 }
908 )
909 )
910
911 def get_auto_created_serial_nos(self):
912 sr_nos = []
913 serial_nos_details = []
914
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530915 if not self.serial_no_series:
916 msg = f"Please set Serial No Series in the item {self.item_code} or create Serial and Batch Bundle manually."
917 frappe.throw(_(msg))
918
Rohit Waghchaurec2d74612023-03-29 11:40:36 +0530919 for i in range(abs(cint(self.actual_qty))):
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530920 serial_no = make_autoname(self.serial_no_series, "Serial No")
921 sr_nos.append(serial_no)
922 serial_nos_details.append(
923 (
924 serial_no,
925 serial_no,
926 now(),
927 now(),
928 frappe.session.user,
929 frappe.session.user,
930 self.warehouse,
931 self.company,
932 self.item_code,
933 self.item_name,
934 self.description,
935 "Active",
936 self.batch_no,
937 )
938 )
939
940 if serial_nos_details:
941 fields = [
942 "name",
943 "serial_no",
944 "creation",
945 "modified",
946 "owner",
947 "modified_by",
948 "warehouse",
949 "company",
950 "item_code",
951 "item_name",
952 "description",
953 "status",
954 "batch_no",
955 ]
956
957 frappe.db.bulk_insert("Serial No", fields=fields, values=set(serial_nos_details))
958
959 return sr_nos
960
961
962def get_serial_or_batch_items(items):
963 serial_or_batch_items = frappe.get_all(
964 "Item",
965 filters={"name": ("in", [d.item_code for d in items])},
966 or_filters={"has_serial_no": 1, "has_batch_no": 1},
967 )
968
969 if not serial_or_batch_items:
970 return
971 else:
972 serial_or_batch_items = [d.name for d in serial_or_batch_items]
973
974 return serial_or_batch_items
s-aga-r2d8363a2023-09-02 11:02:24 +0530975
976
977def get_serial_nos_batch(serial_nos):
978 return frappe._dict(
979 frappe.get_all(
980 "Serial No",
981 fields=["name", "batch_no"],
982 filters={"name": ("in", serial_nos)},
983 as_list=1,
984 )
985 )