blob: 5f11c59917b7efe54cd3ef7a13115972da067370 [file] [log] [blame]
Anand Doshi885e0742015-03-03 14:55:30 +05301# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
Rushabh Mehtae67d1fb2013-08-05 14:59:54 +05302# License: GNU General Public License v3. See license.txt
Nabin Haitc3afb252013-03-19 12:01:24 +05303
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05304import json
marinationfac40352020-12-07 21:35:49 +05305from collections import defaultdict
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05306
7import frappe
rohitwaghchaure8fdc2442024-01-27 21:37:58 +05308from frappe import _, bold
rohitwaghchaure4b24fcd2024-02-20 23:45:07 +05309from frappe.utils import cint, cstr, flt, get_link_to_form, getdate
Rohan Bansal7f8b95e2021-04-14 14:12:03 +053010
11import erpnext
Chillar Anand915b3432021-09-02 16:44:59 +053012from erpnext.accounts.general_ledger import (
13 make_gl_entries,
14 make_reverse_gl_entries,
15 process_gl_map,
16)
ruthra kumar46ea8142023-07-28 08:29:19 +053017from erpnext.accounts.utils import cancel_exchange_gain_loss_journal, get_fiscal_year
Rushabh Mehta1f847992013-12-12 19:12:19 +053018from erpnext.controllers.accounts_controller import AccountsController
Nabin Hait6d7b0ce2017-06-15 11:09:27 +053019from erpnext.stock import get_warehouse_account_map
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +053020from erpnext.stock.doctype.inventory_dimension.inventory_dimension import (
21 get_evaluated_inventory_dimension,
22)
Rohit Waghchaure01650122024-02-06 13:31:36 +053023from erpnext.stock.doctype.serial_and_batch_bundle.serial_and_batch_bundle import (
24 get_type_of_transaction,
25)
Ankush Menat8f577242022-01-07 11:10:23 +053026from erpnext.stock.stock_ledger import get_items_to_be_repost
Rohan Bansal7f8b95e2021-04-14 14:12:03 +053027
Nabin Haitc3afb252013-03-19 12:01:24 +053028
Ankush Menat494bd9e2022-03-28 18:52:46 +053029class QualityInspectionRequiredError(frappe.ValidationError):
30 pass
31
32
33class QualityInspectionRejectedError(frappe.ValidationError):
34 pass
35
36
37class QualityInspectionNotSubmittedError(frappe.ValidationError):
38 pass
39
Nabin Hait5a9579b2018-12-24 14:54:42 +053040
Rohit Waghchaure795c9432022-08-17 13:48:56 +053041class BatchExpiredError(frappe.ValidationError):
42 pass
43
44
Nabin Haitc3afb252013-03-19 12:01:24 +053045class StockController(AccountsController):
Nabin Hait8af429d2016-11-16 17:21:59 +053046 def validate(self):
Akhil Narang3effaf22024-03-27 11:37:26 +053047 super().validate()
s-aga-r094ecc12024-02-12 17:36:14 +053048
49 if self.docstatus == 0:
Rohit Waghchaure34233342024-03-21 20:28:16 +053050 for table_name in ["items", "packed_items", "supplied_items"]:
51 self.validate_duplicate_serial_and_batch_bundle(table_name)
52
Ankush Menat494bd9e2022-03-28 18:52:46 +053053 if not self.get("is_return"):
marination596560c2020-06-11 16:39:03 +053054 self.validate_inspection()
rohitwaghchaure9af557f2019-12-30 13:26:47 +053055 self.validate_serialized_batch()
marinationeecfc4c2021-07-22 13:23:54 +053056 self.clean_serial_nos()
marinationfd04e962020-04-03 15:46:48 +053057 self.validate_customer_provided_item()
Anupam Kumar7e1dcf92021-02-11 20:19:30 +053058 self.set_rate_of_stock_uom()
Deepesh Gargb4be2922021-01-28 13:09:56 +053059 self.validate_internal_transfer()
marinationfac40352020-12-07 21:35:49 +053060 self.validate_putaway_capacity()
Rushabh Mehtaffd80a62017-01-16 17:23:20 +053061
Rohit Waghchaure34233342024-03-21 20:28:16 +053062 def validate_duplicate_serial_and_batch_bundle(self, table_name):
63 if not self.get(table_name):
64 return
65
66 sbb_list = []
67 for item in self.get(table_name):
68 if item.get("serial_and_batch_bundle"):
69 sbb_list.append(item.get("serial_and_batch_bundle"))
70
71 if item.get("rejected_serial_and_batch_bundle"):
72 sbb_list.append(item.get("rejected_serial_and_batch_bundle"))
73
74 if sbb_list:
s-aga-r094ecc12024-02-12 17:36:14 +053075 SLE = frappe.qb.DocType("Stock Ledger Entry")
76 data = (
77 frappe.qb.from_(SLE)
78 .select(SLE.voucher_type, SLE.voucher_no, SLE.serial_and_batch_bundle)
79 .where(
80 (SLE.docstatus == 1)
81 & (SLE.serial_and_batch_bundle.notnull())
82 & (SLE.serial_and_batch_bundle.isin(sbb_list))
83 )
84 .limit(1)
85 ).run(as_dict=True)
86
87 if data:
88 data = data[0]
89 frappe.throw(
90 _("Serial and Batch Bundle {0} is already used in {1} {2}.").format(
91 frappe.bold(data.serial_and_batch_bundle), data.voucher_type, data.voucher_no
92 )
93 )
94
Nabin Haita77b8c92020-12-21 14:45:50 +053095 def make_gl_entries(self, gl_entries=None, from_repost=False):
Anand Doshif78d1ae2014-03-28 13:55:00 +053096 if self.docstatus == 2:
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053097 make_reverse_gl_entries(voucher_type=self.doctype, voucher_no=self.name)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053098
Ankush Menat494bd9e2022-03-28 18:52:46 +053099 provisional_accounting_for_non_stock_items = cint(
Daizy Modi4efc9472022-11-07 09:21:03 +0530100 frappe.get_cached_value(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530101 "Company", self.company, "enable_provisional_accounting_for_non_stock_items"
102 )
103 )
Deepesh Garg528c7132022-02-01 14:42:55 +0530104
Deepesh Gargd1ec0a62023-10-23 00:16:40 +0530105 is_asset_pr = any(d.get("is_fixed_asset") for d in self.get("items"))
106
Ankush Menat494bd9e2022-03-28 18:52:46 +0530107 if (
108 cint(erpnext.is_perpetual_inventory_enabled(self.company))
109 or provisional_accounting_for_non_stock_items
Deepesh Gargd1ec0a62023-10-23 00:16:40 +0530110 or is_asset_pr
Ankush Menat494bd9e2022-03-28 18:52:46 +0530111 ):
Rohit Waghchaure6b33c9b2019-03-08 11:13:35 +0530112 warehouse_account = get_warehouse_account_map(self.company)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530113
Ankush Menat494bd9e2022-03-28 18:52:46 +0530114 if self.docstatus == 1:
Nabin Hait9784d272016-12-30 16:21:35 +0530115 if not gl_entries:
116 gl_entries = self.get_gl_entries(warehouse_account)
Nabin Haita77b8c92020-12-21 14:45:50 +0530117 make_gl_entries(gl_entries, from_repost=from_repost)
Nabin Hait145e5e22013-10-22 23:51:41 +0530118
rohitwaghchaure9af557f2019-12-30 13:26:47 +0530119 def validate_serialized_batch(self):
120 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
Ankush Menat494bd9e2022-03-28 18:52:46 +0530121
Rohit Waghchaure795c9432022-08-17 13:48:56 +0530122 is_material_issue = False
123 if self.doctype == "Stock Entry" and self.purpose == "Material Issue":
124 is_material_issue = True
125
rohitwaghchaure9af557f2019-12-30 13:26:47 +0530126 for d in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530127 if hasattr(d, "serial_no") and hasattr(d, "batch_no") and d.serial_no and d.batch_no:
128 serial_nos = frappe.get_all(
129 "Serial No",
Rohit Waghchaure6b482eb2021-07-23 16:40:45 +0530130 fields=["batch_no", "name", "warehouse"],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530131 filters={"name": ("in", get_serial_nos(d.serial_no))},
Rohit Waghchaure6b482eb2021-07-23 16:40:45 +0530132 )
133
134 for row in serial_nos:
135 if row.warehouse and row.batch_no != d.batch_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530136 frappe.throw(
137 _("Row #{0}: Serial No {1} does not belong to Batch {2}").format(
138 d.idx, row.name, d.batch_no
139 )
140 )
rohitwaghchaure9af557f2019-12-30 13:26:47 +0530141
Rohit Waghchaure795c9432022-08-17 13:48:56 +0530142 if is_material_issue:
143 continue
144
Saqib Ansari903055b2020-10-20 11:59:06 +0530145 if flt(d.qty) > 0.0 and d.get("batch_no") and self.get("posting_date") and self.docstatus < 2:
rohitwaghchaure28a48802020-04-28 13:01:43 +0530146 expiry_date = frappe.get_cached_value("Batch", d.get("batch_no"), "expiry_date")
147
148 if expiry_date and getdate(expiry_date) < getdate(self.posting_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530149 frappe.throw(
150 _("Row #{0}: The batch {1} has already expired.").format(
151 d.idx, get_link_to_form("Batch", d.get("batch_no"))
Rohit Waghchaure795c9432022-08-17 13:48:56 +0530152 ),
153 BatchExpiredError,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530154 )
rohitwaghchaure28a48802020-04-28 13:01:43 +0530155
marinationeecfc4c2021-07-22 13:23:54 +0530156 def clean_serial_nos(self):
Ankush Menatb20df372022-01-24 19:19:58 +0530157 from erpnext.stock.doctype.serial_no.serial_no import clean_serial_no_string
158
marinationeecfc4c2021-07-22 13:23:54 +0530159 for row in self.get("items"):
160 if hasattr(row, "serial_no") and row.serial_no:
Ankush Menatb20df372022-01-24 19:19:58 +0530161 # remove extra whitespace and store one serial no on each line
162 row.serial_no = clean_serial_no_string(row.serial_no)
marinationeecfc4c2021-07-22 13:23:54 +0530163
Ankush Menat494bd9e2022-03-28 18:52:46 +0530164 for row in self.get("packed_items") or []:
Ankush Menate177c522022-01-24 19:28:26 +0530165 if hasattr(row, "serial_no") and row.serial_no:
166 # remove extra whitespace and store one serial no on each line
167 row.serial_no = clean_serial_no_string(row.serial_no)
168
rohitwaghchaurebc9c4802024-02-26 23:57:52 +0530169 def make_bundle_using_old_serial_batch_fields(self, table_name=None):
rohitwaghchaurea4cbfab2024-02-19 10:25:36 +0530170 if self.get("_action") == "update_after_submit":
171 return
172
Rohit Waghchaurec1e869f2024-02-05 12:40:26 +0530173 # To handle test cases
174 if frappe.flags.in_test and frappe.flags.use_serial_and_batch_fields:
175 return
176
rohitwaghchaurebc9c4802024-02-26 23:57:52 +0530177 if not table_name:
178 table_name = "items"
179
Rohit Waghchaurec1e869f2024-02-05 12:40:26 +0530180 if self.doctype == "Asset Capitalization":
181 table_name = "stock_items"
182
183 for row in self.get(table_name):
rohitwaghchaure4b24fcd2024-02-20 23:45:07 +0530184 if row.serial_and_batch_bundle and (row.serial_no or row.batch_no):
185 self.validate_serial_nos_and_batches_with_bundle(row)
186
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530187 if not row.serial_no and not row.batch_no and not row.get("rejected_serial_no"):
188 continue
189
190 if not row.use_serial_batch_fields and (
191 row.serial_no or row.batch_no or row.get("rejected_serial_no")
192 ):
rohitwaghchaure4b24fcd2024-02-20 23:45:07 +0530193 row.use_serial_batch_fields = 1
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530194
195 if row.use_serial_batch_fields and (
Rohit Waghchaurec1e869f2024-02-05 12:40:26 +0530196 not row.serial_and_batch_bundle and not row.get("rejected_serial_and_batch_bundle")
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530197 ):
rohitwaghchaurecef62912024-03-06 19:43:36 +0530198 bundle_details = {
Rohit Waghchaure34233342024-03-21 20:28:16 +0530199 "item_code": row.get("rm_item_code") or row.item_code,
rohitwaghchaurecef62912024-03-06 19:43:36 +0530200 "posting_date": self.posting_date,
201 "posting_time": self.posting_time,
202 "voucher_type": self.doctype,
203 "voucher_no": self.name,
204 "voucher_detail_no": row.name,
205 "company": self.company,
206 "is_rejected": 1 if row.get("rejected_warehouse") else 0,
rohitwaghchaurecef62912024-03-06 19:43:36 +0530207 "use_serial_batch_fields": row.use_serial_batch_fields,
208 "do_not_submit": True,
209 }
Rohit Waghchaure01650122024-02-06 13:31:36 +0530210
Rohit Waghchaure34233342024-03-21 20:28:16 +0530211 if row.get("qty") or row.get("consumed_qty"):
rohitwaghchaure01856a62024-03-07 14:14:19 +0530212 self.update_bundle_details(bundle_details, table_name, row)
213 self.create_serial_batch_bundle(bundle_details, row)
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530214
rohitwaghchaure01856a62024-03-07 14:14:19 +0530215 if row.get("rejected_qty"):
216 self.update_bundle_details(bundle_details, table_name, row, is_rejected=True)
217 self.create_serial_batch_bundle(bundle_details, row)
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530218
rohitwaghchaure01856a62024-03-07 14:14:19 +0530219 def update_bundle_details(self, bundle_details, table_name, row, is_rejected=False):
220 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
221
rohitwaghchaurecef62912024-03-06 19:43:36 +0530222 # Since qty field is different for different doctypes
223 qty = row.get("qty")
224 warehouse = row.get("warehouse")
225
226 if table_name == "packed_items":
227 type_of_transaction = "Inward"
228 if not self.is_return:
229 type_of_transaction = "Outward"
Rohit Waghchaure34233342024-03-21 20:28:16 +0530230 elif table_name == "supplied_items":
231 qty = row.consumed_qty
232 warehouse = self.supplier_warehouse
233 type_of_transaction = "Outward"
234 if self.is_return:
235 type_of_transaction = "Inward"
rohitwaghchaurecef62912024-03-06 19:43:36 +0530236 else:
237 type_of_transaction = get_type_of_transaction(self, row)
238
239 if hasattr(row, "stock_qty"):
240 qty = row.stock_qty
241
242 if self.doctype == "Stock Entry":
243 qty = row.transfer_qty
244 warehouse = row.s_warehouse or row.t_warehouse
245
rohitwaghchaure01856a62024-03-07 14:14:19 +0530246 serial_nos = row.serial_no
247 if is_rejected:
248 serial_nos = row.get("rejected_serial_no")
249 type_of_transaction = "Inward" if not self.is_return else "Outward"
250 qty = row.get("rejected_qty")
251 warehouse = row.get("rejected_warehouse")
252
rohitwaghchaure59222812024-03-15 17:55:41 +0530253 if (
254 self.is_internal_transfer()
255 and self.doctype in ["Sales Invoice", "Delivery Note"]
256 and self.is_return
257 ):
258 warehouse = row.get("target_warehouse") or row.get("warehouse")
259 type_of_transaction = "Outward"
260
rohitwaghchaurecef62912024-03-06 19:43:36 +0530261 bundle_details.update(
262 {
263 "qty": qty,
rohitwaghchaure01856a62024-03-07 14:14:19 +0530264 "is_rejected": is_rejected,
rohitwaghchaurecef62912024-03-06 19:43:36 +0530265 "type_of_transaction": type_of_transaction,
266 "warehouse": warehouse,
267 "batches": frappe._dict({row.batch_no: qty}) if row.batch_no else None,
rohitwaghchaure01856a62024-03-07 14:14:19 +0530268 "serial_nos": get_serial_nos(serial_nos) if serial_nos else None,
269 "batch_no": row.batch_no,
rohitwaghchaurecef62912024-03-06 19:43:36 +0530270 }
271 )
272
rohitwaghchaure01856a62024-03-07 14:14:19 +0530273 def create_serial_batch_bundle(self, bundle_details, row):
274 from erpnext.stock.serial_batch_bundle import SerialBatchCreation
275
276 sn_doc = SerialBatchCreation(bundle_details).make_serial_and_batch_bundle()
277
278 field = "serial_and_batch_bundle"
279 if bundle_details.get("is_rejected"):
280 field = "rejected_serial_and_batch_bundle"
281
282 row.set(field, sn_doc.name)
283 row.db_set({field: sn_doc.name})
284
rohitwaghchaure4b24fcd2024-02-20 23:45:07 +0530285 def validate_serial_nos_and_batches_with_bundle(self, row):
286 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
287
288 throw_error = False
289 if row.serial_no:
290 serial_nos = frappe.get_all(
Akhil Narang3effaf22024-03-27 11:37:26 +0530291 "Serial and Batch Entry",
292 fields=["serial_no"],
293 filters={"parent": row.serial_and_batch_bundle},
rohitwaghchaure4b24fcd2024-02-20 23:45:07 +0530294 )
295 serial_nos = sorted([cstr(d.serial_no) for d in serial_nos])
296 parsed_serial_nos = get_serial_nos(row.serial_no)
297
298 if len(serial_nos) != len(parsed_serial_nos):
299 throw_error = True
300 elif serial_nos != parsed_serial_nos:
301 for serial_no in serial_nos:
302 if serial_no not in parsed_serial_nos:
303 throw_error = True
304 break
305
306 elif row.batch_no:
307 batches = frappe.get_all(
308 "Serial and Batch Entry", fields=["batch_no"], filters={"parent": row.serial_and_batch_bundle}
309 )
310 batches = sorted([d.batch_no for d in batches])
311
312 if batches != [row.batch_no]:
313 throw_error = True
314
315 if throw_error:
316 frappe.throw(
317 _(
318 "At row {0}: Serial and Batch Bundle {1} has already created. Please remove the values from the serial no or batch no fields."
319 ).format(row.idx, row.serial_and_batch_bundle)
320 )
321
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530322 def set_use_serial_batch_fields(self):
323 if frappe.db.get_single_value("Stock Settings", "use_serial_batch_fields"):
324 for row in self.items:
325 row.use_serial_batch_fields = 1
326
Akhil Narang3effaf22024-03-27 11:37:26 +0530327 def get_gl_entries(self, warehouse_account=None, default_expense_account=None, default_cost_center=None):
Nabin Hait142007a2013-09-17 15:15:16 +0530328 if not warehouse_account:
Rohit Waghchaure6b33c9b2019-03-08 11:13:35 +0530329 warehouse_account = get_warehouse_account_map(self.company)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530330
Anand Doshide1a97d2014-04-17 11:37:46 +0530331 sle_map = self.get_stock_ledger_details()
332 voucher_details = self.get_voucher_details(default_expense_account, default_cost_center, sle_map)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530333
Nabin Hait2e296fa2013-08-28 18:53:11 +0530334 gl_list = []
Nabin Hait7a75e102013-09-17 10:21:20 +0530335 warehouse_with_no_account = []
Nabin Hait19f8fa52021-02-22 22:27:22 +0530336 precision = self.get_debit_field_precision()
Nabin Hait8c61f342016-12-15 13:46:03 +0530337 for item_row in voucher_details:
338 sle_list = sle_map.get(item_row.name)
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530339 sle_rounding_diff = 0.0
Nabin Hait2e296fa2013-08-28 18:53:11 +0530340 if sle_list:
341 for sle in sle_list:
342 if warehouse_account.get(sle.warehouse):
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530343 # from warehouse account
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530344
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530345 sle_rounding_diff += flt(sle.stock_value_difference)
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530346
Nabin Hait8c61f342016-12-15 13:46:03 +0530347 self.check_expense_account(item_row)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530348
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530349 # expense account/ target_warehouse / source_warehouse
Ankush Menat494bd9e2022-03-28 18:52:46 +0530350 if item_row.get("target_warehouse"):
351 warehouse = item_row.get("target_warehouse")
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530352 expense_account = warehouse_account[warehouse]["account"]
353 else:
354 expense_account = item_row.expense_account
355
Ankush Menat494bd9e2022-03-28 18:52:46 +0530356 gl_list.append(
357 self.get_gl_dict(
358 {
359 "account": warehouse_account[sle.warehouse]["account"],
360 "against": expense_account,
361 "cost_center": item_row.cost_center,
362 "project": item_row.project or self.get("project"),
363 "remarks": self.get("remarks") or _("Accounting Entry for Stock"),
364 "debit": flt(sle.stock_value_difference, precision),
Akhil Narang3effaf22024-03-27 11:37:26 +0530365 "is_opening": item_row.get("is_opening")
366 or self.get("is_opening")
367 or "No",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530368 },
369 warehouse_account[sle.warehouse]["account_currency"],
370 item=item_row,
371 )
372 )
Nabin Hait27994c22013-08-26 16:53:30 +0530373
Ankush Menat494bd9e2022-03-28 18:52:46 +0530374 gl_list.append(
375 self.get_gl_dict(
376 {
377 "account": expense_account,
378 "against": warehouse_account[sle.warehouse]["account"],
379 "cost_center": item_row.cost_center,
380 "remarks": self.get("remarks") or _("Accounting Entry for Stock"),
Ankush Menat65b21ee2022-06-07 14:49:24 +0530381 "debit": -1 * flt(sle.stock_value_difference, precision),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530382 "project": item_row.get("project") or self.get("project"),
Akhil Narang3effaf22024-03-27 11:37:26 +0530383 "is_opening": item_row.get("is_opening")
384 or self.get("is_opening")
385 or "No",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530386 },
387 item=item_row,
388 )
389 )
Nabin Hait7a75e102013-09-17 10:21:20 +0530390 elif sle.warehouse not in warehouse_with_no_account:
391 warehouse_with_no_account.append(sle.warehouse)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530392
Deepesh Garg9aa5e202022-10-12 15:53:28 +0530393 if abs(sle_rounding_diff) > (1.0 / (10**precision)) and self.is_internal_transfer():
Deepesh Garg1c05c002022-10-12 14:19:09 +0530394 warehouse_asset_account = ""
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530395 if self.get("is_internal_customer"):
Deepesh Garg1c05c002022-10-12 14:19:09 +0530396 warehouse_asset_account = warehouse_account[item_row.get("target_warehouse")]["account"]
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530397 elif self.get("is_internal_supplier"):
Deepesh Garg1c05c002022-10-12 14:19:09 +0530398 warehouse_asset_account = warehouse_account[item_row.get("warehouse")]["account"]
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530399
Daizy Modi4efc9472022-11-07 09:21:03 +0530400 expense_account = frappe.get_cached_value("Company", self.company, "default_expense_account")
Deepesh Gargce9164e2023-07-11 12:03:38 +0530401 if not expense_account:
402 frappe.throw(
403 _(
404 "Please set default cost of goods sold account in company {0} for booking rounding gain and loss during stock transfer"
405 ).format(frappe.bold(self.company))
406 )
Deepesh Garg1c05c002022-10-12 14:19:09 +0530407
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530408 gl_list.append(
409 self.get_gl_dict(
410 {
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530411 "account": expense_account,
Deepesh Garg1c05c002022-10-12 14:19:09 +0530412 "against": warehouse_asset_account,
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530413 "cost_center": item_row.cost_center,
414 "project": item_row.project or self.get("project"),
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530415 "remarks": _("Rounding gain/loss Entry for Stock Transfer"),
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530416 "debit": sle_rounding_diff,
417 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
418 },
419 warehouse_account[sle.warehouse]["account_currency"],
420 item=item_row,
421 )
422 )
423
424 gl_list.append(
425 self.get_gl_dict(
426 {
Deepesh Garg1c05c002022-10-12 14:19:09 +0530427 "account": warehouse_asset_account,
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530428 "against": expense_account,
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530429 "cost_center": item_row.cost_center,
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530430 "remarks": _("Rounding gain/loss Entry for Stock Transfer"),
431 "credit": sle_rounding_diff,
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530432 "project": item_row.get("project") or self.get("project"),
433 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
434 },
435 item=item_row,
436 )
437 )
438
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530439 if warehouse_with_no_account:
Nabin Haitd6625022016-10-24 18:17:57 +0530440 for wh in warehouse_with_no_account:
Daizy Modi4efc9472022-11-07 09:21:03 +0530441 if frappe.get_cached_value("Warehouse", wh, "company"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530442 frappe.throw(
443 _(
444 "Warehouse {0} is not linked to any account, please mention the account in the warehouse record or set default inventory account in company {1}."
445 ).format(wh, self.company)
446 )
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530447
Nabin Hait19f8fa52021-02-22 22:27:22 +0530448 return process_gl_map(gl_list, precision=precision)
449
450 def get_debit_field_precision(self):
451 if not frappe.flags.debit_field_precision:
Akhil Narang3effaf22024-03-27 11:37:26 +0530452 frappe.flags.debit_field_precision = frappe.get_precision("GL Entry", "debit_in_account_currency")
Nabin Hait19f8fa52021-02-22 22:27:22 +0530453
454 return frappe.flags.debit_field_precision
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530455
Anand Doshide1a97d2014-04-17 11:37:46 +0530456 def get_voucher_details(self, default_expense_account, default_cost_center, sle_map):
457 if self.doctype == "Stock Reconciliation":
Nabin Hait3f119ec2019-05-16 17:28:39 +0530458 reconciliation_purpose = frappe.db.get_value(self.doctype, self.name, "purpose")
459 is_opening = "Yes" if reconciliation_purpose == "Opening Stock" else "No"
460 details = []
Nabin Hait34c551d2019-07-03 10:34:31 +0530461 for voucher_detail_no in sle_map:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530462 details.append(
463 frappe._dict(
464 {
465 "name": voucher_detail_no,
466 "expense_account": default_expense_account,
467 "cost_center": default_cost_center,
468 "is_opening": is_opening,
469 }
470 )
471 )
Nabin Hait3f119ec2019-05-16 17:28:39 +0530472 return details
Anand Doshide1a97d2014-04-17 11:37:46 +0530473 else:
Nabin Haitdd38a262014-12-26 13:15:21 +0530474 details = self.get("items")
Anand Doshi094610d2014-04-16 19:56:53 +0530475
Anand Doshide1a97d2014-04-17 11:37:46 +0530476 if default_expense_account or default_cost_center:
477 for d in details:
478 if default_expense_account and not d.get("expense_account"):
479 d.expense_account = default_expense_account
480 if default_cost_center and not d.get("cost_center"):
481 d.cost_center = default_cost_center
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530482
Anand Doshide1a97d2014-04-17 11:37:46 +0530483 return details
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530484
Akhil Narang3effaf22024-03-27 11:37:26 +0530485 def get_items_and_warehouses(self) -> tuple[list[str], list[str]]:
Ankush Menate6ab8df2022-02-06 13:02:34 +0530486 """Get list of items and warehouses affected by a transaction"""
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530487
Ankush Menate6ab8df2022-02-06 13:02:34 +0530488 if not (hasattr(self, "items") or hasattr(self, "packed_items")):
489 return [], []
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530490
Ankush Menate6ab8df2022-02-06 13:02:34 +0530491 item_rows = (self.get("items") or []) + (self.get("packed_items") or [])
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530492
Ankush Menate6ab8df2022-02-06 13:02:34 +0530493 items = {d.item_code for d in item_rows if d.item_code}
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530494
Ankush Menate6ab8df2022-02-06 13:02:34 +0530495 warehouses = set()
496 for d in item_rows:
497 if d.get("warehouse"):
498 warehouses.add(d.warehouse)
Nabin Haitbecf75d2014-03-27 17:18:29 +0530499
Ankush Menate6ab8df2022-02-06 13:02:34 +0530500 if self.doctype == "Stock Entry":
501 if d.get("s_warehouse"):
502 warehouses.add(d.s_warehouse)
503 if d.get("t_warehouse"):
504 warehouses.add(d.t_warehouse)
505
506 return list(items), list(warehouses)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530507
Nabin Hait2e296fa2013-08-28 18:53:11 +0530508 def get_stock_ledger_details(self):
509 stock_ledger = {}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530510 stock_ledger_entries = frappe.db.sql(
511 """
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530512 select
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530513 name, warehouse, stock_value_difference, valuation_rate,
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530514 voucher_detail_no, item_code, posting_date, posting_time,
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530515 actual_qty, qty_after_transaction
Nabin Haitea8fab52017-02-06 17:13:39 +0530516 from
517 `tabStock Ledger Entry`
518 where
Ankush Menat0ca60af2022-02-08 10:24:19 +0530519 voucher_type=%s and voucher_no=%s and is_cancelled = 0
Ankush Menat494bd9e2022-03-28 18:52:46 +0530520 """,
521 (self.doctype, self.name),
522 as_dict=True,
523 )
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530524
Nabin Haitea8fab52017-02-06 17:13:39 +0530525 for sle in stock_ledger_entries:
Deepesh Gargb4be2922021-01-28 13:09:56 +0530526 stock_ledger.setdefault(sle.voucher_detail_no, []).append(sle)
Nabin Hait2e296fa2013-08-28 18:53:11 +0530527 return stock_ledger
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530528
Nabin Hait27994c22013-08-26 16:53:30 +0530529 def check_expense_account(self, item):
Rushabh Mehta052fe822014-04-16 19:20:11 +0530530 if not item.get("expense_account"):
Rohit Waghchaureceab6922020-11-18 17:57:35 +0530531 msg = _("Please set an Expense Account in the Items table")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530532 frappe.throw(
533 _("Row #{0}: Expense Account not set for the Item {1}. {2}").format(
534 item.idx, frappe.bold(item.item_code), msg
535 ),
536 title=_("Expense Account Missing"),
537 )
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530538
Anand Doshi496123a2014-06-19 19:25:19 +0530539 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530540 is_expense_account = (
541 frappe.get_cached_value("Account", item.get("expense_account"), "report_type")
542 == "Profit and Loss"
543 )
544 if (
545 self.doctype
Sagar Sharma2d04e712022-08-17 15:57:41 +0530546 not in (
547 "Purchase Receipt",
548 "Purchase Invoice",
549 "Stock Reconciliation",
550 "Stock Entry",
551 "Subcontracting Receipt",
552 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530553 and not is_expense_account
554 ):
555 frappe.throw(
556 _("Expense / Difference account ({0}) must be a 'Profit or Loss' account").format(
557 item.get("expense_account")
558 )
559 )
Anand Doshi496123a2014-06-19 19:25:19 +0530560 if is_expense_account and not item.get("cost_center"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530561 frappe.throw(
562 _("{0} {1}: Cost Center is mandatory for Item {2}").format(
563 _(self.doctype), self.name, item.get("item_code")
564 )
565 )
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530566
Rohit Waghchaure8996b7d2020-01-23 17:36:52 +0530567 def delete_auto_created_batches(self):
Rohit Waghchaure34233342024-03-21 20:28:16 +0530568 for table_name in ["items", "packed_items", "supplied_items"]:
569 if not self.get(table_name):
570 continue
Rohit Waghchaure8996b7d2020-01-23 17:36:52 +0530571
Rohit Waghchaure34233342024-03-21 20:28:16 +0530572 for row in self.get(table_name):
573 update_values = {}
574 if row.get("batch_no"):
575 update_values["batch_no"] = None
576
577 if row.serial_and_batch_bundle:
578 update_values["serial_and_batch_bundle"] = None
579 frappe.db.set_value(
580 "Serial and Batch Bundle", row.serial_and_batch_bundle, {"is_cancelled": 1}
581 )
582
583 if update_values:
584 row.db_set(update_values)
585
586 if table_name == "items" and row.get("rejected_serial_and_batch_bundle"):
587 frappe.db.set_value(
588 "Serial and Batch Bundle", row.rejected_serial_and_batch_bundle, {"is_cancelled": 1}
589 )
590
591 row.db_set("rejected_serial_and_batch_bundle", None)
Saqibe9ac3e02020-03-02 15:02:58 +0530592
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530593 def set_serial_and_batch_bundle(self, table_name=None, ignore_validate=False):
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530594 if not table_name:
595 table_name = "items"
Rohit Waghchaure8996b7d2020-01-23 17:36:52 +0530596
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530597 QTY_FIELD = {
598 "serial_and_batch_bundle": "qty",
599 "current_serial_and_batch_bundle": "current_qty",
600 "rejected_serial_and_batch_bundle": "rejected_qty",
601 }
602
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530603 for row in self.get(table_name):
s-aga-rc20241f2024-01-12 15:26:35 +0530604 for field in QTY_FIELD.keys():
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530605 if row.get(field):
606 frappe.get_doc("Serial and Batch Bundle", row.get(field)).set_serial_and_batch_values(
607 self, row, qty_field=QTY_FIELD[field]
608 )
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530609
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530610 def make_package_for_transfer(
611 self, serial_and_batch_bundle, warehouse, type_of_transaction=None, do_not_submit=None
612 ):
613 bundle_doc = frappe.get_doc("Serial and Batch Bundle", serial_and_batch_bundle)
614
615 if not type_of_transaction:
616 type_of_transaction = "Inward"
617
618 bundle_doc = frappe.copy_doc(bundle_doc)
619 bundle_doc.warehouse = warehouse
620 bundle_doc.type_of_transaction = type_of_transaction
621 bundle_doc.voucher_type = self.doctype
rohitwaghchaure59222812024-03-15 17:55:41 +0530622 bundle_doc.voucher_no = "" if self.is_new() or self.docstatus == 2 else self.name
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530623 bundle_doc.is_cancelled = 0
624
Rohit Waghchaure5bb31732023-03-21 10:54:41 +0530625 for row in bundle_doc.entries:
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530626 row.is_outward = 0
627 row.qty = abs(row.qty)
628 row.stock_value_difference = abs(row.stock_value_difference)
629 if type_of_transaction == "Outward":
630 row.qty *= -1
631 row.stock_value_difference *= row.stock_value_difference
632 row.is_outward = 1
633
634 row.warehouse = warehouse
635
Rohit Waghchaure5bb31732023-03-21 10:54:41 +0530636 bundle_doc.calculate_qty_and_amount()
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530637 bundle_doc.flags.ignore_permissions = True
rohitwaghchaure59222812024-03-15 17:55:41 +0530638 bundle_doc.flags.ignore_validate = True
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530639 bundle_doc.save(ignore_permissions=True)
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530640
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530641 return bundle_doc.name
Rohit Waghchaure4f4dbf12020-01-23 12:42:42 +0530642
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530643 def get_sl_entries(self, d, args):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530644 sl_dict = frappe._dict(
645 {
646 "item_code": d.get("item_code", None),
647 "warehouse": d.get("warehouse", None),
Rohit Waghchaurebc75a7e2022-10-10 13:28:19 +0530648 "serial_and_batch_bundle": d.get("serial_and_batch_bundle"),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530649 "posting_date": self.posting_date,
650 "posting_time": self.posting_time,
651 "fiscal_year": get_fiscal_year(self.posting_date, company=self.company)[0],
652 "voucher_type": self.doctype,
653 "voucher_no": self.name,
654 "voucher_detail_no": d.name,
655 "actual_qty": (self.docstatus == 1 and 1 or -1) * flt(d.get("stock_qty")),
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +0530656 "stock_uom": frappe.get_cached_value(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530657 "Item", args.get("item_code") or d.get("item_code"), "stock_uom"
658 ),
659 "incoming_rate": 0,
660 "company": self.company,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530661 "project": d.get("project") or self.get("project"),
662 "is_cancelled": 1 if self.docstatus == 2 else 0,
663 }
664 )
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530665
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530666 sl_dict.update(args)
Rohit Waghchauree576f7f2022-06-30 19:12:06 +0530667 self.update_inventory_dimensions(d, sl_dict)
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530668
rohitwaghchaure07432892023-12-17 12:42:07 +0530669 if self.docstatus == 2:
670 # To handle denormalized serial no records, will br deprecated in v16
671 for field in ["serial_no", "batch_no"]:
672 if d.get(field):
673 sl_dict[field] = d.get(field)
674
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530675 return sl_dict
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530676
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530677 def update_inventory_dimensions(self, row, sl_dict) -> None:
Rohit Waghchaure23729992022-09-02 18:43:55 +0530678 # To handle delivery note and sales invoice
679 if row.get("item_row"):
680 row = row.get("item_row")
681
Rohit Waghchaure289e6cd2022-07-15 15:43:38 +0530682 dimensions = get_evaluated_inventory_dimension(row, sl_dict, parent_doc=self)
683 for dimension in dimensions:
Rohit Waghchaure0b39a012022-08-17 11:56:13 +0530684 if not dimension:
685 continue
686
Rohit Waghchaure6798b902023-05-09 16:07:14 +0530687 if self.doctype in [
688 "Purchase Invoice",
689 "Purchase Receipt",
690 "Sales Invoice",
691 "Delivery Note",
692 "Stock Entry",
693 ]:
Rohit Waghchaure38aaba52023-05-13 13:00:05 +0530694 if (
695 (
696 sl_dict.actual_qty > 0
697 and not self.get("is_return")
698 or sl_dict.actual_qty < 0
699 and self.get("is_return")
700 )
701 and self.doctype in ["Purchase Invoice", "Purchase Receipt"]
702 ) or (
703 (
704 sl_dict.actual_qty < 0
705 and not self.get("is_return")
706 or sl_dict.actual_qty > 0
707 and self.get("is_return")
708 )
709 and self.doctype in ["Sales Invoice", "Delivery Note", "Stock Entry"]
Rohit Waghchaure6798b902023-05-09 16:07:14 +0530710 ):
711 sl_dict[dimension.target_fieldname] = row.get(dimension.source_fieldname)
712 else:
713 fieldname_start_with = "to"
714 if self.doctype in ["Purchase Invoice", "Purchase Receipt"]:
715 fieldname_start_with = "from"
716
717 fieldname = f"{fieldname_start_with}_{dimension.source_fieldname}"
718 sl_dict[dimension.target_fieldname] = row.get(fieldname)
719
720 if not sl_dict.get(dimension.target_fieldname):
721 sl_dict[dimension.target_fieldname] = row.get(dimension.source_fieldname)
722
723 elif row.get(dimension.source_fieldname):
Rohit Waghchaure289e6cd2022-07-15 15:43:38 +0530724 sl_dict[dimension.target_fieldname] = row.get(dimension.source_fieldname)
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530725
Rohit Waghchaure0b39a012022-08-17 11:56:13 +0530726 if not sl_dict.get(dimension.target_fieldname) and dimension.fetch_from_parent:
727 sl_dict[dimension.target_fieldname] = self.get(dimension.fetch_from_parent)
728
729 # Get value based on doctype name
730 if not sl_dict.get(dimension.target_fieldname):
Daizy Modi4efc9472022-11-07 09:21:03 +0530731 fieldname = next(
732 (
733 field.fieldname
734 for field in frappe.get_meta(self.doctype).fields
735 if field.options == dimension.fetch_from_parent
736 ),
737 None,
Rohit Waghchaure0b39a012022-08-17 11:56:13 +0530738 )
739
740 if fieldname and self.get(fieldname):
741 sl_dict[dimension.target_fieldname] = self.get(fieldname)
742
Rohit Waghchaure75fcab02022-09-03 17:09:24 +0530743 if sl_dict[dimension.target_fieldname] and self.docstatus == 1:
744 row.db_set(dimension.source_fieldname, sl_dict[dimension.target_fieldname])
Rohit Waghchaure23729992022-09-02 18:43:55 +0530745
Ankush Menat494bd9e2022-03-28 18:52:46 +0530746 def make_sl_entries(self, sl_entries, allow_negative_stock=False, via_landed_cost_voucher=False):
Rushabh Mehta1f847992013-12-12 19:12:19 +0530747 from erpnext.stock.stock_ledger import make_sl_entries
Ankush Menat494bd9e2022-03-28 18:52:46 +0530748
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530749 make_sl_entries(sl_entries, allow_negative_stock, via_landed_cost_voucher)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530750
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530751 def make_gl_entries_on_cancel(self):
ruthra kumar46ea8142023-07-28 08:29:19 +0530752 cancel_exchange_gain_loss_journal(frappe._dict(doctype=self.doctype, name=self.name))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530753 if frappe.db.sql(
754 """select name from `tabGL Entry` where voucher_type=%s
755 and voucher_no=%s""",
756 (self.doctype, self.name),
757 ):
758 self.make_gl_entries()
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530759
Anand Doshia740f752014-06-25 13:31:02 +0530760 def get_serialized_items(self):
761 serialized_items = []
Ankush Menata9c84f72021-06-11 16:00:48 +0530762 item_codes = list(set(d.item_code for d in self.get("items")))
Anand Doshia740f752014-06-25 13:31:02 +0530763 if item_codes:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530764 serialized_items = frappe.db.sql_list(
765 """select name from `tabItem`
Akhil Narang3effaf22024-03-27 11:37:26 +0530766 where has_serial_no=1 and name in ({})""".format(", ".join(["%s"] * len(item_codes))),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530767 tuple(item_codes),
768 )
Anand Doshia740f752014-06-25 13:31:02 +0530769
770 return serialized_items
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +0530771
Saurabh2e292062015-11-18 17:03:33 +0530772 def validate_warehouse(self):
Rohan Bansal7f8b95e2021-04-14 14:12:03 +0530773 from erpnext.stock.utils import validate_disabled_warehouse, validate_warehouse_company
Saurabh2e292062015-11-18 17:03:33 +0530774
Ankush Menat494bd9e2022-03-28 18:52:46 +0530775 warehouses = list(set(d.warehouse for d in self.get("items") if getattr(d, "warehouse", None)))
Saurabh2e292062015-11-18 17:03:33 +0530776
Ankush Menat494bd9e2022-03-28 18:52:46 +0530777 target_warehouses = list(
778 set([d.target_warehouse for d in self.get("items") if getattr(d, "target_warehouse", None)])
779 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530780
781 warehouses.extend(target_warehouses)
782
Ankush Menat494bd9e2022-03-28 18:52:46 +0530783 from_warehouse = list(
784 set([d.from_warehouse for d in self.get("items") if getattr(d, "from_warehouse", None)])
785 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530786
787 warehouses.extend(from_warehouse)
788
Saurabh2e292062015-11-18 17:03:33 +0530789 for w in warehouses:
Jannat Patel30c88732021-02-11 11:46:48 +0530790 validate_disabled_warehouse(w)
Saurabh2e292062015-11-18 17:03:33 +0530791 validate_warehouse_company(w, self.company)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530792
Anand Doshi6b71ef52016-01-06 16:32:06 +0530793 def update_billing_percentage(self, update_modified=True):
marinationd6596a12020-11-02 15:07:48 +0530794 target_ref_field = "amount"
795 if self.doctype == "Delivery Note":
796 target_ref_field = "amount - (returned_qty * rate)"
797
Ankush Menat494bd9e2022-03-28 18:52:46 +0530798 self._update_percent_field(
799 {
800 "target_dt": self.doctype + " Item",
801 "target_parent_dt": self.doctype,
802 "target_parent_field": "per_billed",
803 "target_ref_field": target_ref_field,
804 "target_field": "billed_amt",
805 "name": self.name,
806 },
807 update_modified,
808 )
Anand Doshia740f752014-06-25 13:31:02 +0530809
Nabin Hait8af429d2016-11-16 17:21:59 +0530810 def validate_inspection(self):
marination9ac9a4e2021-06-21 16:18:35 +0530811 """Checks if quality inspection is set/ is valid for Items that require inspection."""
812 inspection_fieldname_map = {
813 "Purchase Receipt": "inspection_required_before_purchase",
814 "Purchase Invoice": "inspection_required_before_purchase",
s-aga-r3fdcd332023-08-23 12:15:35 +0530815 "Subcontracting Receipt": "inspection_required_before_purchase",
marination9ac9a4e2021-06-21 16:18:35 +0530816 "Sales Invoice": "inspection_required_before_delivery",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530817 "Delivery Note": "inspection_required_before_delivery",
marination9ac9a4e2021-06-21 16:18:35 +0530818 }
819 inspection_required_fieldname = inspection_fieldname_map.get(self.doctype)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530820
marination9ac9a4e2021-06-21 16:18:35 +0530821 # return if inspection is not required on document level
Ankush Menat494bd9e2022-03-28 18:52:46 +0530822 if (
823 (not inspection_required_fieldname and self.doctype != "Stock Entry")
824 or (self.doctype == "Stock Entry" and not self.inspection_required)
825 or (self.doctype in ["Sales Invoice", "Purchase Invoice"] and not self.update_stock)
826 ):
827 return
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530828
Ankush Menat494bd9e2022-03-28 18:52:46 +0530829 for row in self.get("items"):
marination9ac9a4e2021-06-21 16:18:35 +0530830 qi_required = False
Ankush Menat494bd9e2022-03-28 18:52:46 +0530831 if inspection_required_fieldname and frappe.db.get_value(
832 "Item", row.item_code, inspection_required_fieldname
833 ):
marination9ac9a4e2021-06-21 16:18:35 +0530834 qi_required = True
835 elif self.doctype == "Stock Entry" and row.t_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530836 qi_required = True # inward stock needs inspection
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530837
Ankush Menat494bd9e2022-03-28 18:52:46 +0530838 if qi_required: # validate row only if inspection is required on item level
marination9ac9a4e2021-06-21 16:18:35 +0530839 self.validate_qi_presence(row)
840 if self.docstatus == 1:
841 self.validate_qi_submission(row)
842 self.validate_qi_rejection(row)
843
844 def validate_qi_presence(self, row):
845 """Check if QI is present on row level. Warn on save and stop on submit if missing."""
846 if not row.quality_inspection:
marination654e9d82021-06-21 16:51:12 +0530847 msg = f"Row #{row.idx}: Quality Inspection is required for Item {frappe.bold(row.item_code)}"
marination9ac9a4e2021-06-21 16:18:35 +0530848 if self.docstatus == 1:
marination654e9d82021-06-21 16:51:12 +0530849 frappe.throw(_(msg), title=_("Inspection Required"), exc=QualityInspectionRequiredError)
marination9ac9a4e2021-06-21 16:18:35 +0530850 else:
marination654e9d82021-06-21 16:51:12 +0530851 frappe.msgprint(_(msg), title=_("Inspection Required"), indicator="blue")
marination9ac9a4e2021-06-21 16:18:35 +0530852
853 def validate_qi_submission(self, row):
854 """Check if QI is submitted on row level, during submission"""
Akhil Narang3effaf22024-03-27 11:37:26 +0530855 action = frappe.db.get_single_value("Stock Settings", "action_if_quality_inspection_is_not_submitted")
marination9ac9a4e2021-06-21 16:18:35 +0530856 qa_docstatus = frappe.db.get_value("Quality Inspection", row.quality_inspection, "docstatus")
857
barredterraeb9ee3f2023-12-05 11:22:55 +0100858 if qa_docstatus != 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530859 link = frappe.utils.get_link_to_form("Quality Inspection", row.quality_inspection)
Akhil Narang3effaf22024-03-27 11:37:26 +0530860 msg = f"Row #{row.idx}: Quality Inspection {link} is not submitted for the item: {row.item_code}"
marination9ac9a4e2021-06-21 16:18:35 +0530861 if action == "Stop":
marination654e9d82021-06-21 16:51:12 +0530862 frappe.throw(_(msg), title=_("Inspection Submission"), exc=QualityInspectionNotSubmittedError)
marination9ac9a4e2021-06-21 16:18:35 +0530863 else:
Marica9ba3fce2021-06-22 11:20:17 +0530864 frappe.msgprint(_(msg), alert=True, indicator="orange")
marination9ac9a4e2021-06-21 16:18:35 +0530865
866 def validate_qi_rejection(self, row):
867 """Check if QI is rejected on row level, during submission"""
marinationf67f13c2021-07-10 18:24:24 +0530868 action = frappe.db.get_single_value("Stock Settings", "action_if_quality_inspection_is_rejected")
marination9ac9a4e2021-06-21 16:18:35 +0530869 qa_status = frappe.db.get_value("Quality Inspection", row.quality_inspection, "status")
870
871 if qa_status == "Rejected":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530872 link = frappe.utils.get_link_to_form("Quality Inspection", row.quality_inspection)
marination654e9d82021-06-21 16:51:12 +0530873 msg = f"Row #{row.idx}: Quality Inspection {link} was rejected for item {row.item_code}"
marination9ac9a4e2021-06-21 16:18:35 +0530874 if action == "Stop":
marination654e9d82021-06-21 16:51:12 +0530875 frappe.throw(_(msg), title=_("Inspection Rejected"), exc=QualityInspectionRejectedError)
marination9ac9a4e2021-06-21 16:18:35 +0530876 else:
marination654e9d82021-06-21 16:51:12 +0530877 frappe.msgprint(_(msg), alert=True, indicator="orange")
Manas Solankicc902412016-11-10 19:15:11 +0530878
Nabin Haitb2d3c0f2018-06-14 15:54:34 +0530879 def update_blanket_order(self):
Nabin Haitd1f40ad2018-06-14 17:09:55 +0530880 blanket_orders = list(set([d.blanket_order for d in self.items if d.blanket_order]))
Nabin Haitb2d3c0f2018-06-14 15:54:34 +0530881 for blanket_order in blanket_orders:
882 frappe.get_doc("Blanket Order", blanket_order).update_ordered_qty()
Manas Solankie5e87f72018-05-28 20:07:08 +0530883
marinationfd04e962020-04-03 15:46:48 +0530884 def validate_customer_provided_item(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530885 for d in self.get("items"):
marinationfd04e962020-04-03 15:46:48 +0530886 # Customer Provided parts will have zero valuation rate
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +0530887 if frappe.get_cached_value("Item", d.item_code, "is_customer_provided_item"):
marinationfd04e962020-04-03 15:46:48 +0530888 d.allow_zero_valuation_rate = 1
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530889
Anupam Kumar7e1dcf92021-02-11 20:19:30 +0530890 def set_rate_of_stock_uom(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530891 if self.doctype in [
892 "Purchase Receipt",
893 "Purchase Invoice",
894 "Purchase Order",
895 "Sales Invoice",
896 "Sales Order",
897 "Delivery Note",
898 "Quotation",
899 ]:
Anupam Kumar7e1dcf92021-02-11 20:19:30 +0530900 for d in self.get("items"):
Rohit Waghchaure13584432021-03-26 14:11:50 +0530901 d.stock_uom_rate = d.rate / (d.conversion_factor or 1)
Anupam Kumar7e1dcf92021-02-11 20:19:30 +0530902
Deepesh Gargb4be2922021-01-28 13:09:56 +0530903 def validate_internal_transfer(self):
rohitwaghchaure5136fe12023-10-22 20:03:02 +0530904 if self.doctype in ("Sales Invoice", "Delivery Note", "Purchase Invoice", "Purchase Receipt"):
905 if self.is_internal_transfer():
906 self.validate_in_transit_warehouses()
907 self.validate_multi_currency()
908 self.validate_packed_items()
rohitwaghchaure8fdc2442024-01-27 21:37:58 +0530909
910 if self.get("is_internal_supplier"):
911 self.validate_internal_transfer_qty()
rohitwaghchaure5136fe12023-10-22 20:03:02 +0530912 else:
913 self.validate_internal_transfer_warehouse()
914
915 def validate_internal_transfer_warehouse(self):
916 for row in self.items:
917 if row.get("target_warehouse"):
918 row.target_warehouse = None
919
920 if row.get("from_warehouse"):
921 row.from_warehouse = None
Deepesh Gargb4be2922021-01-28 13:09:56 +0530922
923 def validate_in_transit_warehouses(self):
Akhil Narang3effaf22024-03-27 11:37:26 +0530924 if (self.doctype == "Sales Invoice" and self.get("update_stock")) or self.doctype == "Delivery Note":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530925 for item in self.get("items"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530926 if not item.target_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530927 frappe.throw(
928 _("Row {0}: Target Warehouse is mandatory for internal transfers").format(item.idx)
929 )
Deepesh Gargb4be2922021-01-28 13:09:56 +0530930
Ankush Menat494bd9e2022-03-28 18:52:46 +0530931 if (
932 self.doctype == "Purchase Invoice" and self.get("update_stock")
933 ) or self.doctype == "Purchase Receipt":
934 for item in self.get("items"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530935 if not item.from_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530936 frappe.throw(
937 _("Row {0}: From Warehouse is mandatory for internal transfers").format(item.idx)
938 )
Deepesh Gargb4be2922021-01-28 13:09:56 +0530939
940 def validate_multi_currency(self):
941 if self.currency != self.company_currency:
942 frappe.throw(_("Internal transfers can only be done in company's default currency"))
943
944 def validate_packed_items(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530945 if self.doctype in ("Sales Invoice", "Delivery Note Item") and self.get("packed_items"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530946 frappe.throw(_("Packed Items cannot be transferred internally"))
947
rohitwaghchaure8fdc2442024-01-27 21:37:58 +0530948 def validate_internal_transfer_qty(self):
949 if self.doctype not in ["Purchase Invoice", "Purchase Receipt"]:
950 return
951
952 item_wise_transfer_qty = self.get_item_wise_inter_transfer_qty()
953 if not item_wise_transfer_qty:
954 return
955
956 item_wise_received_qty = self.get_item_wise_inter_received_qty()
957 precision = frappe.get_precision(self.doctype + " Item", "qty")
958
959 over_receipt_allowance = frappe.db.get_single_value(
960 "Stock Settings", "over_delivery_receipt_allowance"
961 )
962
963 parent_doctype = {
964 "Purchase Receipt": "Delivery Note",
965 "Purchase Invoice": "Sales Invoice",
966 }.get(self.doctype)
967
968 for key, transferred_qty in item_wise_transfer_qty.items():
969 recevied_qty = flt(item_wise_received_qty.get(key), precision)
970 if over_receipt_allowance:
971 transferred_qty = transferred_qty + flt(
972 transferred_qty * over_receipt_allowance / 100, precision
973 )
974
975 if recevied_qty > flt(transferred_qty, precision):
976 frappe.throw(
977 _("For Item {0} cannot be received more than {1} qty against the {2} {3}").format(
978 bold(key[1]),
979 bold(flt(transferred_qty, precision)),
980 bold(parent_doctype),
981 get_link_to_form(parent_doctype, self.get("inter_company_reference")),
982 )
983 )
984
985 def get_item_wise_inter_transfer_qty(self):
986 reference_field = "inter_company_reference"
987 if self.doctype == "Purchase Invoice":
988 reference_field = "inter_company_invoice_reference"
989
990 parent_doctype = {
991 "Purchase Receipt": "Delivery Note",
992 "Purchase Invoice": "Sales Invoice",
993 }.get(self.doctype)
994
995 child_doctype = parent_doctype + " Item"
996
997 parent_tab = frappe.qb.DocType(parent_doctype)
998 child_tab = frappe.qb.DocType(child_doctype)
999
1000 query = (
1001 frappe.qb.from_(parent_doctype)
1002 .inner_join(child_tab)
1003 .on(child_tab.parent == parent_tab.name)
1004 .select(
1005 child_tab.name,
1006 child_tab.item_code,
1007 child_tab.qty,
1008 )
1009 .where((parent_tab.name == self.get(reference_field)) & (parent_tab.docstatus == 1))
1010 )
1011
1012 data = query.run(as_dict=True)
1013 item_wise_transfer_qty = defaultdict(float)
1014 for row in data:
1015 item_wise_transfer_qty[(row.name, row.item_code)] += flt(row.qty)
1016
1017 return item_wise_transfer_qty
1018
1019 def get_item_wise_inter_received_qty(self):
1020 child_doctype = self.doctype + " Item"
1021
1022 parent_tab = frappe.qb.DocType(self.doctype)
1023 child_tab = frappe.qb.DocType(child_doctype)
1024
1025 query = (
1026 frappe.qb.from_(self.doctype)
1027 .inner_join(child_tab)
1028 .on(child_tab.parent == parent_tab.name)
1029 .select(
1030 child_tab.item_code,
1031 child_tab.qty,
1032 )
1033 .where(parent_tab.docstatus < 2)
1034 )
1035
1036 if self.doctype == "Purchase Invoice":
1037 query = query.select(
1038 child_tab.sales_invoice_item.as_("name"),
1039 )
1040
1041 query = query.where(
1042 parent_tab.inter_company_invoice_reference == self.inter_company_invoice_reference
1043 )
1044 else:
1045 query = query.select(
1046 child_tab.delivery_note_item.as_("name"),
1047 )
1048
1049 query = query.where(parent_tab.inter_company_reference == self.inter_company_reference)
1050
1051 data = query.run(as_dict=True)
1052 item_wise_transfer_qty = defaultdict(float)
1053 for row in data:
1054 item_wise_transfer_qty[(row.name, row.item_code)] += flt(row.qty)
1055
1056 return item_wise_transfer_qty
1057
marinationfac40352020-12-07 21:35:49 +05301058 def validate_putaway_capacity(self):
1059 # if over receipt is attempted while 'apply putaway rule' is disabled
1060 # and if rule was applied on the transaction, validate it.
marination957615b2021-01-18 23:47:24 +05301061 from erpnext.stock.doctype.putaway_rule.putaway_rule import get_available_putaway_capacity
Ankush Menat494bd9e2022-03-28 18:52:46 +05301062
1063 valid_doctype = self.doctype in (
1064 "Purchase Receipt",
1065 "Stock Entry",
1066 "Purchase Invoice",
1067 "Stock Reconciliation",
1068 )
marinationfac40352020-12-07 21:35:49 +05301069
rohitwaghchaureb966c062024-02-12 12:49:09 +05301070 if not frappe.get_all("Putaway Rule", limit=1):
1071 return
1072
marination957615b2021-01-18 23:47:24 +05301073 if self.doctype == "Purchase Invoice" and self.get("update_stock") == 0:
1074 valid_doctype = False
1075
1076 if valid_doctype:
marinationfac40352020-12-07 21:35:49 +05301077 rule_map = defaultdict(dict)
1078 for item in self.get("items"):
marination957615b2021-01-18 23:47:24 +05301079 warehouse_field = "t_warehouse" if self.doctype == "Stock Entry" else "warehouse"
Ankush Menat494bd9e2022-03-28 18:52:46 +05301080 rule = frappe.db.get_value(
1081 "Putaway Rule",
1082 {"item_code": item.get("item_code"), "warehouse": item.get(warehouse_field)},
1083 ["name", "disable"],
1084 as_dict=True,
1085 )
marination957615b2021-01-18 23:47:24 +05301086 if rule:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301087 if rule.get("disabled"):
1088 continue # dont validate for disabled rule
marination957615b2021-01-18 23:47:24 +05301089
1090 if self.doctype == "Stock Reconciliation":
1091 stock_qty = flt(item.qty)
1092 else:
Akhil Narang3effaf22024-03-27 11:37:26 +05301093 stock_qty = (
1094 flt(item.transfer_qty) if self.doctype == "Stock Entry" else flt(item.stock_qty)
1095 )
marination957615b2021-01-18 23:47:24 +05301096
1097 rule_name = rule.get("name")
1098 if not rule_map[rule_name]:
1099 rule_map[rule_name]["warehouse"] = item.get(warehouse_field)
1100 rule_map[rule_name]["item"] = item.get("item_code")
1101 rule_map[rule_name]["qty_put"] = 0
1102 rule_map[rule_name]["capacity"] = get_available_putaway_capacity(rule_name)
1103 rule_map[rule_name]["qty_put"] += flt(stock_qty)
marinationfac40352020-12-07 21:35:49 +05301104
1105 for rule, values in rule_map.items():
1106 if flt(values["qty_put"]) > flt(values["capacity"]):
marination957615b2021-01-18 23:47:24 +05301107 message = self.prepare_over_receipt_message(rule, values)
marinationfac40352020-12-07 21:35:49 +05301108 frappe.throw(msg=message, title=_("Over Receipt"))
marination957615b2021-01-18 23:47:24 +05301109
1110 def prepare_over_receipt_message(self, rule, values):
Akhil Narang3effaf22024-03-27 11:37:26 +05301111 message = _("{0} qty of Item {1} is being received into Warehouse {2} with capacity {3}.").format(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301112 frappe.bold(values["qty_put"]),
1113 frappe.bold(values["item"]),
1114 frappe.bold(values["warehouse"]),
1115 frappe.bold(values["capacity"]),
1116 )
marination957615b2021-01-18 23:47:24 +05301117 message += "<br><br>"
1118 rule_link = frappe.utils.get_link_to_form("Putaway Rule", rule)
Ankush Menatad6a2652021-04-17 16:50:02 +05301119 message += _("Please adjust the qty or edit {0} to proceed.").format(rule_link)
marination957615b2021-01-18 23:47:24 +05301120 return message
marinationfac40352020-12-07 21:35:49 +05301121
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +05301122 def repost_future_sle_and_gle(self, force=False):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301123 args = frappe._dict(
1124 {
1125 "posting_date": self.posting_date,
1126 "posting_time": self.posting_time,
1127 "voucher_type": self.doctype,
1128 "voucher_no": self.name,
1129 "company": self.company,
1130 }
1131 )
Ankush Menat3638fbf2022-03-01 18:17:14 +05301132
Rohit Waghchaure6e661e72023-05-16 16:23:52 +05301133 if self.docstatus == 2:
1134 force = True
1135
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +05301136 if force or future_sle_exists(args) or repost_required_for_queue(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301137 item_based_reposting = cint(
1138 frappe.db.get_single_value("Stock Reposting Settings", "item_based_reposting")
1139 )
Ankush Menat45dd46b2021-11-02 10:50:52 +05301140 if item_based_reposting:
1141 create_item_wise_repost_entries(voucher_type=self.doctype, voucher_no=self.name)
1142 else:
1143 create_repost_item_valuation_entry(args)
1144
Sagar Sharmaf4673942022-08-21 21:26:06 +05301145 def add_gl_entry(
1146 self,
1147 gl_entries,
1148 account,
1149 cost_center,
1150 debit,
1151 credit,
1152 remarks,
1153 against_account,
1154 debit_in_account_currency=None,
1155 credit_in_account_currency=None,
1156 account_currency=None,
1157 project=None,
1158 voucher_detail_no=None,
1159 item=None,
1160 posting_date=None,
1161 ):
Sagar Sharmaf4673942022-08-21 21:26:06 +05301162 gl_entry = {
1163 "account": account,
1164 "cost_center": cost_center,
1165 "debit": debit,
1166 "credit": credit,
1167 "against": against_account,
1168 "remarks": remarks,
1169 }
1170
1171 if voucher_detail_no:
1172 gl_entry.update({"voucher_detail_no": voucher_detail_no})
1173
1174 if debit_in_account_currency:
1175 gl_entry.update({"debit_in_account_currency": debit_in_account_currency})
1176
1177 if credit_in_account_currency:
1178 gl_entry.update({"credit_in_account_currency": credit_in_account_currency})
1179
1180 if posting_date:
1181 gl_entry.update({"posting_date": posting_date})
1182
1183 gl_entries.append(self.get_gl_dict(gl_entry, item=item))
1184
Ankush Menat494bd9e2022-03-28 18:52:46 +05301185
Deepesh Garg2e52a632023-06-04 19:20:28 +05301186@frappe.whitelist()
Deepesh Garg0e68da52023-06-22 15:43:32 +05301187def show_accounting_ledger_preview(company, doctype, docname):
Smit Vora77cc91d2023-10-19 22:35:55 +05301188 filters = frappe._dict(company=company, include_dimensions=1)
Deepesh Garg0e68da52023-06-22 15:43:32 +05301189 doc = frappe.get_doc(doctype, docname)
Smit Vora77cc91d2023-10-19 22:35:55 +05301190 doc.run_method("before_gl_preview")
Deepesh Garg0e68da52023-06-22 15:43:32 +05301191
1192 gl_columns, gl_data = get_accounting_ledger_preview(doc, filters)
1193
Deepesh Gargd9e7bc52023-06-22 16:07:32 +05301194 frappe.db.rollback()
Deepesh Garg0e68da52023-06-22 15:43:32 +05301195
1196 return {"gl_columns": gl_columns, "gl_data": gl_data}
1197
1198
1199@frappe.whitelist()
1200def show_stock_ledger_preview(company, doctype, docname):
Smit Vora77cc91d2023-10-19 22:35:55 +05301201 filters = frappe._dict(company=company)
Deepesh Garg2e52a632023-06-04 19:20:28 +05301202 doc = frappe.get_doc(doctype, docname)
Smit Vora77cc91d2023-10-19 22:35:55 +05301203 doc.run_method("before_sl_preview")
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301204
Deepesh Garg011ac132023-06-12 18:42:49 +05301205 sl_columns, sl_data = get_stock_ledger_preview(doc, filters)
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301206
Deepesh Gargd9e7bc52023-06-22 16:07:32 +05301207 frappe.db.rollback()
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301208
Deepesh Garg2e52a632023-06-04 19:20:28 +05301209 return {
Deepesh Garg011ac132023-06-12 18:42:49 +05301210 "sl_columns": sl_columns,
1211 "sl_data": sl_data,
Deepesh Garg2e52a632023-06-04 19:20:28 +05301212 }
1213
1214
Deepesh Garg011ac132023-06-12 18:42:49 +05301215def get_accounting_ledger_preview(doc, filters):
1216 from erpnext.accounts.report.general_ledger.general_ledger import get_columns as get_gl_columns
1217
1218 gl_columns, gl_data = [], []
1219 fields = [
1220 "posting_date",
1221 "account",
1222 "debit",
1223 "credit",
1224 "against",
1225 "party",
1226 "party_type",
Deepesh Garg0e68da52023-06-22 15:43:32 +05301227 "cost_center",
Deepesh Garg011ac132023-06-12 18:42:49 +05301228 "against_voucher_type",
1229 "against_voucher",
1230 ]
1231
1232 doc.docstatus = 1
Deepesh Garg0e68da52023-06-22 15:43:32 +05301233
1234 if doc.get("update_stock") or doc.doctype in ("Purchase Receipt", "Delivery Note"):
1235 doc.update_stock_ledger()
1236
Deepesh Garg011ac132023-06-12 18:42:49 +05301237 doc.make_gl_entries()
1238 columns = get_gl_columns(filters)
1239 gl_entries = get_gl_entries_for_preview(doc.doctype, doc.name, fields)
1240
1241 gl_columns = get_columns(columns, fields)
1242 gl_data = get_data(fields, gl_entries)
1243
1244 return gl_columns, gl_data
1245
1246
1247def get_stock_ledger_preview(doc, filters):
1248 from erpnext.stock.report.stock_ledger.stock_ledger import get_columns as get_sl_columns
1249
1250 sl_columns, sl_data = [], []
1251 fields = [
1252 "item_code",
1253 "stock_uom",
1254 "actual_qty",
1255 "qty_after_transaction",
1256 "warehouse",
1257 "incoming_rate",
1258 "valuation_rate",
1259 "stock_value",
1260 "stock_value_difference",
1261 ]
1262 columns_fields = [
1263 "item_code",
1264 "stock_uom",
1265 "in_qty",
1266 "out_qty",
1267 "qty_after_transaction",
1268 "warehouse",
1269 "incoming_rate",
Deepesh Garg0e68da52023-06-22 15:43:32 +05301270 "in_out_rate",
Deepesh Garg011ac132023-06-12 18:42:49 +05301271 "stock_value",
1272 "stock_value_difference",
1273 ]
1274
Deepesh Garg0e68da52023-06-22 15:43:32 +05301275 if doc.get("update_stock") or doc.doctype in ("Purchase Receipt", "Delivery Note"):
Deepesh Garg011ac132023-06-12 18:42:49 +05301276 doc.docstatus = 1
1277 doc.update_stock_ledger()
1278 columns = get_sl_columns(filters)
1279 sl_entries = get_sl_entries_for_preview(doc.doctype, doc.name, fields)
1280
1281 sl_columns = get_columns(columns, columns_fields)
1282 sl_data = get_data(columns_fields, sl_entries)
1283
1284 return sl_columns, sl_data
1285
1286
1287def get_sl_entries_for_preview(doctype, docname, fields):
1288 sl_entries = frappe.get_all(
1289 "Stock Ledger Entry", filters={"voucher_type": doctype, "voucher_no": docname}, fields=fields
1290 )
1291
1292 for entry in sl_entries:
1293 if entry.actual_qty > 0:
1294 entry["in_qty"] = entry.actual_qty
1295 entry["out_qty"] = 0
1296 else:
1297 entry["out_qty"] = abs(entry.actual_qty)
1298 entry["in_qty"] = 0
1299
Deepesh Garg0e68da52023-06-22 15:43:32 +05301300 entry["in_out_rate"] = entry["valuation_rate"]
1301
Deepesh Garg011ac132023-06-12 18:42:49 +05301302 return sl_entries
1303
1304
1305def get_gl_entries_for_preview(doctype, docname, fields):
Akhil Narang3effaf22024-03-27 11:37:26 +05301306 return frappe.get_all("GL Entry", filters={"voucher_type": doctype, "voucher_no": docname}, fields=fields)
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301307
1308
Deepesh Garg011ac132023-06-12 18:42:49 +05301309def get_columns(raw_columns, fields):
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301310 return [
Deepesh Garg011ac132023-06-12 18:42:49 +05301311 {"name": d.get("label"), "editable": False, "width": 110}
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301312 for d in raw_columns
Deepesh Garg011ac132023-06-12 18:42:49 +05301313 if not d.get("hidden") and d.get("fieldname") in fields
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301314 ]
1315
1316
1317def get_data(raw_columns, raw_data):
1318 datatable_data = []
1319 for row in raw_data:
1320 data_row = []
1321 for column in raw_columns:
Deepesh Garg011ac132023-06-12 18:42:49 +05301322 data_row.append(row.get(column) or "")
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301323
1324 datatable_data.append(data_row)
1325
1326 return datatable_data
1327
1328
Ankush Menat3638fbf2022-03-01 18:17:14 +05301329def repost_required_for_queue(doc: StockController) -> bool:
1330 """check if stock document contains repeated item-warehouse with queue based valuation.
1331
1332 if queue exists for repeated items then SLEs need to reprocessed in background again.
1333 """
1334
Ankush Menat494bd9e2022-03-28 18:52:46 +05301335 consuming_sles = frappe.db.get_all(
1336 "Stock Ledger Entry",
Ankush Menat3638fbf2022-03-01 18:17:14 +05301337 filters={
1338 "voucher_type": doc.doctype,
1339 "voucher_no": doc.name,
1340 "actual_qty": ("<", 0),
Ankush Menat494bd9e2022-03-28 18:52:46 +05301341 "is_cancelled": 0,
Ankush Menat3638fbf2022-03-01 18:17:14 +05301342 },
Ankush Menat494bd9e2022-03-28 18:52:46 +05301343 fields=["item_code", "warehouse", "stock_queue"],
Ankush Menat3638fbf2022-03-01 18:17:14 +05301344 )
1345 item_warehouses = [(sle.item_code, sle.warehouse) for sle in consuming_sles]
1346
1347 unique_item_warehouses = set(item_warehouses)
1348
1349 if len(unique_item_warehouses) == len(item_warehouses):
1350 return False
1351
1352 for sle in consuming_sles:
1353 if sle.stock_queue != "[]": # using FIFO/LIFO valuation
1354 return True
1355 return False
1356
Nabin Hait19f8fa52021-02-22 22:27:22 +05301357
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301358@frappe.whitelist()
1359def make_quality_inspections(doctype, docname, items):
Rohan Bansala06ec032021-06-02 14:55:31 +05301360 if isinstance(items, str):
1361 items = json.loads(items)
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301362
Rohan Bansala06ec032021-06-02 14:55:31 +05301363 inspections = []
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301364 for item in items:
Rohan Bansal1cdf5a02021-05-26 14:42:15 +05301365 if flt(item.get("sample_size")) > flt(item.get("qty")):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301366 frappe.throw(
1367 _(
1368 "{item_name}'s Sample Size ({sample_size}) cannot be greater than the Accepted Quantity ({accepted_quantity})"
1369 ).format(
1370 item_name=item.get("item_name"),
1371 sample_size=item.get("sample_size"),
1372 accepted_quantity=item.get("qty"),
1373 )
1374 )
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301375
Ankush Menat494bd9e2022-03-28 18:52:46 +05301376 quality_inspection = frappe.get_doc(
1377 {
1378 "doctype": "Quality Inspection",
1379 "inspection_type": "Incoming",
1380 "inspected_by": frappe.session.user,
1381 "reference_type": doctype,
1382 "reference_name": docname,
1383 "item_code": item.get("item_code"),
1384 "description": item.get("description"),
1385 "sample_size": flt(item.get("sample_size")),
1386 "item_serial_no": item.get("serial_no").split("\n")[0] if item.get("serial_no") else None,
1387 "batch_no": item.get("batch_no"),
1388 }
1389 ).insert()
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301390 quality_inspection.save()
Rohan Bansal1cdf5a02021-05-26 14:42:15 +05301391 inspections.append(quality_inspection.name)
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301392
Rohan Bansal1cdf5a02021-05-26 14:42:15 +05301393 return inspections
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301394
Ankush Menat494bd9e2022-03-28 18:52:46 +05301395
Nabin Haitb99c77b2020-12-25 18:12:35 +05301396def is_reposting_pending():
Ankush Menat494bd9e2022-03-28 18:52:46 +05301397 return frappe.db.exists(
1398 "Repost Item Valuation", {"docstatus": 1, "status": ["in", ["Queued", "In Progress"]]}
1399 )
1400
Nabin Haitb99c77b2020-12-25 18:12:35 +05301401
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301402def future_sle_exists(args, sl_entries=None):
1403 key = (args.voucher_type, args.voucher_no)
Rohit Waghchaured9dd64b2023-04-14 13:00:12 +05301404 if not hasattr(frappe.local, "future_sle"):
1405 frappe.local.future_sle = {}
Nabin Haita77b8c92020-12-21 14:45:50 +05301406
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301407 if validate_future_sle_not_exists(args, key, sl_entries):
1408 return False
1409 elif get_cached_data(args, key):
1410 return True
1411
1412 if not sl_entries:
1413 sl_entries = get_sle_entries_against_voucher(args)
1414 if not sl_entries:
1415 return
1416
1417 or_conditions = get_conditions_to_validate_future_sle(sl_entries)
1418
Ankush Menat494bd9e2022-03-28 18:52:46 +05301419 data = frappe.db.sql(
1420 """
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301421 select item_code, warehouse, count(name) as total_row
Deepesh Garg6f107da2021-10-12 20:15:55 +05301422 from `tabStock Ledger Entry` force index (item_warehouse)
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301423 where
1424 ({})
1425 and timestamp(posting_date, posting_time)
1426 >= timestamp(%(posting_date)s, %(posting_time)s)
1427 and voucher_no != %(voucher_no)s
1428 and is_cancelled = 0
1429 GROUP BY
1430 item_code, warehouse
Akhil Narang3effaf22024-03-27 11:37:26 +05301431 """.format(" or ".join(or_conditions)),
Ankush Menat494bd9e2022-03-28 18:52:46 +05301432 args,
1433 as_dict=1,
1434 )
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301435
1436 for d in data:
1437 frappe.local.future_sle[key][(d.item_code, d.warehouse)] = d.total_row
1438
1439 return len(data)
1440
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301441
Ankush Menat494bd9e2022-03-28 18:52:46 +05301442def validate_future_sle_not_exists(args, key, sl_entries=None):
1443 item_key = ""
1444 if args.get("item_code"):
1445 item_key = (args.get("item_code"), args.get("warehouse"))
1446
1447 if not sl_entries and hasattr(frappe.local, "future_sle"):
Rohit Waghchaured9dd64b2023-04-14 13:00:12 +05301448 if key not in frappe.local.future_sle:
1449 return False
1450
Ankush Menat494bd9e2022-03-28 18:52:46 +05301451 if not frappe.local.future_sle.get(key) or (
1452 item_key and item_key not in frappe.local.future_sle.get(key)
1453 ):
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301454 return True
1455
Ankush Menat494bd9e2022-03-28 18:52:46 +05301456
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301457def get_cached_data(args, key):
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301458 if key not in frappe.local.future_sle:
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +05301459 frappe.local.future_sle[key] = frappe._dict({})
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301460
Ankush Menat494bd9e2022-03-28 18:52:46 +05301461 if args.get("item_code"):
1462 item_key = (args.get("item_code"), args.get("warehouse"))
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301463 count = frappe.local.future_sle[key].get(item_key)
1464
1465 return True if (count or count == 0) else False
1466 else:
1467 return frappe.local.future_sle[key]
1468
Ankush Menat494bd9e2022-03-28 18:52:46 +05301469
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301470def get_sle_entries_against_voucher(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301471 return frappe.get_all(
1472 "Stock Ledger Entry",
Nabin Haita77b8c92020-12-21 14:45:50 +05301473 filters={"voucher_type": args.voucher_type, "voucher_no": args.voucher_no},
1474 fields=["item_code", "warehouse"],
Ankush Menat494bd9e2022-03-28 18:52:46 +05301475 order_by="creation asc",
1476 )
1477
Nabin Haita77b8c92020-12-21 14:45:50 +05301478
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301479def get_conditions_to_validate_future_sle(sl_entries):
Sagar Vora868c0bf2021-03-27 16:10:20 +05301480 warehouse_items_map = {}
1481 for entry in sl_entries:
1482 if entry.warehouse not in warehouse_items_map:
1483 warehouse_items_map[entry.warehouse] = set()
Nabin Haita77b8c92020-12-21 14:45:50 +05301484
Sagar Vora868c0bf2021-03-27 16:10:20 +05301485 warehouse_items_map[entry.warehouse].add(entry.item_code)
1486
1487 or_conditions = []
1488 for warehouse, items in warehouse_items_map.items():
1489 or_conditions.append(
Noah Jacobb5a14912021-06-15 12:44:04 +05301490 f"""warehouse = {frappe.db.escape(warehouse)}
Ankush Menat494bd9e2022-03-28 18:52:46 +05301491 and item_code in ({', '.join(frappe.db.escape(item) for item in items)})"""
1492 )
Sagar Vora868c0bf2021-03-27 16:10:20 +05301493
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301494 return or_conditions
Nabin Haita77b8c92020-12-21 14:45:50 +05301495
Ankush Menat494bd9e2022-03-28 18:52:46 +05301496
Nabin Haita77b8c92020-12-21 14:45:50 +05301497def create_repost_item_valuation_entry(args):
1498 args = frappe._dict(args)
1499 repost_entry = frappe.new_doc("Repost Item Valuation")
1500 repost_entry.based_on = args.based_on
1501 if not args.based_on:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301502 repost_entry.based_on = "Transaction" if args.voucher_no else "Item and Warehouse"
Nabin Haita77b8c92020-12-21 14:45:50 +05301503 repost_entry.voucher_type = args.voucher_type
1504 repost_entry.voucher_no = args.voucher_no
1505 repost_entry.item_code = args.item_code
1506 repost_entry.warehouse = args.warehouse
1507 repost_entry.posting_date = args.posting_date
1508 repost_entry.posting_time = args.posting_time
1509 repost_entry.company = args.company
1510 repost_entry.allow_zero_rate = args.allow_zero_rate
1511 repost_entry.flags.ignore_links = True
Ankush Menataa024fc2021-11-18 12:51:26 +05301512 repost_entry.flags.ignore_permissions = True
Nabin Haita77b8c92020-12-21 14:45:50 +05301513 repost_entry.save()
Sagar Vora868c0bf2021-03-27 16:10:20 +05301514 repost_entry.submit()
Ankush Menat6dc9b822021-10-28 15:53:18 +05301515
1516
1517def create_item_wise_repost_entries(voucher_type, voucher_no, allow_zero_rate=False):
1518 """Using a voucher create repost item valuation records for all item-warehouse pairs."""
1519
Ankush Menatd220e082021-10-28 17:47:00 +05301520 stock_ledger_entries = get_items_to_be_repost(voucher_type, voucher_no)
1521
Ankush Menat6dc9b822021-10-28 15:53:18 +05301522 distinct_item_warehouses = set()
Ankush Menat6dc9b822021-10-28 15:53:18 +05301523 repost_entries = []
1524
1525 for sle in stock_ledger_entries:
1526 item_wh = (sle.item_code, sle.warehouse)
1527 if item_wh in distinct_item_warehouses:
1528 continue
1529 distinct_item_warehouses.add(item_wh)
1530
1531 repost_entry = frappe.new_doc("Repost Item Valuation")
1532 repost_entry.based_on = "Item and Warehouse"
Ankush Menat6dc9b822021-10-28 15:53:18 +05301533
1534 repost_entry.item_code = sle.item_code
1535 repost_entry.warehouse = sle.warehouse
1536 repost_entry.posting_date = sle.posting_date
1537 repost_entry.posting_time = sle.posting_time
1538 repost_entry.allow_zero_rate = allow_zero_rate
1539 repost_entry.flags.ignore_links = True
Ankush Menat0a2964d2021-11-24 15:55:31 +05301540 repost_entry.flags.ignore_permissions = True
Ankush Menat6dc9b822021-10-28 15:53:18 +05301541 repost_entry.submit()
1542 repost_entries.append(repost_entry)
1543
1544 return repost_entries