blob: dc5ce5e6b58bbf38df9881e2c57c8a4fde9fa2fb [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
Rohit Waghchaurebc75a7e2022-10-10 13:28:19 +053010from frappe.utils import cint, 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:
51 self.validate_duplicate_serial_and_batch_bundle()
Ankush Menat494bd9e2022-03-28 18:52:46 +053052 if not self.get("is_return"):
marination596560c2020-06-11 16:39:03 +053053 self.validate_inspection()
rohitwaghchaure9af557f2019-12-30 13:26:47 +053054 self.validate_serialized_batch()
marinationeecfc4c2021-07-22 13:23:54 +053055 self.clean_serial_nos()
marinationfd04e962020-04-03 15:46:48 +053056 self.validate_customer_provided_item()
Anupam Kumar7e1dcf92021-02-11 20:19:30 +053057 self.set_rate_of_stock_uom()
Deepesh Gargb4be2922021-01-28 13:09:56 +053058 self.validate_internal_transfer()
marinationfac40352020-12-07 21:35:49 +053059 self.validate_putaway_capacity()
Rushabh Mehtaffd80a62017-01-16 17:23:20 +053060
s-aga-r094ecc12024-02-12 17:36:14 +053061 def validate_duplicate_serial_and_batch_bundle(self):
62 if sbb_list := [
63 item.get("serial_and_batch_bundle")
64 for item in self.items
65 if item.get("serial_and_batch_bundle")
66 ]:
67 SLE = frappe.qb.DocType("Stock Ledger Entry")
68 data = (
69 frappe.qb.from_(SLE)
70 .select(SLE.voucher_type, SLE.voucher_no, SLE.serial_and_batch_bundle)
71 .where(
72 (SLE.docstatus == 1)
73 & (SLE.serial_and_batch_bundle.notnull())
74 & (SLE.serial_and_batch_bundle.isin(sbb_list))
75 )
76 .limit(1)
77 ).run(as_dict=True)
78
79 if data:
80 data = data[0]
81 frappe.throw(
82 _("Serial and Batch Bundle {0} is already used in {1} {2}.").format(
83 frappe.bold(data.serial_and_batch_bundle), data.voucher_type, data.voucher_no
84 )
85 )
86
Nabin Haita77b8c92020-12-21 14:45:50 +053087 def make_gl_entries(self, gl_entries=None, from_repost=False):
Anand Doshif78d1ae2014-03-28 13:55:00 +053088 if self.docstatus == 2:
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053089 make_reverse_gl_entries(voucher_type=self.doctype, voucher_no=self.name)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053090
Ankush Menat494bd9e2022-03-28 18:52:46 +053091 provisional_accounting_for_non_stock_items = cint(
Daizy Modi4efc9472022-11-07 09:21:03 +053092 frappe.get_cached_value(
Ankush Menat494bd9e2022-03-28 18:52:46 +053093 "Company", self.company, "enable_provisional_accounting_for_non_stock_items"
94 )
95 )
Deepesh Garg528c7132022-02-01 14:42:55 +053096
Deepesh Gargd1ec0a62023-10-23 00:16:40 +053097 is_asset_pr = any(d.get("is_fixed_asset") for d in self.get("items"))
98
Ankush Menat494bd9e2022-03-28 18:52:46 +053099 if (
100 cint(erpnext.is_perpetual_inventory_enabled(self.company))
101 or provisional_accounting_for_non_stock_items
Deepesh Gargd1ec0a62023-10-23 00:16:40 +0530102 or is_asset_pr
Ankush Menat494bd9e2022-03-28 18:52:46 +0530103 ):
Rohit Waghchaure6b33c9b2019-03-08 11:13:35 +0530104 warehouse_account = get_warehouse_account_map(self.company)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530105
Ankush Menat494bd9e2022-03-28 18:52:46 +0530106 if self.docstatus == 1:
Nabin Hait9784d272016-12-30 16:21:35 +0530107 if not gl_entries:
108 gl_entries = self.get_gl_entries(warehouse_account)
Nabin Haita77b8c92020-12-21 14:45:50 +0530109 make_gl_entries(gl_entries, from_repost=from_repost)
Nabin Hait145e5e22013-10-22 23:51:41 +0530110
rohitwaghchaure9af557f2019-12-30 13:26:47 +0530111 def validate_serialized_batch(self):
112 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
Ankush Menat494bd9e2022-03-28 18:52:46 +0530113
Rohit Waghchaure795c9432022-08-17 13:48:56 +0530114 is_material_issue = False
115 if self.doctype == "Stock Entry" and self.purpose == "Material Issue":
116 is_material_issue = True
117
rohitwaghchaure9af557f2019-12-30 13:26:47 +0530118 for d in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530119 if hasattr(d, "serial_no") and hasattr(d, "batch_no") and d.serial_no and d.batch_no:
120 serial_nos = frappe.get_all(
121 "Serial No",
Rohit Waghchaure6b482eb2021-07-23 16:40:45 +0530122 fields=["batch_no", "name", "warehouse"],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530123 filters={"name": ("in", get_serial_nos(d.serial_no))},
Rohit Waghchaure6b482eb2021-07-23 16:40:45 +0530124 )
125
126 for row in serial_nos:
127 if row.warehouse and row.batch_no != d.batch_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530128 frappe.throw(
129 _("Row #{0}: Serial No {1} does not belong to Batch {2}").format(
130 d.idx, row.name, d.batch_no
131 )
132 )
rohitwaghchaure9af557f2019-12-30 13:26:47 +0530133
Rohit Waghchaure795c9432022-08-17 13:48:56 +0530134 if is_material_issue:
135 continue
136
Saqib Ansari903055b2020-10-20 11:59:06 +0530137 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 +0530138 expiry_date = frappe.get_cached_value("Batch", d.get("batch_no"), "expiry_date")
139
140 if expiry_date and getdate(expiry_date) < getdate(self.posting_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530141 frappe.throw(
142 _("Row #{0}: The batch {1} has already expired.").format(
143 d.idx, get_link_to_form("Batch", d.get("batch_no"))
Rohit Waghchaure795c9432022-08-17 13:48:56 +0530144 ),
145 BatchExpiredError,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530146 )
rohitwaghchaure28a48802020-04-28 13:01:43 +0530147
marinationeecfc4c2021-07-22 13:23:54 +0530148 def clean_serial_nos(self):
Ankush Menatb20df372022-01-24 19:19:58 +0530149 from erpnext.stock.doctype.serial_no.serial_no import clean_serial_no_string
150
marinationeecfc4c2021-07-22 13:23:54 +0530151 for row in self.get("items"):
152 if hasattr(row, "serial_no") and row.serial_no:
Ankush Menatb20df372022-01-24 19:19:58 +0530153 # remove extra whitespace and store one serial no on each line
154 row.serial_no = clean_serial_no_string(row.serial_no)
marinationeecfc4c2021-07-22 13:23:54 +0530155
Ankush Menat494bd9e2022-03-28 18:52:46 +0530156 for row in self.get("packed_items") or []:
Ankush Menate177c522022-01-24 19:28:26 +0530157 if hasattr(row, "serial_no") and row.serial_no:
158 # remove extra whitespace and store one serial no on each line
159 row.serial_no = clean_serial_no_string(row.serial_no)
160
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530161 def make_bundle_using_old_serial_batch_fields(self):
162 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
163 from erpnext.stock.serial_batch_bundle import SerialBatchCreation
164
rohitwaghchaurea4cbfab2024-02-19 10:25:36 +0530165 if self.get("_action") == "update_after_submit":
166 return
167
Rohit Waghchaurec1e869f2024-02-05 12:40:26 +0530168 # To handle test cases
169 if frappe.flags.in_test and frappe.flags.use_serial_and_batch_fields:
170 return
171
172 table_name = "items"
173 if self.doctype == "Asset Capitalization":
174 table_name = "stock_items"
175
176 for row in self.get(table_name):
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530177 if not row.serial_no and not row.batch_no and not row.get("rejected_serial_no"):
178 continue
179
180 if not row.use_serial_batch_fields and (
181 row.serial_no or row.batch_no or row.get("rejected_serial_no")
182 ):
183 frappe.throw(_("Please enable Use Old Serial / Batch Fields to make_bundle"))
184
185 if row.use_serial_batch_fields and (
Rohit Waghchaurec1e869f2024-02-05 12:40:26 +0530186 not row.serial_and_batch_bundle and not row.get("rejected_serial_and_batch_bundle")
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530187 ):
Rohit Waghchaure01650122024-02-06 13:31:36 +0530188 if self.doctype == "Stock Reconciliation":
189 qty = row.qty
190 type_of_transaction = "Inward"
rohitwaghchauree5824fc2024-02-11 11:10:21 +0530191 warehouse = row.warehouse
Rohit Waghchaure01650122024-02-06 13:31:36 +0530192 else:
rohitwaghchauree5824fc2024-02-11 11:10:21 +0530193 qty = row.stock_qty if self.doctype != "Stock Entry" else row.transfer_qty
Rohit Waghchaure01650122024-02-06 13:31:36 +0530194 type_of_transaction = get_type_of_transaction(self, row)
rohitwaghchauree5824fc2024-02-11 11:10:21 +0530195 warehouse = (
196 row.warehouse if self.doctype != "Stock Entry" else row.s_warehouse or row.t_warehouse
197 )
Rohit Waghchaure01650122024-02-06 13:31:36 +0530198
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530199 sn_doc = SerialBatchCreation(
200 {
201 "item_code": row.item_code,
rohitwaghchauree5824fc2024-02-11 11:10:21 +0530202 "warehouse": warehouse,
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530203 "posting_date": self.posting_date,
204 "posting_time": self.posting_time,
205 "voucher_type": self.doctype,
206 "voucher_no": self.name,
207 "voucher_detail_no": row.name,
Rohit Waghchaure01650122024-02-06 13:31:36 +0530208 "qty": qty,
209 "type_of_transaction": type_of_transaction,
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530210 "company": self.company,
211 "is_rejected": 1 if row.get("rejected_warehouse") else 0,
212 "serial_nos": get_serial_nos(row.serial_no) if row.serial_no else None,
Rohit Waghchaure01650122024-02-06 13:31:36 +0530213 "batches": frappe._dict({row.batch_no: qty}) if row.batch_no else None,
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530214 "batch_no": row.batch_no,
215 "use_serial_batch_fields": row.use_serial_batch_fields,
Rohit Waghchaure01650122024-02-06 13:31:36 +0530216 "do_not_submit": True,
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530217 }
218 ).make_serial_and_batch_bundle()
219
220 if sn_doc.is_rejected:
221 row.rejected_serial_and_batch_bundle = sn_doc.name
Rohit Waghchaurec1e869f2024-02-05 12:40:26 +0530222 row.db_set(
223 {
224 "rejected_serial_and_batch_bundle": sn_doc.name,
Rohit Waghchaurec1e869f2024-02-05 12:40:26 +0530225 }
226 )
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530227 else:
228 row.serial_and_batch_bundle = sn_doc.name
Rohit Waghchaurec1e869f2024-02-05 12:40:26 +0530229 row.db_set(
230 {
231 "serial_and_batch_bundle": sn_doc.name,
Rohit Waghchaurec1e869f2024-02-05 12:40:26 +0530232 }
233 )
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530234
235 def set_use_serial_batch_fields(self):
236 if frappe.db.get_single_value("Stock Settings", "use_serial_batch_fields"):
237 for row in self.items:
238 row.use_serial_batch_fields = 1
239
Ankush Menat494bd9e2022-03-28 18:52:46 +0530240 def get_gl_entries(
241 self, warehouse_account=None, default_expense_account=None, default_cost_center=None
242 ):
Nabin Haitadeb9762014-10-06 11:53:52 +0530243
Nabin Hait142007a2013-09-17 15:15:16 +0530244 if not warehouse_account:
Rohit Waghchaure6b33c9b2019-03-08 11:13:35 +0530245 warehouse_account = get_warehouse_account_map(self.company)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530246
Anand Doshide1a97d2014-04-17 11:37:46 +0530247 sle_map = self.get_stock_ledger_details()
248 voucher_details = self.get_voucher_details(default_expense_account, default_cost_center, sle_map)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530249
Nabin Hait2e296fa2013-08-28 18:53:11 +0530250 gl_list = []
Nabin Hait7a75e102013-09-17 10:21:20 +0530251 warehouse_with_no_account = []
Nabin Hait19f8fa52021-02-22 22:27:22 +0530252 precision = self.get_debit_field_precision()
Nabin Hait8c61f342016-12-15 13:46:03 +0530253 for item_row in voucher_details:
254 sle_list = sle_map.get(item_row.name)
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530255 sle_rounding_diff = 0.0
Nabin Hait2e296fa2013-08-28 18:53:11 +0530256 if sle_list:
257 for sle in sle_list:
258 if warehouse_account.get(sle.warehouse):
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530259 # from warehouse account
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530260
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530261 sle_rounding_diff += flt(sle.stock_value_difference)
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530262
Nabin Hait8c61f342016-12-15 13:46:03 +0530263 self.check_expense_account(item_row)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530264
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530265 # expense account/ target_warehouse / source_warehouse
Ankush Menat494bd9e2022-03-28 18:52:46 +0530266 if item_row.get("target_warehouse"):
267 warehouse = item_row.get("target_warehouse")
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530268 expense_account = warehouse_account[warehouse]["account"]
269 else:
270 expense_account = item_row.expense_account
271
Ankush Menat494bd9e2022-03-28 18:52:46 +0530272 gl_list.append(
273 self.get_gl_dict(
274 {
275 "account": warehouse_account[sle.warehouse]["account"],
276 "against": expense_account,
277 "cost_center": item_row.cost_center,
278 "project": item_row.project or self.get("project"),
279 "remarks": self.get("remarks") or _("Accounting Entry for Stock"),
280 "debit": flt(sle.stock_value_difference, precision),
281 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
282 },
283 warehouse_account[sle.warehouse]["account_currency"],
284 item=item_row,
285 )
286 )
Nabin Hait27994c22013-08-26 16:53:30 +0530287
Ankush Menat494bd9e2022-03-28 18:52:46 +0530288 gl_list.append(
289 self.get_gl_dict(
290 {
291 "account": expense_account,
292 "against": warehouse_account[sle.warehouse]["account"],
293 "cost_center": item_row.cost_center,
294 "remarks": self.get("remarks") or _("Accounting Entry for Stock"),
Ankush Menat65b21ee2022-06-07 14:49:24 +0530295 "debit": -1 * flt(sle.stock_value_difference, precision),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530296 "project": item_row.get("project") or self.get("project"),
297 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
298 },
299 item=item_row,
300 )
301 )
Nabin Hait7a75e102013-09-17 10:21:20 +0530302 elif sle.warehouse not in warehouse_with_no_account:
303 warehouse_with_no_account.append(sle.warehouse)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530304
Deepesh Garg9aa5e202022-10-12 15:53:28 +0530305 if abs(sle_rounding_diff) > (1.0 / (10**precision)) and self.is_internal_transfer():
Deepesh Garg1c05c002022-10-12 14:19:09 +0530306 warehouse_asset_account = ""
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530307 if self.get("is_internal_customer"):
Deepesh Garg1c05c002022-10-12 14:19:09 +0530308 warehouse_asset_account = warehouse_account[item_row.get("target_warehouse")]["account"]
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530309 elif self.get("is_internal_supplier"):
Deepesh Garg1c05c002022-10-12 14:19:09 +0530310 warehouse_asset_account = warehouse_account[item_row.get("warehouse")]["account"]
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530311
Daizy Modi4efc9472022-11-07 09:21:03 +0530312 expense_account = frappe.get_cached_value("Company", self.company, "default_expense_account")
Deepesh Gargce9164e2023-07-11 12:03:38 +0530313 if not expense_account:
314 frappe.throw(
315 _(
316 "Please set default cost of goods sold account in company {0} for booking rounding gain and loss during stock transfer"
317 ).format(frappe.bold(self.company))
318 )
Deepesh Garg1c05c002022-10-12 14:19:09 +0530319
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530320 gl_list.append(
321 self.get_gl_dict(
322 {
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530323 "account": expense_account,
Deepesh Garg1c05c002022-10-12 14:19:09 +0530324 "against": warehouse_asset_account,
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530325 "cost_center": item_row.cost_center,
326 "project": item_row.project or self.get("project"),
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530327 "remarks": _("Rounding gain/loss Entry for Stock Transfer"),
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530328 "debit": sle_rounding_diff,
329 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
330 },
331 warehouse_account[sle.warehouse]["account_currency"],
332 item=item_row,
333 )
334 )
335
336 gl_list.append(
337 self.get_gl_dict(
338 {
Deepesh Garg1c05c002022-10-12 14:19:09 +0530339 "account": warehouse_asset_account,
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530340 "against": expense_account,
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530341 "cost_center": item_row.cost_center,
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530342 "remarks": _("Rounding gain/loss Entry for Stock Transfer"),
343 "credit": sle_rounding_diff,
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530344 "project": item_row.get("project") or self.get("project"),
345 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
346 },
347 item=item_row,
348 )
349 )
350
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530351 if warehouse_with_no_account:
Nabin Haitd6625022016-10-24 18:17:57 +0530352 for wh in warehouse_with_no_account:
Daizy Modi4efc9472022-11-07 09:21:03 +0530353 if frappe.get_cached_value("Warehouse", wh, "company"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530354 frappe.throw(
355 _(
356 "Warehouse {0} is not linked to any account, please mention the account in the warehouse record or set default inventory account in company {1}."
357 ).format(wh, self.company)
358 )
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530359
Nabin Hait19f8fa52021-02-22 22:27:22 +0530360 return process_gl_map(gl_list, precision=precision)
361
362 def get_debit_field_precision(self):
363 if not frappe.flags.debit_field_precision:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530364 frappe.flags.debit_field_precision = frappe.get_precision(
365 "GL Entry", "debit_in_account_currency"
366 )
Nabin Hait19f8fa52021-02-22 22:27:22 +0530367
368 return frappe.flags.debit_field_precision
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530369
Anand Doshide1a97d2014-04-17 11:37:46 +0530370 def get_voucher_details(self, default_expense_account, default_cost_center, sle_map):
371 if self.doctype == "Stock Reconciliation":
Nabin Hait3f119ec2019-05-16 17:28:39 +0530372 reconciliation_purpose = frappe.db.get_value(self.doctype, self.name, "purpose")
373 is_opening = "Yes" if reconciliation_purpose == "Opening Stock" else "No"
374 details = []
Nabin Hait34c551d2019-07-03 10:34:31 +0530375 for voucher_detail_no in sle_map:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530376 details.append(
377 frappe._dict(
378 {
379 "name": voucher_detail_no,
380 "expense_account": default_expense_account,
381 "cost_center": default_cost_center,
382 "is_opening": is_opening,
383 }
384 )
385 )
Nabin Hait3f119ec2019-05-16 17:28:39 +0530386 return details
Anand Doshide1a97d2014-04-17 11:37:46 +0530387 else:
Nabin Haitdd38a262014-12-26 13:15:21 +0530388 details = self.get("items")
Anand Doshi094610d2014-04-16 19:56:53 +0530389
Anand Doshide1a97d2014-04-17 11:37:46 +0530390 if default_expense_account or default_cost_center:
391 for d in details:
392 if default_expense_account and not d.get("expense_account"):
393 d.expense_account = default_expense_account
394 if default_cost_center and not d.get("cost_center"):
395 d.cost_center = default_cost_center
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530396
Anand Doshide1a97d2014-04-17 11:37:46 +0530397 return details
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530398
Ankush Menate6ab8df2022-02-06 13:02:34 +0530399 def get_items_and_warehouses(self) -> Tuple[List[str], List[str]]:
400 """Get list of items and warehouses affected by a transaction"""
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530401
Ankush Menate6ab8df2022-02-06 13:02:34 +0530402 if not (hasattr(self, "items") or hasattr(self, "packed_items")):
403 return [], []
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530404
Ankush Menate6ab8df2022-02-06 13:02:34 +0530405 item_rows = (self.get("items") or []) + (self.get("packed_items") or [])
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530406
Ankush Menate6ab8df2022-02-06 13:02:34 +0530407 items = {d.item_code for d in item_rows if d.item_code}
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530408
Ankush Menate6ab8df2022-02-06 13:02:34 +0530409 warehouses = set()
410 for d in item_rows:
411 if d.get("warehouse"):
412 warehouses.add(d.warehouse)
Nabin Haitbecf75d2014-03-27 17:18:29 +0530413
Ankush Menate6ab8df2022-02-06 13:02:34 +0530414 if self.doctype == "Stock Entry":
415 if d.get("s_warehouse"):
416 warehouses.add(d.s_warehouse)
417 if d.get("t_warehouse"):
418 warehouses.add(d.t_warehouse)
419
420 return list(items), list(warehouses)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530421
Nabin Hait2e296fa2013-08-28 18:53:11 +0530422 def get_stock_ledger_details(self):
423 stock_ledger = {}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530424 stock_ledger_entries = frappe.db.sql(
425 """
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530426 select
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530427 name, warehouse, stock_value_difference, valuation_rate,
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530428 voucher_detail_no, item_code, posting_date, posting_time,
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530429 actual_qty, qty_after_transaction
Nabin Haitea8fab52017-02-06 17:13:39 +0530430 from
431 `tabStock Ledger Entry`
432 where
Ankush Menat0ca60af2022-02-08 10:24:19 +0530433 voucher_type=%s and voucher_no=%s and is_cancelled = 0
Ankush Menat494bd9e2022-03-28 18:52:46 +0530434 """,
435 (self.doctype, self.name),
436 as_dict=True,
437 )
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530438
Nabin Haitea8fab52017-02-06 17:13:39 +0530439 for sle in stock_ledger_entries:
Deepesh Gargb4be2922021-01-28 13:09:56 +0530440 stock_ledger.setdefault(sle.voucher_detail_no, []).append(sle)
Nabin Hait2e296fa2013-08-28 18:53:11 +0530441 return stock_ledger
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530442
Nabin Hait27994c22013-08-26 16:53:30 +0530443 def check_expense_account(self, item):
Rushabh Mehta052fe822014-04-16 19:20:11 +0530444 if not item.get("expense_account"):
Rohit Waghchaureceab6922020-11-18 17:57:35 +0530445 msg = _("Please set an Expense Account in the Items table")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530446 frappe.throw(
447 _("Row #{0}: Expense Account not set for the Item {1}. {2}").format(
448 item.idx, frappe.bold(item.item_code), msg
449 ),
450 title=_("Expense Account Missing"),
451 )
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530452
Anand Doshi496123a2014-06-19 19:25:19 +0530453 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530454 is_expense_account = (
455 frappe.get_cached_value("Account", item.get("expense_account"), "report_type")
456 == "Profit and Loss"
457 )
458 if (
459 self.doctype
Sagar Sharma2d04e712022-08-17 15:57:41 +0530460 not in (
461 "Purchase Receipt",
462 "Purchase Invoice",
463 "Stock Reconciliation",
464 "Stock Entry",
465 "Subcontracting Receipt",
466 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530467 and not is_expense_account
468 ):
469 frappe.throw(
470 _("Expense / Difference account ({0}) must be a 'Profit or Loss' account").format(
471 item.get("expense_account")
472 )
473 )
Anand Doshi496123a2014-06-19 19:25:19 +0530474 if is_expense_account and not item.get("cost_center"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530475 frappe.throw(
476 _("{0} {1}: Cost Center is mandatory for Item {2}").format(
477 _(self.doctype), self.name, item.get("item_code")
478 )
479 )
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530480
Rohit Waghchaure8996b7d2020-01-23 17:36:52 +0530481 def delete_auto_created_batches(self):
Rohit Waghchaurebc75a7e2022-10-10 13:28:19 +0530482 for row in self.items:
483 if row.serial_and_batch_bundle:
484 frappe.db.set_value(
485 "Serial and Batch Bundle", row.serial_and_batch_bundle, {"is_cancelled": 1}
486 )
Rohit Waghchaure8996b7d2020-01-23 17:36:52 +0530487
Rohit Waghchaurebc75a7e2022-10-10 13:28:19 +0530488 row.db_set("serial_and_batch_bundle", None)
Saqibe9ac3e02020-03-02 15:02:58 +0530489
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530490 def set_serial_and_batch_bundle(self, table_name=None, ignore_validate=False):
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530491 if not table_name:
492 table_name = "items"
Rohit Waghchaure8996b7d2020-01-23 17:36:52 +0530493
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530494 QTY_FIELD = {
495 "serial_and_batch_bundle": "qty",
496 "current_serial_and_batch_bundle": "current_qty",
497 "rejected_serial_and_batch_bundle": "rejected_qty",
498 }
499
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530500 for row in self.get(table_name):
s-aga-rc20241f2024-01-12 15:26:35 +0530501 for field in QTY_FIELD.keys():
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530502 if row.get(field):
503 frappe.get_doc("Serial and Batch Bundle", row.get(field)).set_serial_and_batch_values(
504 self, row, qty_field=QTY_FIELD[field]
505 )
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530506
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530507 def make_package_for_transfer(
508 self, serial_and_batch_bundle, warehouse, type_of_transaction=None, do_not_submit=None
509 ):
510 bundle_doc = frappe.get_doc("Serial and Batch Bundle", serial_and_batch_bundle)
511
512 if not type_of_transaction:
513 type_of_transaction = "Inward"
514
515 bundle_doc = frappe.copy_doc(bundle_doc)
516 bundle_doc.warehouse = warehouse
517 bundle_doc.type_of_transaction = type_of_transaction
518 bundle_doc.voucher_type = self.doctype
519 bundle_doc.voucher_no = self.name
520 bundle_doc.is_cancelled = 0
521
Rohit Waghchaure5bb31732023-03-21 10:54:41 +0530522 for row in bundle_doc.entries:
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530523 row.is_outward = 0
524 row.qty = abs(row.qty)
525 row.stock_value_difference = abs(row.stock_value_difference)
526 if type_of_transaction == "Outward":
527 row.qty *= -1
528 row.stock_value_difference *= row.stock_value_difference
529 row.is_outward = 1
530
531 row.warehouse = warehouse
532
Rohit Waghchaure5bb31732023-03-21 10:54:41 +0530533 bundle_doc.calculate_qty_and_amount()
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530534 bundle_doc.flags.ignore_permissions = True
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530535 bundle_doc.save(ignore_permissions=True)
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530536
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530537 return bundle_doc.name
Rohit Waghchaure4f4dbf12020-01-23 12:42:42 +0530538
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530539 def get_sl_entries(self, d, args):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530540 sl_dict = frappe._dict(
541 {
542 "item_code": d.get("item_code", None),
543 "warehouse": d.get("warehouse", None),
Rohit Waghchaurebc75a7e2022-10-10 13:28:19 +0530544 "serial_and_batch_bundle": d.get("serial_and_batch_bundle"),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530545 "posting_date": self.posting_date,
546 "posting_time": self.posting_time,
547 "fiscal_year": get_fiscal_year(self.posting_date, company=self.company)[0],
548 "voucher_type": self.doctype,
549 "voucher_no": self.name,
550 "voucher_detail_no": d.name,
551 "actual_qty": (self.docstatus == 1 and 1 or -1) * flt(d.get("stock_qty")),
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +0530552 "stock_uom": frappe.get_cached_value(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530553 "Item", args.get("item_code") or d.get("item_code"), "stock_uom"
554 ),
555 "incoming_rate": 0,
556 "company": self.company,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530557 "project": d.get("project") or self.get("project"),
558 "is_cancelled": 1 if self.docstatus == 2 else 0,
559 }
560 )
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530561
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530562 sl_dict.update(args)
Rohit Waghchauree576f7f2022-06-30 19:12:06 +0530563 self.update_inventory_dimensions(d, sl_dict)
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530564
rohitwaghchaure07432892023-12-17 12:42:07 +0530565 if self.docstatus == 2:
566 # To handle denormalized serial no records, will br deprecated in v16
567 for field in ["serial_no", "batch_no"]:
568 if d.get(field):
569 sl_dict[field] = d.get(field)
570
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530571 return sl_dict
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530572
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530573 def update_inventory_dimensions(self, row, sl_dict) -> None:
Rohit Waghchaure23729992022-09-02 18:43:55 +0530574 # To handle delivery note and sales invoice
575 if row.get("item_row"):
576 row = row.get("item_row")
577
Rohit Waghchaure289e6cd2022-07-15 15:43:38 +0530578 dimensions = get_evaluated_inventory_dimension(row, sl_dict, parent_doc=self)
579 for dimension in dimensions:
Rohit Waghchaure0b39a012022-08-17 11:56:13 +0530580 if not dimension:
581 continue
582
Rohit Waghchaure6798b902023-05-09 16:07:14 +0530583 if self.doctype in [
584 "Purchase Invoice",
585 "Purchase Receipt",
586 "Sales Invoice",
587 "Delivery Note",
588 "Stock Entry",
589 ]:
Rohit Waghchaure38aaba52023-05-13 13:00:05 +0530590 if (
591 (
592 sl_dict.actual_qty > 0
593 and not self.get("is_return")
594 or sl_dict.actual_qty < 0
595 and self.get("is_return")
596 )
597 and self.doctype in ["Purchase Invoice", "Purchase Receipt"]
598 ) or (
599 (
600 sl_dict.actual_qty < 0
601 and not self.get("is_return")
602 or sl_dict.actual_qty > 0
603 and self.get("is_return")
604 )
605 and self.doctype in ["Sales Invoice", "Delivery Note", "Stock Entry"]
Rohit Waghchaure6798b902023-05-09 16:07:14 +0530606 ):
607 sl_dict[dimension.target_fieldname] = row.get(dimension.source_fieldname)
608 else:
609 fieldname_start_with = "to"
610 if self.doctype in ["Purchase Invoice", "Purchase Receipt"]:
611 fieldname_start_with = "from"
612
613 fieldname = f"{fieldname_start_with}_{dimension.source_fieldname}"
614 sl_dict[dimension.target_fieldname] = row.get(fieldname)
615
616 if not sl_dict.get(dimension.target_fieldname):
617 sl_dict[dimension.target_fieldname] = row.get(dimension.source_fieldname)
618
619 elif row.get(dimension.source_fieldname):
Rohit Waghchaure289e6cd2022-07-15 15:43:38 +0530620 sl_dict[dimension.target_fieldname] = row.get(dimension.source_fieldname)
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530621
Rohit Waghchaure0b39a012022-08-17 11:56:13 +0530622 if not sl_dict.get(dimension.target_fieldname) and dimension.fetch_from_parent:
623 sl_dict[dimension.target_fieldname] = self.get(dimension.fetch_from_parent)
624
625 # Get value based on doctype name
626 if not sl_dict.get(dimension.target_fieldname):
Daizy Modi4efc9472022-11-07 09:21:03 +0530627 fieldname = next(
628 (
629 field.fieldname
630 for field in frappe.get_meta(self.doctype).fields
631 if field.options == dimension.fetch_from_parent
632 ),
633 None,
Rohit Waghchaure0b39a012022-08-17 11:56:13 +0530634 )
635
636 if fieldname and self.get(fieldname):
637 sl_dict[dimension.target_fieldname] = self.get(fieldname)
638
Rohit Waghchaure75fcab02022-09-03 17:09:24 +0530639 if sl_dict[dimension.target_fieldname] and self.docstatus == 1:
640 row.db_set(dimension.source_fieldname, sl_dict[dimension.target_fieldname])
Rohit Waghchaure23729992022-09-02 18:43:55 +0530641
Ankush Menat494bd9e2022-03-28 18:52:46 +0530642 def make_sl_entries(self, sl_entries, allow_negative_stock=False, via_landed_cost_voucher=False):
Rushabh Mehta1f847992013-12-12 19:12:19 +0530643 from erpnext.stock.stock_ledger import make_sl_entries
Ankush Menat494bd9e2022-03-28 18:52:46 +0530644
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530645 make_sl_entries(sl_entries, allow_negative_stock, via_landed_cost_voucher)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530646
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530647 def make_gl_entries_on_cancel(self):
ruthra kumar46ea8142023-07-28 08:29:19 +0530648 cancel_exchange_gain_loss_journal(frappe._dict(doctype=self.doctype, name=self.name))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530649 if frappe.db.sql(
650 """select name from `tabGL Entry` where voucher_type=%s
651 and voucher_no=%s""",
652 (self.doctype, self.name),
653 ):
654 self.make_gl_entries()
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530655
Anand Doshia740f752014-06-25 13:31:02 +0530656 def get_serialized_items(self):
657 serialized_items = []
Ankush Menata9c84f72021-06-11 16:00:48 +0530658 item_codes = list(set(d.item_code for d in self.get("items")))
Anand Doshia740f752014-06-25 13:31:02 +0530659 if item_codes:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530660 serialized_items = frappe.db.sql_list(
661 """select name from `tabItem`
662 where has_serial_no=1 and name in ({})""".format(
663 ", ".join(["%s"] * len(item_codes))
664 ),
665 tuple(item_codes),
666 )
Anand Doshia740f752014-06-25 13:31:02 +0530667
668 return serialized_items
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +0530669
Saurabh2e292062015-11-18 17:03:33 +0530670 def validate_warehouse(self):
Rohan Bansal7f8b95e2021-04-14 14:12:03 +0530671 from erpnext.stock.utils import validate_disabled_warehouse, validate_warehouse_company
Saurabh2e292062015-11-18 17:03:33 +0530672
Ankush Menat494bd9e2022-03-28 18:52:46 +0530673 warehouses = list(set(d.warehouse for d in self.get("items") if getattr(d, "warehouse", None)))
Saurabh2e292062015-11-18 17:03:33 +0530674
Ankush Menat494bd9e2022-03-28 18:52:46 +0530675 target_warehouses = list(
676 set([d.target_warehouse for d in self.get("items") if getattr(d, "target_warehouse", None)])
677 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530678
679 warehouses.extend(target_warehouses)
680
Ankush Menat494bd9e2022-03-28 18:52:46 +0530681 from_warehouse = list(
682 set([d.from_warehouse for d in self.get("items") if getattr(d, "from_warehouse", None)])
683 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530684
685 warehouses.extend(from_warehouse)
686
Saurabh2e292062015-11-18 17:03:33 +0530687 for w in warehouses:
Jannat Patel30c88732021-02-11 11:46:48 +0530688 validate_disabled_warehouse(w)
Saurabh2e292062015-11-18 17:03:33 +0530689 validate_warehouse_company(w, self.company)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530690
Anand Doshi6b71ef52016-01-06 16:32:06 +0530691 def update_billing_percentage(self, update_modified=True):
marinationd6596a12020-11-02 15:07:48 +0530692 target_ref_field = "amount"
693 if self.doctype == "Delivery Note":
694 target_ref_field = "amount - (returned_qty * rate)"
695
Ankush Menat494bd9e2022-03-28 18:52:46 +0530696 self._update_percent_field(
697 {
698 "target_dt": self.doctype + " Item",
699 "target_parent_dt": self.doctype,
700 "target_parent_field": "per_billed",
701 "target_ref_field": target_ref_field,
702 "target_field": "billed_amt",
703 "name": self.name,
704 },
705 update_modified,
706 )
Anand Doshia740f752014-06-25 13:31:02 +0530707
Nabin Hait8af429d2016-11-16 17:21:59 +0530708 def validate_inspection(self):
marination9ac9a4e2021-06-21 16:18:35 +0530709 """Checks if quality inspection is set/ is valid for Items that require inspection."""
710 inspection_fieldname_map = {
711 "Purchase Receipt": "inspection_required_before_purchase",
712 "Purchase Invoice": "inspection_required_before_purchase",
s-aga-r3fdcd332023-08-23 12:15:35 +0530713 "Subcontracting Receipt": "inspection_required_before_purchase",
marination9ac9a4e2021-06-21 16:18:35 +0530714 "Sales Invoice": "inspection_required_before_delivery",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530715 "Delivery Note": "inspection_required_before_delivery",
marination9ac9a4e2021-06-21 16:18:35 +0530716 }
717 inspection_required_fieldname = inspection_fieldname_map.get(self.doctype)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530718
marination9ac9a4e2021-06-21 16:18:35 +0530719 # return if inspection is not required on document level
Ankush Menat494bd9e2022-03-28 18:52:46 +0530720 if (
721 (not inspection_required_fieldname and self.doctype != "Stock Entry")
722 or (self.doctype == "Stock Entry" and not self.inspection_required)
723 or (self.doctype in ["Sales Invoice", "Purchase Invoice"] and not self.update_stock)
724 ):
725 return
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530726
Ankush Menat494bd9e2022-03-28 18:52:46 +0530727 for row in self.get("items"):
marination9ac9a4e2021-06-21 16:18:35 +0530728 qi_required = False
Ankush Menat494bd9e2022-03-28 18:52:46 +0530729 if inspection_required_fieldname and frappe.db.get_value(
730 "Item", row.item_code, inspection_required_fieldname
731 ):
marination9ac9a4e2021-06-21 16:18:35 +0530732 qi_required = True
733 elif self.doctype == "Stock Entry" and row.t_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530734 qi_required = True # inward stock needs inspection
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530735
Ankush Menat494bd9e2022-03-28 18:52:46 +0530736 if qi_required: # validate row only if inspection is required on item level
marination9ac9a4e2021-06-21 16:18:35 +0530737 self.validate_qi_presence(row)
738 if self.docstatus == 1:
739 self.validate_qi_submission(row)
740 self.validate_qi_rejection(row)
741
742 def validate_qi_presence(self, row):
743 """Check if QI is present on row level. Warn on save and stop on submit if missing."""
744 if not row.quality_inspection:
marination654e9d82021-06-21 16:51:12 +0530745 msg = f"Row #{row.idx}: Quality Inspection is required for Item {frappe.bold(row.item_code)}"
marination9ac9a4e2021-06-21 16:18:35 +0530746 if self.docstatus == 1:
marination654e9d82021-06-21 16:51:12 +0530747 frappe.throw(_(msg), title=_("Inspection Required"), exc=QualityInspectionRequiredError)
marination9ac9a4e2021-06-21 16:18:35 +0530748 else:
marination654e9d82021-06-21 16:51:12 +0530749 frappe.msgprint(_(msg), title=_("Inspection Required"), indicator="blue")
marination9ac9a4e2021-06-21 16:18:35 +0530750
751 def validate_qi_submission(self, row):
752 """Check if QI is submitted on row level, during submission"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530753 action = frappe.db.get_single_value(
754 "Stock Settings", "action_if_quality_inspection_is_not_submitted"
755 )
marination9ac9a4e2021-06-21 16:18:35 +0530756 qa_docstatus = frappe.db.get_value("Quality Inspection", row.quality_inspection, "docstatus")
757
barredterraeb9ee3f2023-12-05 11:22:55 +0100758 if qa_docstatus != 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530759 link = frappe.utils.get_link_to_form("Quality Inspection", row.quality_inspection)
760 msg = (
761 f"Row #{row.idx}: Quality Inspection {link} is not submitted for the item: {row.item_code}"
762 )
marination9ac9a4e2021-06-21 16:18:35 +0530763 if action == "Stop":
marination654e9d82021-06-21 16:51:12 +0530764 frappe.throw(_(msg), title=_("Inspection Submission"), exc=QualityInspectionNotSubmittedError)
marination9ac9a4e2021-06-21 16:18:35 +0530765 else:
Marica9ba3fce2021-06-22 11:20:17 +0530766 frappe.msgprint(_(msg), alert=True, indicator="orange")
marination9ac9a4e2021-06-21 16:18:35 +0530767
768 def validate_qi_rejection(self, row):
769 """Check if QI is rejected on row level, during submission"""
marinationf67f13c2021-07-10 18:24:24 +0530770 action = frappe.db.get_single_value("Stock Settings", "action_if_quality_inspection_is_rejected")
marination9ac9a4e2021-06-21 16:18:35 +0530771 qa_status = frappe.db.get_value("Quality Inspection", row.quality_inspection, "status")
772
773 if qa_status == "Rejected":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530774 link = frappe.utils.get_link_to_form("Quality Inspection", row.quality_inspection)
marination654e9d82021-06-21 16:51:12 +0530775 msg = f"Row #{row.idx}: Quality Inspection {link} was rejected for item {row.item_code}"
marination9ac9a4e2021-06-21 16:18:35 +0530776 if action == "Stop":
marination654e9d82021-06-21 16:51:12 +0530777 frappe.throw(_(msg), title=_("Inspection Rejected"), exc=QualityInspectionRejectedError)
marination9ac9a4e2021-06-21 16:18:35 +0530778 else:
marination654e9d82021-06-21 16:51:12 +0530779 frappe.msgprint(_(msg), alert=True, indicator="orange")
Manas Solankicc902412016-11-10 19:15:11 +0530780
Nabin Haitb2d3c0f2018-06-14 15:54:34 +0530781 def update_blanket_order(self):
Nabin Haitd1f40ad2018-06-14 17:09:55 +0530782 blanket_orders = list(set([d.blanket_order for d in self.items if d.blanket_order]))
Nabin Haitb2d3c0f2018-06-14 15:54:34 +0530783 for blanket_order in blanket_orders:
784 frappe.get_doc("Blanket Order", blanket_order).update_ordered_qty()
Manas Solankie5e87f72018-05-28 20:07:08 +0530785
marinationfd04e962020-04-03 15:46:48 +0530786 def validate_customer_provided_item(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530787 for d in self.get("items"):
marinationfd04e962020-04-03 15:46:48 +0530788 # Customer Provided parts will have zero valuation rate
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +0530789 if frappe.get_cached_value("Item", d.item_code, "is_customer_provided_item"):
marinationfd04e962020-04-03 15:46:48 +0530790 d.allow_zero_valuation_rate = 1
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530791
Anupam Kumar7e1dcf92021-02-11 20:19:30 +0530792 def set_rate_of_stock_uom(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530793 if self.doctype in [
794 "Purchase Receipt",
795 "Purchase Invoice",
796 "Purchase Order",
797 "Sales Invoice",
798 "Sales Order",
799 "Delivery Note",
800 "Quotation",
801 ]:
Anupam Kumar7e1dcf92021-02-11 20:19:30 +0530802 for d in self.get("items"):
Rohit Waghchaure13584432021-03-26 14:11:50 +0530803 d.stock_uom_rate = d.rate / (d.conversion_factor or 1)
Anupam Kumar7e1dcf92021-02-11 20:19:30 +0530804
Deepesh Gargb4be2922021-01-28 13:09:56 +0530805 def validate_internal_transfer(self):
rohitwaghchaure5136fe12023-10-22 20:03:02 +0530806 if self.doctype in ("Sales Invoice", "Delivery Note", "Purchase Invoice", "Purchase Receipt"):
807 if self.is_internal_transfer():
808 self.validate_in_transit_warehouses()
809 self.validate_multi_currency()
810 self.validate_packed_items()
rohitwaghchaure8fdc2442024-01-27 21:37:58 +0530811
812 if self.get("is_internal_supplier"):
813 self.validate_internal_transfer_qty()
rohitwaghchaure5136fe12023-10-22 20:03:02 +0530814 else:
815 self.validate_internal_transfer_warehouse()
816
817 def validate_internal_transfer_warehouse(self):
818 for row in self.items:
819 if row.get("target_warehouse"):
820 row.target_warehouse = None
821
822 if row.get("from_warehouse"):
823 row.from_warehouse = None
Deepesh Gargb4be2922021-01-28 13:09:56 +0530824
825 def validate_in_transit_warehouses(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530826 if (
827 self.doctype == "Sales Invoice" and self.get("update_stock")
828 ) or self.doctype == "Delivery Note":
829 for item in self.get("items"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530830 if not item.target_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530831 frappe.throw(
832 _("Row {0}: Target Warehouse is mandatory for internal transfers").format(item.idx)
833 )
Deepesh Gargb4be2922021-01-28 13:09:56 +0530834
Ankush Menat494bd9e2022-03-28 18:52:46 +0530835 if (
836 self.doctype == "Purchase Invoice" and self.get("update_stock")
837 ) or self.doctype == "Purchase Receipt":
838 for item in self.get("items"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530839 if not item.from_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530840 frappe.throw(
841 _("Row {0}: From Warehouse is mandatory for internal transfers").format(item.idx)
842 )
Deepesh Gargb4be2922021-01-28 13:09:56 +0530843
844 def validate_multi_currency(self):
845 if self.currency != self.company_currency:
846 frappe.throw(_("Internal transfers can only be done in company's default currency"))
847
848 def validate_packed_items(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530849 if self.doctype in ("Sales Invoice", "Delivery Note Item") and self.get("packed_items"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530850 frappe.throw(_("Packed Items cannot be transferred internally"))
851
rohitwaghchaure8fdc2442024-01-27 21:37:58 +0530852 def validate_internal_transfer_qty(self):
853 if self.doctype not in ["Purchase Invoice", "Purchase Receipt"]:
854 return
855
856 item_wise_transfer_qty = self.get_item_wise_inter_transfer_qty()
857 if not item_wise_transfer_qty:
858 return
859
860 item_wise_received_qty = self.get_item_wise_inter_received_qty()
861 precision = frappe.get_precision(self.doctype + " Item", "qty")
862
863 over_receipt_allowance = frappe.db.get_single_value(
864 "Stock Settings", "over_delivery_receipt_allowance"
865 )
866
867 parent_doctype = {
868 "Purchase Receipt": "Delivery Note",
869 "Purchase Invoice": "Sales Invoice",
870 }.get(self.doctype)
871
872 for key, transferred_qty in item_wise_transfer_qty.items():
873 recevied_qty = flt(item_wise_received_qty.get(key), precision)
874 if over_receipt_allowance:
875 transferred_qty = transferred_qty + flt(
876 transferred_qty * over_receipt_allowance / 100, precision
877 )
878
879 if recevied_qty > flt(transferred_qty, precision):
880 frappe.throw(
881 _("For Item {0} cannot be received more than {1} qty against the {2} {3}").format(
882 bold(key[1]),
883 bold(flt(transferred_qty, precision)),
884 bold(parent_doctype),
885 get_link_to_form(parent_doctype, self.get("inter_company_reference")),
886 )
887 )
888
889 def get_item_wise_inter_transfer_qty(self):
890 reference_field = "inter_company_reference"
891 if self.doctype == "Purchase Invoice":
892 reference_field = "inter_company_invoice_reference"
893
894 parent_doctype = {
895 "Purchase Receipt": "Delivery Note",
896 "Purchase Invoice": "Sales Invoice",
897 }.get(self.doctype)
898
899 child_doctype = parent_doctype + " Item"
900
901 parent_tab = frappe.qb.DocType(parent_doctype)
902 child_tab = frappe.qb.DocType(child_doctype)
903
904 query = (
905 frappe.qb.from_(parent_doctype)
906 .inner_join(child_tab)
907 .on(child_tab.parent == parent_tab.name)
908 .select(
909 child_tab.name,
910 child_tab.item_code,
911 child_tab.qty,
912 )
913 .where((parent_tab.name == self.get(reference_field)) & (parent_tab.docstatus == 1))
914 )
915
916 data = query.run(as_dict=True)
917 item_wise_transfer_qty = defaultdict(float)
918 for row in data:
919 item_wise_transfer_qty[(row.name, row.item_code)] += flt(row.qty)
920
921 return item_wise_transfer_qty
922
923 def get_item_wise_inter_received_qty(self):
924 child_doctype = self.doctype + " Item"
925
926 parent_tab = frappe.qb.DocType(self.doctype)
927 child_tab = frappe.qb.DocType(child_doctype)
928
929 query = (
930 frappe.qb.from_(self.doctype)
931 .inner_join(child_tab)
932 .on(child_tab.parent == parent_tab.name)
933 .select(
934 child_tab.item_code,
935 child_tab.qty,
936 )
937 .where(parent_tab.docstatus < 2)
938 )
939
940 if self.doctype == "Purchase Invoice":
941 query = query.select(
942 child_tab.sales_invoice_item.as_("name"),
943 )
944
945 query = query.where(
946 parent_tab.inter_company_invoice_reference == self.inter_company_invoice_reference
947 )
948 else:
949 query = query.select(
950 child_tab.delivery_note_item.as_("name"),
951 )
952
953 query = query.where(parent_tab.inter_company_reference == self.inter_company_reference)
954
955 data = query.run(as_dict=True)
956 item_wise_transfer_qty = defaultdict(float)
957 for row in data:
958 item_wise_transfer_qty[(row.name, row.item_code)] += flt(row.qty)
959
960 return item_wise_transfer_qty
961
marinationfac40352020-12-07 21:35:49 +0530962 def validate_putaway_capacity(self):
963 # if over receipt is attempted while 'apply putaway rule' is disabled
964 # and if rule was applied on the transaction, validate it.
marination957615b2021-01-18 23:47:24 +0530965 from erpnext.stock.doctype.putaway_rule.putaway_rule import get_available_putaway_capacity
Ankush Menat494bd9e2022-03-28 18:52:46 +0530966
967 valid_doctype = self.doctype in (
968 "Purchase Receipt",
969 "Stock Entry",
970 "Purchase Invoice",
971 "Stock Reconciliation",
972 )
marinationfac40352020-12-07 21:35:49 +0530973
rohitwaghchaureb966c062024-02-12 12:49:09 +0530974 if not frappe.get_all("Putaway Rule", limit=1):
975 return
976
marination957615b2021-01-18 23:47:24 +0530977 if self.doctype == "Purchase Invoice" and self.get("update_stock") == 0:
978 valid_doctype = False
979
980 if valid_doctype:
marinationfac40352020-12-07 21:35:49 +0530981 rule_map = defaultdict(dict)
982 for item in self.get("items"):
marination957615b2021-01-18 23:47:24 +0530983 warehouse_field = "t_warehouse" if self.doctype == "Stock Entry" else "warehouse"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530984 rule = frappe.db.get_value(
985 "Putaway Rule",
986 {"item_code": item.get("item_code"), "warehouse": item.get(warehouse_field)},
987 ["name", "disable"],
988 as_dict=True,
989 )
marination957615b2021-01-18 23:47:24 +0530990 if rule:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530991 if rule.get("disabled"):
992 continue # dont validate for disabled rule
marination957615b2021-01-18 23:47:24 +0530993
994 if self.doctype == "Stock Reconciliation":
995 stock_qty = flt(item.qty)
996 else:
997 stock_qty = flt(item.transfer_qty) if self.doctype == "Stock Entry" else flt(item.stock_qty)
998
999 rule_name = rule.get("name")
1000 if not rule_map[rule_name]:
1001 rule_map[rule_name]["warehouse"] = item.get(warehouse_field)
1002 rule_map[rule_name]["item"] = item.get("item_code")
1003 rule_map[rule_name]["qty_put"] = 0
1004 rule_map[rule_name]["capacity"] = get_available_putaway_capacity(rule_name)
1005 rule_map[rule_name]["qty_put"] += flt(stock_qty)
marinationfac40352020-12-07 21:35:49 +05301006
1007 for rule, values in rule_map.items():
1008 if flt(values["qty_put"]) > flt(values["capacity"]):
marination957615b2021-01-18 23:47:24 +05301009 message = self.prepare_over_receipt_message(rule, values)
marinationfac40352020-12-07 21:35:49 +05301010 frappe.throw(msg=message, title=_("Over Receipt"))
marination957615b2021-01-18 23:47:24 +05301011
1012 def prepare_over_receipt_message(self, rule, values):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301013 message = _(
1014 "{0} qty of Item {1} is being received into Warehouse {2} with capacity {3}."
1015 ).format(
1016 frappe.bold(values["qty_put"]),
1017 frappe.bold(values["item"]),
1018 frappe.bold(values["warehouse"]),
1019 frappe.bold(values["capacity"]),
1020 )
marination957615b2021-01-18 23:47:24 +05301021 message += "<br><br>"
1022 rule_link = frappe.utils.get_link_to_form("Putaway Rule", rule)
Ankush Menatad6a2652021-04-17 16:50:02 +05301023 message += _("Please adjust the qty or edit {0} to proceed.").format(rule_link)
marination957615b2021-01-18 23:47:24 +05301024 return message
marinationfac40352020-12-07 21:35:49 +05301025
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +05301026 def repost_future_sle_and_gle(self, force=False):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301027 args = frappe._dict(
1028 {
1029 "posting_date": self.posting_date,
1030 "posting_time": self.posting_time,
1031 "voucher_type": self.doctype,
1032 "voucher_no": self.name,
1033 "company": self.company,
1034 }
1035 )
Ankush Menat3638fbf2022-03-01 18:17:14 +05301036
Rohit Waghchaure6e661e72023-05-16 16:23:52 +05301037 if self.docstatus == 2:
1038 force = True
1039
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +05301040 if force or future_sle_exists(args) or repost_required_for_queue(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301041 item_based_reposting = cint(
1042 frappe.db.get_single_value("Stock Reposting Settings", "item_based_reposting")
1043 )
Ankush Menat45dd46b2021-11-02 10:50:52 +05301044 if item_based_reposting:
1045 create_item_wise_repost_entries(voucher_type=self.doctype, voucher_no=self.name)
1046 else:
1047 create_repost_item_valuation_entry(args)
1048
Sagar Sharmaf4673942022-08-21 21:26:06 +05301049 def add_gl_entry(
1050 self,
1051 gl_entries,
1052 account,
1053 cost_center,
1054 debit,
1055 credit,
1056 remarks,
1057 against_account,
1058 debit_in_account_currency=None,
1059 credit_in_account_currency=None,
1060 account_currency=None,
1061 project=None,
1062 voucher_detail_no=None,
1063 item=None,
1064 posting_date=None,
1065 ):
1066
1067 gl_entry = {
1068 "account": account,
1069 "cost_center": cost_center,
1070 "debit": debit,
1071 "credit": credit,
1072 "against": against_account,
1073 "remarks": remarks,
1074 }
1075
1076 if voucher_detail_no:
1077 gl_entry.update({"voucher_detail_no": voucher_detail_no})
1078
1079 if debit_in_account_currency:
1080 gl_entry.update({"debit_in_account_currency": debit_in_account_currency})
1081
1082 if credit_in_account_currency:
1083 gl_entry.update({"credit_in_account_currency": credit_in_account_currency})
1084
1085 if posting_date:
1086 gl_entry.update({"posting_date": posting_date})
1087
1088 gl_entries.append(self.get_gl_dict(gl_entry, item=item))
1089
Ankush Menat494bd9e2022-03-28 18:52:46 +05301090
Deepesh Garg2e52a632023-06-04 19:20:28 +05301091@frappe.whitelist()
Deepesh Garg0e68da52023-06-22 15:43:32 +05301092def show_accounting_ledger_preview(company, doctype, docname):
Smit Vora77cc91d2023-10-19 22:35:55 +05301093 filters = frappe._dict(company=company, include_dimensions=1)
Deepesh Garg0e68da52023-06-22 15:43:32 +05301094 doc = frappe.get_doc(doctype, docname)
Smit Vora77cc91d2023-10-19 22:35:55 +05301095 doc.run_method("before_gl_preview")
Deepesh Garg0e68da52023-06-22 15:43:32 +05301096
1097 gl_columns, gl_data = get_accounting_ledger_preview(doc, filters)
1098
Deepesh Gargd9e7bc52023-06-22 16:07:32 +05301099 frappe.db.rollback()
Deepesh Garg0e68da52023-06-22 15:43:32 +05301100
1101 return {"gl_columns": gl_columns, "gl_data": gl_data}
1102
1103
1104@frappe.whitelist()
1105def show_stock_ledger_preview(company, doctype, docname):
Smit Vora77cc91d2023-10-19 22:35:55 +05301106 filters = frappe._dict(company=company)
Deepesh Garg2e52a632023-06-04 19:20:28 +05301107 doc = frappe.get_doc(doctype, docname)
Smit Vora77cc91d2023-10-19 22:35:55 +05301108 doc.run_method("before_sl_preview")
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301109
Deepesh Garg011ac132023-06-12 18:42:49 +05301110 sl_columns, sl_data = get_stock_ledger_preview(doc, filters)
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301111
Deepesh Gargd9e7bc52023-06-22 16:07:32 +05301112 frappe.db.rollback()
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301113
Deepesh Garg2e52a632023-06-04 19:20:28 +05301114 return {
Deepesh Garg011ac132023-06-12 18:42:49 +05301115 "sl_columns": sl_columns,
1116 "sl_data": sl_data,
Deepesh Garg2e52a632023-06-04 19:20:28 +05301117 }
1118
1119
Deepesh Garg011ac132023-06-12 18:42:49 +05301120def get_accounting_ledger_preview(doc, filters):
1121 from erpnext.accounts.report.general_ledger.general_ledger import get_columns as get_gl_columns
1122
1123 gl_columns, gl_data = [], []
1124 fields = [
1125 "posting_date",
1126 "account",
1127 "debit",
1128 "credit",
1129 "against",
1130 "party",
1131 "party_type",
Deepesh Garg0e68da52023-06-22 15:43:32 +05301132 "cost_center",
Deepesh Garg011ac132023-06-12 18:42:49 +05301133 "against_voucher_type",
1134 "against_voucher",
1135 ]
1136
1137 doc.docstatus = 1
Deepesh Garg0e68da52023-06-22 15:43:32 +05301138
1139 if doc.get("update_stock") or doc.doctype in ("Purchase Receipt", "Delivery Note"):
1140 doc.update_stock_ledger()
1141
Deepesh Garg011ac132023-06-12 18:42:49 +05301142 doc.make_gl_entries()
1143 columns = get_gl_columns(filters)
1144 gl_entries = get_gl_entries_for_preview(doc.doctype, doc.name, fields)
1145
1146 gl_columns = get_columns(columns, fields)
1147 gl_data = get_data(fields, gl_entries)
1148
1149 return gl_columns, gl_data
1150
1151
1152def get_stock_ledger_preview(doc, filters):
1153 from erpnext.stock.report.stock_ledger.stock_ledger import get_columns as get_sl_columns
1154
1155 sl_columns, sl_data = [], []
1156 fields = [
1157 "item_code",
1158 "stock_uom",
1159 "actual_qty",
1160 "qty_after_transaction",
1161 "warehouse",
1162 "incoming_rate",
1163 "valuation_rate",
1164 "stock_value",
1165 "stock_value_difference",
1166 ]
1167 columns_fields = [
1168 "item_code",
1169 "stock_uom",
1170 "in_qty",
1171 "out_qty",
1172 "qty_after_transaction",
1173 "warehouse",
1174 "incoming_rate",
Deepesh Garg0e68da52023-06-22 15:43:32 +05301175 "in_out_rate",
Deepesh Garg011ac132023-06-12 18:42:49 +05301176 "stock_value",
1177 "stock_value_difference",
1178 ]
1179
Deepesh Garg0e68da52023-06-22 15:43:32 +05301180 if doc.get("update_stock") or doc.doctype in ("Purchase Receipt", "Delivery Note"):
Deepesh Garg011ac132023-06-12 18:42:49 +05301181 doc.docstatus = 1
1182 doc.update_stock_ledger()
1183 columns = get_sl_columns(filters)
1184 sl_entries = get_sl_entries_for_preview(doc.doctype, doc.name, fields)
1185
1186 sl_columns = get_columns(columns, columns_fields)
1187 sl_data = get_data(columns_fields, sl_entries)
1188
1189 return sl_columns, sl_data
1190
1191
1192def get_sl_entries_for_preview(doctype, docname, fields):
1193 sl_entries = frappe.get_all(
1194 "Stock Ledger Entry", filters={"voucher_type": doctype, "voucher_no": docname}, fields=fields
1195 )
1196
1197 for entry in sl_entries:
1198 if entry.actual_qty > 0:
1199 entry["in_qty"] = entry.actual_qty
1200 entry["out_qty"] = 0
1201 else:
1202 entry["out_qty"] = abs(entry.actual_qty)
1203 entry["in_qty"] = 0
1204
Deepesh Garg0e68da52023-06-22 15:43:32 +05301205 entry["in_out_rate"] = entry["valuation_rate"]
1206
Deepesh Garg011ac132023-06-12 18:42:49 +05301207 return sl_entries
1208
1209
1210def get_gl_entries_for_preview(doctype, docname, fields):
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301211 return frappe.get_all(
Deepesh Garg011ac132023-06-12 18:42:49 +05301212 "GL Entry", filters={"voucher_type": doctype, "voucher_no": docname}, fields=fields
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301213 )
1214
1215
Deepesh Garg011ac132023-06-12 18:42:49 +05301216def get_columns(raw_columns, fields):
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301217 return [
Deepesh Garg011ac132023-06-12 18:42:49 +05301218 {"name": d.get("label"), "editable": False, "width": 110}
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301219 for d in raw_columns
Deepesh Garg011ac132023-06-12 18:42:49 +05301220 if not d.get("hidden") and d.get("fieldname") in fields
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301221 ]
1222
1223
1224def get_data(raw_columns, raw_data):
1225 datatable_data = []
1226 for row in raw_data:
1227 data_row = []
1228 for column in raw_columns:
Deepesh Garg011ac132023-06-12 18:42:49 +05301229 data_row.append(row.get(column) or "")
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301230
1231 datatable_data.append(data_row)
1232
1233 return datatable_data
1234
1235
Ankush Menat3638fbf2022-03-01 18:17:14 +05301236def repost_required_for_queue(doc: StockController) -> bool:
1237 """check if stock document contains repeated item-warehouse with queue based valuation.
1238
1239 if queue exists for repeated items then SLEs need to reprocessed in background again.
1240 """
1241
Ankush Menat494bd9e2022-03-28 18:52:46 +05301242 consuming_sles = frappe.db.get_all(
1243 "Stock Ledger Entry",
Ankush Menat3638fbf2022-03-01 18:17:14 +05301244 filters={
1245 "voucher_type": doc.doctype,
1246 "voucher_no": doc.name,
1247 "actual_qty": ("<", 0),
Ankush Menat494bd9e2022-03-28 18:52:46 +05301248 "is_cancelled": 0,
Ankush Menat3638fbf2022-03-01 18:17:14 +05301249 },
Ankush Menat494bd9e2022-03-28 18:52:46 +05301250 fields=["item_code", "warehouse", "stock_queue"],
Ankush Menat3638fbf2022-03-01 18:17:14 +05301251 )
1252 item_warehouses = [(sle.item_code, sle.warehouse) for sle in consuming_sles]
1253
1254 unique_item_warehouses = set(item_warehouses)
1255
1256 if len(unique_item_warehouses) == len(item_warehouses):
1257 return False
1258
1259 for sle in consuming_sles:
1260 if sle.stock_queue != "[]": # using FIFO/LIFO valuation
1261 return True
1262 return False
1263
Nabin Hait19f8fa52021-02-22 22:27:22 +05301264
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301265@frappe.whitelist()
1266def make_quality_inspections(doctype, docname, items):
Rohan Bansala06ec032021-06-02 14:55:31 +05301267 if isinstance(items, str):
1268 items = json.loads(items)
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301269
Rohan Bansala06ec032021-06-02 14:55:31 +05301270 inspections = []
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301271 for item in items:
Rohan Bansal1cdf5a02021-05-26 14:42:15 +05301272 if flt(item.get("sample_size")) > flt(item.get("qty")):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301273 frappe.throw(
1274 _(
1275 "{item_name}'s Sample Size ({sample_size}) cannot be greater than the Accepted Quantity ({accepted_quantity})"
1276 ).format(
1277 item_name=item.get("item_name"),
1278 sample_size=item.get("sample_size"),
1279 accepted_quantity=item.get("qty"),
1280 )
1281 )
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301282
Ankush Menat494bd9e2022-03-28 18:52:46 +05301283 quality_inspection = frappe.get_doc(
1284 {
1285 "doctype": "Quality Inspection",
1286 "inspection_type": "Incoming",
1287 "inspected_by": frappe.session.user,
1288 "reference_type": doctype,
1289 "reference_name": docname,
1290 "item_code": item.get("item_code"),
1291 "description": item.get("description"),
1292 "sample_size": flt(item.get("sample_size")),
1293 "item_serial_no": item.get("serial_no").split("\n")[0] if item.get("serial_no") else None,
1294 "batch_no": item.get("batch_no"),
1295 }
1296 ).insert()
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301297 quality_inspection.save()
Rohan Bansal1cdf5a02021-05-26 14:42:15 +05301298 inspections.append(quality_inspection.name)
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301299
Rohan Bansal1cdf5a02021-05-26 14:42:15 +05301300 return inspections
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301301
Ankush Menat494bd9e2022-03-28 18:52:46 +05301302
Nabin Haitb99c77b2020-12-25 18:12:35 +05301303def is_reposting_pending():
Ankush Menat494bd9e2022-03-28 18:52:46 +05301304 return frappe.db.exists(
1305 "Repost Item Valuation", {"docstatus": 1, "status": ["in", ["Queued", "In Progress"]]}
1306 )
1307
Nabin Haitb99c77b2020-12-25 18:12:35 +05301308
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301309def future_sle_exists(args, sl_entries=None):
1310 key = (args.voucher_type, args.voucher_no)
Rohit Waghchaured9dd64b2023-04-14 13:00:12 +05301311 if not hasattr(frappe.local, "future_sle"):
1312 frappe.local.future_sle = {}
Nabin Haita77b8c92020-12-21 14:45:50 +05301313
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301314 if validate_future_sle_not_exists(args, key, sl_entries):
1315 return False
1316 elif get_cached_data(args, key):
1317 return True
1318
1319 if not sl_entries:
1320 sl_entries = get_sle_entries_against_voucher(args)
1321 if not sl_entries:
1322 return
1323
1324 or_conditions = get_conditions_to_validate_future_sle(sl_entries)
1325
Ankush Menat494bd9e2022-03-28 18:52:46 +05301326 data = frappe.db.sql(
1327 """
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301328 select item_code, warehouse, count(name) as total_row
Deepesh Garg6f107da2021-10-12 20:15:55 +05301329 from `tabStock Ledger Entry` force index (item_warehouse)
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301330 where
1331 ({})
1332 and timestamp(posting_date, posting_time)
1333 >= timestamp(%(posting_date)s, %(posting_time)s)
1334 and voucher_no != %(voucher_no)s
1335 and is_cancelled = 0
1336 GROUP BY
1337 item_code, warehouse
Ankush Menat494bd9e2022-03-28 18:52:46 +05301338 """.format(
1339 " or ".join(or_conditions)
1340 ),
1341 args,
1342 as_dict=1,
1343 )
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301344
1345 for d in data:
1346 frappe.local.future_sle[key][(d.item_code, d.warehouse)] = d.total_row
1347
1348 return len(data)
1349
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301350
Ankush Menat494bd9e2022-03-28 18:52:46 +05301351def validate_future_sle_not_exists(args, key, sl_entries=None):
1352 item_key = ""
1353 if args.get("item_code"):
1354 item_key = (args.get("item_code"), args.get("warehouse"))
1355
1356 if not sl_entries and hasattr(frappe.local, "future_sle"):
Rohit Waghchaured9dd64b2023-04-14 13:00:12 +05301357 if key not in frappe.local.future_sle:
1358 return False
1359
Ankush Menat494bd9e2022-03-28 18:52:46 +05301360 if not frappe.local.future_sle.get(key) or (
1361 item_key and item_key not in frappe.local.future_sle.get(key)
1362 ):
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301363 return True
1364
Ankush Menat494bd9e2022-03-28 18:52:46 +05301365
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301366def get_cached_data(args, key):
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301367 if key not in frappe.local.future_sle:
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +05301368 frappe.local.future_sle[key] = frappe._dict({})
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301369
Ankush Menat494bd9e2022-03-28 18:52:46 +05301370 if args.get("item_code"):
1371 item_key = (args.get("item_code"), args.get("warehouse"))
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301372 count = frappe.local.future_sle[key].get(item_key)
1373
1374 return True if (count or count == 0) else False
1375 else:
1376 return frappe.local.future_sle[key]
1377
Ankush Menat494bd9e2022-03-28 18:52:46 +05301378
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301379def get_sle_entries_against_voucher(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301380 return frappe.get_all(
1381 "Stock Ledger Entry",
Nabin Haita77b8c92020-12-21 14:45:50 +05301382 filters={"voucher_type": args.voucher_type, "voucher_no": args.voucher_no},
1383 fields=["item_code", "warehouse"],
Ankush Menat494bd9e2022-03-28 18:52:46 +05301384 order_by="creation asc",
1385 )
1386
Nabin Haita77b8c92020-12-21 14:45:50 +05301387
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301388def get_conditions_to_validate_future_sle(sl_entries):
Sagar Vora868c0bf2021-03-27 16:10:20 +05301389 warehouse_items_map = {}
1390 for entry in sl_entries:
1391 if entry.warehouse not in warehouse_items_map:
1392 warehouse_items_map[entry.warehouse] = set()
Nabin Haita77b8c92020-12-21 14:45:50 +05301393
Sagar Vora868c0bf2021-03-27 16:10:20 +05301394 warehouse_items_map[entry.warehouse].add(entry.item_code)
1395
1396 or_conditions = []
1397 for warehouse, items in warehouse_items_map.items():
1398 or_conditions.append(
Noah Jacobb5a14912021-06-15 12:44:04 +05301399 f"""warehouse = {frappe.db.escape(warehouse)}
Ankush Menat494bd9e2022-03-28 18:52:46 +05301400 and item_code in ({', '.join(frappe.db.escape(item) for item in items)})"""
1401 )
Sagar Vora868c0bf2021-03-27 16:10:20 +05301402
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301403 return or_conditions
Nabin Haita77b8c92020-12-21 14:45:50 +05301404
Ankush Menat494bd9e2022-03-28 18:52:46 +05301405
Nabin Haita77b8c92020-12-21 14:45:50 +05301406def create_repost_item_valuation_entry(args):
1407 args = frappe._dict(args)
1408 repost_entry = frappe.new_doc("Repost Item Valuation")
1409 repost_entry.based_on = args.based_on
1410 if not args.based_on:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301411 repost_entry.based_on = "Transaction" if args.voucher_no else "Item and Warehouse"
Nabin Haita77b8c92020-12-21 14:45:50 +05301412 repost_entry.voucher_type = args.voucher_type
1413 repost_entry.voucher_no = args.voucher_no
1414 repost_entry.item_code = args.item_code
1415 repost_entry.warehouse = args.warehouse
1416 repost_entry.posting_date = args.posting_date
1417 repost_entry.posting_time = args.posting_time
1418 repost_entry.company = args.company
1419 repost_entry.allow_zero_rate = args.allow_zero_rate
1420 repost_entry.flags.ignore_links = True
Ankush Menataa024fc2021-11-18 12:51:26 +05301421 repost_entry.flags.ignore_permissions = True
Nabin Haita77b8c92020-12-21 14:45:50 +05301422 repost_entry.save()
Sagar Vora868c0bf2021-03-27 16:10:20 +05301423 repost_entry.submit()
Ankush Menat6dc9b822021-10-28 15:53:18 +05301424
1425
1426def create_item_wise_repost_entries(voucher_type, voucher_no, allow_zero_rate=False):
1427 """Using a voucher create repost item valuation records for all item-warehouse pairs."""
1428
Ankush Menatd220e082021-10-28 17:47:00 +05301429 stock_ledger_entries = get_items_to_be_repost(voucher_type, voucher_no)
1430
Ankush Menat6dc9b822021-10-28 15:53:18 +05301431 distinct_item_warehouses = set()
Ankush Menat6dc9b822021-10-28 15:53:18 +05301432 repost_entries = []
1433
1434 for sle in stock_ledger_entries:
1435 item_wh = (sle.item_code, sle.warehouse)
1436 if item_wh in distinct_item_warehouses:
1437 continue
1438 distinct_item_warehouses.add(item_wh)
1439
1440 repost_entry = frappe.new_doc("Repost Item Valuation")
1441 repost_entry.based_on = "Item and Warehouse"
Ankush Menat6dc9b822021-10-28 15:53:18 +05301442
1443 repost_entry.item_code = sle.item_code
1444 repost_entry.warehouse = sle.warehouse
1445 repost_entry.posting_date = sle.posting_date
1446 repost_entry.posting_time = sle.posting_time
1447 repost_entry.allow_zero_rate = allow_zero_rate
1448 repost_entry.flags.ignore_links = True
Ankush Menat0a2964d2021-11-24 15:55:31 +05301449 repost_entry.flags.ignore_permissions = True
Ankush Menat6dc9b822021-10-28 15:53:18 +05301450 repost_entry.submit()
1451 repost_entries.append(repost_entry)
1452
1453 return repost_entries