blob: 74c835c7455a417c1d7f2611b418ae99b4f4c677 [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"
159 else:
160 qty = row.stock_qty
161 type_of_transaction = get_type_of_transaction(self, row)
162
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530163 sn_doc = SerialBatchCreation(
164 {
165 "item_code": row.item_code,
166 "warehouse": row.warehouse,
167 "posting_date": self.posting_date,
168 "posting_time": self.posting_time,
169 "voucher_type": self.doctype,
170 "voucher_no": self.name,
171 "voucher_detail_no": row.name,
Rohit Waghchaure01650122024-02-06 13:31:36 +0530172 "qty": qty,
173 "type_of_transaction": type_of_transaction,
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530174 "company": self.company,
175 "is_rejected": 1 if row.get("rejected_warehouse") else 0,
176 "serial_nos": get_serial_nos(row.serial_no) if row.serial_no else None,
Rohit Waghchaure01650122024-02-06 13:31:36 +0530177 "batches": frappe._dict({row.batch_no: qty}) if row.batch_no else None,
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530178 "batch_no": row.batch_no,
179 "use_serial_batch_fields": row.use_serial_batch_fields,
Rohit Waghchaure01650122024-02-06 13:31:36 +0530180 "do_not_submit": True,
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530181 }
182 ).make_serial_and_batch_bundle()
183
184 if sn_doc.is_rejected:
185 row.rejected_serial_and_batch_bundle = sn_doc.name
Rohit Waghchaurec1e869f2024-02-05 12:40:26 +0530186 row.db_set(
187 {
188 "rejected_serial_and_batch_bundle": sn_doc.name,
189 "rejected_serial_no": "",
190 }
191 )
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530192 else:
193 row.serial_and_batch_bundle = sn_doc.name
Rohit Waghchaurec1e869f2024-02-05 12:40:26 +0530194 row.db_set(
195 {
196 "serial_and_batch_bundle": sn_doc.name,
197 "serial_no": "",
198 "batch_no": "",
199 }
200 )
Rohit Waghchaure9fafc832024-02-04 10:42:31 +0530201
202 def set_use_serial_batch_fields(self):
203 if frappe.db.get_single_value("Stock Settings", "use_serial_batch_fields"):
204 for row in self.items:
205 row.use_serial_batch_fields = 1
206
Ankush Menat494bd9e2022-03-28 18:52:46 +0530207 def get_gl_entries(
208 self, warehouse_account=None, default_expense_account=None, default_cost_center=None
209 ):
Nabin Haitadeb9762014-10-06 11:53:52 +0530210
Nabin Hait142007a2013-09-17 15:15:16 +0530211 if not warehouse_account:
Rohit Waghchaure6b33c9b2019-03-08 11:13:35 +0530212 warehouse_account = get_warehouse_account_map(self.company)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530213
Anand Doshide1a97d2014-04-17 11:37:46 +0530214 sle_map = self.get_stock_ledger_details()
215 voucher_details = self.get_voucher_details(default_expense_account, default_cost_center, sle_map)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530216
Nabin Hait2e296fa2013-08-28 18:53:11 +0530217 gl_list = []
Nabin Hait7a75e102013-09-17 10:21:20 +0530218 warehouse_with_no_account = []
Nabin Hait19f8fa52021-02-22 22:27:22 +0530219 precision = self.get_debit_field_precision()
Nabin Hait8c61f342016-12-15 13:46:03 +0530220 for item_row in voucher_details:
221 sle_list = sle_map.get(item_row.name)
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530222 sle_rounding_diff = 0.0
Nabin Hait2e296fa2013-08-28 18:53:11 +0530223 if sle_list:
224 for sle in sle_list:
225 if warehouse_account.get(sle.warehouse):
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530226 # from warehouse account
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530227
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530228 sle_rounding_diff += flt(sle.stock_value_difference)
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530229
Nabin Hait8c61f342016-12-15 13:46:03 +0530230 self.check_expense_account(item_row)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530231
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530232 # expense account/ target_warehouse / source_warehouse
Ankush Menat494bd9e2022-03-28 18:52:46 +0530233 if item_row.get("target_warehouse"):
234 warehouse = item_row.get("target_warehouse")
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530235 expense_account = warehouse_account[warehouse]["account"]
236 else:
237 expense_account = item_row.expense_account
238
Ankush Menat494bd9e2022-03-28 18:52:46 +0530239 gl_list.append(
240 self.get_gl_dict(
241 {
242 "account": warehouse_account[sle.warehouse]["account"],
243 "against": expense_account,
244 "cost_center": item_row.cost_center,
245 "project": item_row.project or self.get("project"),
246 "remarks": self.get("remarks") or _("Accounting Entry for Stock"),
247 "debit": flt(sle.stock_value_difference, precision),
248 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
249 },
250 warehouse_account[sle.warehouse]["account_currency"],
251 item=item_row,
252 )
253 )
Nabin Hait27994c22013-08-26 16:53:30 +0530254
Ankush Menat494bd9e2022-03-28 18:52:46 +0530255 gl_list.append(
256 self.get_gl_dict(
257 {
258 "account": expense_account,
259 "against": warehouse_account[sle.warehouse]["account"],
260 "cost_center": item_row.cost_center,
261 "remarks": self.get("remarks") or _("Accounting Entry for Stock"),
Ankush Menat65b21ee2022-06-07 14:49:24 +0530262 "debit": -1 * flt(sle.stock_value_difference, precision),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530263 "project": item_row.get("project") or self.get("project"),
264 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
265 },
266 item=item_row,
267 )
268 )
Nabin Hait7a75e102013-09-17 10:21:20 +0530269 elif sle.warehouse not in warehouse_with_no_account:
270 warehouse_with_no_account.append(sle.warehouse)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530271
Deepesh Garg9aa5e202022-10-12 15:53:28 +0530272 if abs(sle_rounding_diff) > (1.0 / (10**precision)) and self.is_internal_transfer():
Deepesh Garg1c05c002022-10-12 14:19:09 +0530273 warehouse_asset_account = ""
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530274 if self.get("is_internal_customer"):
Deepesh Garg1c05c002022-10-12 14:19:09 +0530275 warehouse_asset_account = warehouse_account[item_row.get("target_warehouse")]["account"]
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530276 elif self.get("is_internal_supplier"):
Deepesh Garg1c05c002022-10-12 14:19:09 +0530277 warehouse_asset_account = warehouse_account[item_row.get("warehouse")]["account"]
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530278
Daizy Modi4efc9472022-11-07 09:21:03 +0530279 expense_account = frappe.get_cached_value("Company", self.company, "default_expense_account")
Deepesh Gargce9164e2023-07-11 12:03:38 +0530280 if not expense_account:
281 frappe.throw(
282 _(
283 "Please set default cost of goods sold account in company {0} for booking rounding gain and loss during stock transfer"
284 ).format(frappe.bold(self.company))
285 )
Deepesh Garg1c05c002022-10-12 14:19:09 +0530286
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530287 gl_list.append(
288 self.get_gl_dict(
289 {
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530290 "account": expense_account,
Deepesh Garg1c05c002022-10-12 14:19:09 +0530291 "against": warehouse_asset_account,
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530292 "cost_center": item_row.cost_center,
293 "project": item_row.project or self.get("project"),
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530294 "remarks": _("Rounding gain/loss Entry for Stock Transfer"),
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530295 "debit": sle_rounding_diff,
296 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
297 },
298 warehouse_account[sle.warehouse]["account_currency"],
299 item=item_row,
300 )
301 )
302
303 gl_list.append(
304 self.get_gl_dict(
305 {
Deepesh Garg1c05c002022-10-12 14:19:09 +0530306 "account": warehouse_asset_account,
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530307 "against": expense_account,
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530308 "cost_center": item_row.cost_center,
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530309 "remarks": _("Rounding gain/loss Entry for Stock Transfer"),
310 "credit": sle_rounding_diff,
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530311 "project": item_row.get("project") or self.get("project"),
312 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
313 },
314 item=item_row,
315 )
316 )
317
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530318 if warehouse_with_no_account:
Nabin Haitd6625022016-10-24 18:17:57 +0530319 for wh in warehouse_with_no_account:
Daizy Modi4efc9472022-11-07 09:21:03 +0530320 if frappe.get_cached_value("Warehouse", wh, "company"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530321 frappe.throw(
322 _(
323 "Warehouse {0} is not linked to any account, please mention the account in the warehouse record or set default inventory account in company {1}."
324 ).format(wh, self.company)
325 )
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530326
Nabin Hait19f8fa52021-02-22 22:27:22 +0530327 return process_gl_map(gl_list, precision=precision)
328
329 def get_debit_field_precision(self):
330 if not frappe.flags.debit_field_precision:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530331 frappe.flags.debit_field_precision = frappe.get_precision(
332 "GL Entry", "debit_in_account_currency"
333 )
Nabin Hait19f8fa52021-02-22 22:27:22 +0530334
335 return frappe.flags.debit_field_precision
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530336
Anand Doshide1a97d2014-04-17 11:37:46 +0530337 def get_voucher_details(self, default_expense_account, default_cost_center, sle_map):
338 if self.doctype == "Stock Reconciliation":
Nabin Hait3f119ec2019-05-16 17:28:39 +0530339 reconciliation_purpose = frappe.db.get_value(self.doctype, self.name, "purpose")
340 is_opening = "Yes" if reconciliation_purpose == "Opening Stock" else "No"
341 details = []
Nabin Hait34c551d2019-07-03 10:34:31 +0530342 for voucher_detail_no in sle_map:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530343 details.append(
344 frappe._dict(
345 {
346 "name": voucher_detail_no,
347 "expense_account": default_expense_account,
348 "cost_center": default_cost_center,
349 "is_opening": is_opening,
350 }
351 )
352 )
Nabin Hait3f119ec2019-05-16 17:28:39 +0530353 return details
Anand Doshide1a97d2014-04-17 11:37:46 +0530354 else:
Nabin Haitdd38a262014-12-26 13:15:21 +0530355 details = self.get("items")
Anand Doshi094610d2014-04-16 19:56:53 +0530356
Anand Doshide1a97d2014-04-17 11:37:46 +0530357 if default_expense_account or default_cost_center:
358 for d in details:
359 if default_expense_account and not d.get("expense_account"):
360 d.expense_account = default_expense_account
361 if default_cost_center and not d.get("cost_center"):
362 d.cost_center = default_cost_center
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530363
Anand Doshide1a97d2014-04-17 11:37:46 +0530364 return details
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530365
Ankush Menate6ab8df2022-02-06 13:02:34 +0530366 def get_items_and_warehouses(self) -> Tuple[List[str], List[str]]:
367 """Get list of items and warehouses affected by a transaction"""
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530368
Ankush Menate6ab8df2022-02-06 13:02:34 +0530369 if not (hasattr(self, "items") or hasattr(self, "packed_items")):
370 return [], []
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530371
Ankush Menate6ab8df2022-02-06 13:02:34 +0530372 item_rows = (self.get("items") or []) + (self.get("packed_items") or [])
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530373
Ankush Menate6ab8df2022-02-06 13:02:34 +0530374 items = {d.item_code for d in item_rows if d.item_code}
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530375
Ankush Menate6ab8df2022-02-06 13:02:34 +0530376 warehouses = set()
377 for d in item_rows:
378 if d.get("warehouse"):
379 warehouses.add(d.warehouse)
Nabin Haitbecf75d2014-03-27 17:18:29 +0530380
Ankush Menate6ab8df2022-02-06 13:02:34 +0530381 if self.doctype == "Stock Entry":
382 if d.get("s_warehouse"):
383 warehouses.add(d.s_warehouse)
384 if d.get("t_warehouse"):
385 warehouses.add(d.t_warehouse)
386
387 return list(items), list(warehouses)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530388
Nabin Hait2e296fa2013-08-28 18:53:11 +0530389 def get_stock_ledger_details(self):
390 stock_ledger = {}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530391 stock_ledger_entries = frappe.db.sql(
392 """
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530393 select
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530394 name, warehouse, stock_value_difference, valuation_rate,
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530395 voucher_detail_no, item_code, posting_date, posting_time,
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530396 actual_qty, qty_after_transaction
Nabin Haitea8fab52017-02-06 17:13:39 +0530397 from
398 `tabStock Ledger Entry`
399 where
Ankush Menat0ca60af2022-02-08 10:24:19 +0530400 voucher_type=%s and voucher_no=%s and is_cancelled = 0
Ankush Menat494bd9e2022-03-28 18:52:46 +0530401 """,
402 (self.doctype, self.name),
403 as_dict=True,
404 )
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530405
Nabin Haitea8fab52017-02-06 17:13:39 +0530406 for sle in stock_ledger_entries:
Deepesh Gargb4be2922021-01-28 13:09:56 +0530407 stock_ledger.setdefault(sle.voucher_detail_no, []).append(sle)
Nabin Hait2e296fa2013-08-28 18:53:11 +0530408 return stock_ledger
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530409
Nabin Hait27994c22013-08-26 16:53:30 +0530410 def check_expense_account(self, item):
Rushabh Mehta052fe822014-04-16 19:20:11 +0530411 if not item.get("expense_account"):
Rohit Waghchaureceab6922020-11-18 17:57:35 +0530412 msg = _("Please set an Expense Account in the Items table")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530413 frappe.throw(
414 _("Row #{0}: Expense Account not set for the Item {1}. {2}").format(
415 item.idx, frappe.bold(item.item_code), msg
416 ),
417 title=_("Expense Account Missing"),
418 )
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530419
Anand Doshi496123a2014-06-19 19:25:19 +0530420 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530421 is_expense_account = (
422 frappe.get_cached_value("Account", item.get("expense_account"), "report_type")
423 == "Profit and Loss"
424 )
425 if (
426 self.doctype
Sagar Sharma2d04e712022-08-17 15:57:41 +0530427 not in (
428 "Purchase Receipt",
429 "Purchase Invoice",
430 "Stock Reconciliation",
431 "Stock Entry",
432 "Subcontracting Receipt",
433 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530434 and not is_expense_account
435 ):
436 frappe.throw(
437 _("Expense / Difference account ({0}) must be a 'Profit or Loss' account").format(
438 item.get("expense_account")
439 )
440 )
Anand Doshi496123a2014-06-19 19:25:19 +0530441 if is_expense_account and not item.get("cost_center"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530442 frappe.throw(
443 _("{0} {1}: Cost Center is mandatory for Item {2}").format(
444 _(self.doctype), self.name, item.get("item_code")
445 )
446 )
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530447
Rohit Waghchaure8996b7d2020-01-23 17:36:52 +0530448 def delete_auto_created_batches(self):
Rohit Waghchaurebc75a7e2022-10-10 13:28:19 +0530449 for row in self.items:
450 if row.serial_and_batch_bundle:
451 frappe.db.set_value(
452 "Serial and Batch Bundle", row.serial_and_batch_bundle, {"is_cancelled": 1}
453 )
Rohit Waghchaure8996b7d2020-01-23 17:36:52 +0530454
Rohit Waghchaurebc75a7e2022-10-10 13:28:19 +0530455 row.db_set("serial_and_batch_bundle", None)
Saqibe9ac3e02020-03-02 15:02:58 +0530456
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530457 def set_serial_and_batch_bundle(self, table_name=None, ignore_validate=False):
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530458 if not table_name:
459 table_name = "items"
Rohit Waghchaure8996b7d2020-01-23 17:36:52 +0530460
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530461 QTY_FIELD = {
462 "serial_and_batch_bundle": "qty",
463 "current_serial_and_batch_bundle": "current_qty",
464 "rejected_serial_and_batch_bundle": "rejected_qty",
465 }
466
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530467 for row in self.get(table_name):
s-aga-rc20241f2024-01-12 15:26:35 +0530468 for field in QTY_FIELD.keys():
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530469 if row.get(field):
470 frappe.get_doc("Serial and Batch Bundle", row.get(field)).set_serial_and_batch_values(
471 self, row, qty_field=QTY_FIELD[field]
472 )
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530473
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530474 def make_package_for_transfer(
475 self, serial_and_batch_bundle, warehouse, type_of_transaction=None, do_not_submit=None
476 ):
477 bundle_doc = frappe.get_doc("Serial and Batch Bundle", serial_and_batch_bundle)
478
479 if not type_of_transaction:
480 type_of_transaction = "Inward"
481
482 bundle_doc = frappe.copy_doc(bundle_doc)
483 bundle_doc.warehouse = warehouse
484 bundle_doc.type_of_transaction = type_of_transaction
485 bundle_doc.voucher_type = self.doctype
486 bundle_doc.voucher_no = self.name
487 bundle_doc.is_cancelled = 0
488
Rohit Waghchaure5bb31732023-03-21 10:54:41 +0530489 for row in bundle_doc.entries:
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530490 row.is_outward = 0
491 row.qty = abs(row.qty)
492 row.stock_value_difference = abs(row.stock_value_difference)
493 if type_of_transaction == "Outward":
494 row.qty *= -1
495 row.stock_value_difference *= row.stock_value_difference
496 row.is_outward = 1
497
498 row.warehouse = warehouse
499
Rohit Waghchaure5bb31732023-03-21 10:54:41 +0530500 bundle_doc.calculate_qty_and_amount()
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530501 bundle_doc.flags.ignore_permissions = True
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530502 bundle_doc.save(ignore_permissions=True)
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530503
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530504 return bundle_doc.name
Rohit Waghchaure4f4dbf12020-01-23 12:42:42 +0530505
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530506 def get_sl_entries(self, d, args):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530507 sl_dict = frappe._dict(
508 {
509 "item_code": d.get("item_code", None),
510 "warehouse": d.get("warehouse", None),
Rohit Waghchaurebc75a7e2022-10-10 13:28:19 +0530511 "serial_and_batch_bundle": d.get("serial_and_batch_bundle"),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530512 "posting_date": self.posting_date,
513 "posting_time": self.posting_time,
514 "fiscal_year": get_fiscal_year(self.posting_date, company=self.company)[0],
515 "voucher_type": self.doctype,
516 "voucher_no": self.name,
517 "voucher_detail_no": d.name,
518 "actual_qty": (self.docstatus == 1 and 1 or -1) * flt(d.get("stock_qty")),
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +0530519 "stock_uom": frappe.get_cached_value(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530520 "Item", args.get("item_code") or d.get("item_code"), "stock_uom"
521 ),
522 "incoming_rate": 0,
523 "company": self.company,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530524 "project": d.get("project") or self.get("project"),
525 "is_cancelled": 1 if self.docstatus == 2 else 0,
526 }
527 )
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530528
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530529 sl_dict.update(args)
Rohit Waghchauree576f7f2022-06-30 19:12:06 +0530530 self.update_inventory_dimensions(d, sl_dict)
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530531
rohitwaghchaure07432892023-12-17 12:42:07 +0530532 if self.docstatus == 2:
533 # To handle denormalized serial no records, will br deprecated in v16
534 for field in ["serial_no", "batch_no"]:
535 if d.get(field):
536 sl_dict[field] = d.get(field)
537
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530538 return sl_dict
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530539
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530540 def update_inventory_dimensions(self, row, sl_dict) -> None:
Rohit Waghchaure23729992022-09-02 18:43:55 +0530541 # To handle delivery note and sales invoice
542 if row.get("item_row"):
543 row = row.get("item_row")
544
Rohit Waghchaure289e6cd2022-07-15 15:43:38 +0530545 dimensions = get_evaluated_inventory_dimension(row, sl_dict, parent_doc=self)
546 for dimension in dimensions:
Rohit Waghchaure0b39a012022-08-17 11:56:13 +0530547 if not dimension:
548 continue
549
Rohit Waghchaure6798b902023-05-09 16:07:14 +0530550 if self.doctype in [
551 "Purchase Invoice",
552 "Purchase Receipt",
553 "Sales Invoice",
554 "Delivery Note",
555 "Stock Entry",
556 ]:
Rohit Waghchaure38aaba52023-05-13 13:00:05 +0530557 if (
558 (
559 sl_dict.actual_qty > 0
560 and not self.get("is_return")
561 or sl_dict.actual_qty < 0
562 and self.get("is_return")
563 )
564 and self.doctype in ["Purchase Invoice", "Purchase Receipt"]
565 ) or (
566 (
567 sl_dict.actual_qty < 0
568 and not self.get("is_return")
569 or sl_dict.actual_qty > 0
570 and self.get("is_return")
571 )
572 and self.doctype in ["Sales Invoice", "Delivery Note", "Stock Entry"]
Rohit Waghchaure6798b902023-05-09 16:07:14 +0530573 ):
574 sl_dict[dimension.target_fieldname] = row.get(dimension.source_fieldname)
575 else:
576 fieldname_start_with = "to"
577 if self.doctype in ["Purchase Invoice", "Purchase Receipt"]:
578 fieldname_start_with = "from"
579
580 fieldname = f"{fieldname_start_with}_{dimension.source_fieldname}"
581 sl_dict[dimension.target_fieldname] = row.get(fieldname)
582
583 if not sl_dict.get(dimension.target_fieldname):
584 sl_dict[dimension.target_fieldname] = row.get(dimension.source_fieldname)
585
586 elif row.get(dimension.source_fieldname):
Rohit Waghchaure289e6cd2022-07-15 15:43:38 +0530587 sl_dict[dimension.target_fieldname] = row.get(dimension.source_fieldname)
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530588
Rohit Waghchaure0b39a012022-08-17 11:56:13 +0530589 if not sl_dict.get(dimension.target_fieldname) and dimension.fetch_from_parent:
590 sl_dict[dimension.target_fieldname] = self.get(dimension.fetch_from_parent)
591
592 # Get value based on doctype name
593 if not sl_dict.get(dimension.target_fieldname):
Daizy Modi4efc9472022-11-07 09:21:03 +0530594 fieldname = next(
595 (
596 field.fieldname
597 for field in frappe.get_meta(self.doctype).fields
598 if field.options == dimension.fetch_from_parent
599 ),
600 None,
Rohit Waghchaure0b39a012022-08-17 11:56:13 +0530601 )
602
603 if fieldname and self.get(fieldname):
604 sl_dict[dimension.target_fieldname] = self.get(fieldname)
605
Rohit Waghchaure75fcab02022-09-03 17:09:24 +0530606 if sl_dict[dimension.target_fieldname] and self.docstatus == 1:
607 row.db_set(dimension.source_fieldname, sl_dict[dimension.target_fieldname])
Rohit Waghchaure23729992022-09-02 18:43:55 +0530608
Ankush Menat494bd9e2022-03-28 18:52:46 +0530609 def make_sl_entries(self, sl_entries, allow_negative_stock=False, via_landed_cost_voucher=False):
Rushabh Mehta1f847992013-12-12 19:12:19 +0530610 from erpnext.stock.stock_ledger import make_sl_entries
Ankush Menat494bd9e2022-03-28 18:52:46 +0530611
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530612 make_sl_entries(sl_entries, allow_negative_stock, via_landed_cost_voucher)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530613
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530614 def make_gl_entries_on_cancel(self):
ruthra kumar46ea8142023-07-28 08:29:19 +0530615 cancel_exchange_gain_loss_journal(frappe._dict(doctype=self.doctype, name=self.name))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530616 if frappe.db.sql(
617 """select name from `tabGL Entry` where voucher_type=%s
618 and voucher_no=%s""",
619 (self.doctype, self.name),
620 ):
621 self.make_gl_entries()
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530622
Anand Doshia740f752014-06-25 13:31:02 +0530623 def get_serialized_items(self):
624 serialized_items = []
Ankush Menata9c84f72021-06-11 16:00:48 +0530625 item_codes = list(set(d.item_code for d in self.get("items")))
Anand Doshia740f752014-06-25 13:31:02 +0530626 if item_codes:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530627 serialized_items = frappe.db.sql_list(
628 """select name from `tabItem`
629 where has_serial_no=1 and name in ({})""".format(
630 ", ".join(["%s"] * len(item_codes))
631 ),
632 tuple(item_codes),
633 )
Anand Doshia740f752014-06-25 13:31:02 +0530634
635 return serialized_items
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +0530636
Saurabh2e292062015-11-18 17:03:33 +0530637 def validate_warehouse(self):
Rohan Bansal7f8b95e2021-04-14 14:12:03 +0530638 from erpnext.stock.utils import validate_disabled_warehouse, validate_warehouse_company
Saurabh2e292062015-11-18 17:03:33 +0530639
Ankush Menat494bd9e2022-03-28 18:52:46 +0530640 warehouses = list(set(d.warehouse for d in self.get("items") if getattr(d, "warehouse", None)))
Saurabh2e292062015-11-18 17:03:33 +0530641
Ankush Menat494bd9e2022-03-28 18:52:46 +0530642 target_warehouses = list(
643 set([d.target_warehouse for d in self.get("items") if getattr(d, "target_warehouse", None)])
644 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530645
646 warehouses.extend(target_warehouses)
647
Ankush Menat494bd9e2022-03-28 18:52:46 +0530648 from_warehouse = list(
649 set([d.from_warehouse for d in self.get("items") if getattr(d, "from_warehouse", None)])
650 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530651
652 warehouses.extend(from_warehouse)
653
Saurabh2e292062015-11-18 17:03:33 +0530654 for w in warehouses:
Jannat Patel30c88732021-02-11 11:46:48 +0530655 validate_disabled_warehouse(w)
Saurabh2e292062015-11-18 17:03:33 +0530656 validate_warehouse_company(w, self.company)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530657
Anand Doshi6b71ef52016-01-06 16:32:06 +0530658 def update_billing_percentage(self, update_modified=True):
marinationd6596a12020-11-02 15:07:48 +0530659 target_ref_field = "amount"
660 if self.doctype == "Delivery Note":
661 target_ref_field = "amount - (returned_qty * rate)"
662
Ankush Menat494bd9e2022-03-28 18:52:46 +0530663 self._update_percent_field(
664 {
665 "target_dt": self.doctype + " Item",
666 "target_parent_dt": self.doctype,
667 "target_parent_field": "per_billed",
668 "target_ref_field": target_ref_field,
669 "target_field": "billed_amt",
670 "name": self.name,
671 },
672 update_modified,
673 )
Anand Doshia740f752014-06-25 13:31:02 +0530674
Nabin Hait8af429d2016-11-16 17:21:59 +0530675 def validate_inspection(self):
marination9ac9a4e2021-06-21 16:18:35 +0530676 """Checks if quality inspection is set/ is valid for Items that require inspection."""
677 inspection_fieldname_map = {
678 "Purchase Receipt": "inspection_required_before_purchase",
679 "Purchase Invoice": "inspection_required_before_purchase",
s-aga-r3fdcd332023-08-23 12:15:35 +0530680 "Subcontracting Receipt": "inspection_required_before_purchase",
marination9ac9a4e2021-06-21 16:18:35 +0530681 "Sales Invoice": "inspection_required_before_delivery",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530682 "Delivery Note": "inspection_required_before_delivery",
marination9ac9a4e2021-06-21 16:18:35 +0530683 }
684 inspection_required_fieldname = inspection_fieldname_map.get(self.doctype)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530685
marination9ac9a4e2021-06-21 16:18:35 +0530686 # return if inspection is not required on document level
Ankush Menat494bd9e2022-03-28 18:52:46 +0530687 if (
688 (not inspection_required_fieldname and self.doctype != "Stock Entry")
689 or (self.doctype == "Stock Entry" and not self.inspection_required)
690 or (self.doctype in ["Sales Invoice", "Purchase Invoice"] and not self.update_stock)
691 ):
692 return
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530693
Ankush Menat494bd9e2022-03-28 18:52:46 +0530694 for row in self.get("items"):
marination9ac9a4e2021-06-21 16:18:35 +0530695 qi_required = False
Ankush Menat494bd9e2022-03-28 18:52:46 +0530696 if inspection_required_fieldname and frappe.db.get_value(
697 "Item", row.item_code, inspection_required_fieldname
698 ):
marination9ac9a4e2021-06-21 16:18:35 +0530699 qi_required = True
700 elif self.doctype == "Stock Entry" and row.t_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530701 qi_required = True # inward stock needs inspection
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530702
Ankush Menat494bd9e2022-03-28 18:52:46 +0530703 if qi_required: # validate row only if inspection is required on item level
marination9ac9a4e2021-06-21 16:18:35 +0530704 self.validate_qi_presence(row)
705 if self.docstatus == 1:
706 self.validate_qi_submission(row)
707 self.validate_qi_rejection(row)
708
709 def validate_qi_presence(self, row):
710 """Check if QI is present on row level. Warn on save and stop on submit if missing."""
711 if not row.quality_inspection:
marination654e9d82021-06-21 16:51:12 +0530712 msg = f"Row #{row.idx}: Quality Inspection is required for Item {frappe.bold(row.item_code)}"
marination9ac9a4e2021-06-21 16:18:35 +0530713 if self.docstatus == 1:
marination654e9d82021-06-21 16:51:12 +0530714 frappe.throw(_(msg), title=_("Inspection Required"), exc=QualityInspectionRequiredError)
marination9ac9a4e2021-06-21 16:18:35 +0530715 else:
marination654e9d82021-06-21 16:51:12 +0530716 frappe.msgprint(_(msg), title=_("Inspection Required"), indicator="blue")
marination9ac9a4e2021-06-21 16:18:35 +0530717
718 def validate_qi_submission(self, row):
719 """Check if QI is submitted on row level, during submission"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530720 action = frappe.db.get_single_value(
721 "Stock Settings", "action_if_quality_inspection_is_not_submitted"
722 )
marination9ac9a4e2021-06-21 16:18:35 +0530723 qa_docstatus = frappe.db.get_value("Quality Inspection", row.quality_inspection, "docstatus")
724
barredterraeb9ee3f2023-12-05 11:22:55 +0100725 if qa_docstatus != 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530726 link = frappe.utils.get_link_to_form("Quality Inspection", row.quality_inspection)
727 msg = (
728 f"Row #{row.idx}: Quality Inspection {link} is not submitted for the item: {row.item_code}"
729 )
marination9ac9a4e2021-06-21 16:18:35 +0530730 if action == "Stop":
marination654e9d82021-06-21 16:51:12 +0530731 frappe.throw(_(msg), title=_("Inspection Submission"), exc=QualityInspectionNotSubmittedError)
marination9ac9a4e2021-06-21 16:18:35 +0530732 else:
Marica9ba3fce2021-06-22 11:20:17 +0530733 frappe.msgprint(_(msg), alert=True, indicator="orange")
marination9ac9a4e2021-06-21 16:18:35 +0530734
735 def validate_qi_rejection(self, row):
736 """Check if QI is rejected on row level, during submission"""
marinationf67f13c2021-07-10 18:24:24 +0530737 action = frappe.db.get_single_value("Stock Settings", "action_if_quality_inspection_is_rejected")
marination9ac9a4e2021-06-21 16:18:35 +0530738 qa_status = frappe.db.get_value("Quality Inspection", row.quality_inspection, "status")
739
740 if qa_status == "Rejected":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530741 link = frappe.utils.get_link_to_form("Quality Inspection", row.quality_inspection)
marination654e9d82021-06-21 16:51:12 +0530742 msg = f"Row #{row.idx}: Quality Inspection {link} was rejected for item {row.item_code}"
marination9ac9a4e2021-06-21 16:18:35 +0530743 if action == "Stop":
marination654e9d82021-06-21 16:51:12 +0530744 frappe.throw(_(msg), title=_("Inspection Rejected"), exc=QualityInspectionRejectedError)
marination9ac9a4e2021-06-21 16:18:35 +0530745 else:
marination654e9d82021-06-21 16:51:12 +0530746 frappe.msgprint(_(msg), alert=True, indicator="orange")
Manas Solankicc902412016-11-10 19:15:11 +0530747
Nabin Haitb2d3c0f2018-06-14 15:54:34 +0530748 def update_blanket_order(self):
Nabin Haitd1f40ad2018-06-14 17:09:55 +0530749 blanket_orders = list(set([d.blanket_order for d in self.items if d.blanket_order]))
Nabin Haitb2d3c0f2018-06-14 15:54:34 +0530750 for blanket_order in blanket_orders:
751 frappe.get_doc("Blanket Order", blanket_order).update_ordered_qty()
Manas Solankie5e87f72018-05-28 20:07:08 +0530752
marinationfd04e962020-04-03 15:46:48 +0530753 def validate_customer_provided_item(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530754 for d in self.get("items"):
marinationfd04e962020-04-03 15:46:48 +0530755 # Customer Provided parts will have zero valuation rate
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +0530756 if frappe.get_cached_value("Item", d.item_code, "is_customer_provided_item"):
marinationfd04e962020-04-03 15:46:48 +0530757 d.allow_zero_valuation_rate = 1
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530758
Anupam Kumar7e1dcf92021-02-11 20:19:30 +0530759 def set_rate_of_stock_uom(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530760 if self.doctype in [
761 "Purchase Receipt",
762 "Purchase Invoice",
763 "Purchase Order",
764 "Sales Invoice",
765 "Sales Order",
766 "Delivery Note",
767 "Quotation",
768 ]:
Anupam Kumar7e1dcf92021-02-11 20:19:30 +0530769 for d in self.get("items"):
Rohit Waghchaure13584432021-03-26 14:11:50 +0530770 d.stock_uom_rate = d.rate / (d.conversion_factor or 1)
Anupam Kumar7e1dcf92021-02-11 20:19:30 +0530771
Deepesh Gargb4be2922021-01-28 13:09:56 +0530772 def validate_internal_transfer(self):
rohitwaghchaure5136fe12023-10-22 20:03:02 +0530773 if self.doctype in ("Sales Invoice", "Delivery Note", "Purchase Invoice", "Purchase Receipt"):
774 if self.is_internal_transfer():
775 self.validate_in_transit_warehouses()
776 self.validate_multi_currency()
777 self.validate_packed_items()
rohitwaghchaure8fdc2442024-01-27 21:37:58 +0530778
779 if self.get("is_internal_supplier"):
780 self.validate_internal_transfer_qty()
rohitwaghchaure5136fe12023-10-22 20:03:02 +0530781 else:
782 self.validate_internal_transfer_warehouse()
783
784 def validate_internal_transfer_warehouse(self):
785 for row in self.items:
786 if row.get("target_warehouse"):
787 row.target_warehouse = None
788
789 if row.get("from_warehouse"):
790 row.from_warehouse = None
Deepesh Gargb4be2922021-01-28 13:09:56 +0530791
792 def validate_in_transit_warehouses(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530793 if (
794 self.doctype == "Sales Invoice" and self.get("update_stock")
795 ) or self.doctype == "Delivery Note":
796 for item in self.get("items"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530797 if not item.target_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530798 frappe.throw(
799 _("Row {0}: Target Warehouse is mandatory for internal transfers").format(item.idx)
800 )
Deepesh Gargb4be2922021-01-28 13:09:56 +0530801
Ankush Menat494bd9e2022-03-28 18:52:46 +0530802 if (
803 self.doctype == "Purchase Invoice" and self.get("update_stock")
804 ) or self.doctype == "Purchase Receipt":
805 for item in self.get("items"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530806 if not item.from_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530807 frappe.throw(
808 _("Row {0}: From Warehouse is mandatory for internal transfers").format(item.idx)
809 )
Deepesh Gargb4be2922021-01-28 13:09:56 +0530810
811 def validate_multi_currency(self):
812 if self.currency != self.company_currency:
813 frappe.throw(_("Internal transfers can only be done in company's default currency"))
814
815 def validate_packed_items(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530816 if self.doctype in ("Sales Invoice", "Delivery Note Item") and self.get("packed_items"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530817 frappe.throw(_("Packed Items cannot be transferred internally"))
818
rohitwaghchaure8fdc2442024-01-27 21:37:58 +0530819 def validate_internal_transfer_qty(self):
820 if self.doctype not in ["Purchase Invoice", "Purchase Receipt"]:
821 return
822
823 item_wise_transfer_qty = self.get_item_wise_inter_transfer_qty()
824 if not item_wise_transfer_qty:
825 return
826
827 item_wise_received_qty = self.get_item_wise_inter_received_qty()
828 precision = frappe.get_precision(self.doctype + " Item", "qty")
829
830 over_receipt_allowance = frappe.db.get_single_value(
831 "Stock Settings", "over_delivery_receipt_allowance"
832 )
833
834 parent_doctype = {
835 "Purchase Receipt": "Delivery Note",
836 "Purchase Invoice": "Sales Invoice",
837 }.get(self.doctype)
838
839 for key, transferred_qty in item_wise_transfer_qty.items():
840 recevied_qty = flt(item_wise_received_qty.get(key), precision)
841 if over_receipt_allowance:
842 transferred_qty = transferred_qty + flt(
843 transferred_qty * over_receipt_allowance / 100, precision
844 )
845
846 if recevied_qty > flt(transferred_qty, precision):
847 frappe.throw(
848 _("For Item {0} cannot be received more than {1} qty against the {2} {3}").format(
849 bold(key[1]),
850 bold(flt(transferred_qty, precision)),
851 bold(parent_doctype),
852 get_link_to_form(parent_doctype, self.get("inter_company_reference")),
853 )
854 )
855
856 def get_item_wise_inter_transfer_qty(self):
857 reference_field = "inter_company_reference"
858 if self.doctype == "Purchase Invoice":
859 reference_field = "inter_company_invoice_reference"
860
861 parent_doctype = {
862 "Purchase Receipt": "Delivery Note",
863 "Purchase Invoice": "Sales Invoice",
864 }.get(self.doctype)
865
866 child_doctype = parent_doctype + " Item"
867
868 parent_tab = frappe.qb.DocType(parent_doctype)
869 child_tab = frappe.qb.DocType(child_doctype)
870
871 query = (
872 frappe.qb.from_(parent_doctype)
873 .inner_join(child_tab)
874 .on(child_tab.parent == parent_tab.name)
875 .select(
876 child_tab.name,
877 child_tab.item_code,
878 child_tab.qty,
879 )
880 .where((parent_tab.name == self.get(reference_field)) & (parent_tab.docstatus == 1))
881 )
882
883 data = query.run(as_dict=True)
884 item_wise_transfer_qty = defaultdict(float)
885 for row in data:
886 item_wise_transfer_qty[(row.name, row.item_code)] += flt(row.qty)
887
888 return item_wise_transfer_qty
889
890 def get_item_wise_inter_received_qty(self):
891 child_doctype = self.doctype + " Item"
892
893 parent_tab = frappe.qb.DocType(self.doctype)
894 child_tab = frappe.qb.DocType(child_doctype)
895
896 query = (
897 frappe.qb.from_(self.doctype)
898 .inner_join(child_tab)
899 .on(child_tab.parent == parent_tab.name)
900 .select(
901 child_tab.item_code,
902 child_tab.qty,
903 )
904 .where(parent_tab.docstatus < 2)
905 )
906
907 if self.doctype == "Purchase Invoice":
908 query = query.select(
909 child_tab.sales_invoice_item.as_("name"),
910 )
911
912 query = query.where(
913 parent_tab.inter_company_invoice_reference == self.inter_company_invoice_reference
914 )
915 else:
916 query = query.select(
917 child_tab.delivery_note_item.as_("name"),
918 )
919
920 query = query.where(parent_tab.inter_company_reference == self.inter_company_reference)
921
922 data = query.run(as_dict=True)
923 item_wise_transfer_qty = defaultdict(float)
924 for row in data:
925 item_wise_transfer_qty[(row.name, row.item_code)] += flt(row.qty)
926
927 return item_wise_transfer_qty
928
marinationfac40352020-12-07 21:35:49 +0530929 def validate_putaway_capacity(self):
930 # if over receipt is attempted while 'apply putaway rule' is disabled
931 # and if rule was applied on the transaction, validate it.
marination957615b2021-01-18 23:47:24 +0530932 from erpnext.stock.doctype.putaway_rule.putaway_rule import get_available_putaway_capacity
Ankush Menat494bd9e2022-03-28 18:52:46 +0530933
934 valid_doctype = self.doctype in (
935 "Purchase Receipt",
936 "Stock Entry",
937 "Purchase Invoice",
938 "Stock Reconciliation",
939 )
marinationfac40352020-12-07 21:35:49 +0530940
marination957615b2021-01-18 23:47:24 +0530941 if self.doctype == "Purchase Invoice" and self.get("update_stock") == 0:
942 valid_doctype = False
943
944 if valid_doctype:
marinationfac40352020-12-07 21:35:49 +0530945 rule_map = defaultdict(dict)
946 for item in self.get("items"):
marination957615b2021-01-18 23:47:24 +0530947 warehouse_field = "t_warehouse" if self.doctype == "Stock Entry" else "warehouse"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530948 rule = frappe.db.get_value(
949 "Putaway Rule",
950 {"item_code": item.get("item_code"), "warehouse": item.get(warehouse_field)},
951 ["name", "disable"],
952 as_dict=True,
953 )
marination957615b2021-01-18 23:47:24 +0530954 if rule:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530955 if rule.get("disabled"):
956 continue # dont validate for disabled rule
marination957615b2021-01-18 23:47:24 +0530957
958 if self.doctype == "Stock Reconciliation":
959 stock_qty = flt(item.qty)
960 else:
961 stock_qty = flt(item.transfer_qty) if self.doctype == "Stock Entry" else flt(item.stock_qty)
962
963 rule_name = rule.get("name")
964 if not rule_map[rule_name]:
965 rule_map[rule_name]["warehouse"] = item.get(warehouse_field)
966 rule_map[rule_name]["item"] = item.get("item_code")
967 rule_map[rule_name]["qty_put"] = 0
968 rule_map[rule_name]["capacity"] = get_available_putaway_capacity(rule_name)
969 rule_map[rule_name]["qty_put"] += flt(stock_qty)
marinationfac40352020-12-07 21:35:49 +0530970
971 for rule, values in rule_map.items():
972 if flt(values["qty_put"]) > flt(values["capacity"]):
marination957615b2021-01-18 23:47:24 +0530973 message = self.prepare_over_receipt_message(rule, values)
marinationfac40352020-12-07 21:35:49 +0530974 frappe.throw(msg=message, title=_("Over Receipt"))
marination957615b2021-01-18 23:47:24 +0530975
976 def prepare_over_receipt_message(self, rule, values):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530977 message = _(
978 "{0} qty of Item {1} is being received into Warehouse {2} with capacity {3}."
979 ).format(
980 frappe.bold(values["qty_put"]),
981 frappe.bold(values["item"]),
982 frappe.bold(values["warehouse"]),
983 frappe.bold(values["capacity"]),
984 )
marination957615b2021-01-18 23:47:24 +0530985 message += "<br><br>"
986 rule_link = frappe.utils.get_link_to_form("Putaway Rule", rule)
Ankush Menatad6a2652021-04-17 16:50:02 +0530987 message += _("Please adjust the qty or edit {0} to proceed.").format(rule_link)
marination957615b2021-01-18 23:47:24 +0530988 return message
marinationfac40352020-12-07 21:35:49 +0530989
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +0530990 def repost_future_sle_and_gle(self, force=False):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530991 args = frappe._dict(
992 {
993 "posting_date": self.posting_date,
994 "posting_time": self.posting_time,
995 "voucher_type": self.doctype,
996 "voucher_no": self.name,
997 "company": self.company,
998 }
999 )
Ankush Menat3638fbf2022-03-01 18:17:14 +05301000
Rohit Waghchaure6e661e72023-05-16 16:23:52 +05301001 if self.docstatus == 2:
1002 force = True
1003
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +05301004 if force or future_sle_exists(args) or repost_required_for_queue(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301005 item_based_reposting = cint(
1006 frappe.db.get_single_value("Stock Reposting Settings", "item_based_reposting")
1007 )
Ankush Menat45dd46b2021-11-02 10:50:52 +05301008 if item_based_reposting:
1009 create_item_wise_repost_entries(voucher_type=self.doctype, voucher_no=self.name)
1010 else:
1011 create_repost_item_valuation_entry(args)
1012
Sagar Sharmaf4673942022-08-21 21:26:06 +05301013 def add_gl_entry(
1014 self,
1015 gl_entries,
1016 account,
1017 cost_center,
1018 debit,
1019 credit,
1020 remarks,
1021 against_account,
1022 debit_in_account_currency=None,
1023 credit_in_account_currency=None,
1024 account_currency=None,
1025 project=None,
1026 voucher_detail_no=None,
1027 item=None,
1028 posting_date=None,
1029 ):
1030
1031 gl_entry = {
1032 "account": account,
1033 "cost_center": cost_center,
1034 "debit": debit,
1035 "credit": credit,
1036 "against": against_account,
1037 "remarks": remarks,
1038 }
1039
1040 if voucher_detail_no:
1041 gl_entry.update({"voucher_detail_no": voucher_detail_no})
1042
1043 if debit_in_account_currency:
1044 gl_entry.update({"debit_in_account_currency": debit_in_account_currency})
1045
1046 if credit_in_account_currency:
1047 gl_entry.update({"credit_in_account_currency": credit_in_account_currency})
1048
1049 if posting_date:
1050 gl_entry.update({"posting_date": posting_date})
1051
1052 gl_entries.append(self.get_gl_dict(gl_entry, item=item))
1053
Ankush Menat494bd9e2022-03-28 18:52:46 +05301054
Deepesh Garg2e52a632023-06-04 19:20:28 +05301055@frappe.whitelist()
Deepesh Garg0e68da52023-06-22 15:43:32 +05301056def show_accounting_ledger_preview(company, doctype, docname):
Smit Vora77cc91d2023-10-19 22:35:55 +05301057 filters = frappe._dict(company=company, include_dimensions=1)
Deepesh Garg0e68da52023-06-22 15:43:32 +05301058 doc = frappe.get_doc(doctype, docname)
Smit Vora77cc91d2023-10-19 22:35:55 +05301059 doc.run_method("before_gl_preview")
Deepesh Garg0e68da52023-06-22 15:43:32 +05301060
1061 gl_columns, gl_data = get_accounting_ledger_preview(doc, filters)
1062
Deepesh Gargd9e7bc52023-06-22 16:07:32 +05301063 frappe.db.rollback()
Deepesh Garg0e68da52023-06-22 15:43:32 +05301064
1065 return {"gl_columns": gl_columns, "gl_data": gl_data}
1066
1067
1068@frappe.whitelist()
1069def show_stock_ledger_preview(company, doctype, docname):
Smit Vora77cc91d2023-10-19 22:35:55 +05301070 filters = frappe._dict(company=company)
Deepesh Garg2e52a632023-06-04 19:20:28 +05301071 doc = frappe.get_doc(doctype, docname)
Smit Vora77cc91d2023-10-19 22:35:55 +05301072 doc.run_method("before_sl_preview")
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301073
Deepesh Garg011ac132023-06-12 18:42:49 +05301074 sl_columns, sl_data = get_stock_ledger_preview(doc, filters)
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301075
Deepesh Gargd9e7bc52023-06-22 16:07:32 +05301076 frappe.db.rollback()
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301077
Deepesh Garg2e52a632023-06-04 19:20:28 +05301078 return {
Deepesh Garg011ac132023-06-12 18:42:49 +05301079 "sl_columns": sl_columns,
1080 "sl_data": sl_data,
Deepesh Garg2e52a632023-06-04 19:20:28 +05301081 }
1082
1083
Deepesh Garg011ac132023-06-12 18:42:49 +05301084def get_accounting_ledger_preview(doc, filters):
1085 from erpnext.accounts.report.general_ledger.general_ledger import get_columns as get_gl_columns
1086
1087 gl_columns, gl_data = [], []
1088 fields = [
1089 "posting_date",
1090 "account",
1091 "debit",
1092 "credit",
1093 "against",
1094 "party",
1095 "party_type",
Deepesh Garg0e68da52023-06-22 15:43:32 +05301096 "cost_center",
Deepesh Garg011ac132023-06-12 18:42:49 +05301097 "against_voucher_type",
1098 "against_voucher",
1099 ]
1100
1101 doc.docstatus = 1
Deepesh Garg0e68da52023-06-22 15:43:32 +05301102
1103 if doc.get("update_stock") or doc.doctype in ("Purchase Receipt", "Delivery Note"):
1104 doc.update_stock_ledger()
1105
Deepesh Garg011ac132023-06-12 18:42:49 +05301106 doc.make_gl_entries()
1107 columns = get_gl_columns(filters)
1108 gl_entries = get_gl_entries_for_preview(doc.doctype, doc.name, fields)
1109
1110 gl_columns = get_columns(columns, fields)
1111 gl_data = get_data(fields, gl_entries)
1112
1113 return gl_columns, gl_data
1114
1115
1116def get_stock_ledger_preview(doc, filters):
1117 from erpnext.stock.report.stock_ledger.stock_ledger import get_columns as get_sl_columns
1118
1119 sl_columns, sl_data = [], []
1120 fields = [
1121 "item_code",
1122 "stock_uom",
1123 "actual_qty",
1124 "qty_after_transaction",
1125 "warehouse",
1126 "incoming_rate",
1127 "valuation_rate",
1128 "stock_value",
1129 "stock_value_difference",
1130 ]
1131 columns_fields = [
1132 "item_code",
1133 "stock_uom",
1134 "in_qty",
1135 "out_qty",
1136 "qty_after_transaction",
1137 "warehouse",
1138 "incoming_rate",
Deepesh Garg0e68da52023-06-22 15:43:32 +05301139 "in_out_rate",
Deepesh Garg011ac132023-06-12 18:42:49 +05301140 "stock_value",
1141 "stock_value_difference",
1142 ]
1143
Deepesh Garg0e68da52023-06-22 15:43:32 +05301144 if doc.get("update_stock") or doc.doctype in ("Purchase Receipt", "Delivery Note"):
Deepesh Garg011ac132023-06-12 18:42:49 +05301145 doc.docstatus = 1
1146 doc.update_stock_ledger()
1147 columns = get_sl_columns(filters)
1148 sl_entries = get_sl_entries_for_preview(doc.doctype, doc.name, fields)
1149
1150 sl_columns = get_columns(columns, columns_fields)
1151 sl_data = get_data(columns_fields, sl_entries)
1152
1153 return sl_columns, sl_data
1154
1155
1156def get_sl_entries_for_preview(doctype, docname, fields):
1157 sl_entries = frappe.get_all(
1158 "Stock Ledger Entry", filters={"voucher_type": doctype, "voucher_no": docname}, fields=fields
1159 )
1160
1161 for entry in sl_entries:
1162 if entry.actual_qty > 0:
1163 entry["in_qty"] = entry.actual_qty
1164 entry["out_qty"] = 0
1165 else:
1166 entry["out_qty"] = abs(entry.actual_qty)
1167 entry["in_qty"] = 0
1168
Deepesh Garg0e68da52023-06-22 15:43:32 +05301169 entry["in_out_rate"] = entry["valuation_rate"]
1170
Deepesh Garg011ac132023-06-12 18:42:49 +05301171 return sl_entries
1172
1173
1174def get_gl_entries_for_preview(doctype, docname, fields):
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301175 return frappe.get_all(
Deepesh Garg011ac132023-06-12 18:42:49 +05301176 "GL Entry", filters={"voucher_type": doctype, "voucher_no": docname}, fields=fields
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301177 )
1178
1179
Deepesh Garg011ac132023-06-12 18:42:49 +05301180def get_columns(raw_columns, fields):
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301181 return [
Deepesh Garg011ac132023-06-12 18:42:49 +05301182 {"name": d.get("label"), "editable": False, "width": 110}
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301183 for d in raw_columns
Deepesh Garg011ac132023-06-12 18:42:49 +05301184 if not d.get("hidden") and d.get("fieldname") in fields
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301185 ]
1186
1187
1188def get_data(raw_columns, raw_data):
1189 datatable_data = []
1190 for row in raw_data:
1191 data_row = []
1192 for column in raw_columns:
Deepesh Garg011ac132023-06-12 18:42:49 +05301193 data_row.append(row.get(column) or "")
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301194
1195 datatable_data.append(data_row)
1196
1197 return datatable_data
1198
1199
Ankush Menat3638fbf2022-03-01 18:17:14 +05301200def repost_required_for_queue(doc: StockController) -> bool:
1201 """check if stock document contains repeated item-warehouse with queue based valuation.
1202
1203 if queue exists for repeated items then SLEs need to reprocessed in background again.
1204 """
1205
Ankush Menat494bd9e2022-03-28 18:52:46 +05301206 consuming_sles = frappe.db.get_all(
1207 "Stock Ledger Entry",
Ankush Menat3638fbf2022-03-01 18:17:14 +05301208 filters={
1209 "voucher_type": doc.doctype,
1210 "voucher_no": doc.name,
1211 "actual_qty": ("<", 0),
Ankush Menat494bd9e2022-03-28 18:52:46 +05301212 "is_cancelled": 0,
Ankush Menat3638fbf2022-03-01 18:17:14 +05301213 },
Ankush Menat494bd9e2022-03-28 18:52:46 +05301214 fields=["item_code", "warehouse", "stock_queue"],
Ankush Menat3638fbf2022-03-01 18:17:14 +05301215 )
1216 item_warehouses = [(sle.item_code, sle.warehouse) for sle in consuming_sles]
1217
1218 unique_item_warehouses = set(item_warehouses)
1219
1220 if len(unique_item_warehouses) == len(item_warehouses):
1221 return False
1222
1223 for sle in consuming_sles:
1224 if sle.stock_queue != "[]": # using FIFO/LIFO valuation
1225 return True
1226 return False
1227
Nabin Hait19f8fa52021-02-22 22:27:22 +05301228
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301229@frappe.whitelist()
1230def make_quality_inspections(doctype, docname, items):
Rohan Bansala06ec032021-06-02 14:55:31 +05301231 if isinstance(items, str):
1232 items = json.loads(items)
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301233
Rohan Bansala06ec032021-06-02 14:55:31 +05301234 inspections = []
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301235 for item in items:
Rohan Bansal1cdf5a02021-05-26 14:42:15 +05301236 if flt(item.get("sample_size")) > flt(item.get("qty")):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301237 frappe.throw(
1238 _(
1239 "{item_name}'s Sample Size ({sample_size}) cannot be greater than the Accepted Quantity ({accepted_quantity})"
1240 ).format(
1241 item_name=item.get("item_name"),
1242 sample_size=item.get("sample_size"),
1243 accepted_quantity=item.get("qty"),
1244 )
1245 )
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301246
Ankush Menat494bd9e2022-03-28 18:52:46 +05301247 quality_inspection = frappe.get_doc(
1248 {
1249 "doctype": "Quality Inspection",
1250 "inspection_type": "Incoming",
1251 "inspected_by": frappe.session.user,
1252 "reference_type": doctype,
1253 "reference_name": docname,
1254 "item_code": item.get("item_code"),
1255 "description": item.get("description"),
1256 "sample_size": flt(item.get("sample_size")),
1257 "item_serial_no": item.get("serial_no").split("\n")[0] if item.get("serial_no") else None,
1258 "batch_no": item.get("batch_no"),
1259 }
1260 ).insert()
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301261 quality_inspection.save()
Rohan Bansal1cdf5a02021-05-26 14:42:15 +05301262 inspections.append(quality_inspection.name)
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301263
Rohan Bansal1cdf5a02021-05-26 14:42:15 +05301264 return inspections
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301265
Ankush Menat494bd9e2022-03-28 18:52:46 +05301266
Nabin Haitb99c77b2020-12-25 18:12:35 +05301267def is_reposting_pending():
Ankush Menat494bd9e2022-03-28 18:52:46 +05301268 return frappe.db.exists(
1269 "Repost Item Valuation", {"docstatus": 1, "status": ["in", ["Queued", "In Progress"]]}
1270 )
1271
Nabin Haitb99c77b2020-12-25 18:12:35 +05301272
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301273def future_sle_exists(args, sl_entries=None):
1274 key = (args.voucher_type, args.voucher_no)
Rohit Waghchaured9dd64b2023-04-14 13:00:12 +05301275 if not hasattr(frappe.local, "future_sle"):
1276 frappe.local.future_sle = {}
Nabin Haita77b8c92020-12-21 14:45:50 +05301277
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301278 if validate_future_sle_not_exists(args, key, sl_entries):
1279 return False
1280 elif get_cached_data(args, key):
1281 return True
1282
1283 if not sl_entries:
1284 sl_entries = get_sle_entries_against_voucher(args)
1285 if not sl_entries:
1286 return
1287
1288 or_conditions = get_conditions_to_validate_future_sle(sl_entries)
1289
Ankush Menat494bd9e2022-03-28 18:52:46 +05301290 data = frappe.db.sql(
1291 """
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301292 select item_code, warehouse, count(name) as total_row
Deepesh Garg6f107da2021-10-12 20:15:55 +05301293 from `tabStock Ledger Entry` force index (item_warehouse)
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301294 where
1295 ({})
1296 and timestamp(posting_date, posting_time)
1297 >= timestamp(%(posting_date)s, %(posting_time)s)
1298 and voucher_no != %(voucher_no)s
1299 and is_cancelled = 0
1300 GROUP BY
1301 item_code, warehouse
Ankush Menat494bd9e2022-03-28 18:52:46 +05301302 """.format(
1303 " or ".join(or_conditions)
1304 ),
1305 args,
1306 as_dict=1,
1307 )
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301308
1309 for d in data:
1310 frappe.local.future_sle[key][(d.item_code, d.warehouse)] = d.total_row
1311
1312 return len(data)
1313
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301314
Ankush Menat494bd9e2022-03-28 18:52:46 +05301315def validate_future_sle_not_exists(args, key, sl_entries=None):
1316 item_key = ""
1317 if args.get("item_code"):
1318 item_key = (args.get("item_code"), args.get("warehouse"))
1319
1320 if not sl_entries and hasattr(frappe.local, "future_sle"):
Rohit Waghchaured9dd64b2023-04-14 13:00:12 +05301321 if key not in frappe.local.future_sle:
1322 return False
1323
Ankush Menat494bd9e2022-03-28 18:52:46 +05301324 if not frappe.local.future_sle.get(key) or (
1325 item_key and item_key not in frappe.local.future_sle.get(key)
1326 ):
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301327 return True
1328
Ankush Menat494bd9e2022-03-28 18:52:46 +05301329
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301330def get_cached_data(args, key):
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301331 if key not in frappe.local.future_sle:
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +05301332 frappe.local.future_sle[key] = frappe._dict({})
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301333
Ankush Menat494bd9e2022-03-28 18:52:46 +05301334 if args.get("item_code"):
1335 item_key = (args.get("item_code"), args.get("warehouse"))
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301336 count = frappe.local.future_sle[key].get(item_key)
1337
1338 return True if (count or count == 0) else False
1339 else:
1340 return frappe.local.future_sle[key]
1341
Ankush Menat494bd9e2022-03-28 18:52:46 +05301342
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301343def get_sle_entries_against_voucher(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301344 return frappe.get_all(
1345 "Stock Ledger Entry",
Nabin Haita77b8c92020-12-21 14:45:50 +05301346 filters={"voucher_type": args.voucher_type, "voucher_no": args.voucher_no},
1347 fields=["item_code", "warehouse"],
Ankush Menat494bd9e2022-03-28 18:52:46 +05301348 order_by="creation asc",
1349 )
1350
Nabin Haita77b8c92020-12-21 14:45:50 +05301351
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301352def get_conditions_to_validate_future_sle(sl_entries):
Sagar Vora868c0bf2021-03-27 16:10:20 +05301353 warehouse_items_map = {}
1354 for entry in sl_entries:
1355 if entry.warehouse not in warehouse_items_map:
1356 warehouse_items_map[entry.warehouse] = set()
Nabin Haita77b8c92020-12-21 14:45:50 +05301357
Sagar Vora868c0bf2021-03-27 16:10:20 +05301358 warehouse_items_map[entry.warehouse].add(entry.item_code)
1359
1360 or_conditions = []
1361 for warehouse, items in warehouse_items_map.items():
1362 or_conditions.append(
Noah Jacobb5a14912021-06-15 12:44:04 +05301363 f"""warehouse = {frappe.db.escape(warehouse)}
Ankush Menat494bd9e2022-03-28 18:52:46 +05301364 and item_code in ({', '.join(frappe.db.escape(item) for item in items)})"""
1365 )
Sagar Vora868c0bf2021-03-27 16:10:20 +05301366
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301367 return or_conditions
Nabin Haita77b8c92020-12-21 14:45:50 +05301368
Ankush Menat494bd9e2022-03-28 18:52:46 +05301369
Nabin Haita77b8c92020-12-21 14:45:50 +05301370def create_repost_item_valuation_entry(args):
1371 args = frappe._dict(args)
1372 repost_entry = frappe.new_doc("Repost Item Valuation")
1373 repost_entry.based_on = args.based_on
1374 if not args.based_on:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301375 repost_entry.based_on = "Transaction" if args.voucher_no else "Item and Warehouse"
Nabin Haita77b8c92020-12-21 14:45:50 +05301376 repost_entry.voucher_type = args.voucher_type
1377 repost_entry.voucher_no = args.voucher_no
1378 repost_entry.item_code = args.item_code
1379 repost_entry.warehouse = args.warehouse
1380 repost_entry.posting_date = args.posting_date
1381 repost_entry.posting_time = args.posting_time
1382 repost_entry.company = args.company
1383 repost_entry.allow_zero_rate = args.allow_zero_rate
1384 repost_entry.flags.ignore_links = True
Ankush Menataa024fc2021-11-18 12:51:26 +05301385 repost_entry.flags.ignore_permissions = True
Nabin Haita77b8c92020-12-21 14:45:50 +05301386 repost_entry.save()
Sagar Vora868c0bf2021-03-27 16:10:20 +05301387 repost_entry.submit()
Ankush Menat6dc9b822021-10-28 15:53:18 +05301388
1389
1390def create_item_wise_repost_entries(voucher_type, voucher_no, allow_zero_rate=False):
1391 """Using a voucher create repost item valuation records for all item-warehouse pairs."""
1392
Ankush Menatd220e082021-10-28 17:47:00 +05301393 stock_ledger_entries = get_items_to_be_repost(voucher_type, voucher_no)
1394
Ankush Menat6dc9b822021-10-28 15:53:18 +05301395 distinct_item_warehouses = set()
Ankush Menat6dc9b822021-10-28 15:53:18 +05301396 repost_entries = []
1397
1398 for sle in stock_ledger_entries:
1399 item_wh = (sle.item_code, sle.warehouse)
1400 if item_wh in distinct_item_warehouses:
1401 continue
1402 distinct_item_warehouses.add(item_wh)
1403
1404 repost_entry = frappe.new_doc("Repost Item Valuation")
1405 repost_entry.based_on = "Item and Warehouse"
Ankush Menat6dc9b822021-10-28 15:53:18 +05301406
1407 repost_entry.item_code = sle.item_code
1408 repost_entry.warehouse = sle.warehouse
1409 repost_entry.posting_date = sle.posting_date
1410 repost_entry.posting_time = sle.posting_time
1411 repost_entry.allow_zero_rate = allow_zero_rate
1412 repost_entry.flags.ignore_links = True
Ankush Menat0a2964d2021-11-24 15:55:31 +05301413 repost_entry.flags.ignore_permissions = True
Ankush Menat6dc9b822021-10-28 15:53:18 +05301414 repost_entry.submit()
1415 repost_entries.append(repost_entry)
1416
1417 return repost_entries