blob: 8ffbaa101553ed066371a7b7b0b99023534ddc92 [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()
Ankush Menat494bd9e2022-03-28 18:52:46 +053049 if not self.get("is_return"):
marination596560c2020-06-11 16:39:03 +053050 self.validate_inspection()
rohitwaghchaure9af557f2019-12-30 13:26:47 +053051 self.validate_serialized_batch()
marinationeecfc4c2021-07-22 13:23:54 +053052 self.clean_serial_nos()
marinationfd04e962020-04-03 15:46:48 +053053 self.validate_customer_provided_item()
Anupam Kumar7e1dcf92021-02-11 20:19:30 +053054 self.set_rate_of_stock_uom()
Deepesh Gargb4be2922021-01-28 13:09:56 +053055 self.validate_internal_transfer()
marinationfac40352020-12-07 21:35:49 +053056 self.validate_putaway_capacity()
Rushabh Mehtaffd80a62017-01-16 17:23:20 +053057
Nabin Haita77b8c92020-12-21 14:45:50 +053058 def make_gl_entries(self, gl_entries=None, from_repost=False):
Anand Doshif78d1ae2014-03-28 13:55:00 +053059 if self.docstatus == 2:
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053060 make_reverse_gl_entries(voucher_type=self.doctype, voucher_no=self.name)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053061
Ankush Menat494bd9e2022-03-28 18:52:46 +053062 provisional_accounting_for_non_stock_items = cint(
Daizy Modi4efc9472022-11-07 09:21:03 +053063 frappe.get_cached_value(
Ankush Menat494bd9e2022-03-28 18:52:46 +053064 "Company", self.company, "enable_provisional_accounting_for_non_stock_items"
65 )
66 )
Deepesh Garg528c7132022-02-01 14:42:55 +053067
Deepesh Gargd1ec0a62023-10-23 00:16:40 +053068 is_asset_pr = any(d.get("is_fixed_asset") for d in self.get("items"))
69
Ankush Menat494bd9e2022-03-28 18:52:46 +053070 if (
71 cint(erpnext.is_perpetual_inventory_enabled(self.company))
72 or provisional_accounting_for_non_stock_items
Deepesh Gargd1ec0a62023-10-23 00:16:40 +053073 or is_asset_pr
Ankush Menat494bd9e2022-03-28 18:52:46 +053074 ):
Rohit Waghchaure6b33c9b2019-03-08 11:13:35 +053075 warehouse_account = get_warehouse_account_map(self.company)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053076
Ankush Menat494bd9e2022-03-28 18:52:46 +053077 if self.docstatus == 1:
Nabin Hait9784d272016-12-30 16:21:35 +053078 if not gl_entries:
79 gl_entries = self.get_gl_entries(warehouse_account)
Nabin Haita77b8c92020-12-21 14:45:50 +053080 make_gl_entries(gl_entries, from_repost=from_repost)
Nabin Hait145e5e22013-10-22 23:51:41 +053081
rohitwaghchaure9af557f2019-12-30 13:26:47 +053082 def validate_serialized_batch(self):
83 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
Ankush Menat494bd9e2022-03-28 18:52:46 +053084
Rohit Waghchaure795c9432022-08-17 13:48:56 +053085 is_material_issue = False
86 if self.doctype == "Stock Entry" and self.purpose == "Material Issue":
87 is_material_issue = True
88
rohitwaghchaure9af557f2019-12-30 13:26:47 +053089 for d in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +053090 if hasattr(d, "serial_no") and hasattr(d, "batch_no") and d.serial_no and d.batch_no:
91 serial_nos = frappe.get_all(
92 "Serial No",
Rohit Waghchaure6b482eb2021-07-23 16:40:45 +053093 fields=["batch_no", "name", "warehouse"],
Ankush Menat494bd9e2022-03-28 18:52:46 +053094 filters={"name": ("in", get_serial_nos(d.serial_no))},
Rohit Waghchaure6b482eb2021-07-23 16:40:45 +053095 )
96
97 for row in serial_nos:
98 if row.warehouse and row.batch_no != d.batch_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +053099 frappe.throw(
100 _("Row #{0}: Serial No {1} does not belong to Batch {2}").format(
101 d.idx, row.name, d.batch_no
102 )
103 )
rohitwaghchaure9af557f2019-12-30 13:26:47 +0530104
Rohit Waghchaure795c9432022-08-17 13:48:56 +0530105 if is_material_issue:
106 continue
107
Saqib Ansari903055b2020-10-20 11:59:06 +0530108 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 +0530109 expiry_date = frappe.get_cached_value("Batch", d.get("batch_no"), "expiry_date")
110
111 if expiry_date and getdate(expiry_date) < getdate(self.posting_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530112 frappe.throw(
113 _("Row #{0}: The batch {1} has already expired.").format(
114 d.idx, get_link_to_form("Batch", d.get("batch_no"))
Rohit Waghchaure795c9432022-08-17 13:48:56 +0530115 ),
116 BatchExpiredError,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530117 )
rohitwaghchaure28a48802020-04-28 13:01:43 +0530118
marinationeecfc4c2021-07-22 13:23:54 +0530119 def clean_serial_nos(self):
Ankush Menatb20df372022-01-24 19:19:58 +0530120 from erpnext.stock.doctype.serial_no.serial_no import clean_serial_no_string
121
marinationeecfc4c2021-07-22 13:23:54 +0530122 for row in self.get("items"):
123 if hasattr(row, "serial_no") and row.serial_no:
Ankush Menatb20df372022-01-24 19:19:58 +0530124 # remove extra whitespace and store one serial no on each line
125 row.serial_no = clean_serial_no_string(row.serial_no)
marinationeecfc4c2021-07-22 13:23:54 +0530126
Ankush Menat494bd9e2022-03-28 18:52:46 +0530127 for row in self.get("packed_items") or []:
Ankush Menate177c522022-01-24 19:28:26 +0530128 if hasattr(row, "serial_no") and row.serial_no:
129 # remove extra whitespace and store one serial no on each line
130 row.serial_no = clean_serial_no_string(row.serial_no)
131
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530132 def make_bundle_using_old_serial_batch_fields(self):
133 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
134 from erpnext.stock.serial_batch_bundle import SerialBatchCreation
135
Rohit Waghchaurec1e869f2024-02-05 12:40:26 +0530136 # To handle test cases
137 if frappe.flags.in_test and frappe.flags.use_serial_and_batch_fields:
138 return
139
140 table_name = "items"
141 if self.doctype == "Asset Capitalization":
142 table_name = "stock_items"
143
144 for row in self.get(table_name):
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530145 if not row.serial_no and not row.batch_no and not row.get("rejected_serial_no"):
146 continue
147
148 if not row.use_serial_batch_fields and (
149 row.serial_no or row.batch_no or row.get("rejected_serial_no")
150 ):
151 frappe.throw(_("Please enable Use Old Serial / Batch Fields to make_bundle"))
152
153 if row.use_serial_batch_fields and (
Rohit Waghchaurec1e869f2024-02-05 12:40:26 +0530154 not row.serial_and_batch_bundle and not row.get("rejected_serial_and_batch_bundle")
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530155 ):
Rohit Waghchaure01650122024-02-06 13:31:36 +0530156 if self.doctype == "Stock Reconciliation":
157 qty = row.qty
158 type_of_transaction = "Inward"
rohitwaghchauree5824fc2024-02-11 11:10:21 +0530159 warehouse = row.warehouse
Rohit Waghchaure01650122024-02-06 13:31:36 +0530160 else:
rohitwaghchauree5824fc2024-02-11 11:10:21 +0530161 qty = row.stock_qty if self.doctype != "Stock Entry" else row.transfer_qty
Rohit Waghchaure01650122024-02-06 13:31:36 +0530162 type_of_transaction = get_type_of_transaction(self, row)
rohitwaghchauree5824fc2024-02-11 11:10:21 +0530163 warehouse = (
164 row.warehouse if self.doctype != "Stock Entry" else row.s_warehouse or row.t_warehouse
165 )
Rohit Waghchaure01650122024-02-06 13:31:36 +0530166
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530167 sn_doc = SerialBatchCreation(
168 {
169 "item_code": row.item_code,
rohitwaghchauree5824fc2024-02-11 11:10:21 +0530170 "warehouse": warehouse,
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530171 "posting_date": self.posting_date,
172 "posting_time": self.posting_time,
173 "voucher_type": self.doctype,
174 "voucher_no": self.name,
175 "voucher_detail_no": row.name,
Rohit Waghchaure01650122024-02-06 13:31:36 +0530176 "qty": qty,
177 "type_of_transaction": type_of_transaction,
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530178 "company": self.company,
179 "is_rejected": 1 if row.get("rejected_warehouse") else 0,
180 "serial_nos": get_serial_nos(row.serial_no) if row.serial_no else None,
Rohit Waghchaure01650122024-02-06 13:31:36 +0530181 "batches": frappe._dict({row.batch_no: qty}) if row.batch_no else None,
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530182 "batch_no": row.batch_no,
183 "use_serial_batch_fields": row.use_serial_batch_fields,
Rohit Waghchaure01650122024-02-06 13:31:36 +0530184 "do_not_submit": True,
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530185 }
186 ).make_serial_and_batch_bundle()
187
188 if sn_doc.is_rejected:
189 row.rejected_serial_and_batch_bundle = sn_doc.name
Rohit Waghchaurec1e869f2024-02-05 12:40:26 +0530190 row.db_set(
191 {
192 "rejected_serial_and_batch_bundle": sn_doc.name,
193 "rejected_serial_no": "",
194 }
195 )
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530196 else:
197 row.serial_and_batch_bundle = sn_doc.name
Rohit Waghchaurec1e869f2024-02-05 12:40:26 +0530198 row.db_set(
199 {
200 "serial_and_batch_bundle": sn_doc.name,
201 "serial_no": "",
202 "batch_no": "",
203 }
204 )
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530205
206 def set_use_serial_batch_fields(self):
207 if frappe.db.get_single_value("Stock Settings", "use_serial_batch_fields"):
208 for row in self.items:
209 row.use_serial_batch_fields = 1
210
Ankush Menat494bd9e2022-03-28 18:52:46 +0530211 def get_gl_entries(
212 self, warehouse_account=None, default_expense_account=None, default_cost_center=None
213 ):
Nabin Haitadeb9762014-10-06 11:53:52 +0530214
Nabin Hait142007a2013-09-17 15:15:16 +0530215 if not warehouse_account:
Rohit Waghchaure6b33c9b2019-03-08 11:13:35 +0530216 warehouse_account = get_warehouse_account_map(self.company)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530217
Anand Doshide1a97d2014-04-17 11:37:46 +0530218 sle_map = self.get_stock_ledger_details()
219 voucher_details = self.get_voucher_details(default_expense_account, default_cost_center, sle_map)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530220
Nabin Hait2e296fa2013-08-28 18:53:11 +0530221 gl_list = []
Nabin Hait7a75e102013-09-17 10:21:20 +0530222 warehouse_with_no_account = []
Nabin Hait19f8fa52021-02-22 22:27:22 +0530223 precision = self.get_debit_field_precision()
Nabin Hait8c61f342016-12-15 13:46:03 +0530224 for item_row in voucher_details:
225 sle_list = sle_map.get(item_row.name)
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530226 sle_rounding_diff = 0.0
Nabin Hait2e296fa2013-08-28 18:53:11 +0530227 if sle_list:
228 for sle in sle_list:
229 if warehouse_account.get(sle.warehouse):
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530230 # from warehouse account
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530231
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530232 sle_rounding_diff += flt(sle.stock_value_difference)
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530233
Nabin Hait8c61f342016-12-15 13:46:03 +0530234 self.check_expense_account(item_row)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530235
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530236 # expense account/ target_warehouse / source_warehouse
Ankush Menat494bd9e2022-03-28 18:52:46 +0530237 if item_row.get("target_warehouse"):
238 warehouse = item_row.get("target_warehouse")
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530239 expense_account = warehouse_account[warehouse]["account"]
240 else:
241 expense_account = item_row.expense_account
242
Ankush Menat494bd9e2022-03-28 18:52:46 +0530243 gl_list.append(
244 self.get_gl_dict(
245 {
246 "account": warehouse_account[sle.warehouse]["account"],
247 "against": expense_account,
248 "cost_center": item_row.cost_center,
249 "project": item_row.project or self.get("project"),
250 "remarks": self.get("remarks") or _("Accounting Entry for Stock"),
251 "debit": flt(sle.stock_value_difference, precision),
252 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
253 },
254 warehouse_account[sle.warehouse]["account_currency"],
255 item=item_row,
256 )
257 )
Nabin Hait27994c22013-08-26 16:53:30 +0530258
Ankush Menat494bd9e2022-03-28 18:52:46 +0530259 gl_list.append(
260 self.get_gl_dict(
261 {
262 "account": expense_account,
263 "against": warehouse_account[sle.warehouse]["account"],
264 "cost_center": item_row.cost_center,
265 "remarks": self.get("remarks") or _("Accounting Entry for Stock"),
Ankush Menat65b21ee2022-06-07 14:49:24 +0530266 "debit": -1 * flt(sle.stock_value_difference, precision),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530267 "project": item_row.get("project") or self.get("project"),
268 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
269 },
270 item=item_row,
271 )
272 )
Nabin Hait7a75e102013-09-17 10:21:20 +0530273 elif sle.warehouse not in warehouse_with_no_account:
274 warehouse_with_no_account.append(sle.warehouse)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530275
Deepesh Garg9aa5e202022-10-12 15:53:28 +0530276 if abs(sle_rounding_diff) > (1.0 / (10**precision)) and self.is_internal_transfer():
Deepesh Garg1c05c002022-10-12 14:19:09 +0530277 warehouse_asset_account = ""
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530278 if self.get("is_internal_customer"):
Deepesh Garg1c05c002022-10-12 14:19:09 +0530279 warehouse_asset_account = warehouse_account[item_row.get("target_warehouse")]["account"]
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530280 elif self.get("is_internal_supplier"):
Deepesh Garg1c05c002022-10-12 14:19:09 +0530281 warehouse_asset_account = warehouse_account[item_row.get("warehouse")]["account"]
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530282
Daizy Modi4efc9472022-11-07 09:21:03 +0530283 expense_account = frappe.get_cached_value("Company", self.company, "default_expense_account")
Deepesh Gargce9164e2023-07-11 12:03:38 +0530284 if not expense_account:
285 frappe.throw(
286 _(
287 "Please set default cost of goods sold account in company {0} for booking rounding gain and loss during stock transfer"
288 ).format(frappe.bold(self.company))
289 )
Deepesh Garg1c05c002022-10-12 14:19:09 +0530290
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530291 gl_list.append(
292 self.get_gl_dict(
293 {
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530294 "account": expense_account,
Deepesh Garg1c05c002022-10-12 14:19:09 +0530295 "against": warehouse_asset_account,
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530296 "cost_center": item_row.cost_center,
297 "project": item_row.project or self.get("project"),
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530298 "remarks": _("Rounding gain/loss Entry for Stock Transfer"),
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530299 "debit": sle_rounding_diff,
300 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
301 },
302 warehouse_account[sle.warehouse]["account_currency"],
303 item=item_row,
304 )
305 )
306
307 gl_list.append(
308 self.get_gl_dict(
309 {
Deepesh Garg1c05c002022-10-12 14:19:09 +0530310 "account": warehouse_asset_account,
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530311 "against": expense_account,
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530312 "cost_center": item_row.cost_center,
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530313 "remarks": _("Rounding gain/loss Entry for Stock Transfer"),
314 "credit": sle_rounding_diff,
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530315 "project": item_row.get("project") or self.get("project"),
316 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
317 },
318 item=item_row,
319 )
320 )
321
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530322 if warehouse_with_no_account:
Nabin Haitd6625022016-10-24 18:17:57 +0530323 for wh in warehouse_with_no_account:
Daizy Modi4efc9472022-11-07 09:21:03 +0530324 if frappe.get_cached_value("Warehouse", wh, "company"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530325 frappe.throw(
326 _(
327 "Warehouse {0} is not linked to any account, please mention the account in the warehouse record or set default inventory account in company {1}."
328 ).format(wh, self.company)
329 )
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530330
Nabin Hait19f8fa52021-02-22 22:27:22 +0530331 return process_gl_map(gl_list, precision=precision)
332
333 def get_debit_field_precision(self):
334 if not frappe.flags.debit_field_precision:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530335 frappe.flags.debit_field_precision = frappe.get_precision(
336 "GL Entry", "debit_in_account_currency"
337 )
Nabin Hait19f8fa52021-02-22 22:27:22 +0530338
339 return frappe.flags.debit_field_precision
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530340
Anand Doshide1a97d2014-04-17 11:37:46 +0530341 def get_voucher_details(self, default_expense_account, default_cost_center, sle_map):
342 if self.doctype == "Stock Reconciliation":
Nabin Hait3f119ec2019-05-16 17:28:39 +0530343 reconciliation_purpose = frappe.db.get_value(self.doctype, self.name, "purpose")
344 is_opening = "Yes" if reconciliation_purpose == "Opening Stock" else "No"
345 details = []
Nabin Hait34c551d2019-07-03 10:34:31 +0530346 for voucher_detail_no in sle_map:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530347 details.append(
348 frappe._dict(
349 {
350 "name": voucher_detail_no,
351 "expense_account": default_expense_account,
352 "cost_center": default_cost_center,
353 "is_opening": is_opening,
354 }
355 )
356 )
Nabin Hait3f119ec2019-05-16 17:28:39 +0530357 return details
Anand Doshide1a97d2014-04-17 11:37:46 +0530358 else:
Nabin Haitdd38a262014-12-26 13:15:21 +0530359 details = self.get("items")
Anand Doshi094610d2014-04-16 19:56:53 +0530360
Anand Doshide1a97d2014-04-17 11:37:46 +0530361 if default_expense_account or default_cost_center:
362 for d in details:
363 if default_expense_account and not d.get("expense_account"):
364 d.expense_account = default_expense_account
365 if default_cost_center and not d.get("cost_center"):
366 d.cost_center = default_cost_center
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530367
Anand Doshide1a97d2014-04-17 11:37:46 +0530368 return details
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530369
Ankush Menate6ab8df2022-02-06 13:02:34 +0530370 def get_items_and_warehouses(self) -> Tuple[List[str], List[str]]:
371 """Get list of items and warehouses affected by a transaction"""
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530372
Ankush Menate6ab8df2022-02-06 13:02:34 +0530373 if not (hasattr(self, "items") or hasattr(self, "packed_items")):
374 return [], []
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530375
Ankush Menate6ab8df2022-02-06 13:02:34 +0530376 item_rows = (self.get("items") or []) + (self.get("packed_items") or [])
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530377
Ankush Menate6ab8df2022-02-06 13:02:34 +0530378 items = {d.item_code for d in item_rows if d.item_code}
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530379
Ankush Menate6ab8df2022-02-06 13:02:34 +0530380 warehouses = set()
381 for d in item_rows:
382 if d.get("warehouse"):
383 warehouses.add(d.warehouse)
Nabin Haitbecf75d2014-03-27 17:18:29 +0530384
Ankush Menate6ab8df2022-02-06 13:02:34 +0530385 if self.doctype == "Stock Entry":
386 if d.get("s_warehouse"):
387 warehouses.add(d.s_warehouse)
388 if d.get("t_warehouse"):
389 warehouses.add(d.t_warehouse)
390
391 return list(items), list(warehouses)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530392
Nabin Hait2e296fa2013-08-28 18:53:11 +0530393 def get_stock_ledger_details(self):
394 stock_ledger = {}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530395 stock_ledger_entries = frappe.db.sql(
396 """
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530397 select
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530398 name, warehouse, stock_value_difference, valuation_rate,
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530399 voucher_detail_no, item_code, posting_date, posting_time,
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530400 actual_qty, qty_after_transaction
Nabin Haitea8fab52017-02-06 17:13:39 +0530401 from
402 `tabStock Ledger Entry`
403 where
Ankush Menat0ca60af2022-02-08 10:24:19 +0530404 voucher_type=%s and voucher_no=%s and is_cancelled = 0
Ankush Menat494bd9e2022-03-28 18:52:46 +0530405 """,
406 (self.doctype, self.name),
407 as_dict=True,
408 )
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530409
Nabin Haitea8fab52017-02-06 17:13:39 +0530410 for sle in stock_ledger_entries:
Deepesh Gargb4be2922021-01-28 13:09:56 +0530411 stock_ledger.setdefault(sle.voucher_detail_no, []).append(sle)
Nabin Hait2e296fa2013-08-28 18:53:11 +0530412 return stock_ledger
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530413
Nabin Hait27994c22013-08-26 16:53:30 +0530414 def check_expense_account(self, item):
Rushabh Mehta052fe822014-04-16 19:20:11 +0530415 if not item.get("expense_account"):
Rohit Waghchaureceab6922020-11-18 17:57:35 +0530416 msg = _("Please set an Expense Account in the Items table")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530417 frappe.throw(
418 _("Row #{0}: Expense Account not set for the Item {1}. {2}").format(
419 item.idx, frappe.bold(item.item_code), msg
420 ),
421 title=_("Expense Account Missing"),
422 )
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530423
Anand Doshi496123a2014-06-19 19:25:19 +0530424 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530425 is_expense_account = (
426 frappe.get_cached_value("Account", item.get("expense_account"), "report_type")
427 == "Profit and Loss"
428 )
429 if (
430 self.doctype
Sagar Sharma2d04e712022-08-17 15:57:41 +0530431 not in (
432 "Purchase Receipt",
433 "Purchase Invoice",
434 "Stock Reconciliation",
435 "Stock Entry",
436 "Subcontracting Receipt",
437 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530438 and not is_expense_account
439 ):
440 frappe.throw(
441 _("Expense / Difference account ({0}) must be a 'Profit or Loss' account").format(
442 item.get("expense_account")
443 )
444 )
Anand Doshi496123a2014-06-19 19:25:19 +0530445 if is_expense_account and not item.get("cost_center"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530446 frappe.throw(
447 _("{0} {1}: Cost Center is mandatory for Item {2}").format(
448 _(self.doctype), self.name, item.get("item_code")
449 )
450 )
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530451
Rohit Waghchaure8996b7d2020-01-23 17:36:52 +0530452 def delete_auto_created_batches(self):
Rohit Waghchaurebc75a7e2022-10-10 13:28:19 +0530453 for row in self.items:
454 if row.serial_and_batch_bundle:
455 frappe.db.set_value(
456 "Serial and Batch Bundle", row.serial_and_batch_bundle, {"is_cancelled": 1}
457 )
Rohit Waghchaure8996b7d2020-01-23 17:36:52 +0530458
Rohit Waghchaurebc75a7e2022-10-10 13:28:19 +0530459 row.db_set("serial_and_batch_bundle", None)
Saqibe9ac3e02020-03-02 15:02:58 +0530460
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530461 def set_serial_and_batch_bundle(self, table_name=None, ignore_validate=False):
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530462 if not table_name:
463 table_name = "items"
Rohit Waghchaure8996b7d2020-01-23 17:36:52 +0530464
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530465 QTY_FIELD = {
466 "serial_and_batch_bundle": "qty",
467 "current_serial_and_batch_bundle": "current_qty",
468 "rejected_serial_and_batch_bundle": "rejected_qty",
469 }
470
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530471 for row in self.get(table_name):
s-aga-rc20241f2024-01-12 15:26:35 +0530472 for field in QTY_FIELD.keys():
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530473 if row.get(field):
474 frappe.get_doc("Serial and Batch Bundle", row.get(field)).set_serial_and_batch_values(
475 self, row, qty_field=QTY_FIELD[field]
476 )
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530477
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530478 def make_package_for_transfer(
479 self, serial_and_batch_bundle, warehouse, type_of_transaction=None, do_not_submit=None
480 ):
481 bundle_doc = frappe.get_doc("Serial and Batch Bundle", serial_and_batch_bundle)
482
483 if not type_of_transaction:
484 type_of_transaction = "Inward"
485
486 bundle_doc = frappe.copy_doc(bundle_doc)
487 bundle_doc.warehouse = warehouse
488 bundle_doc.type_of_transaction = type_of_transaction
489 bundle_doc.voucher_type = self.doctype
490 bundle_doc.voucher_no = self.name
491 bundle_doc.is_cancelled = 0
492
Rohit Waghchaure5bb31732023-03-21 10:54:41 +0530493 for row in bundle_doc.entries:
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530494 row.is_outward = 0
495 row.qty = abs(row.qty)
496 row.stock_value_difference = abs(row.stock_value_difference)
497 if type_of_transaction == "Outward":
498 row.qty *= -1
499 row.stock_value_difference *= row.stock_value_difference
500 row.is_outward = 1
501
502 row.warehouse = warehouse
503
Rohit Waghchaure5bb31732023-03-21 10:54:41 +0530504 bundle_doc.calculate_qty_and_amount()
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530505 bundle_doc.flags.ignore_permissions = True
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530506 bundle_doc.save(ignore_permissions=True)
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530507
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530508 return bundle_doc.name
Rohit Waghchaure4f4dbf12020-01-23 12:42:42 +0530509
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530510 def get_sl_entries(self, d, args):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530511 sl_dict = frappe._dict(
512 {
513 "item_code": d.get("item_code", None),
514 "warehouse": d.get("warehouse", None),
Rohit Waghchaurebc75a7e2022-10-10 13:28:19 +0530515 "serial_and_batch_bundle": d.get("serial_and_batch_bundle"),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530516 "posting_date": self.posting_date,
517 "posting_time": self.posting_time,
518 "fiscal_year": get_fiscal_year(self.posting_date, company=self.company)[0],
519 "voucher_type": self.doctype,
520 "voucher_no": self.name,
521 "voucher_detail_no": d.name,
522 "actual_qty": (self.docstatus == 1 and 1 or -1) * flt(d.get("stock_qty")),
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +0530523 "stock_uom": frappe.get_cached_value(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530524 "Item", args.get("item_code") or d.get("item_code"), "stock_uom"
525 ),
526 "incoming_rate": 0,
527 "company": self.company,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530528 "project": d.get("project") or self.get("project"),
529 "is_cancelled": 1 if self.docstatus == 2 else 0,
530 }
531 )
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530532
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530533 sl_dict.update(args)
Rohit Waghchauree576f7f2022-06-30 19:12:06 +0530534 self.update_inventory_dimensions(d, sl_dict)
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530535
rohitwaghchaure07432892023-12-17 12:42:07 +0530536 if self.docstatus == 2:
537 # To handle denormalized serial no records, will br deprecated in v16
538 for field in ["serial_no", "batch_no"]:
539 if d.get(field):
540 sl_dict[field] = d.get(field)
541
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530542 return sl_dict
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530543
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530544 def update_inventory_dimensions(self, row, sl_dict) -> None:
Rohit Waghchaure23729992022-09-02 18:43:55 +0530545 # To handle delivery note and sales invoice
546 if row.get("item_row"):
547 row = row.get("item_row")
548
Rohit Waghchaure289e6cd2022-07-15 15:43:38 +0530549 dimensions = get_evaluated_inventory_dimension(row, sl_dict, parent_doc=self)
550 for dimension in dimensions:
Rohit Waghchaure0b39a012022-08-17 11:56:13 +0530551 if not dimension:
552 continue
553
Rohit Waghchaure6798b902023-05-09 16:07:14 +0530554 if self.doctype in [
555 "Purchase Invoice",
556 "Purchase Receipt",
557 "Sales Invoice",
558 "Delivery Note",
559 "Stock Entry",
560 ]:
Rohit Waghchaure38aaba52023-05-13 13:00:05 +0530561 if (
562 (
563 sl_dict.actual_qty > 0
564 and not self.get("is_return")
565 or sl_dict.actual_qty < 0
566 and self.get("is_return")
567 )
568 and self.doctype in ["Purchase Invoice", "Purchase Receipt"]
569 ) or (
570 (
571 sl_dict.actual_qty < 0
572 and not self.get("is_return")
573 or sl_dict.actual_qty > 0
574 and self.get("is_return")
575 )
576 and self.doctype in ["Sales Invoice", "Delivery Note", "Stock Entry"]
Rohit Waghchaure6798b902023-05-09 16:07:14 +0530577 ):
578 sl_dict[dimension.target_fieldname] = row.get(dimension.source_fieldname)
579 else:
580 fieldname_start_with = "to"
581 if self.doctype in ["Purchase Invoice", "Purchase Receipt"]:
582 fieldname_start_with = "from"
583
584 fieldname = f"{fieldname_start_with}_{dimension.source_fieldname}"
585 sl_dict[dimension.target_fieldname] = row.get(fieldname)
586
587 if not sl_dict.get(dimension.target_fieldname):
588 sl_dict[dimension.target_fieldname] = row.get(dimension.source_fieldname)
589
590 elif row.get(dimension.source_fieldname):
Rohit Waghchaure289e6cd2022-07-15 15:43:38 +0530591 sl_dict[dimension.target_fieldname] = row.get(dimension.source_fieldname)
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530592
Rohit Waghchaure0b39a012022-08-17 11:56:13 +0530593 if not sl_dict.get(dimension.target_fieldname) and dimension.fetch_from_parent:
594 sl_dict[dimension.target_fieldname] = self.get(dimension.fetch_from_parent)
595
596 # Get value based on doctype name
597 if not sl_dict.get(dimension.target_fieldname):
Daizy Modi4efc9472022-11-07 09:21:03 +0530598 fieldname = next(
599 (
600 field.fieldname
601 for field in frappe.get_meta(self.doctype).fields
602 if field.options == dimension.fetch_from_parent
603 ),
604 None,
Rohit Waghchaure0b39a012022-08-17 11:56:13 +0530605 )
606
607 if fieldname and self.get(fieldname):
608 sl_dict[dimension.target_fieldname] = self.get(fieldname)
609
Rohit Waghchaure75fcab02022-09-03 17:09:24 +0530610 if sl_dict[dimension.target_fieldname] and self.docstatus == 1:
611 row.db_set(dimension.source_fieldname, sl_dict[dimension.target_fieldname])
Rohit Waghchaure23729992022-09-02 18:43:55 +0530612
Ankush Menat494bd9e2022-03-28 18:52:46 +0530613 def make_sl_entries(self, sl_entries, allow_negative_stock=False, via_landed_cost_voucher=False):
Rushabh Mehta1f847992013-12-12 19:12:19 +0530614 from erpnext.stock.stock_ledger import make_sl_entries
Ankush Menat494bd9e2022-03-28 18:52:46 +0530615
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530616 make_sl_entries(sl_entries, allow_negative_stock, via_landed_cost_voucher)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530617
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530618 def make_gl_entries_on_cancel(self):
ruthra kumar46ea8142023-07-28 08:29:19 +0530619 cancel_exchange_gain_loss_journal(frappe._dict(doctype=self.doctype, name=self.name))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530620 if frappe.db.sql(
621 """select name from `tabGL Entry` where voucher_type=%s
622 and voucher_no=%s""",
623 (self.doctype, self.name),
624 ):
625 self.make_gl_entries()
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530626
Anand Doshia740f752014-06-25 13:31:02 +0530627 def get_serialized_items(self):
628 serialized_items = []
Ankush Menata9c84f72021-06-11 16:00:48 +0530629 item_codes = list(set(d.item_code for d in self.get("items")))
Anand Doshia740f752014-06-25 13:31:02 +0530630 if item_codes:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530631 serialized_items = frappe.db.sql_list(
632 """select name from `tabItem`
633 where has_serial_no=1 and name in ({})""".format(
634 ", ".join(["%s"] * len(item_codes))
635 ),
636 tuple(item_codes),
637 )
Anand Doshia740f752014-06-25 13:31:02 +0530638
639 return serialized_items
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +0530640
Saurabh2e292062015-11-18 17:03:33 +0530641 def validate_warehouse(self):
Rohan Bansal7f8b95e2021-04-14 14:12:03 +0530642 from erpnext.stock.utils import validate_disabled_warehouse, validate_warehouse_company
Saurabh2e292062015-11-18 17:03:33 +0530643
Ankush Menat494bd9e2022-03-28 18:52:46 +0530644 warehouses = list(set(d.warehouse for d in self.get("items") if getattr(d, "warehouse", None)))
Saurabh2e292062015-11-18 17:03:33 +0530645
Ankush Menat494bd9e2022-03-28 18:52:46 +0530646 target_warehouses = list(
647 set([d.target_warehouse for d in self.get("items") if getattr(d, "target_warehouse", None)])
648 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530649
650 warehouses.extend(target_warehouses)
651
Ankush Menat494bd9e2022-03-28 18:52:46 +0530652 from_warehouse = list(
653 set([d.from_warehouse for d in self.get("items") if getattr(d, "from_warehouse", None)])
654 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530655
656 warehouses.extend(from_warehouse)
657
Saurabh2e292062015-11-18 17:03:33 +0530658 for w in warehouses:
Jannat Patel30c88732021-02-11 11:46:48 +0530659 validate_disabled_warehouse(w)
Saurabh2e292062015-11-18 17:03:33 +0530660 validate_warehouse_company(w, self.company)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530661
Anand Doshi6b71ef52016-01-06 16:32:06 +0530662 def update_billing_percentage(self, update_modified=True):
marinationd6596a12020-11-02 15:07:48 +0530663 target_ref_field = "amount"
664 if self.doctype == "Delivery Note":
665 target_ref_field = "amount - (returned_qty * rate)"
666
Ankush Menat494bd9e2022-03-28 18:52:46 +0530667 self._update_percent_field(
668 {
669 "target_dt": self.doctype + " Item",
670 "target_parent_dt": self.doctype,
671 "target_parent_field": "per_billed",
672 "target_ref_field": target_ref_field,
673 "target_field": "billed_amt",
674 "name": self.name,
675 },
676 update_modified,
677 )
Anand Doshia740f752014-06-25 13:31:02 +0530678
Nabin Hait8af429d2016-11-16 17:21:59 +0530679 def validate_inspection(self):
marination9ac9a4e2021-06-21 16:18:35 +0530680 """Checks if quality inspection is set/ is valid for Items that require inspection."""
681 inspection_fieldname_map = {
682 "Purchase Receipt": "inspection_required_before_purchase",
683 "Purchase Invoice": "inspection_required_before_purchase",
s-aga-r3fdcd332023-08-23 12:15:35 +0530684 "Subcontracting Receipt": "inspection_required_before_purchase",
marination9ac9a4e2021-06-21 16:18:35 +0530685 "Sales Invoice": "inspection_required_before_delivery",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530686 "Delivery Note": "inspection_required_before_delivery",
marination9ac9a4e2021-06-21 16:18:35 +0530687 }
688 inspection_required_fieldname = inspection_fieldname_map.get(self.doctype)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530689
marination9ac9a4e2021-06-21 16:18:35 +0530690 # return if inspection is not required on document level
Ankush Menat494bd9e2022-03-28 18:52:46 +0530691 if (
692 (not inspection_required_fieldname and self.doctype != "Stock Entry")
693 or (self.doctype == "Stock Entry" and not self.inspection_required)
694 or (self.doctype in ["Sales Invoice", "Purchase Invoice"] and not self.update_stock)
695 ):
696 return
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530697
Ankush Menat494bd9e2022-03-28 18:52:46 +0530698 for row in self.get("items"):
marination9ac9a4e2021-06-21 16:18:35 +0530699 qi_required = False
Ankush Menat494bd9e2022-03-28 18:52:46 +0530700 if inspection_required_fieldname and frappe.db.get_value(
701 "Item", row.item_code, inspection_required_fieldname
702 ):
marination9ac9a4e2021-06-21 16:18:35 +0530703 qi_required = True
704 elif self.doctype == "Stock Entry" and row.t_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530705 qi_required = True # inward stock needs inspection
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530706
Ankush Menat494bd9e2022-03-28 18:52:46 +0530707 if qi_required: # validate row only if inspection is required on item level
marination9ac9a4e2021-06-21 16:18:35 +0530708 self.validate_qi_presence(row)
709 if self.docstatus == 1:
710 self.validate_qi_submission(row)
711 self.validate_qi_rejection(row)
712
713 def validate_qi_presence(self, row):
714 """Check if QI is present on row level. Warn on save and stop on submit if missing."""
715 if not row.quality_inspection:
marination654e9d82021-06-21 16:51:12 +0530716 msg = f"Row #{row.idx}: Quality Inspection is required for Item {frappe.bold(row.item_code)}"
marination9ac9a4e2021-06-21 16:18:35 +0530717 if self.docstatus == 1:
marination654e9d82021-06-21 16:51:12 +0530718 frappe.throw(_(msg), title=_("Inspection Required"), exc=QualityInspectionRequiredError)
marination9ac9a4e2021-06-21 16:18:35 +0530719 else:
marination654e9d82021-06-21 16:51:12 +0530720 frappe.msgprint(_(msg), title=_("Inspection Required"), indicator="blue")
marination9ac9a4e2021-06-21 16:18:35 +0530721
722 def validate_qi_submission(self, row):
723 """Check if QI is submitted on row level, during submission"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530724 action = frappe.db.get_single_value(
725 "Stock Settings", "action_if_quality_inspection_is_not_submitted"
726 )
marination9ac9a4e2021-06-21 16:18:35 +0530727 qa_docstatus = frappe.db.get_value("Quality Inspection", row.quality_inspection, "docstatus")
728
barredterraeb9ee3f2023-12-05 11:22:55 +0100729 if qa_docstatus != 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530730 link = frappe.utils.get_link_to_form("Quality Inspection", row.quality_inspection)
731 msg = (
732 f"Row #{row.idx}: Quality Inspection {link} is not submitted for the item: {row.item_code}"
733 )
marination9ac9a4e2021-06-21 16:18:35 +0530734 if action == "Stop":
marination654e9d82021-06-21 16:51:12 +0530735 frappe.throw(_(msg), title=_("Inspection Submission"), exc=QualityInspectionNotSubmittedError)
marination9ac9a4e2021-06-21 16:18:35 +0530736 else:
Marica9ba3fce2021-06-22 11:20:17 +0530737 frappe.msgprint(_(msg), alert=True, indicator="orange")
marination9ac9a4e2021-06-21 16:18:35 +0530738
739 def validate_qi_rejection(self, row):
740 """Check if QI is rejected on row level, during submission"""
marinationf67f13c2021-07-10 18:24:24 +0530741 action = frappe.db.get_single_value("Stock Settings", "action_if_quality_inspection_is_rejected")
marination9ac9a4e2021-06-21 16:18:35 +0530742 qa_status = frappe.db.get_value("Quality Inspection", row.quality_inspection, "status")
743
744 if qa_status == "Rejected":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530745 link = frappe.utils.get_link_to_form("Quality Inspection", row.quality_inspection)
marination654e9d82021-06-21 16:51:12 +0530746 msg = f"Row #{row.idx}: Quality Inspection {link} was rejected for item {row.item_code}"
marination9ac9a4e2021-06-21 16:18:35 +0530747 if action == "Stop":
marination654e9d82021-06-21 16:51:12 +0530748 frappe.throw(_(msg), title=_("Inspection Rejected"), exc=QualityInspectionRejectedError)
marination9ac9a4e2021-06-21 16:18:35 +0530749 else:
marination654e9d82021-06-21 16:51:12 +0530750 frappe.msgprint(_(msg), alert=True, indicator="orange")
Manas Solankicc902412016-11-10 19:15:11 +0530751
Nabin Haitb2d3c0f2018-06-14 15:54:34 +0530752 def update_blanket_order(self):
Nabin Haitd1f40ad2018-06-14 17:09:55 +0530753 blanket_orders = list(set([d.blanket_order for d in self.items if d.blanket_order]))
Nabin Haitb2d3c0f2018-06-14 15:54:34 +0530754 for blanket_order in blanket_orders:
755 frappe.get_doc("Blanket Order", blanket_order).update_ordered_qty()
Manas Solankie5e87f72018-05-28 20:07:08 +0530756
marinationfd04e962020-04-03 15:46:48 +0530757 def validate_customer_provided_item(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530758 for d in self.get("items"):
marinationfd04e962020-04-03 15:46:48 +0530759 # Customer Provided parts will have zero valuation rate
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +0530760 if frappe.get_cached_value("Item", d.item_code, "is_customer_provided_item"):
marinationfd04e962020-04-03 15:46:48 +0530761 d.allow_zero_valuation_rate = 1
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530762
Anupam Kumar7e1dcf92021-02-11 20:19:30 +0530763 def set_rate_of_stock_uom(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530764 if self.doctype in [
765 "Purchase Receipt",
766 "Purchase Invoice",
767 "Purchase Order",
768 "Sales Invoice",
769 "Sales Order",
770 "Delivery Note",
771 "Quotation",
772 ]:
Anupam Kumar7e1dcf92021-02-11 20:19:30 +0530773 for d in self.get("items"):
Rohit Waghchaure13584432021-03-26 14:11:50 +0530774 d.stock_uom_rate = d.rate / (d.conversion_factor or 1)
Anupam Kumar7e1dcf92021-02-11 20:19:30 +0530775
Deepesh Gargb4be2922021-01-28 13:09:56 +0530776 def validate_internal_transfer(self):
rohitwaghchaure5136fe12023-10-22 20:03:02 +0530777 if self.doctype in ("Sales Invoice", "Delivery Note", "Purchase Invoice", "Purchase Receipt"):
778 if self.is_internal_transfer():
779 self.validate_in_transit_warehouses()
780 self.validate_multi_currency()
781 self.validate_packed_items()
rohitwaghchaure8fdc2442024-01-27 21:37:58 +0530782
783 if self.get("is_internal_supplier"):
784 self.validate_internal_transfer_qty()
rohitwaghchaure5136fe12023-10-22 20:03:02 +0530785 else:
786 self.validate_internal_transfer_warehouse()
787
788 def validate_internal_transfer_warehouse(self):
789 for row in self.items:
790 if row.get("target_warehouse"):
791 row.target_warehouse = None
792
793 if row.get("from_warehouse"):
794 row.from_warehouse = None
Deepesh Gargb4be2922021-01-28 13:09:56 +0530795
796 def validate_in_transit_warehouses(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530797 if (
798 self.doctype == "Sales Invoice" and self.get("update_stock")
799 ) or self.doctype == "Delivery Note":
800 for item in self.get("items"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530801 if not item.target_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530802 frappe.throw(
803 _("Row {0}: Target Warehouse is mandatory for internal transfers").format(item.idx)
804 )
Deepesh Gargb4be2922021-01-28 13:09:56 +0530805
Ankush Menat494bd9e2022-03-28 18:52:46 +0530806 if (
807 self.doctype == "Purchase Invoice" and self.get("update_stock")
808 ) or self.doctype == "Purchase Receipt":
809 for item in self.get("items"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530810 if not item.from_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530811 frappe.throw(
812 _("Row {0}: From Warehouse is mandatory for internal transfers").format(item.idx)
813 )
Deepesh Gargb4be2922021-01-28 13:09:56 +0530814
815 def validate_multi_currency(self):
816 if self.currency != self.company_currency:
817 frappe.throw(_("Internal transfers can only be done in company's default currency"))
818
819 def validate_packed_items(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530820 if self.doctype in ("Sales Invoice", "Delivery Note Item") and self.get("packed_items"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530821 frappe.throw(_("Packed Items cannot be transferred internally"))
822
rohitwaghchaure8fdc2442024-01-27 21:37:58 +0530823 def validate_internal_transfer_qty(self):
824 if self.doctype not in ["Purchase Invoice", "Purchase Receipt"]:
825 return
826
827 item_wise_transfer_qty = self.get_item_wise_inter_transfer_qty()
828 if not item_wise_transfer_qty:
829 return
830
831 item_wise_received_qty = self.get_item_wise_inter_received_qty()
832 precision = frappe.get_precision(self.doctype + " Item", "qty")
833
834 over_receipt_allowance = frappe.db.get_single_value(
835 "Stock Settings", "over_delivery_receipt_allowance"
836 )
837
838 parent_doctype = {
839 "Purchase Receipt": "Delivery Note",
840 "Purchase Invoice": "Sales Invoice",
841 }.get(self.doctype)
842
843 for key, transferred_qty in item_wise_transfer_qty.items():
844 recevied_qty = flt(item_wise_received_qty.get(key), precision)
845 if over_receipt_allowance:
846 transferred_qty = transferred_qty + flt(
847 transferred_qty * over_receipt_allowance / 100, precision
848 )
849
850 if recevied_qty > flt(transferred_qty, precision):
851 frappe.throw(
852 _("For Item {0} cannot be received more than {1} qty against the {2} {3}").format(
853 bold(key[1]),
854 bold(flt(transferred_qty, precision)),
855 bold(parent_doctype),
856 get_link_to_form(parent_doctype, self.get("inter_company_reference")),
857 )
858 )
859
860 def get_item_wise_inter_transfer_qty(self):
861 reference_field = "inter_company_reference"
862 if self.doctype == "Purchase Invoice":
863 reference_field = "inter_company_invoice_reference"
864
865 parent_doctype = {
866 "Purchase Receipt": "Delivery Note",
867 "Purchase Invoice": "Sales Invoice",
868 }.get(self.doctype)
869
870 child_doctype = parent_doctype + " Item"
871
872 parent_tab = frappe.qb.DocType(parent_doctype)
873 child_tab = frappe.qb.DocType(child_doctype)
874
875 query = (
876 frappe.qb.from_(parent_doctype)
877 .inner_join(child_tab)
878 .on(child_tab.parent == parent_tab.name)
879 .select(
880 child_tab.name,
881 child_tab.item_code,
882 child_tab.qty,
883 )
884 .where((parent_tab.name == self.get(reference_field)) & (parent_tab.docstatus == 1))
885 )
886
887 data = query.run(as_dict=True)
888 item_wise_transfer_qty = defaultdict(float)
889 for row in data:
890 item_wise_transfer_qty[(row.name, row.item_code)] += flt(row.qty)
891
892 return item_wise_transfer_qty
893
894 def get_item_wise_inter_received_qty(self):
895 child_doctype = self.doctype + " Item"
896
897 parent_tab = frappe.qb.DocType(self.doctype)
898 child_tab = frappe.qb.DocType(child_doctype)
899
900 query = (
901 frappe.qb.from_(self.doctype)
902 .inner_join(child_tab)
903 .on(child_tab.parent == parent_tab.name)
904 .select(
905 child_tab.item_code,
906 child_tab.qty,
907 )
908 .where(parent_tab.docstatus < 2)
909 )
910
911 if self.doctype == "Purchase Invoice":
912 query = query.select(
913 child_tab.sales_invoice_item.as_("name"),
914 )
915
916 query = query.where(
917 parent_tab.inter_company_invoice_reference == self.inter_company_invoice_reference
918 )
919 else:
920 query = query.select(
921 child_tab.delivery_note_item.as_("name"),
922 )
923
924 query = query.where(parent_tab.inter_company_reference == self.inter_company_reference)
925
926 data = query.run(as_dict=True)
927 item_wise_transfer_qty = defaultdict(float)
928 for row in data:
929 item_wise_transfer_qty[(row.name, row.item_code)] += flt(row.qty)
930
931 return item_wise_transfer_qty
932
marinationfac40352020-12-07 21:35:49 +0530933 def validate_putaway_capacity(self):
934 # if over receipt is attempted while 'apply putaway rule' is disabled
935 # and if rule was applied on the transaction, validate it.
marination957615b2021-01-18 23:47:24 +0530936 from erpnext.stock.doctype.putaway_rule.putaway_rule import get_available_putaway_capacity
Ankush Menat494bd9e2022-03-28 18:52:46 +0530937
938 valid_doctype = self.doctype in (
939 "Purchase Receipt",
940 "Stock Entry",
941 "Purchase Invoice",
942 "Stock Reconciliation",
943 )
marinationfac40352020-12-07 21:35:49 +0530944
rohitwaghchaureb966c062024-02-12 12:49:09 +0530945 if not frappe.get_all("Putaway Rule", limit=1):
946 return
947
marination957615b2021-01-18 23:47:24 +0530948 if self.doctype == "Purchase Invoice" and self.get("update_stock") == 0:
949 valid_doctype = False
950
951 if valid_doctype:
marinationfac40352020-12-07 21:35:49 +0530952 rule_map = defaultdict(dict)
953 for item in self.get("items"):
marination957615b2021-01-18 23:47:24 +0530954 warehouse_field = "t_warehouse" if self.doctype == "Stock Entry" else "warehouse"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530955 rule = frappe.db.get_value(
956 "Putaway Rule",
957 {"item_code": item.get("item_code"), "warehouse": item.get(warehouse_field)},
958 ["name", "disable"],
959 as_dict=True,
960 )
marination957615b2021-01-18 23:47:24 +0530961 if rule:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530962 if rule.get("disabled"):
963 continue # dont validate for disabled rule
marination957615b2021-01-18 23:47:24 +0530964
965 if self.doctype == "Stock Reconciliation":
966 stock_qty = flt(item.qty)
967 else:
968 stock_qty = flt(item.transfer_qty) if self.doctype == "Stock Entry" else flt(item.stock_qty)
969
970 rule_name = rule.get("name")
971 if not rule_map[rule_name]:
972 rule_map[rule_name]["warehouse"] = item.get(warehouse_field)
973 rule_map[rule_name]["item"] = item.get("item_code")
974 rule_map[rule_name]["qty_put"] = 0
975 rule_map[rule_name]["capacity"] = get_available_putaway_capacity(rule_name)
976 rule_map[rule_name]["qty_put"] += flt(stock_qty)
marinationfac40352020-12-07 21:35:49 +0530977
978 for rule, values in rule_map.items():
979 if flt(values["qty_put"]) > flt(values["capacity"]):
marination957615b2021-01-18 23:47:24 +0530980 message = self.prepare_over_receipt_message(rule, values)
marinationfac40352020-12-07 21:35:49 +0530981 frappe.throw(msg=message, title=_("Over Receipt"))
marination957615b2021-01-18 23:47:24 +0530982
983 def prepare_over_receipt_message(self, rule, values):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530984 message = _(
985 "{0} qty of Item {1} is being received into Warehouse {2} with capacity {3}."
986 ).format(
987 frappe.bold(values["qty_put"]),
988 frappe.bold(values["item"]),
989 frappe.bold(values["warehouse"]),
990 frappe.bold(values["capacity"]),
991 )
marination957615b2021-01-18 23:47:24 +0530992 message += "<br><br>"
993 rule_link = frappe.utils.get_link_to_form("Putaway Rule", rule)
Ankush Menatad6a2652021-04-17 16:50:02 +0530994 message += _("Please adjust the qty or edit {0} to proceed.").format(rule_link)
marination957615b2021-01-18 23:47:24 +0530995 return message
marinationfac40352020-12-07 21:35:49 +0530996
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +0530997 def repost_future_sle_and_gle(self, force=False):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530998 args = frappe._dict(
999 {
1000 "posting_date": self.posting_date,
1001 "posting_time": self.posting_time,
1002 "voucher_type": self.doctype,
1003 "voucher_no": self.name,
1004 "company": self.company,
1005 }
1006 )
Ankush Menat3638fbf2022-03-01 18:17:14 +05301007
Rohit Waghchaure6e661e72023-05-16 16:23:52 +05301008 if self.docstatus == 2:
1009 force = True
1010
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +05301011 if force or future_sle_exists(args) or repost_required_for_queue(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301012 item_based_reposting = cint(
1013 frappe.db.get_single_value("Stock Reposting Settings", "item_based_reposting")
1014 )
Ankush Menat45dd46b2021-11-02 10:50:52 +05301015 if item_based_reposting:
1016 create_item_wise_repost_entries(voucher_type=self.doctype, voucher_no=self.name)
1017 else:
1018 create_repost_item_valuation_entry(args)
1019
Sagar Sharmaf4673942022-08-21 21:26:06 +05301020 def add_gl_entry(
1021 self,
1022 gl_entries,
1023 account,
1024 cost_center,
1025 debit,
1026 credit,
1027 remarks,
1028 against_account,
1029 debit_in_account_currency=None,
1030 credit_in_account_currency=None,
1031 account_currency=None,
1032 project=None,
1033 voucher_detail_no=None,
1034 item=None,
1035 posting_date=None,
1036 ):
1037
1038 gl_entry = {
1039 "account": account,
1040 "cost_center": cost_center,
1041 "debit": debit,
1042 "credit": credit,
1043 "against": against_account,
1044 "remarks": remarks,
1045 }
1046
1047 if voucher_detail_no:
1048 gl_entry.update({"voucher_detail_no": voucher_detail_no})
1049
1050 if debit_in_account_currency:
1051 gl_entry.update({"debit_in_account_currency": debit_in_account_currency})
1052
1053 if credit_in_account_currency:
1054 gl_entry.update({"credit_in_account_currency": credit_in_account_currency})
1055
1056 if posting_date:
1057 gl_entry.update({"posting_date": posting_date})
1058
1059 gl_entries.append(self.get_gl_dict(gl_entry, item=item))
1060
Ankush Menat494bd9e2022-03-28 18:52:46 +05301061
Deepesh Garg2e52a632023-06-04 19:20:28 +05301062@frappe.whitelist()
Deepesh Garg0e68da52023-06-22 15:43:32 +05301063def show_accounting_ledger_preview(company, doctype, docname):
Smit Vora77cc91d2023-10-19 22:35:55 +05301064 filters = frappe._dict(company=company, include_dimensions=1)
Deepesh Garg0e68da52023-06-22 15:43:32 +05301065 doc = frappe.get_doc(doctype, docname)
Smit Vora77cc91d2023-10-19 22:35:55 +05301066 doc.run_method("before_gl_preview")
Deepesh Garg0e68da52023-06-22 15:43:32 +05301067
1068 gl_columns, gl_data = get_accounting_ledger_preview(doc, filters)
1069
Deepesh Gargd9e7bc52023-06-22 16:07:32 +05301070 frappe.db.rollback()
Deepesh Garg0e68da52023-06-22 15:43:32 +05301071
1072 return {"gl_columns": gl_columns, "gl_data": gl_data}
1073
1074
1075@frappe.whitelist()
1076def show_stock_ledger_preview(company, doctype, docname):
Smit Vora77cc91d2023-10-19 22:35:55 +05301077 filters = frappe._dict(company=company)
Deepesh Garg2e52a632023-06-04 19:20:28 +05301078 doc = frappe.get_doc(doctype, docname)
Smit Vora77cc91d2023-10-19 22:35:55 +05301079 doc.run_method("before_sl_preview")
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301080
Deepesh Garg011ac132023-06-12 18:42:49 +05301081 sl_columns, sl_data = get_stock_ledger_preview(doc, filters)
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301082
Deepesh Gargd9e7bc52023-06-22 16:07:32 +05301083 frappe.db.rollback()
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301084
Deepesh Garg2e52a632023-06-04 19:20:28 +05301085 return {
Deepesh Garg011ac132023-06-12 18:42:49 +05301086 "sl_columns": sl_columns,
1087 "sl_data": sl_data,
Deepesh Garg2e52a632023-06-04 19:20:28 +05301088 }
1089
1090
Deepesh Garg011ac132023-06-12 18:42:49 +05301091def get_accounting_ledger_preview(doc, filters):
1092 from erpnext.accounts.report.general_ledger.general_ledger import get_columns as get_gl_columns
1093
1094 gl_columns, gl_data = [], []
1095 fields = [
1096 "posting_date",
1097 "account",
1098 "debit",
1099 "credit",
1100 "against",
1101 "party",
1102 "party_type",
Deepesh Garg0e68da52023-06-22 15:43:32 +05301103 "cost_center",
Deepesh Garg011ac132023-06-12 18:42:49 +05301104 "against_voucher_type",
1105 "against_voucher",
1106 ]
1107
1108 doc.docstatus = 1
Deepesh Garg0e68da52023-06-22 15:43:32 +05301109
1110 if doc.get("update_stock") or doc.doctype in ("Purchase Receipt", "Delivery Note"):
1111 doc.update_stock_ledger()
1112
Deepesh Garg011ac132023-06-12 18:42:49 +05301113 doc.make_gl_entries()
1114 columns = get_gl_columns(filters)
1115 gl_entries = get_gl_entries_for_preview(doc.doctype, doc.name, fields)
1116
1117 gl_columns = get_columns(columns, fields)
1118 gl_data = get_data(fields, gl_entries)
1119
1120 return gl_columns, gl_data
1121
1122
1123def get_stock_ledger_preview(doc, filters):
1124 from erpnext.stock.report.stock_ledger.stock_ledger import get_columns as get_sl_columns
1125
1126 sl_columns, sl_data = [], []
1127 fields = [
1128 "item_code",
1129 "stock_uom",
1130 "actual_qty",
1131 "qty_after_transaction",
1132 "warehouse",
1133 "incoming_rate",
1134 "valuation_rate",
1135 "stock_value",
1136 "stock_value_difference",
1137 ]
1138 columns_fields = [
1139 "item_code",
1140 "stock_uom",
1141 "in_qty",
1142 "out_qty",
1143 "qty_after_transaction",
1144 "warehouse",
1145 "incoming_rate",
Deepesh Garg0e68da52023-06-22 15:43:32 +05301146 "in_out_rate",
Deepesh Garg011ac132023-06-12 18:42:49 +05301147 "stock_value",
1148 "stock_value_difference",
1149 ]
1150
Deepesh Garg0e68da52023-06-22 15:43:32 +05301151 if doc.get("update_stock") or doc.doctype in ("Purchase Receipt", "Delivery Note"):
Deepesh Garg011ac132023-06-12 18:42:49 +05301152 doc.docstatus = 1
1153 doc.update_stock_ledger()
1154 columns = get_sl_columns(filters)
1155 sl_entries = get_sl_entries_for_preview(doc.doctype, doc.name, fields)
1156
1157 sl_columns = get_columns(columns, columns_fields)
1158 sl_data = get_data(columns_fields, sl_entries)
1159
1160 return sl_columns, sl_data
1161
1162
1163def get_sl_entries_for_preview(doctype, docname, fields):
1164 sl_entries = frappe.get_all(
1165 "Stock Ledger Entry", filters={"voucher_type": doctype, "voucher_no": docname}, fields=fields
1166 )
1167
1168 for entry in sl_entries:
1169 if entry.actual_qty > 0:
1170 entry["in_qty"] = entry.actual_qty
1171 entry["out_qty"] = 0
1172 else:
1173 entry["out_qty"] = abs(entry.actual_qty)
1174 entry["in_qty"] = 0
1175
Deepesh Garg0e68da52023-06-22 15:43:32 +05301176 entry["in_out_rate"] = entry["valuation_rate"]
1177
Deepesh Garg011ac132023-06-12 18:42:49 +05301178 return sl_entries
1179
1180
1181def get_gl_entries_for_preview(doctype, docname, fields):
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301182 return frappe.get_all(
Deepesh Garg011ac132023-06-12 18:42:49 +05301183 "GL Entry", filters={"voucher_type": doctype, "voucher_no": docname}, fields=fields
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301184 )
1185
1186
Deepesh Garg011ac132023-06-12 18:42:49 +05301187def get_columns(raw_columns, fields):
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301188 return [
Deepesh Garg011ac132023-06-12 18:42:49 +05301189 {"name": d.get("label"), "editable": False, "width": 110}
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301190 for d in raw_columns
Deepesh Garg011ac132023-06-12 18:42:49 +05301191 if not d.get("hidden") and d.get("fieldname") in fields
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301192 ]
1193
1194
1195def get_data(raw_columns, raw_data):
1196 datatable_data = []
1197 for row in raw_data:
1198 data_row = []
1199 for column in raw_columns:
Deepesh Garg011ac132023-06-12 18:42:49 +05301200 data_row.append(row.get(column) or "")
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301201
1202 datatable_data.append(data_row)
1203
1204 return datatable_data
1205
1206
Ankush Menat3638fbf2022-03-01 18:17:14 +05301207def repost_required_for_queue(doc: StockController) -> bool:
1208 """check if stock document contains repeated item-warehouse with queue based valuation.
1209
1210 if queue exists for repeated items then SLEs need to reprocessed in background again.
1211 """
1212
Ankush Menat494bd9e2022-03-28 18:52:46 +05301213 consuming_sles = frappe.db.get_all(
1214 "Stock Ledger Entry",
Ankush Menat3638fbf2022-03-01 18:17:14 +05301215 filters={
1216 "voucher_type": doc.doctype,
1217 "voucher_no": doc.name,
1218 "actual_qty": ("<", 0),
Ankush Menat494bd9e2022-03-28 18:52:46 +05301219 "is_cancelled": 0,
Ankush Menat3638fbf2022-03-01 18:17:14 +05301220 },
Ankush Menat494bd9e2022-03-28 18:52:46 +05301221 fields=["item_code", "warehouse", "stock_queue"],
Ankush Menat3638fbf2022-03-01 18:17:14 +05301222 )
1223 item_warehouses = [(sle.item_code, sle.warehouse) for sle in consuming_sles]
1224
1225 unique_item_warehouses = set(item_warehouses)
1226
1227 if len(unique_item_warehouses) == len(item_warehouses):
1228 return False
1229
1230 for sle in consuming_sles:
1231 if sle.stock_queue != "[]": # using FIFO/LIFO valuation
1232 return True
1233 return False
1234
Nabin Hait19f8fa52021-02-22 22:27:22 +05301235
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301236@frappe.whitelist()
1237def make_quality_inspections(doctype, docname, items):
Rohan Bansala06ec032021-06-02 14:55:31 +05301238 if isinstance(items, str):
1239 items = json.loads(items)
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301240
Rohan Bansala06ec032021-06-02 14:55:31 +05301241 inspections = []
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301242 for item in items:
Rohan Bansal1cdf5a02021-05-26 14:42:15 +05301243 if flt(item.get("sample_size")) > flt(item.get("qty")):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301244 frappe.throw(
1245 _(
1246 "{item_name}'s Sample Size ({sample_size}) cannot be greater than the Accepted Quantity ({accepted_quantity})"
1247 ).format(
1248 item_name=item.get("item_name"),
1249 sample_size=item.get("sample_size"),
1250 accepted_quantity=item.get("qty"),
1251 )
1252 )
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301253
Ankush Menat494bd9e2022-03-28 18:52:46 +05301254 quality_inspection = frappe.get_doc(
1255 {
1256 "doctype": "Quality Inspection",
1257 "inspection_type": "Incoming",
1258 "inspected_by": frappe.session.user,
1259 "reference_type": doctype,
1260 "reference_name": docname,
1261 "item_code": item.get("item_code"),
1262 "description": item.get("description"),
1263 "sample_size": flt(item.get("sample_size")),
1264 "item_serial_no": item.get("serial_no").split("\n")[0] if item.get("serial_no") else None,
1265 "batch_no": item.get("batch_no"),
1266 }
1267 ).insert()
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301268 quality_inspection.save()
Rohan Bansal1cdf5a02021-05-26 14:42:15 +05301269 inspections.append(quality_inspection.name)
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301270
Rohan Bansal1cdf5a02021-05-26 14:42:15 +05301271 return inspections
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301272
Ankush Menat494bd9e2022-03-28 18:52:46 +05301273
Nabin Haitb99c77b2020-12-25 18:12:35 +05301274def is_reposting_pending():
Ankush Menat494bd9e2022-03-28 18:52:46 +05301275 return frappe.db.exists(
1276 "Repost Item Valuation", {"docstatus": 1, "status": ["in", ["Queued", "In Progress"]]}
1277 )
1278
Nabin Haitb99c77b2020-12-25 18:12:35 +05301279
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301280def future_sle_exists(args, sl_entries=None):
1281 key = (args.voucher_type, args.voucher_no)
Rohit Waghchaured9dd64b2023-04-14 13:00:12 +05301282 if not hasattr(frappe.local, "future_sle"):
1283 frappe.local.future_sle = {}
Nabin Haita77b8c92020-12-21 14:45:50 +05301284
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301285 if validate_future_sle_not_exists(args, key, sl_entries):
1286 return False
1287 elif get_cached_data(args, key):
1288 return True
1289
1290 if not sl_entries:
1291 sl_entries = get_sle_entries_against_voucher(args)
1292 if not sl_entries:
1293 return
1294
1295 or_conditions = get_conditions_to_validate_future_sle(sl_entries)
1296
Ankush Menat494bd9e2022-03-28 18:52:46 +05301297 data = frappe.db.sql(
1298 """
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301299 select item_code, warehouse, count(name) as total_row
Deepesh Garg6f107da2021-10-12 20:15:55 +05301300 from `tabStock Ledger Entry` force index (item_warehouse)
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301301 where
1302 ({})
1303 and timestamp(posting_date, posting_time)
1304 >= timestamp(%(posting_date)s, %(posting_time)s)
1305 and voucher_no != %(voucher_no)s
1306 and is_cancelled = 0
1307 GROUP BY
1308 item_code, warehouse
Ankush Menat494bd9e2022-03-28 18:52:46 +05301309 """.format(
1310 " or ".join(or_conditions)
1311 ),
1312 args,
1313 as_dict=1,
1314 )
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301315
1316 for d in data:
1317 frappe.local.future_sle[key][(d.item_code, d.warehouse)] = d.total_row
1318
1319 return len(data)
1320
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301321
Ankush Menat494bd9e2022-03-28 18:52:46 +05301322def validate_future_sle_not_exists(args, key, sl_entries=None):
1323 item_key = ""
1324 if args.get("item_code"):
1325 item_key = (args.get("item_code"), args.get("warehouse"))
1326
1327 if not sl_entries and hasattr(frappe.local, "future_sle"):
Rohit Waghchaured9dd64b2023-04-14 13:00:12 +05301328 if key not in frappe.local.future_sle:
1329 return False
1330
Ankush Menat494bd9e2022-03-28 18:52:46 +05301331 if not frappe.local.future_sle.get(key) or (
1332 item_key and item_key not in frappe.local.future_sle.get(key)
1333 ):
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301334 return True
1335
Ankush Menat494bd9e2022-03-28 18:52:46 +05301336
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301337def get_cached_data(args, key):
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301338 if key not in frappe.local.future_sle:
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +05301339 frappe.local.future_sle[key] = frappe._dict({})
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301340
Ankush Menat494bd9e2022-03-28 18:52:46 +05301341 if args.get("item_code"):
1342 item_key = (args.get("item_code"), args.get("warehouse"))
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301343 count = frappe.local.future_sle[key].get(item_key)
1344
1345 return True if (count or count == 0) else False
1346 else:
1347 return frappe.local.future_sle[key]
1348
Ankush Menat494bd9e2022-03-28 18:52:46 +05301349
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301350def get_sle_entries_against_voucher(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301351 return frappe.get_all(
1352 "Stock Ledger Entry",
Nabin Haita77b8c92020-12-21 14:45:50 +05301353 filters={"voucher_type": args.voucher_type, "voucher_no": args.voucher_no},
1354 fields=["item_code", "warehouse"],
Ankush Menat494bd9e2022-03-28 18:52:46 +05301355 order_by="creation asc",
1356 )
1357
Nabin Haita77b8c92020-12-21 14:45:50 +05301358
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301359def get_conditions_to_validate_future_sle(sl_entries):
Sagar Vora868c0bf2021-03-27 16:10:20 +05301360 warehouse_items_map = {}
1361 for entry in sl_entries:
1362 if entry.warehouse not in warehouse_items_map:
1363 warehouse_items_map[entry.warehouse] = set()
Nabin Haita77b8c92020-12-21 14:45:50 +05301364
Sagar Vora868c0bf2021-03-27 16:10:20 +05301365 warehouse_items_map[entry.warehouse].add(entry.item_code)
1366
1367 or_conditions = []
1368 for warehouse, items in warehouse_items_map.items():
1369 or_conditions.append(
Noah Jacobb5a14912021-06-15 12:44:04 +05301370 f"""warehouse = {frappe.db.escape(warehouse)}
Ankush Menat494bd9e2022-03-28 18:52:46 +05301371 and item_code in ({', '.join(frappe.db.escape(item) for item in items)})"""
1372 )
Sagar Vora868c0bf2021-03-27 16:10:20 +05301373
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301374 return or_conditions
Nabin Haita77b8c92020-12-21 14:45:50 +05301375
Ankush Menat494bd9e2022-03-28 18:52:46 +05301376
Nabin Haita77b8c92020-12-21 14:45:50 +05301377def create_repost_item_valuation_entry(args):
1378 args = frappe._dict(args)
1379 repost_entry = frappe.new_doc("Repost Item Valuation")
1380 repost_entry.based_on = args.based_on
1381 if not args.based_on:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301382 repost_entry.based_on = "Transaction" if args.voucher_no else "Item and Warehouse"
Nabin Haita77b8c92020-12-21 14:45:50 +05301383 repost_entry.voucher_type = args.voucher_type
1384 repost_entry.voucher_no = args.voucher_no
1385 repost_entry.item_code = args.item_code
1386 repost_entry.warehouse = args.warehouse
1387 repost_entry.posting_date = args.posting_date
1388 repost_entry.posting_time = args.posting_time
1389 repost_entry.company = args.company
1390 repost_entry.allow_zero_rate = args.allow_zero_rate
1391 repost_entry.flags.ignore_links = True
Ankush Menataa024fc2021-11-18 12:51:26 +05301392 repost_entry.flags.ignore_permissions = True
Nabin Haita77b8c92020-12-21 14:45:50 +05301393 repost_entry.save()
Sagar Vora868c0bf2021-03-27 16:10:20 +05301394 repost_entry.submit()
Ankush Menat6dc9b822021-10-28 15:53:18 +05301395
1396
1397def create_item_wise_repost_entries(voucher_type, voucher_no, allow_zero_rate=False):
1398 """Using a voucher create repost item valuation records for all item-warehouse pairs."""
1399
Ankush Menatd220e082021-10-28 17:47:00 +05301400 stock_ledger_entries = get_items_to_be_repost(voucher_type, voucher_no)
1401
Ankush Menat6dc9b822021-10-28 15:53:18 +05301402 distinct_item_warehouses = set()
Ankush Menat6dc9b822021-10-28 15:53:18 +05301403 repost_entries = []
1404
1405 for sle in stock_ledger_entries:
1406 item_wh = (sle.item_code, sle.warehouse)
1407 if item_wh in distinct_item_warehouses:
1408 continue
1409 distinct_item_warehouses.add(item_wh)
1410
1411 repost_entry = frappe.new_doc("Repost Item Valuation")
1412 repost_entry.based_on = "Item and Warehouse"
Ankush Menat6dc9b822021-10-28 15:53:18 +05301413
1414 repost_entry.item_code = sle.item_code
1415 repost_entry.warehouse = sle.warehouse
1416 repost_entry.posting_date = sle.posting_date
1417 repost_entry.posting_time = sle.posting_time
1418 repost_entry.allow_zero_rate = allow_zero_rate
1419 repost_entry.flags.ignore_links = True
Ankush Menat0a2964d2021-11-24 15:55:31 +05301420 repost_entry.flags.ignore_permissions = True
Ankush Menat6dc9b822021-10-28 15:53:18 +05301421 repost_entry.submit()
1422 repost_entries.append(repost_entry)
1423
1424 return repost_entries