blob: a1946e8a181873aac785f71d47c95c1c723768e3 [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
Ankush Menate6ab8df2022-02-06 13:02:34 +05306from typing import List, Tuple
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05307
8import frappe
rohitwaghchaure8fdc2442024-01-27 21:37:58 +05309from frappe import _, bold
rohitwaghchaure4b24fcd2024-02-20 23:45:07 +053010from frappe.utils import cint, cstr, flt, get_link_to_form, getdate
Rohan Bansal7f8b95e2021-04-14 14:12:03 +053011
12import erpnext
Chillar Anand915b3432021-09-02 16:44:59 +053013from erpnext.accounts.general_ledger import (
14 make_gl_entries,
15 make_reverse_gl_entries,
16 process_gl_map,
17)
ruthra kumar46ea8142023-07-28 08:29:19 +053018from erpnext.accounts.utils import cancel_exchange_gain_loss_journal, get_fiscal_year
Rushabh Mehta1f847992013-12-12 19:12:19 +053019from erpnext.controllers.accounts_controller import AccountsController
Nabin Hait6d7b0ce2017-06-15 11:09:27 +053020from erpnext.stock import get_warehouse_account_map
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +053021from erpnext.stock.doctype.inventory_dimension.inventory_dimension import (
22 get_evaluated_inventory_dimension,
23)
Rohit Waghchaure01650122024-02-06 13:31:36 +053024from erpnext.stock.doctype.serial_and_batch_bundle.serial_and_batch_bundle import (
25 get_type_of_transaction,
26)
Ankush Menat8f577242022-01-07 11:10:23 +053027from erpnext.stock.stock_ledger import get_items_to_be_repost
Rohan Bansal7f8b95e2021-04-14 14:12:03 +053028
Nabin Haitc3afb252013-03-19 12:01:24 +053029
Ankush Menat494bd9e2022-03-28 18:52:46 +053030class QualityInspectionRequiredError(frappe.ValidationError):
31 pass
32
33
34class QualityInspectionRejectedError(frappe.ValidationError):
35 pass
36
37
38class QualityInspectionNotSubmittedError(frappe.ValidationError):
39 pass
40
Nabin Hait5a9579b2018-12-24 14:54:42 +053041
Rohit Waghchaure795c9432022-08-17 13:48:56 +053042class BatchExpiredError(frappe.ValidationError):
43 pass
44
45
Nabin Haitc3afb252013-03-19 12:01:24 +053046class StockController(AccountsController):
Nabin Hait8af429d2016-11-16 17:21:59 +053047 def validate(self):
48 super(StockController, self).validate()
s-aga-r094ecc12024-02-12 17:36:14 +053049
50 if self.docstatus == 0:
Rohit Waghchaure34233342024-03-21 20:28:16 +053051 for table_name in ["items", "packed_items", "supplied_items"]:
52 self.validate_duplicate_serial_and_batch_bundle(table_name)
53
Ankush Menat494bd9e2022-03-28 18:52:46 +053054 if not self.get("is_return"):
marination596560c2020-06-11 16:39:03 +053055 self.validate_inspection()
rohitwaghchaure9af557f2019-12-30 13:26:47 +053056 self.validate_serialized_batch()
marinationeecfc4c2021-07-22 13:23:54 +053057 self.clean_serial_nos()
marinationfd04e962020-04-03 15:46:48 +053058 self.validate_customer_provided_item()
Anupam Kumar7e1dcf92021-02-11 20:19:30 +053059 self.set_rate_of_stock_uom()
Deepesh Gargb4be2922021-01-28 13:09:56 +053060 self.validate_internal_transfer()
marinationfac40352020-12-07 21:35:49 +053061 self.validate_putaway_capacity()
Rushabh Mehtaffd80a62017-01-16 17:23:20 +053062
Rohit Waghchaure34233342024-03-21 20:28:16 +053063 def validate_duplicate_serial_and_batch_bundle(self, table_name):
64 if not self.get(table_name):
65 return
66
67 sbb_list = []
68 for item in self.get(table_name):
69 if item.get("serial_and_batch_bundle"):
70 sbb_list.append(item.get("serial_and_batch_bundle"))
71
72 if item.get("rejected_serial_and_batch_bundle"):
73 sbb_list.append(item.get("rejected_serial_and_batch_bundle"))
74
75 if sbb_list:
s-aga-r094ecc12024-02-12 17:36:14 +053076 SLE = frappe.qb.DocType("Stock Ledger Entry")
77 data = (
78 frappe.qb.from_(SLE)
79 .select(SLE.voucher_type, SLE.voucher_no, SLE.serial_and_batch_bundle)
80 .where(
81 (SLE.docstatus == 1)
82 & (SLE.serial_and_batch_bundle.notnull())
83 & (SLE.serial_and_batch_bundle.isin(sbb_list))
84 )
85 .limit(1)
86 ).run(as_dict=True)
87
88 if data:
89 data = data[0]
90 frappe.throw(
91 _("Serial and Batch Bundle {0} is already used in {1} {2}.").format(
92 frappe.bold(data.serial_and_batch_bundle), data.voucher_type, data.voucher_no
93 )
94 )
95
Nabin Haita77b8c92020-12-21 14:45:50 +053096 def make_gl_entries(self, gl_entries=None, from_repost=False):
Anand Doshif78d1ae2014-03-28 13:55:00 +053097 if self.docstatus == 2:
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053098 make_reverse_gl_entries(voucher_type=self.doctype, voucher_no=self.name)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053099
Ankush Menat494bd9e2022-03-28 18:52:46 +0530100 provisional_accounting_for_non_stock_items = cint(
Daizy Modi4efc9472022-11-07 09:21:03 +0530101 frappe.get_cached_value(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530102 "Company", self.company, "enable_provisional_accounting_for_non_stock_items"
103 )
104 )
Deepesh Garg528c7132022-02-01 14:42:55 +0530105
Deepesh Gargd1ec0a62023-10-23 00:16:40 +0530106 is_asset_pr = any(d.get("is_fixed_asset") for d in self.get("items"))
107
Ankush Menat494bd9e2022-03-28 18:52:46 +0530108 if (
109 cint(erpnext.is_perpetual_inventory_enabled(self.company))
110 or provisional_accounting_for_non_stock_items
Deepesh Gargd1ec0a62023-10-23 00:16:40 +0530111 or is_asset_pr
Ankush Menat494bd9e2022-03-28 18:52:46 +0530112 ):
Rohit Waghchaure6b33c9b2019-03-08 11:13:35 +0530113 warehouse_account = get_warehouse_account_map(self.company)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530114
Ankush Menat494bd9e2022-03-28 18:52:46 +0530115 if self.docstatus == 1:
Nabin Hait9784d272016-12-30 16:21:35 +0530116 if not gl_entries:
117 gl_entries = self.get_gl_entries(warehouse_account)
Nabin Haita77b8c92020-12-21 14:45:50 +0530118 make_gl_entries(gl_entries, from_repost=from_repost)
Nabin Hait145e5e22013-10-22 23:51:41 +0530119
rohitwaghchaure9af557f2019-12-30 13:26:47 +0530120 def validate_serialized_batch(self):
121 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
Ankush Menat494bd9e2022-03-28 18:52:46 +0530122
Rohit Waghchaure795c9432022-08-17 13:48:56 +0530123 is_material_issue = False
124 if self.doctype == "Stock Entry" and self.purpose == "Material Issue":
125 is_material_issue = True
126
rohitwaghchaure9af557f2019-12-30 13:26:47 +0530127 for d in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530128 if hasattr(d, "serial_no") and hasattr(d, "batch_no") and d.serial_no and d.batch_no:
129 serial_nos = frappe.get_all(
130 "Serial No",
Rohit Waghchaure6b482eb2021-07-23 16:40:45 +0530131 fields=["batch_no", "name", "warehouse"],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530132 filters={"name": ("in", get_serial_nos(d.serial_no))},
Rohit Waghchaure6b482eb2021-07-23 16:40:45 +0530133 )
134
135 for row in serial_nos:
136 if row.warehouse and row.batch_no != d.batch_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530137 frappe.throw(
138 _("Row #{0}: Serial No {1} does not belong to Batch {2}").format(
139 d.idx, row.name, d.batch_no
140 )
141 )
rohitwaghchaure9af557f2019-12-30 13:26:47 +0530142
Rohit Waghchaure795c9432022-08-17 13:48:56 +0530143 if is_material_issue:
144 continue
145
Saqib Ansari903055b2020-10-20 11:59:06 +0530146 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 +0530147 expiry_date = frappe.get_cached_value("Batch", d.get("batch_no"), "expiry_date")
148
149 if expiry_date and getdate(expiry_date) < getdate(self.posting_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530150 frappe.throw(
151 _("Row #{0}: The batch {1} has already expired.").format(
152 d.idx, get_link_to_form("Batch", d.get("batch_no"))
Rohit Waghchaure795c9432022-08-17 13:48:56 +0530153 ),
154 BatchExpiredError,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530155 )
rohitwaghchaure28a48802020-04-28 13:01:43 +0530156
marinationeecfc4c2021-07-22 13:23:54 +0530157 def clean_serial_nos(self):
Ankush Menatb20df372022-01-24 19:19:58 +0530158 from erpnext.stock.doctype.serial_no.serial_no import clean_serial_no_string
159
marinationeecfc4c2021-07-22 13:23:54 +0530160 for row in self.get("items"):
161 if hasattr(row, "serial_no") and row.serial_no:
Ankush Menatb20df372022-01-24 19:19:58 +0530162 # remove extra whitespace and store one serial no on each line
163 row.serial_no = clean_serial_no_string(row.serial_no)
marinationeecfc4c2021-07-22 13:23:54 +0530164
Ankush Menat494bd9e2022-03-28 18:52:46 +0530165 for row in self.get("packed_items") or []:
Ankush Menate177c522022-01-24 19:28:26 +0530166 if hasattr(row, "serial_no") and row.serial_no:
167 # remove extra whitespace and store one serial no on each line
168 row.serial_no = clean_serial_no_string(row.serial_no)
169
rohitwaghchaurebc9c4802024-02-26 23:57:52 +0530170 def make_bundle_using_old_serial_batch_fields(self, table_name=None):
rohitwaghchaurea4cbfab2024-02-19 10:25:36 +0530171 if self.get("_action") == "update_after_submit":
172 return
173
Rohit Waghchaurec1e869f2024-02-05 12:40:26 +0530174 # To handle test cases
175 if frappe.flags.in_test and frappe.flags.use_serial_and_batch_fields:
176 return
177
rohitwaghchaurebc9c4802024-02-26 23:57:52 +0530178 if not table_name:
179 table_name = "items"
180
Rohit Waghchaurec1e869f2024-02-05 12:40:26 +0530181 if self.doctype == "Asset Capitalization":
182 table_name = "stock_items"
183
184 for row in self.get(table_name):
rohitwaghchaure4b24fcd2024-02-20 23:45:07 +0530185 if row.serial_and_batch_bundle and (row.serial_no or row.batch_no):
186 self.validate_serial_nos_and_batches_with_bundle(row)
187
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530188 if not row.serial_no and not row.batch_no and not row.get("rejected_serial_no"):
189 continue
190
191 if not row.use_serial_batch_fields and (
192 row.serial_no or row.batch_no or row.get("rejected_serial_no")
193 ):
rohitwaghchaure4b24fcd2024-02-20 23:45:07 +0530194 row.use_serial_batch_fields = 1
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530195
196 if row.use_serial_batch_fields and (
Rohit Waghchaurec1e869f2024-02-05 12:40:26 +0530197 not row.serial_and_batch_bundle and not row.get("rejected_serial_and_batch_bundle")
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530198 ):
rohitwaghchaurecef62912024-03-06 19:43:36 +0530199 bundle_details = {
Rohit Waghchaure34233342024-03-21 20:28:16 +0530200 "item_code": row.get("rm_item_code") or row.item_code,
rohitwaghchaurecef62912024-03-06 19:43:36 +0530201 "posting_date": self.posting_date,
202 "posting_time": self.posting_time,
203 "voucher_type": self.doctype,
204 "voucher_no": self.name,
205 "voucher_detail_no": row.name,
206 "company": self.company,
207 "is_rejected": 1 if row.get("rejected_warehouse") else 0,
rohitwaghchaurecef62912024-03-06 19:43:36 +0530208 "use_serial_batch_fields": row.use_serial_batch_fields,
209 "do_not_submit": True,
210 }
Rohit Waghchaure01650122024-02-06 13:31:36 +0530211
Rohit Waghchaure34233342024-03-21 20:28:16 +0530212 if row.get("qty") or row.get("consumed_qty"):
rohitwaghchaure01856a62024-03-07 14:14:19 +0530213 self.update_bundle_details(bundle_details, table_name, row)
214 self.create_serial_batch_bundle(bundle_details, row)
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530215
rohitwaghchaure01856a62024-03-07 14:14:19 +0530216 if row.get("rejected_qty"):
217 self.update_bundle_details(bundle_details, table_name, row, is_rejected=True)
218 self.create_serial_batch_bundle(bundle_details, row)
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530219
rohitwaghchaure01856a62024-03-07 14:14:19 +0530220 def update_bundle_details(self, bundle_details, table_name, row, is_rejected=False):
221 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
222
rohitwaghchaurecef62912024-03-06 19:43:36 +0530223 # Since qty field is different for different doctypes
224 qty = row.get("qty")
225 warehouse = row.get("warehouse")
226
227 if table_name == "packed_items":
228 type_of_transaction = "Inward"
229 if not self.is_return:
230 type_of_transaction = "Outward"
Rohit Waghchaure34233342024-03-21 20:28:16 +0530231 elif table_name == "supplied_items":
232 qty = row.consumed_qty
233 warehouse = self.supplier_warehouse
234 type_of_transaction = "Outward"
235 if self.is_return:
236 type_of_transaction = "Inward"
rohitwaghchaurecef62912024-03-06 19:43:36 +0530237 else:
238 type_of_transaction = get_type_of_transaction(self, row)
239
240 if hasattr(row, "stock_qty"):
241 qty = row.stock_qty
242
243 if self.doctype == "Stock Entry":
244 qty = row.transfer_qty
245 warehouse = row.s_warehouse or row.t_warehouse
246
rohitwaghchaure01856a62024-03-07 14:14:19 +0530247 serial_nos = row.serial_no
248 if is_rejected:
249 serial_nos = row.get("rejected_serial_no")
250 type_of_transaction = "Inward" if not self.is_return else "Outward"
251 qty = row.get("rejected_qty")
252 warehouse = row.get("rejected_warehouse")
253
rohitwaghchaure59222812024-03-15 17:55:41 +0530254 if (
255 self.is_internal_transfer()
256 and self.doctype in ["Sales Invoice", "Delivery Note"]
257 and self.is_return
258 ):
259 warehouse = row.get("target_warehouse") or row.get("warehouse")
260 type_of_transaction = "Outward"
261
rohitwaghchaurecef62912024-03-06 19:43:36 +0530262 bundle_details.update(
263 {
264 "qty": qty,
rohitwaghchaure01856a62024-03-07 14:14:19 +0530265 "is_rejected": is_rejected,
rohitwaghchaurecef62912024-03-06 19:43:36 +0530266 "type_of_transaction": type_of_transaction,
267 "warehouse": warehouse,
268 "batches": frappe._dict({row.batch_no: qty}) if row.batch_no else None,
rohitwaghchaure01856a62024-03-07 14:14:19 +0530269 "serial_nos": get_serial_nos(serial_nos) if serial_nos else None,
270 "batch_no": row.batch_no,
rohitwaghchaurecef62912024-03-06 19:43:36 +0530271 }
272 )
273
rohitwaghchaure01856a62024-03-07 14:14:19 +0530274 def create_serial_batch_bundle(self, bundle_details, row):
275 from erpnext.stock.serial_batch_bundle import SerialBatchCreation
276
277 sn_doc = SerialBatchCreation(bundle_details).make_serial_and_batch_bundle()
278
279 field = "serial_and_batch_bundle"
280 if bundle_details.get("is_rejected"):
281 field = "rejected_serial_and_batch_bundle"
282
283 row.set(field, sn_doc.name)
284 row.db_set({field: sn_doc.name})
285
rohitwaghchaure4b24fcd2024-02-20 23:45:07 +0530286 def validate_serial_nos_and_batches_with_bundle(self, row):
287 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
288
289 throw_error = False
290 if row.serial_no:
291 serial_nos = frappe.get_all(
292 "Serial and Batch Entry", fields=["serial_no"], filters={"parent": row.serial_and_batch_bundle}
293 )
294 serial_nos = sorted([cstr(d.serial_no) for d in serial_nos])
295 parsed_serial_nos = get_serial_nos(row.serial_no)
296
297 if len(serial_nos) != len(parsed_serial_nos):
298 throw_error = True
299 elif serial_nos != parsed_serial_nos:
300 for serial_no in serial_nos:
301 if serial_no not in parsed_serial_nos:
302 throw_error = True
303 break
304
305 elif row.batch_no:
306 batches = frappe.get_all(
307 "Serial and Batch Entry", fields=["batch_no"], filters={"parent": row.serial_and_batch_bundle}
308 )
309 batches = sorted([d.batch_no for d in batches])
310
311 if batches != [row.batch_no]:
312 throw_error = True
313
314 if throw_error:
315 frappe.throw(
316 _(
317 "At row {0}: Serial and Batch Bundle {1} has already created. Please remove the values from the serial no or batch no fields."
318 ).format(row.idx, row.serial_and_batch_bundle)
319 )
320
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530321 def set_use_serial_batch_fields(self):
322 if frappe.db.get_single_value("Stock Settings", "use_serial_batch_fields"):
323 for row in self.items:
324 row.use_serial_batch_fields = 1
325
Ankush Menat494bd9e2022-03-28 18:52:46 +0530326 def get_gl_entries(
327 self, warehouse_account=None, default_expense_account=None, default_cost_center=None
328 ):
Nabin Haitadeb9762014-10-06 11:53:52 +0530329
Nabin Hait142007a2013-09-17 15:15:16 +0530330 if not warehouse_account:
Rohit Waghchaure6b33c9b2019-03-08 11:13:35 +0530331 warehouse_account = get_warehouse_account_map(self.company)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530332
Anand Doshide1a97d2014-04-17 11:37:46 +0530333 sle_map = self.get_stock_ledger_details()
334 voucher_details = self.get_voucher_details(default_expense_account, default_cost_center, sle_map)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530335
Nabin Hait2e296fa2013-08-28 18:53:11 +0530336 gl_list = []
Nabin Hait7a75e102013-09-17 10:21:20 +0530337 warehouse_with_no_account = []
Nabin Hait19f8fa52021-02-22 22:27:22 +0530338 precision = self.get_debit_field_precision()
Nabin Hait8c61f342016-12-15 13:46:03 +0530339 for item_row in voucher_details:
340 sle_list = sle_map.get(item_row.name)
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530341 sle_rounding_diff = 0.0
Nabin Hait2e296fa2013-08-28 18:53:11 +0530342 if sle_list:
343 for sle in sle_list:
344 if warehouse_account.get(sle.warehouse):
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530345 # from warehouse account
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530346
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530347 sle_rounding_diff += flt(sle.stock_value_difference)
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530348
Nabin Hait8c61f342016-12-15 13:46:03 +0530349 self.check_expense_account(item_row)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530350
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530351 # expense account/ target_warehouse / source_warehouse
Ankush Menat494bd9e2022-03-28 18:52:46 +0530352 if item_row.get("target_warehouse"):
353 warehouse = item_row.get("target_warehouse")
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530354 expense_account = warehouse_account[warehouse]["account"]
355 else:
356 expense_account = item_row.expense_account
357
Ankush Menat494bd9e2022-03-28 18:52:46 +0530358 gl_list.append(
359 self.get_gl_dict(
360 {
361 "account": warehouse_account[sle.warehouse]["account"],
362 "against": expense_account,
363 "cost_center": item_row.cost_center,
364 "project": item_row.project or self.get("project"),
365 "remarks": self.get("remarks") or _("Accounting Entry for Stock"),
366 "debit": flt(sle.stock_value_difference, precision),
367 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
368 },
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"),
383 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
384 },
385 item=item_row,
386 )
387 )
Nabin Hait7a75e102013-09-17 10:21:20 +0530388 elif sle.warehouse not in warehouse_with_no_account:
389 warehouse_with_no_account.append(sle.warehouse)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530390
Deepesh Garg9aa5e202022-10-12 15:53:28 +0530391 if abs(sle_rounding_diff) > (1.0 / (10**precision)) and self.is_internal_transfer():
Deepesh Garg1c05c002022-10-12 14:19:09 +0530392 warehouse_asset_account = ""
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530393 if self.get("is_internal_customer"):
Deepesh Garg1c05c002022-10-12 14:19:09 +0530394 warehouse_asset_account = warehouse_account[item_row.get("target_warehouse")]["account"]
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530395 elif self.get("is_internal_supplier"):
Deepesh Garg1c05c002022-10-12 14:19:09 +0530396 warehouse_asset_account = warehouse_account[item_row.get("warehouse")]["account"]
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530397
Daizy Modi4efc9472022-11-07 09:21:03 +0530398 expense_account = frappe.get_cached_value("Company", self.company, "default_expense_account")
Deepesh Gargce9164e2023-07-11 12:03:38 +0530399 if not expense_account:
400 frappe.throw(
401 _(
402 "Please set default cost of goods sold account in company {0} for booking rounding gain and loss during stock transfer"
403 ).format(frappe.bold(self.company))
404 )
Deepesh Garg1c05c002022-10-12 14:19:09 +0530405
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530406 gl_list.append(
407 self.get_gl_dict(
408 {
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530409 "account": expense_account,
Deepesh Garg1c05c002022-10-12 14:19:09 +0530410 "against": warehouse_asset_account,
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530411 "cost_center": item_row.cost_center,
412 "project": item_row.project or self.get("project"),
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530413 "remarks": _("Rounding gain/loss Entry for Stock Transfer"),
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530414 "debit": sle_rounding_diff,
415 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
416 },
417 warehouse_account[sle.warehouse]["account_currency"],
418 item=item_row,
419 )
420 )
421
422 gl_list.append(
423 self.get_gl_dict(
424 {
Deepesh Garg1c05c002022-10-12 14:19:09 +0530425 "account": warehouse_asset_account,
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530426 "against": expense_account,
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530427 "cost_center": item_row.cost_center,
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530428 "remarks": _("Rounding gain/loss Entry for Stock Transfer"),
429 "credit": sle_rounding_diff,
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530430 "project": item_row.get("project") or self.get("project"),
431 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
432 },
433 item=item_row,
434 )
435 )
436
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530437 if warehouse_with_no_account:
Nabin Haitd6625022016-10-24 18:17:57 +0530438 for wh in warehouse_with_no_account:
Daizy Modi4efc9472022-11-07 09:21:03 +0530439 if frappe.get_cached_value("Warehouse", wh, "company"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530440 frappe.throw(
441 _(
442 "Warehouse {0} is not linked to any account, please mention the account in the warehouse record or set default inventory account in company {1}."
443 ).format(wh, self.company)
444 )
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530445
Nabin Hait19f8fa52021-02-22 22:27:22 +0530446 return process_gl_map(gl_list, precision=precision)
447
448 def get_debit_field_precision(self):
449 if not frappe.flags.debit_field_precision:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530450 frappe.flags.debit_field_precision = frappe.get_precision(
451 "GL Entry", "debit_in_account_currency"
452 )
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
Ankush Menate6ab8df2022-02-06 13:02:34 +0530485 def get_items_and_warehouses(self) -> Tuple[List[str], List[str]]:
486 """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`
766 where has_serial_no=1 and name in ({})""".format(
767 ", ".join(["%s"] * len(item_codes))
768 ),
769 tuple(item_codes),
770 )
Anand Doshia740f752014-06-25 13:31:02 +0530771
772 return serialized_items
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +0530773
Saurabh2e292062015-11-18 17:03:33 +0530774 def validate_warehouse(self):
Rohan Bansal7f8b95e2021-04-14 14:12:03 +0530775 from erpnext.stock.utils import validate_disabled_warehouse, validate_warehouse_company
Saurabh2e292062015-11-18 17:03:33 +0530776
Ankush Menat494bd9e2022-03-28 18:52:46 +0530777 warehouses = list(set(d.warehouse for d in self.get("items") if getattr(d, "warehouse", None)))
Saurabh2e292062015-11-18 17:03:33 +0530778
Ankush Menat494bd9e2022-03-28 18:52:46 +0530779 target_warehouses = list(
780 set([d.target_warehouse for d in self.get("items") if getattr(d, "target_warehouse", None)])
781 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530782
783 warehouses.extend(target_warehouses)
784
Ankush Menat494bd9e2022-03-28 18:52:46 +0530785 from_warehouse = list(
786 set([d.from_warehouse for d in self.get("items") if getattr(d, "from_warehouse", None)])
787 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530788
789 warehouses.extend(from_warehouse)
790
Saurabh2e292062015-11-18 17:03:33 +0530791 for w in warehouses:
Jannat Patel30c88732021-02-11 11:46:48 +0530792 validate_disabled_warehouse(w)
Saurabh2e292062015-11-18 17:03:33 +0530793 validate_warehouse_company(w, self.company)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530794
Anand Doshi6b71ef52016-01-06 16:32:06 +0530795 def update_billing_percentage(self, update_modified=True):
marinationd6596a12020-11-02 15:07:48 +0530796 target_ref_field = "amount"
797 if self.doctype == "Delivery Note":
798 target_ref_field = "amount - (returned_qty * rate)"
799
Ankush Menat494bd9e2022-03-28 18:52:46 +0530800 self._update_percent_field(
801 {
802 "target_dt": self.doctype + " Item",
803 "target_parent_dt": self.doctype,
804 "target_parent_field": "per_billed",
805 "target_ref_field": target_ref_field,
806 "target_field": "billed_amt",
807 "name": self.name,
808 },
809 update_modified,
810 )
Anand Doshia740f752014-06-25 13:31:02 +0530811
Nabin Hait8af429d2016-11-16 17:21:59 +0530812 def validate_inspection(self):
marination9ac9a4e2021-06-21 16:18:35 +0530813 """Checks if quality inspection is set/ is valid for Items that require inspection."""
814 inspection_fieldname_map = {
815 "Purchase Receipt": "inspection_required_before_purchase",
816 "Purchase Invoice": "inspection_required_before_purchase",
s-aga-r3fdcd332023-08-23 12:15:35 +0530817 "Subcontracting Receipt": "inspection_required_before_purchase",
marination9ac9a4e2021-06-21 16:18:35 +0530818 "Sales Invoice": "inspection_required_before_delivery",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530819 "Delivery Note": "inspection_required_before_delivery",
marination9ac9a4e2021-06-21 16:18:35 +0530820 }
821 inspection_required_fieldname = inspection_fieldname_map.get(self.doctype)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530822
marination9ac9a4e2021-06-21 16:18:35 +0530823 # return if inspection is not required on document level
Ankush Menat494bd9e2022-03-28 18:52:46 +0530824 if (
825 (not inspection_required_fieldname and self.doctype != "Stock Entry")
826 or (self.doctype == "Stock Entry" and not self.inspection_required)
827 or (self.doctype in ["Sales Invoice", "Purchase Invoice"] and not self.update_stock)
828 ):
829 return
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530830
Ankush Menat494bd9e2022-03-28 18:52:46 +0530831 for row in self.get("items"):
marination9ac9a4e2021-06-21 16:18:35 +0530832 qi_required = False
Ankush Menat494bd9e2022-03-28 18:52:46 +0530833 if inspection_required_fieldname and frappe.db.get_value(
834 "Item", row.item_code, inspection_required_fieldname
835 ):
marination9ac9a4e2021-06-21 16:18:35 +0530836 qi_required = True
837 elif self.doctype == "Stock Entry" and row.t_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530838 qi_required = True # inward stock needs inspection
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530839
Ankush Menat494bd9e2022-03-28 18:52:46 +0530840 if qi_required: # validate row only if inspection is required on item level
marination9ac9a4e2021-06-21 16:18:35 +0530841 self.validate_qi_presence(row)
842 if self.docstatus == 1:
843 self.validate_qi_submission(row)
844 self.validate_qi_rejection(row)
845
846 def validate_qi_presence(self, row):
847 """Check if QI is present on row level. Warn on save and stop on submit if missing."""
848 if not row.quality_inspection:
marination654e9d82021-06-21 16:51:12 +0530849 msg = f"Row #{row.idx}: Quality Inspection is required for Item {frappe.bold(row.item_code)}"
marination9ac9a4e2021-06-21 16:18:35 +0530850 if self.docstatus == 1:
marination654e9d82021-06-21 16:51:12 +0530851 frappe.throw(_(msg), title=_("Inspection Required"), exc=QualityInspectionRequiredError)
marination9ac9a4e2021-06-21 16:18:35 +0530852 else:
marination654e9d82021-06-21 16:51:12 +0530853 frappe.msgprint(_(msg), title=_("Inspection Required"), indicator="blue")
marination9ac9a4e2021-06-21 16:18:35 +0530854
855 def validate_qi_submission(self, row):
856 """Check if QI is submitted on row level, during submission"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530857 action = frappe.db.get_single_value(
858 "Stock Settings", "action_if_quality_inspection_is_not_submitted"
859 )
marination9ac9a4e2021-06-21 16:18:35 +0530860 qa_docstatus = frappe.db.get_value("Quality Inspection", row.quality_inspection, "docstatus")
861
barredterraeb9ee3f2023-12-05 11:22:55 +0100862 if qa_docstatus != 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530863 link = frappe.utils.get_link_to_form("Quality Inspection", row.quality_inspection)
864 msg = (
865 f"Row #{row.idx}: Quality Inspection {link} is not submitted for the item: {row.item_code}"
866 )
marination9ac9a4e2021-06-21 16:18:35 +0530867 if action == "Stop":
marination654e9d82021-06-21 16:51:12 +0530868 frappe.throw(_(msg), title=_("Inspection Submission"), exc=QualityInspectionNotSubmittedError)
marination9ac9a4e2021-06-21 16:18:35 +0530869 else:
Marica9ba3fce2021-06-22 11:20:17 +0530870 frappe.msgprint(_(msg), alert=True, indicator="orange")
marination9ac9a4e2021-06-21 16:18:35 +0530871
872 def validate_qi_rejection(self, row):
873 """Check if QI is rejected on row level, during submission"""
marinationf67f13c2021-07-10 18:24:24 +0530874 action = frappe.db.get_single_value("Stock Settings", "action_if_quality_inspection_is_rejected")
marination9ac9a4e2021-06-21 16:18:35 +0530875 qa_status = frappe.db.get_value("Quality Inspection", row.quality_inspection, "status")
876
877 if qa_status == "Rejected":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530878 link = frappe.utils.get_link_to_form("Quality Inspection", row.quality_inspection)
marination654e9d82021-06-21 16:51:12 +0530879 msg = f"Row #{row.idx}: Quality Inspection {link} was rejected for item {row.item_code}"
marination9ac9a4e2021-06-21 16:18:35 +0530880 if action == "Stop":
marination654e9d82021-06-21 16:51:12 +0530881 frappe.throw(_(msg), title=_("Inspection Rejected"), exc=QualityInspectionRejectedError)
marination9ac9a4e2021-06-21 16:18:35 +0530882 else:
marination654e9d82021-06-21 16:51:12 +0530883 frappe.msgprint(_(msg), alert=True, indicator="orange")
Manas Solankicc902412016-11-10 19:15:11 +0530884
Nabin Haitb2d3c0f2018-06-14 15:54:34 +0530885 def update_blanket_order(self):
Nabin Haitd1f40ad2018-06-14 17:09:55 +0530886 blanket_orders = list(set([d.blanket_order for d in self.items if d.blanket_order]))
Nabin Haitb2d3c0f2018-06-14 15:54:34 +0530887 for blanket_order in blanket_orders:
888 frappe.get_doc("Blanket Order", blanket_order).update_ordered_qty()
Manas Solankie5e87f72018-05-28 20:07:08 +0530889
marinationfd04e962020-04-03 15:46:48 +0530890 def validate_customer_provided_item(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530891 for d in self.get("items"):
marinationfd04e962020-04-03 15:46:48 +0530892 # Customer Provided parts will have zero valuation rate
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +0530893 if frappe.get_cached_value("Item", d.item_code, "is_customer_provided_item"):
marinationfd04e962020-04-03 15:46:48 +0530894 d.allow_zero_valuation_rate = 1
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530895
Anupam Kumar7e1dcf92021-02-11 20:19:30 +0530896 def set_rate_of_stock_uom(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530897 if self.doctype in [
898 "Purchase Receipt",
899 "Purchase Invoice",
900 "Purchase Order",
901 "Sales Invoice",
902 "Sales Order",
903 "Delivery Note",
904 "Quotation",
905 ]:
Anupam Kumar7e1dcf92021-02-11 20:19:30 +0530906 for d in self.get("items"):
Rohit Waghchaure13584432021-03-26 14:11:50 +0530907 d.stock_uom_rate = d.rate / (d.conversion_factor or 1)
Anupam Kumar7e1dcf92021-02-11 20:19:30 +0530908
Deepesh Gargb4be2922021-01-28 13:09:56 +0530909 def validate_internal_transfer(self):
rohitwaghchaure5136fe12023-10-22 20:03:02 +0530910 if self.doctype in ("Sales Invoice", "Delivery Note", "Purchase Invoice", "Purchase Receipt"):
911 if self.is_internal_transfer():
912 self.validate_in_transit_warehouses()
913 self.validate_multi_currency()
914 self.validate_packed_items()
rohitwaghchaure8fdc2442024-01-27 21:37:58 +0530915
916 if self.get("is_internal_supplier"):
917 self.validate_internal_transfer_qty()
rohitwaghchaure5136fe12023-10-22 20:03:02 +0530918 else:
919 self.validate_internal_transfer_warehouse()
920
921 def validate_internal_transfer_warehouse(self):
922 for row in self.items:
923 if row.get("target_warehouse"):
924 row.target_warehouse = None
925
926 if row.get("from_warehouse"):
927 row.from_warehouse = None
Deepesh Gargb4be2922021-01-28 13:09:56 +0530928
929 def validate_in_transit_warehouses(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530930 if (
931 self.doctype == "Sales Invoice" and self.get("update_stock")
932 ) or self.doctype == "Delivery Note":
933 for item in self.get("items"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530934 if not item.target_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530935 frappe.throw(
936 _("Row {0}: Target Warehouse is mandatory for internal transfers").format(item.idx)
937 )
Deepesh Gargb4be2922021-01-28 13:09:56 +0530938
Ankush Menat494bd9e2022-03-28 18:52:46 +0530939 if (
940 self.doctype == "Purchase Invoice" and self.get("update_stock")
941 ) or self.doctype == "Purchase Receipt":
942 for item in self.get("items"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530943 if not item.from_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530944 frappe.throw(
945 _("Row {0}: From Warehouse is mandatory for internal transfers").format(item.idx)
946 )
Deepesh Gargb4be2922021-01-28 13:09:56 +0530947
948 def validate_multi_currency(self):
949 if self.currency != self.company_currency:
950 frappe.throw(_("Internal transfers can only be done in company's default currency"))
951
952 def validate_packed_items(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530953 if self.doctype in ("Sales Invoice", "Delivery Note Item") and self.get("packed_items"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530954 frappe.throw(_("Packed Items cannot be transferred internally"))
955
rohitwaghchaure8fdc2442024-01-27 21:37:58 +0530956 def validate_internal_transfer_qty(self):
957 if self.doctype not in ["Purchase Invoice", "Purchase Receipt"]:
958 return
959
960 item_wise_transfer_qty = self.get_item_wise_inter_transfer_qty()
961 if not item_wise_transfer_qty:
962 return
963
964 item_wise_received_qty = self.get_item_wise_inter_received_qty()
965 precision = frappe.get_precision(self.doctype + " Item", "qty")
966
967 over_receipt_allowance = frappe.db.get_single_value(
968 "Stock Settings", "over_delivery_receipt_allowance"
969 )
970
971 parent_doctype = {
972 "Purchase Receipt": "Delivery Note",
973 "Purchase Invoice": "Sales Invoice",
974 }.get(self.doctype)
975
976 for key, transferred_qty in item_wise_transfer_qty.items():
977 recevied_qty = flt(item_wise_received_qty.get(key), precision)
978 if over_receipt_allowance:
979 transferred_qty = transferred_qty + flt(
980 transferred_qty * over_receipt_allowance / 100, precision
981 )
982
983 if recevied_qty > flt(transferred_qty, precision):
984 frappe.throw(
985 _("For Item {0} cannot be received more than {1} qty against the {2} {3}").format(
986 bold(key[1]),
987 bold(flt(transferred_qty, precision)),
988 bold(parent_doctype),
989 get_link_to_form(parent_doctype, self.get("inter_company_reference")),
990 )
991 )
992
993 def get_item_wise_inter_transfer_qty(self):
994 reference_field = "inter_company_reference"
995 if self.doctype == "Purchase Invoice":
996 reference_field = "inter_company_invoice_reference"
997
998 parent_doctype = {
999 "Purchase Receipt": "Delivery Note",
1000 "Purchase Invoice": "Sales Invoice",
1001 }.get(self.doctype)
1002
1003 child_doctype = parent_doctype + " Item"
1004
1005 parent_tab = frappe.qb.DocType(parent_doctype)
1006 child_tab = frappe.qb.DocType(child_doctype)
1007
1008 query = (
1009 frappe.qb.from_(parent_doctype)
1010 .inner_join(child_tab)
1011 .on(child_tab.parent == parent_tab.name)
1012 .select(
1013 child_tab.name,
1014 child_tab.item_code,
1015 child_tab.qty,
1016 )
1017 .where((parent_tab.name == self.get(reference_field)) & (parent_tab.docstatus == 1))
1018 )
1019
1020 data = query.run(as_dict=True)
1021 item_wise_transfer_qty = defaultdict(float)
1022 for row in data:
1023 item_wise_transfer_qty[(row.name, row.item_code)] += flt(row.qty)
1024
1025 return item_wise_transfer_qty
1026
1027 def get_item_wise_inter_received_qty(self):
1028 child_doctype = self.doctype + " Item"
1029
1030 parent_tab = frappe.qb.DocType(self.doctype)
1031 child_tab = frappe.qb.DocType(child_doctype)
1032
1033 query = (
1034 frappe.qb.from_(self.doctype)
1035 .inner_join(child_tab)
1036 .on(child_tab.parent == parent_tab.name)
1037 .select(
1038 child_tab.item_code,
1039 child_tab.qty,
1040 )
1041 .where(parent_tab.docstatus < 2)
1042 )
1043
1044 if self.doctype == "Purchase Invoice":
1045 query = query.select(
1046 child_tab.sales_invoice_item.as_("name"),
1047 )
1048
1049 query = query.where(
1050 parent_tab.inter_company_invoice_reference == self.inter_company_invoice_reference
1051 )
1052 else:
1053 query = query.select(
1054 child_tab.delivery_note_item.as_("name"),
1055 )
1056
1057 query = query.where(parent_tab.inter_company_reference == self.inter_company_reference)
1058
1059 data = query.run(as_dict=True)
1060 item_wise_transfer_qty = defaultdict(float)
1061 for row in data:
1062 item_wise_transfer_qty[(row.name, row.item_code)] += flt(row.qty)
1063
1064 return item_wise_transfer_qty
1065
marinationfac40352020-12-07 21:35:49 +05301066 def validate_putaway_capacity(self):
1067 # if over receipt is attempted while 'apply putaway rule' is disabled
1068 # and if rule was applied on the transaction, validate it.
marination957615b2021-01-18 23:47:24 +05301069 from erpnext.stock.doctype.putaway_rule.putaway_rule import get_available_putaway_capacity
Ankush Menat494bd9e2022-03-28 18:52:46 +05301070
1071 valid_doctype = self.doctype in (
1072 "Purchase Receipt",
1073 "Stock Entry",
1074 "Purchase Invoice",
1075 "Stock Reconciliation",
1076 )
marinationfac40352020-12-07 21:35:49 +05301077
rohitwaghchaureb966c062024-02-12 12:49:09 +05301078 if not frappe.get_all("Putaway Rule", limit=1):
1079 return
1080
marination957615b2021-01-18 23:47:24 +05301081 if self.doctype == "Purchase Invoice" and self.get("update_stock") == 0:
1082 valid_doctype = False
1083
1084 if valid_doctype:
marinationfac40352020-12-07 21:35:49 +05301085 rule_map = defaultdict(dict)
1086 for item in self.get("items"):
marination957615b2021-01-18 23:47:24 +05301087 warehouse_field = "t_warehouse" if self.doctype == "Stock Entry" else "warehouse"
Ankush Menat494bd9e2022-03-28 18:52:46 +05301088 rule = frappe.db.get_value(
1089 "Putaway Rule",
1090 {"item_code": item.get("item_code"), "warehouse": item.get(warehouse_field)},
1091 ["name", "disable"],
1092 as_dict=True,
1093 )
marination957615b2021-01-18 23:47:24 +05301094 if rule:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301095 if rule.get("disabled"):
1096 continue # dont validate for disabled rule
marination957615b2021-01-18 23:47:24 +05301097
1098 if self.doctype == "Stock Reconciliation":
1099 stock_qty = flt(item.qty)
1100 else:
1101 stock_qty = flt(item.transfer_qty) if self.doctype == "Stock Entry" else flt(item.stock_qty)
1102
1103 rule_name = rule.get("name")
1104 if not rule_map[rule_name]:
1105 rule_map[rule_name]["warehouse"] = item.get(warehouse_field)
1106 rule_map[rule_name]["item"] = item.get("item_code")
1107 rule_map[rule_name]["qty_put"] = 0
1108 rule_map[rule_name]["capacity"] = get_available_putaway_capacity(rule_name)
1109 rule_map[rule_name]["qty_put"] += flt(stock_qty)
marinationfac40352020-12-07 21:35:49 +05301110
1111 for rule, values in rule_map.items():
1112 if flt(values["qty_put"]) > flt(values["capacity"]):
marination957615b2021-01-18 23:47:24 +05301113 message = self.prepare_over_receipt_message(rule, values)
marinationfac40352020-12-07 21:35:49 +05301114 frappe.throw(msg=message, title=_("Over Receipt"))
marination957615b2021-01-18 23:47:24 +05301115
1116 def prepare_over_receipt_message(self, rule, values):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301117 message = _(
1118 "{0} qty of Item {1} is being received into Warehouse {2} with capacity {3}."
1119 ).format(
1120 frappe.bold(values["qty_put"]),
1121 frappe.bold(values["item"]),
1122 frappe.bold(values["warehouse"]),
1123 frappe.bold(values["capacity"]),
1124 )
marination957615b2021-01-18 23:47:24 +05301125 message += "<br><br>"
1126 rule_link = frappe.utils.get_link_to_form("Putaway Rule", rule)
Ankush Menatad6a2652021-04-17 16:50:02 +05301127 message += _("Please adjust the qty or edit {0} to proceed.").format(rule_link)
marination957615b2021-01-18 23:47:24 +05301128 return message
marinationfac40352020-12-07 21:35:49 +05301129
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +05301130 def repost_future_sle_and_gle(self, force=False):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301131 args = frappe._dict(
1132 {
1133 "posting_date": self.posting_date,
1134 "posting_time": self.posting_time,
1135 "voucher_type": self.doctype,
1136 "voucher_no": self.name,
1137 "company": self.company,
1138 }
1139 )
Ankush Menat3638fbf2022-03-01 18:17:14 +05301140
Rohit Waghchaure6e661e72023-05-16 16:23:52 +05301141 if self.docstatus == 2:
1142 force = True
1143
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +05301144 if force or future_sle_exists(args) or repost_required_for_queue(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301145 item_based_reposting = cint(
1146 frappe.db.get_single_value("Stock Reposting Settings", "item_based_reposting")
1147 )
Ankush Menat45dd46b2021-11-02 10:50:52 +05301148 if item_based_reposting:
1149 create_item_wise_repost_entries(voucher_type=self.doctype, voucher_no=self.name)
1150 else:
1151 create_repost_item_valuation_entry(args)
1152
Sagar Sharmaf4673942022-08-21 21:26:06 +05301153 def add_gl_entry(
1154 self,
1155 gl_entries,
1156 account,
1157 cost_center,
1158 debit,
1159 credit,
1160 remarks,
1161 against_account,
1162 debit_in_account_currency=None,
1163 credit_in_account_currency=None,
1164 account_currency=None,
1165 project=None,
1166 voucher_detail_no=None,
1167 item=None,
1168 posting_date=None,
1169 ):
1170
1171 gl_entry = {
1172 "account": account,
1173 "cost_center": cost_center,
1174 "debit": debit,
1175 "credit": credit,
1176 "against": against_account,
1177 "remarks": remarks,
1178 }
1179
1180 if voucher_detail_no:
1181 gl_entry.update({"voucher_detail_no": voucher_detail_no})
1182
1183 if debit_in_account_currency:
1184 gl_entry.update({"debit_in_account_currency": debit_in_account_currency})
1185
1186 if credit_in_account_currency:
1187 gl_entry.update({"credit_in_account_currency": credit_in_account_currency})
1188
1189 if posting_date:
1190 gl_entry.update({"posting_date": posting_date})
1191
1192 gl_entries.append(self.get_gl_dict(gl_entry, item=item))
1193
Ankush Menat494bd9e2022-03-28 18:52:46 +05301194
Deepesh Garg2e52a632023-06-04 19:20:28 +05301195@frappe.whitelist()
Deepesh Garg0e68da52023-06-22 15:43:32 +05301196def show_accounting_ledger_preview(company, doctype, docname):
Smit Vora77cc91d2023-10-19 22:35:55 +05301197 filters = frappe._dict(company=company, include_dimensions=1)
Deepesh Garg0e68da52023-06-22 15:43:32 +05301198 doc = frappe.get_doc(doctype, docname)
Smit Vora77cc91d2023-10-19 22:35:55 +05301199 doc.run_method("before_gl_preview")
Deepesh Garg0e68da52023-06-22 15:43:32 +05301200
1201 gl_columns, gl_data = get_accounting_ledger_preview(doc, filters)
1202
Deepesh Gargd9e7bc52023-06-22 16:07:32 +05301203 frappe.db.rollback()
Deepesh Garg0e68da52023-06-22 15:43:32 +05301204
1205 return {"gl_columns": gl_columns, "gl_data": gl_data}
1206
1207
1208@frappe.whitelist()
1209def show_stock_ledger_preview(company, doctype, docname):
Smit Vora77cc91d2023-10-19 22:35:55 +05301210 filters = frappe._dict(company=company)
Deepesh Garg2e52a632023-06-04 19:20:28 +05301211 doc = frappe.get_doc(doctype, docname)
Smit Vora77cc91d2023-10-19 22:35:55 +05301212 doc.run_method("before_sl_preview")
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301213
Deepesh Garg011ac132023-06-12 18:42:49 +05301214 sl_columns, sl_data = get_stock_ledger_preview(doc, filters)
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301215
Deepesh Gargd9e7bc52023-06-22 16:07:32 +05301216 frappe.db.rollback()
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301217
Deepesh Garg2e52a632023-06-04 19:20:28 +05301218 return {
Deepesh Garg011ac132023-06-12 18:42:49 +05301219 "sl_columns": sl_columns,
1220 "sl_data": sl_data,
Deepesh Garg2e52a632023-06-04 19:20:28 +05301221 }
1222
1223
Deepesh Garg011ac132023-06-12 18:42:49 +05301224def get_accounting_ledger_preview(doc, filters):
1225 from erpnext.accounts.report.general_ledger.general_ledger import get_columns as get_gl_columns
1226
1227 gl_columns, gl_data = [], []
1228 fields = [
1229 "posting_date",
1230 "account",
1231 "debit",
1232 "credit",
1233 "against",
1234 "party",
1235 "party_type",
Deepesh Garg0e68da52023-06-22 15:43:32 +05301236 "cost_center",
Deepesh Garg011ac132023-06-12 18:42:49 +05301237 "against_voucher_type",
1238 "against_voucher",
1239 ]
1240
1241 doc.docstatus = 1
Deepesh Garg0e68da52023-06-22 15:43:32 +05301242
1243 if doc.get("update_stock") or doc.doctype in ("Purchase Receipt", "Delivery Note"):
1244 doc.update_stock_ledger()
1245
Deepesh Garg011ac132023-06-12 18:42:49 +05301246 doc.make_gl_entries()
1247 columns = get_gl_columns(filters)
1248 gl_entries = get_gl_entries_for_preview(doc.doctype, doc.name, fields)
1249
1250 gl_columns = get_columns(columns, fields)
1251 gl_data = get_data(fields, gl_entries)
1252
1253 return gl_columns, gl_data
1254
1255
1256def get_stock_ledger_preview(doc, filters):
1257 from erpnext.stock.report.stock_ledger.stock_ledger import get_columns as get_sl_columns
1258
1259 sl_columns, sl_data = [], []
1260 fields = [
1261 "item_code",
1262 "stock_uom",
1263 "actual_qty",
1264 "qty_after_transaction",
1265 "warehouse",
1266 "incoming_rate",
1267 "valuation_rate",
1268 "stock_value",
1269 "stock_value_difference",
1270 ]
1271 columns_fields = [
1272 "item_code",
1273 "stock_uom",
1274 "in_qty",
1275 "out_qty",
1276 "qty_after_transaction",
1277 "warehouse",
1278 "incoming_rate",
Deepesh Garg0e68da52023-06-22 15:43:32 +05301279 "in_out_rate",
Deepesh Garg011ac132023-06-12 18:42:49 +05301280 "stock_value",
1281 "stock_value_difference",
1282 ]
1283
Deepesh Garg0e68da52023-06-22 15:43:32 +05301284 if doc.get("update_stock") or doc.doctype in ("Purchase Receipt", "Delivery Note"):
Deepesh Garg011ac132023-06-12 18:42:49 +05301285 doc.docstatus = 1
1286 doc.update_stock_ledger()
1287 columns = get_sl_columns(filters)
1288 sl_entries = get_sl_entries_for_preview(doc.doctype, doc.name, fields)
1289
1290 sl_columns = get_columns(columns, columns_fields)
1291 sl_data = get_data(columns_fields, sl_entries)
1292
1293 return sl_columns, sl_data
1294
1295
1296def get_sl_entries_for_preview(doctype, docname, fields):
1297 sl_entries = frappe.get_all(
1298 "Stock Ledger Entry", filters={"voucher_type": doctype, "voucher_no": docname}, fields=fields
1299 )
1300
1301 for entry in sl_entries:
1302 if entry.actual_qty > 0:
1303 entry["in_qty"] = entry.actual_qty
1304 entry["out_qty"] = 0
1305 else:
1306 entry["out_qty"] = abs(entry.actual_qty)
1307 entry["in_qty"] = 0
1308
Deepesh Garg0e68da52023-06-22 15:43:32 +05301309 entry["in_out_rate"] = entry["valuation_rate"]
1310
Deepesh Garg011ac132023-06-12 18:42:49 +05301311 return sl_entries
1312
1313
1314def get_gl_entries_for_preview(doctype, docname, fields):
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301315 return frappe.get_all(
Deepesh Garg011ac132023-06-12 18:42:49 +05301316 "GL Entry", filters={"voucher_type": doctype, "voucher_no": docname}, fields=fields
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301317 )
1318
1319
Deepesh Garg011ac132023-06-12 18:42:49 +05301320def get_columns(raw_columns, fields):
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301321 return [
Deepesh Garg011ac132023-06-12 18:42:49 +05301322 {"name": d.get("label"), "editable": False, "width": 110}
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301323 for d in raw_columns
Deepesh Garg011ac132023-06-12 18:42:49 +05301324 if not d.get("hidden") and d.get("fieldname") in fields
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301325 ]
1326
1327
1328def get_data(raw_columns, raw_data):
1329 datatable_data = []
1330 for row in raw_data:
1331 data_row = []
1332 for column in raw_columns:
Deepesh Garg011ac132023-06-12 18:42:49 +05301333 data_row.append(row.get(column) or "")
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301334
1335 datatable_data.append(data_row)
1336
1337 return datatable_data
1338
1339
Ankush Menat3638fbf2022-03-01 18:17:14 +05301340def repost_required_for_queue(doc: StockController) -> bool:
1341 """check if stock document contains repeated item-warehouse with queue based valuation.
1342
1343 if queue exists for repeated items then SLEs need to reprocessed in background again.
1344 """
1345
Ankush Menat494bd9e2022-03-28 18:52:46 +05301346 consuming_sles = frappe.db.get_all(
1347 "Stock Ledger Entry",
Ankush Menat3638fbf2022-03-01 18:17:14 +05301348 filters={
1349 "voucher_type": doc.doctype,
1350 "voucher_no": doc.name,
1351 "actual_qty": ("<", 0),
Ankush Menat494bd9e2022-03-28 18:52:46 +05301352 "is_cancelled": 0,
Ankush Menat3638fbf2022-03-01 18:17:14 +05301353 },
Ankush Menat494bd9e2022-03-28 18:52:46 +05301354 fields=["item_code", "warehouse", "stock_queue"],
Ankush Menat3638fbf2022-03-01 18:17:14 +05301355 )
1356 item_warehouses = [(sle.item_code, sle.warehouse) for sle in consuming_sles]
1357
1358 unique_item_warehouses = set(item_warehouses)
1359
1360 if len(unique_item_warehouses) == len(item_warehouses):
1361 return False
1362
1363 for sle in consuming_sles:
1364 if sle.stock_queue != "[]": # using FIFO/LIFO valuation
1365 return True
1366 return False
1367
Nabin Hait19f8fa52021-02-22 22:27:22 +05301368
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301369@frappe.whitelist()
1370def make_quality_inspections(doctype, docname, items):
Rohan Bansala06ec032021-06-02 14:55:31 +05301371 if isinstance(items, str):
1372 items = json.loads(items)
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301373
Rohan Bansala06ec032021-06-02 14:55:31 +05301374 inspections = []
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301375 for item in items:
Rohan Bansal1cdf5a02021-05-26 14:42:15 +05301376 if flt(item.get("sample_size")) > flt(item.get("qty")):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301377 frappe.throw(
1378 _(
1379 "{item_name}'s Sample Size ({sample_size}) cannot be greater than the Accepted Quantity ({accepted_quantity})"
1380 ).format(
1381 item_name=item.get("item_name"),
1382 sample_size=item.get("sample_size"),
1383 accepted_quantity=item.get("qty"),
1384 )
1385 )
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301386
Ankush Menat494bd9e2022-03-28 18:52:46 +05301387 quality_inspection = frappe.get_doc(
1388 {
1389 "doctype": "Quality Inspection",
1390 "inspection_type": "Incoming",
1391 "inspected_by": frappe.session.user,
1392 "reference_type": doctype,
1393 "reference_name": docname,
1394 "item_code": item.get("item_code"),
1395 "description": item.get("description"),
1396 "sample_size": flt(item.get("sample_size")),
1397 "item_serial_no": item.get("serial_no").split("\n")[0] if item.get("serial_no") else None,
1398 "batch_no": item.get("batch_no"),
1399 }
1400 ).insert()
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301401 quality_inspection.save()
Rohan Bansal1cdf5a02021-05-26 14:42:15 +05301402 inspections.append(quality_inspection.name)
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301403
Rohan Bansal1cdf5a02021-05-26 14:42:15 +05301404 return inspections
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301405
Ankush Menat494bd9e2022-03-28 18:52:46 +05301406
Nabin Haitb99c77b2020-12-25 18:12:35 +05301407def is_reposting_pending():
Ankush Menat494bd9e2022-03-28 18:52:46 +05301408 return frappe.db.exists(
1409 "Repost Item Valuation", {"docstatus": 1, "status": ["in", ["Queued", "In Progress"]]}
1410 )
1411
Nabin Haitb99c77b2020-12-25 18:12:35 +05301412
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301413def future_sle_exists(args, sl_entries=None):
1414 key = (args.voucher_type, args.voucher_no)
Rohit Waghchaured9dd64b2023-04-14 13:00:12 +05301415 if not hasattr(frappe.local, "future_sle"):
1416 frappe.local.future_sle = {}
Nabin Haita77b8c92020-12-21 14:45:50 +05301417
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301418 if validate_future_sle_not_exists(args, key, sl_entries):
1419 return False
1420 elif get_cached_data(args, key):
1421 return True
1422
1423 if not sl_entries:
1424 sl_entries = get_sle_entries_against_voucher(args)
1425 if not sl_entries:
1426 return
1427
1428 or_conditions = get_conditions_to_validate_future_sle(sl_entries)
1429
Ankush Menat494bd9e2022-03-28 18:52:46 +05301430 data = frappe.db.sql(
1431 """
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301432 select item_code, warehouse, count(name) as total_row
Deepesh Garg6f107da2021-10-12 20:15:55 +05301433 from `tabStock Ledger Entry` force index (item_warehouse)
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301434 where
1435 ({})
1436 and timestamp(posting_date, posting_time)
1437 >= timestamp(%(posting_date)s, %(posting_time)s)
1438 and voucher_no != %(voucher_no)s
1439 and is_cancelled = 0
1440 GROUP BY
1441 item_code, warehouse
Ankush Menat494bd9e2022-03-28 18:52:46 +05301442 """.format(
1443 " or ".join(or_conditions)
1444 ),
1445 args,
1446 as_dict=1,
1447 )
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301448
1449 for d in data:
1450 frappe.local.future_sle[key][(d.item_code, d.warehouse)] = d.total_row
1451
1452 return len(data)
1453
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301454
Ankush Menat494bd9e2022-03-28 18:52:46 +05301455def validate_future_sle_not_exists(args, key, sl_entries=None):
1456 item_key = ""
1457 if args.get("item_code"):
1458 item_key = (args.get("item_code"), args.get("warehouse"))
1459
1460 if not sl_entries and hasattr(frappe.local, "future_sle"):
Rohit Waghchaured9dd64b2023-04-14 13:00:12 +05301461 if key not in frappe.local.future_sle:
1462 return False
1463
Ankush Menat494bd9e2022-03-28 18:52:46 +05301464 if not frappe.local.future_sle.get(key) or (
1465 item_key and item_key not in frappe.local.future_sle.get(key)
1466 ):
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301467 return True
1468
Ankush Menat494bd9e2022-03-28 18:52:46 +05301469
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301470def get_cached_data(args, key):
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301471 if key not in frappe.local.future_sle:
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +05301472 frappe.local.future_sle[key] = frappe._dict({})
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301473
Ankush Menat494bd9e2022-03-28 18:52:46 +05301474 if args.get("item_code"):
1475 item_key = (args.get("item_code"), args.get("warehouse"))
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301476 count = frappe.local.future_sle[key].get(item_key)
1477
1478 return True if (count or count == 0) else False
1479 else:
1480 return frappe.local.future_sle[key]
1481
Ankush Menat494bd9e2022-03-28 18:52:46 +05301482
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301483def get_sle_entries_against_voucher(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301484 return frappe.get_all(
1485 "Stock Ledger Entry",
Nabin Haita77b8c92020-12-21 14:45:50 +05301486 filters={"voucher_type": args.voucher_type, "voucher_no": args.voucher_no},
1487 fields=["item_code", "warehouse"],
Ankush Menat494bd9e2022-03-28 18:52:46 +05301488 order_by="creation asc",
1489 )
1490
Nabin Haita77b8c92020-12-21 14:45:50 +05301491
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301492def get_conditions_to_validate_future_sle(sl_entries):
Sagar Vora868c0bf2021-03-27 16:10:20 +05301493 warehouse_items_map = {}
1494 for entry in sl_entries:
1495 if entry.warehouse not in warehouse_items_map:
1496 warehouse_items_map[entry.warehouse] = set()
Nabin Haita77b8c92020-12-21 14:45:50 +05301497
Sagar Vora868c0bf2021-03-27 16:10:20 +05301498 warehouse_items_map[entry.warehouse].add(entry.item_code)
1499
1500 or_conditions = []
1501 for warehouse, items in warehouse_items_map.items():
1502 or_conditions.append(
Noah Jacobb5a14912021-06-15 12:44:04 +05301503 f"""warehouse = {frappe.db.escape(warehouse)}
Ankush Menat494bd9e2022-03-28 18:52:46 +05301504 and item_code in ({', '.join(frappe.db.escape(item) for item in items)})"""
1505 )
Sagar Vora868c0bf2021-03-27 16:10:20 +05301506
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301507 return or_conditions
Nabin Haita77b8c92020-12-21 14:45:50 +05301508
Ankush Menat494bd9e2022-03-28 18:52:46 +05301509
Nabin Haita77b8c92020-12-21 14:45:50 +05301510def create_repost_item_valuation_entry(args):
1511 args = frappe._dict(args)
1512 repost_entry = frappe.new_doc("Repost Item Valuation")
1513 repost_entry.based_on = args.based_on
1514 if not args.based_on:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301515 repost_entry.based_on = "Transaction" if args.voucher_no else "Item and Warehouse"
Nabin Haita77b8c92020-12-21 14:45:50 +05301516 repost_entry.voucher_type = args.voucher_type
1517 repost_entry.voucher_no = args.voucher_no
1518 repost_entry.item_code = args.item_code
1519 repost_entry.warehouse = args.warehouse
1520 repost_entry.posting_date = args.posting_date
1521 repost_entry.posting_time = args.posting_time
1522 repost_entry.company = args.company
1523 repost_entry.allow_zero_rate = args.allow_zero_rate
1524 repost_entry.flags.ignore_links = True
Ankush Menataa024fc2021-11-18 12:51:26 +05301525 repost_entry.flags.ignore_permissions = True
Nabin Haita77b8c92020-12-21 14:45:50 +05301526 repost_entry.save()
Sagar Vora868c0bf2021-03-27 16:10:20 +05301527 repost_entry.submit()
Ankush Menat6dc9b822021-10-28 15:53:18 +05301528
1529
1530def create_item_wise_repost_entries(voucher_type, voucher_no, allow_zero_rate=False):
1531 """Using a voucher create repost item valuation records for all item-warehouse pairs."""
1532
Ankush Menatd220e082021-10-28 17:47:00 +05301533 stock_ledger_entries = get_items_to_be_repost(voucher_type, voucher_no)
1534
Ankush Menat6dc9b822021-10-28 15:53:18 +05301535 distinct_item_warehouses = set()
Ankush Menat6dc9b822021-10-28 15:53:18 +05301536 repost_entries = []
1537
1538 for sle in stock_ledger_entries:
1539 item_wh = (sle.item_code, sle.warehouse)
1540 if item_wh in distinct_item_warehouses:
1541 continue
1542 distinct_item_warehouses.add(item_wh)
1543
1544 repost_entry = frappe.new_doc("Repost Item Valuation")
1545 repost_entry.based_on = "Item and Warehouse"
Ankush Menat6dc9b822021-10-28 15:53:18 +05301546
1547 repost_entry.item_code = sle.item_code
1548 repost_entry.warehouse = sle.warehouse
1549 repost_entry.posting_date = sle.posting_date
1550 repost_entry.posting_time = sle.posting_time
1551 repost_entry.allow_zero_rate = allow_zero_rate
1552 repost_entry.flags.ignore_links = True
Ankush Menat0a2964d2021-11-24 15:55:31 +05301553 repost_entry.flags.ignore_permissions = True
Ankush Menat6dc9b822021-10-28 15:53:18 +05301554 repost_entry.submit()
1555 repost_entries.append(repost_entry)
1556
1557 return repost_entries