blob: 31c480f98d0aa5cdbc75a5dc9ae19ac0cecdee76 [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
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05309from frappe import _
10from frappe.utils import cint, cstr, flt, get_link_to_form, getdate
11
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)
Rohit Waghchaure5d5dc562021-06-22 15:23:04 +053018from erpnext.accounts.utils import 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)
Ankush Menat8f577242022-01-07 11:10:23 +053024from erpnext.stock.stock_ledger import get_items_to_be_repost
Rohan Bansal7f8b95e2021-04-14 14:12:03 +053025
Nabin Haitc3afb252013-03-19 12:01:24 +053026
Ankush Menat494bd9e2022-03-28 18:52:46 +053027class QualityInspectionRequiredError(frappe.ValidationError):
28 pass
29
30
31class QualityInspectionRejectedError(frappe.ValidationError):
32 pass
33
34
35class QualityInspectionNotSubmittedError(frappe.ValidationError):
36 pass
37
Nabin Hait5a9579b2018-12-24 14:54:42 +053038
Rohit Waghchaure795c9432022-08-17 13:48:56 +053039class BatchExpiredError(frappe.ValidationError):
40 pass
41
42
Nabin Haitc3afb252013-03-19 12:01:24 +053043class StockController(AccountsController):
Nabin Hait8af429d2016-11-16 17:21:59 +053044 def validate(self):
45 super(StockController, self).validate()
Ankush Menat494bd9e2022-03-28 18:52:46 +053046 if not self.get("is_return"):
marination596560c2020-06-11 16:39:03 +053047 self.validate_inspection()
rohitwaghchaure9af557f2019-12-30 13:26:47 +053048 self.validate_serialized_batch()
marinationeecfc4c2021-07-22 13:23:54 +053049 self.clean_serial_nos()
marinationfd04e962020-04-03 15:46:48 +053050 self.validate_customer_provided_item()
Anupam Kumar7e1dcf92021-02-11 20:19:30 +053051 self.set_rate_of_stock_uom()
Deepesh Gargb4be2922021-01-28 13:09:56 +053052 self.validate_internal_transfer()
marinationfac40352020-12-07 21:35:49 +053053 self.validate_putaway_capacity()
Rushabh Mehtaffd80a62017-01-16 17:23:20 +053054
Nabin Haita77b8c92020-12-21 14:45:50 +053055 def make_gl_entries(self, gl_entries=None, from_repost=False):
Anand Doshif78d1ae2014-03-28 13:55:00 +053056 if self.docstatus == 2:
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053057 make_reverse_gl_entries(voucher_type=self.doctype, voucher_no=self.name)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053058
Ankush Menat494bd9e2022-03-28 18:52:46 +053059 provisional_accounting_for_non_stock_items = cint(
60 frappe.db.get_value(
61 "Company", self.company, "enable_provisional_accounting_for_non_stock_items"
62 )
63 )
Deepesh Garg528c7132022-02-01 14:42:55 +053064
Ankush Menat494bd9e2022-03-28 18:52:46 +053065 if (
66 cint(erpnext.is_perpetual_inventory_enabled(self.company))
67 or provisional_accounting_for_non_stock_items
68 ):
Rohit Waghchaure6b33c9b2019-03-08 11:13:35 +053069 warehouse_account = get_warehouse_account_map(self.company)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053070
Ankush Menat494bd9e2022-03-28 18:52:46 +053071 if self.docstatus == 1:
Nabin Hait9784d272016-12-30 16:21:35 +053072 if not gl_entries:
73 gl_entries = self.get_gl_entries(warehouse_account)
Nabin Haita77b8c92020-12-21 14:45:50 +053074 make_gl_entries(gl_entries, from_repost=from_repost)
Nabin Hait145e5e22013-10-22 23:51:41 +053075
Ankush Menat494bd9e2022-03-28 18:52:46 +053076 elif self.doctype in ["Purchase Receipt", "Purchase Invoice"] and self.docstatus == 1:
Rohit Waghchaure42169722018-05-16 18:16:08 +053077 gl_entries = []
78 gl_entries = self.get_asset_gl_entry(gl_entries)
Nabin Haita77b8c92020-12-21 14:45:50 +053079 make_gl_entries(gl_entries, from_repost=from_repost)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053080
rohitwaghchaure9af557f2019-12-30 13:26:47 +053081 def validate_serialized_batch(self):
82 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
Ankush Menat494bd9e2022-03-28 18:52:46 +053083
Rohit Waghchaure795c9432022-08-17 13:48:56 +053084 is_material_issue = False
85 if self.doctype == "Stock Entry" and self.purpose == "Material Issue":
86 is_material_issue = True
87
rohitwaghchaure9af557f2019-12-30 13:26:47 +053088 for d in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +053089 if hasattr(d, "serial_no") and hasattr(d, "batch_no") and d.serial_no and d.batch_no:
90 serial_nos = frappe.get_all(
91 "Serial No",
Rohit Waghchaure6b482eb2021-07-23 16:40:45 +053092 fields=["batch_no", "name", "warehouse"],
Ankush Menat494bd9e2022-03-28 18:52:46 +053093 filters={"name": ("in", get_serial_nos(d.serial_no))},
Rohit Waghchaure6b482eb2021-07-23 16:40:45 +053094 )
95
96 for row in serial_nos:
97 if row.warehouse and row.batch_no != d.batch_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +053098 frappe.throw(
99 _("Row #{0}: Serial No {1} does not belong to Batch {2}").format(
100 d.idx, row.name, d.batch_no
101 )
102 )
rohitwaghchaure9af557f2019-12-30 13:26:47 +0530103
Rohit Waghchaure795c9432022-08-17 13:48:56 +0530104 if is_material_issue:
105 continue
106
Saqib Ansari903055b2020-10-20 11:59:06 +0530107 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 +0530108 expiry_date = frappe.get_cached_value("Batch", d.get("batch_no"), "expiry_date")
109
110 if expiry_date and getdate(expiry_date) < getdate(self.posting_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530111 frappe.throw(
112 _("Row #{0}: The batch {1} has already expired.").format(
113 d.idx, get_link_to_form("Batch", d.get("batch_no"))
Rohit Waghchaure795c9432022-08-17 13:48:56 +0530114 ),
115 BatchExpiredError,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530116 )
rohitwaghchaure28a48802020-04-28 13:01:43 +0530117
marinationeecfc4c2021-07-22 13:23:54 +0530118 def clean_serial_nos(self):
Ankush Menatb20df372022-01-24 19:19:58 +0530119 from erpnext.stock.doctype.serial_no.serial_no import clean_serial_no_string
120
marinationeecfc4c2021-07-22 13:23:54 +0530121 for row in self.get("items"):
122 if hasattr(row, "serial_no") and row.serial_no:
Ankush Menatb20df372022-01-24 19:19:58 +0530123 # remove extra whitespace and store one serial no on each line
124 row.serial_no = clean_serial_no_string(row.serial_no)
marinationeecfc4c2021-07-22 13:23:54 +0530125
Ankush Menat494bd9e2022-03-28 18:52:46 +0530126 for row in self.get("packed_items") or []:
Ankush Menate177c522022-01-24 19:28:26 +0530127 if hasattr(row, "serial_no") and row.serial_no:
128 # remove extra whitespace and store one serial no on each line
129 row.serial_no = clean_serial_no_string(row.serial_no)
130
Ankush Menat494bd9e2022-03-28 18:52:46 +0530131 def get_gl_entries(
132 self, warehouse_account=None, default_expense_account=None, default_cost_center=None
133 ):
Nabin Haitadeb9762014-10-06 11:53:52 +0530134
Nabin Hait142007a2013-09-17 15:15:16 +0530135 if not warehouse_account:
Rohit Waghchaure6b33c9b2019-03-08 11:13:35 +0530136 warehouse_account = get_warehouse_account_map(self.company)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530137
Anand Doshide1a97d2014-04-17 11:37:46 +0530138 sle_map = self.get_stock_ledger_details()
139 voucher_details = self.get_voucher_details(default_expense_account, default_cost_center, sle_map)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530140
Nabin Hait2e296fa2013-08-28 18:53:11 +0530141 gl_list = []
Nabin Hait7a75e102013-09-17 10:21:20 +0530142 warehouse_with_no_account = []
Nabin Hait19f8fa52021-02-22 22:27:22 +0530143 precision = self.get_debit_field_precision()
Nabin Hait8c61f342016-12-15 13:46:03 +0530144 for item_row in voucher_details:
145 sle_list = sle_map.get(item_row.name)
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530146 sle_rounding_diff = 0.0
Nabin Hait2e296fa2013-08-28 18:53:11 +0530147 if sle_list:
148 for sle in sle_list:
149 if warehouse_account.get(sle.warehouse):
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530150 # from warehouse account
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530151
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530152 sle_rounding_diff += flt(sle.stock_value_difference)
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530153
Nabin Hait8c61f342016-12-15 13:46:03 +0530154 self.check_expense_account(item_row)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530155
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530156 # expense account/ target_warehouse / source_warehouse
Ankush Menat494bd9e2022-03-28 18:52:46 +0530157 if item_row.get("target_warehouse"):
158 warehouse = item_row.get("target_warehouse")
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530159 expense_account = warehouse_account[warehouse]["account"]
160 else:
161 expense_account = item_row.expense_account
162
Ankush Menat494bd9e2022-03-28 18:52:46 +0530163 gl_list.append(
164 self.get_gl_dict(
165 {
166 "account": warehouse_account[sle.warehouse]["account"],
167 "against": expense_account,
168 "cost_center": item_row.cost_center,
169 "project": item_row.project or self.get("project"),
170 "remarks": self.get("remarks") or _("Accounting Entry for Stock"),
171 "debit": flt(sle.stock_value_difference, precision),
172 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
173 },
174 warehouse_account[sle.warehouse]["account_currency"],
175 item=item_row,
176 )
177 )
Nabin Hait27994c22013-08-26 16:53:30 +0530178
Ankush Menat494bd9e2022-03-28 18:52:46 +0530179 gl_list.append(
180 self.get_gl_dict(
181 {
182 "account": expense_account,
183 "against": warehouse_account[sle.warehouse]["account"],
184 "cost_center": item_row.cost_center,
185 "remarks": self.get("remarks") or _("Accounting Entry for Stock"),
Ankush Menat65b21ee2022-06-07 14:49:24 +0530186 "debit": -1 * flt(sle.stock_value_difference, precision),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530187 "project": item_row.get("project") or self.get("project"),
188 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
189 },
190 item=item_row,
191 )
192 )
Nabin Hait7a75e102013-09-17 10:21:20 +0530193 elif sle.warehouse not in warehouse_with_no_account:
194 warehouse_with_no_account.append(sle.warehouse)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530195
Deepesh Garg49601552022-10-12 14:57:16 +0530196 if abs(sle_rounding_diff) > (1.0 / (10**precision)) and (
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530197 self.get("is_internal_customer") or self.get("is_internal_supplier")
198 ):
Deepesh Garg1c05c002022-10-12 14:19:09 +0530199 warehouse_asset_account = ""
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530200 if self.get("is_internal_customer"):
Deepesh Garg1c05c002022-10-12 14:19:09 +0530201 warehouse_asset_account = warehouse_account[item_row.get("target_warehouse")]["account"]
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530202 elif self.get("is_internal_supplier"):
Deepesh Garg1c05c002022-10-12 14:19:09 +0530203 warehouse_asset_account = warehouse_account[item_row.get("warehouse")]["account"]
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530204
Deepesh Garg1c05c002022-10-12 14:19:09 +0530205 expense_account = frappe.db.get_value("Company", self.company, "default_expense_account")
206
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530207 gl_list.append(
208 self.get_gl_dict(
209 {
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530210 "account": expense_account,
Deepesh Garg1c05c002022-10-12 14:19:09 +0530211 "against": warehouse_asset_account,
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530212 "cost_center": item_row.cost_center,
213 "project": item_row.project or self.get("project"),
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530214 "remarks": _("Rounding gain/loss Entry for Stock Transfer"),
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530215 "debit": sle_rounding_diff,
216 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
217 },
218 warehouse_account[sle.warehouse]["account_currency"],
219 item=item_row,
220 )
221 )
222
223 gl_list.append(
224 self.get_gl_dict(
225 {
Deepesh Garg1c05c002022-10-12 14:19:09 +0530226 "account": warehouse_asset_account,
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530227 "against": expense_account,
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530228 "cost_center": item_row.cost_center,
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530229 "remarks": _("Rounding gain/loss Entry for Stock Transfer"),
230 "credit": sle_rounding_diff,
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530231 "project": item_row.get("project") or self.get("project"),
232 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
233 },
234 item=item_row,
235 )
236 )
237
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530238 if warehouse_with_no_account:
Nabin Haitd6625022016-10-24 18:17:57 +0530239 for wh in warehouse_with_no_account:
240 if frappe.db.get_value("Warehouse", wh, "company"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530241 frappe.throw(
242 _(
243 "Warehouse {0} is not linked to any account, please mention the account in the warehouse record or set default inventory account in company {1}."
244 ).format(wh, self.company)
245 )
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530246
Nabin Hait19f8fa52021-02-22 22:27:22 +0530247 return process_gl_map(gl_list, precision=precision)
248
249 def get_debit_field_precision(self):
250 if not frappe.flags.debit_field_precision:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530251 frappe.flags.debit_field_precision = frappe.get_precision(
252 "GL Entry", "debit_in_account_currency"
253 )
Nabin Hait19f8fa52021-02-22 22:27:22 +0530254
255 return frappe.flags.debit_field_precision
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530256
Anand Doshide1a97d2014-04-17 11:37:46 +0530257 def get_voucher_details(self, default_expense_account, default_cost_center, sle_map):
258 if self.doctype == "Stock Reconciliation":
Nabin Hait3f119ec2019-05-16 17:28:39 +0530259 reconciliation_purpose = frappe.db.get_value(self.doctype, self.name, "purpose")
260 is_opening = "Yes" if reconciliation_purpose == "Opening Stock" else "No"
261 details = []
Nabin Hait34c551d2019-07-03 10:34:31 +0530262 for voucher_detail_no in sle_map:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530263 details.append(
264 frappe._dict(
265 {
266 "name": voucher_detail_no,
267 "expense_account": default_expense_account,
268 "cost_center": default_cost_center,
269 "is_opening": is_opening,
270 }
271 )
272 )
Nabin Hait3f119ec2019-05-16 17:28:39 +0530273 return details
Anand Doshide1a97d2014-04-17 11:37:46 +0530274 else:
Nabin Haitdd38a262014-12-26 13:15:21 +0530275 details = self.get("items")
Anand Doshi094610d2014-04-16 19:56:53 +0530276
Anand Doshide1a97d2014-04-17 11:37:46 +0530277 if default_expense_account or default_cost_center:
278 for d in details:
279 if default_expense_account and not d.get("expense_account"):
280 d.expense_account = default_expense_account
281 if default_cost_center and not d.get("cost_center"):
282 d.cost_center = default_cost_center
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530283
Anand Doshide1a97d2014-04-17 11:37:46 +0530284 return details
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530285
Ankush Menate6ab8df2022-02-06 13:02:34 +0530286 def get_items_and_warehouses(self) -> Tuple[List[str], List[str]]:
287 """Get list of items and warehouses affected by a transaction"""
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530288
Ankush Menate6ab8df2022-02-06 13:02:34 +0530289 if not (hasattr(self, "items") or hasattr(self, "packed_items")):
290 return [], []
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530291
Ankush Menate6ab8df2022-02-06 13:02:34 +0530292 item_rows = (self.get("items") or []) + (self.get("packed_items") or [])
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530293
Ankush Menate6ab8df2022-02-06 13:02:34 +0530294 items = {d.item_code for d in item_rows if d.item_code}
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530295
Ankush Menate6ab8df2022-02-06 13:02:34 +0530296 warehouses = set()
297 for d in item_rows:
298 if d.get("warehouse"):
299 warehouses.add(d.warehouse)
Nabin Haitbecf75d2014-03-27 17:18:29 +0530300
Ankush Menate6ab8df2022-02-06 13:02:34 +0530301 if self.doctype == "Stock Entry":
302 if d.get("s_warehouse"):
303 warehouses.add(d.s_warehouse)
304 if d.get("t_warehouse"):
305 warehouses.add(d.t_warehouse)
306
307 return list(items), list(warehouses)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530308
Nabin Hait2e296fa2013-08-28 18:53:11 +0530309 def get_stock_ledger_details(self):
310 stock_ledger = {}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530311 stock_ledger_entries = frappe.db.sql(
312 """
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530313 select
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530314 name, warehouse, stock_value_difference, valuation_rate,
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530315 voucher_detail_no, item_code, posting_date, posting_time,
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530316 actual_qty, qty_after_transaction
Nabin Haitea8fab52017-02-06 17:13:39 +0530317 from
318 `tabStock Ledger Entry`
319 where
Ankush Menat0ca60af2022-02-08 10:24:19 +0530320 voucher_type=%s and voucher_no=%s and is_cancelled = 0
Ankush Menat494bd9e2022-03-28 18:52:46 +0530321 """,
322 (self.doctype, self.name),
323 as_dict=True,
324 )
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530325
Nabin Haitea8fab52017-02-06 17:13:39 +0530326 for sle in stock_ledger_entries:
Deepesh Gargb4be2922021-01-28 13:09:56 +0530327 stock_ledger.setdefault(sle.voucher_detail_no, []).append(sle)
Nabin Hait2e296fa2013-08-28 18:53:11 +0530328 return stock_ledger
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530329
Rushabh Mehta551406a2017-04-21 12:40:19 +0530330 def make_batches(self, warehouse_field):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530331 """Create batches if required. Called before submit"""
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530332 for d in self.items:
Rushabh Mehta551406a2017-04-21 12:40:19 +0530333 if d.get(warehouse_field) and not d.batch_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530334 has_batch_no, create_new_batch = frappe.db.get_value(
335 "Item", d.item_code, ["has_batch_no", "create_new_batch"]
336 )
Rushabh Mehta551406a2017-04-21 12:40:19 +0530337 if has_batch_no and create_new_batch:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530338 d.batch_no = (
339 frappe.get_doc(
340 dict(
341 doctype="Batch",
342 item=d.item_code,
343 supplier=getattr(self, "supplier", None),
344 reference_doctype=self.doctype,
345 reference_name=self.name,
346 )
347 )
348 .insert()
349 .name
350 )
Rushabh Mehtae385b5b2017-04-20 15:21:01 +0530351
Nabin Hait27994c22013-08-26 16:53:30 +0530352 def check_expense_account(self, item):
Rushabh Mehta052fe822014-04-16 19:20:11 +0530353 if not item.get("expense_account"):
Rohit Waghchaureceab6922020-11-18 17:57:35 +0530354 msg = _("Please set an Expense Account in the Items table")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530355 frappe.throw(
356 _("Row #{0}: Expense Account not set for the Item {1}. {2}").format(
357 item.idx, frappe.bold(item.item_code), msg
358 ),
359 title=_("Expense Account Missing"),
360 )
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530361
Anand Doshi496123a2014-06-19 19:25:19 +0530362 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530363 is_expense_account = (
364 frappe.get_cached_value("Account", item.get("expense_account"), "report_type")
365 == "Profit and Loss"
366 )
367 if (
368 self.doctype
Sagar Sharma2d04e712022-08-17 15:57:41 +0530369 not in (
370 "Purchase Receipt",
371 "Purchase Invoice",
372 "Stock Reconciliation",
373 "Stock Entry",
374 "Subcontracting Receipt",
375 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530376 and not is_expense_account
377 ):
378 frappe.throw(
379 _("Expense / Difference account ({0}) must be a 'Profit or Loss' account").format(
380 item.get("expense_account")
381 )
382 )
Anand Doshi496123a2014-06-19 19:25:19 +0530383 if is_expense_account and not item.get("cost_center"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530384 frappe.throw(
385 _("{0} {1}: Cost Center is mandatory for Item {2}").format(
386 _(self.doctype), self.name, item.get("item_code")
387 )
388 )
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530389
Rohit Waghchaure8996b7d2020-01-23 17:36:52 +0530390 def delete_auto_created_batches(self):
391 for d in self.items:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530392 if not d.batch_no:
393 continue
Rohit Waghchaure8996b7d2020-01-23 17:36:52 +0530394
Ankush Menat494bd9e2022-03-28 18:52:46 +0530395 frappe.db.set_value(
396 "Serial No", {"batch_no": d.batch_no, "status": "Inactive"}, "batch_no", None
397 )
Saqibe9ac3e02020-03-02 15:02:58 +0530398
Rohit Waghchaure8996b7d2020-01-23 17:36:52 +0530399 d.batch_no = None
400 d.db_set("batch_no", None)
401
Ankush Menat494bd9e2022-03-28 18:52:46 +0530402 for data in frappe.get_all(
403 "Batch", {"reference_name": self.name, "reference_doctype": self.doctype}
404 ):
Rohit Waghchaure8996b7d2020-01-23 17:36:52 +0530405 frappe.delete_doc("Batch", data.name)
Rohit Waghchaure4f4dbf12020-01-23 12:42:42 +0530406
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530407 def get_sl_entries(self, d, args):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530408 sl_dict = frappe._dict(
409 {
410 "item_code": d.get("item_code", None),
411 "warehouse": d.get("warehouse", None),
412 "posting_date": self.posting_date,
413 "posting_time": self.posting_time,
414 "fiscal_year": get_fiscal_year(self.posting_date, company=self.company)[0],
415 "voucher_type": self.doctype,
416 "voucher_no": self.name,
417 "voucher_detail_no": d.name,
418 "actual_qty": (self.docstatus == 1 and 1 or -1) * flt(d.get("stock_qty")),
419 "stock_uom": frappe.db.get_value(
420 "Item", args.get("item_code") or d.get("item_code"), "stock_uom"
421 ),
422 "incoming_rate": 0,
423 "company": self.company,
424 "batch_no": cstr(d.get("batch_no")).strip(),
425 "serial_no": d.get("serial_no"),
426 "project": d.get("project") or self.get("project"),
427 "is_cancelled": 1 if self.docstatus == 2 else 0,
428 }
429 )
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530430
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530431 sl_dict.update(args)
Rohit Waghchauree576f7f2022-06-30 19:12:06 +0530432 self.update_inventory_dimensions(d, sl_dict)
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530433
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530434 return sl_dict
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530435
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530436 def update_inventory_dimensions(self, row, sl_dict) -> None:
Rohit Waghchaure23729992022-09-02 18:43:55 +0530437 # To handle delivery note and sales invoice
438 if row.get("item_row"):
439 row = row.get("item_row")
440
Rohit Waghchaure289e6cd2022-07-15 15:43:38 +0530441 dimensions = get_evaluated_inventory_dimension(row, sl_dict, parent_doc=self)
442 for dimension in dimensions:
Rohit Waghchaure0b39a012022-08-17 11:56:13 +0530443 if not dimension:
444 continue
445
446 if row.get(dimension.source_fieldname):
Rohit Waghchaure289e6cd2022-07-15 15:43:38 +0530447 sl_dict[dimension.target_fieldname] = row.get(dimension.source_fieldname)
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530448
Rohit Waghchaure0b39a012022-08-17 11:56:13 +0530449 if not sl_dict.get(dimension.target_fieldname) and dimension.fetch_from_parent:
450 sl_dict[dimension.target_fieldname] = self.get(dimension.fetch_from_parent)
451
452 # Get value based on doctype name
453 if not sl_dict.get(dimension.target_fieldname):
454 fieldname = frappe.get_cached_value(
455 "DocField", {"parent": self.doctype, "options": dimension.fetch_from_parent}, "fieldname"
456 )
457
Rohit Waghchaure23729992022-09-02 18:43:55 +0530458 if not fieldname:
459 fieldname = frappe.get_cached_value(
460 "Custom Field", {"dt": self.doctype, "options": dimension.fetch_from_parent}, "fieldname"
461 )
462
Rohit Waghchaure0b39a012022-08-17 11:56:13 +0530463 if fieldname and self.get(fieldname):
464 sl_dict[dimension.target_fieldname] = self.get(fieldname)
465
Rohit Waghchaure75fcab02022-09-03 17:09:24 +0530466 if sl_dict[dimension.target_fieldname] and self.docstatus == 1:
467 row.db_set(dimension.source_fieldname, sl_dict[dimension.target_fieldname])
Rohit Waghchaure23729992022-09-02 18:43:55 +0530468
Ankush Menat494bd9e2022-03-28 18:52:46 +0530469 def make_sl_entries(self, sl_entries, allow_negative_stock=False, via_landed_cost_voucher=False):
Rushabh Mehta1f847992013-12-12 19:12:19 +0530470 from erpnext.stock.stock_ledger import make_sl_entries
Ankush Menat494bd9e2022-03-28 18:52:46 +0530471
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530472 make_sl_entries(sl_entries, allow_negative_stock, via_landed_cost_voucher)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530473
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530474 def make_gl_entries_on_cancel(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530475 if frappe.db.sql(
476 """select name from `tabGL Entry` where voucher_type=%s
477 and voucher_no=%s""",
478 (self.doctype, self.name),
479 ):
480 self.make_gl_entries()
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530481
Anand Doshia740f752014-06-25 13:31:02 +0530482 def get_serialized_items(self):
483 serialized_items = []
Ankush Menata9c84f72021-06-11 16:00:48 +0530484 item_codes = list(set(d.item_code for d in self.get("items")))
Anand Doshia740f752014-06-25 13:31:02 +0530485 if item_codes:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530486 serialized_items = frappe.db.sql_list(
487 """select name from `tabItem`
488 where has_serial_no=1 and name in ({})""".format(
489 ", ".join(["%s"] * len(item_codes))
490 ),
491 tuple(item_codes),
492 )
Anand Doshia740f752014-06-25 13:31:02 +0530493
494 return serialized_items
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +0530495
Saurabh2e292062015-11-18 17:03:33 +0530496 def validate_warehouse(self):
Rohan Bansal7f8b95e2021-04-14 14:12:03 +0530497 from erpnext.stock.utils import validate_disabled_warehouse, validate_warehouse_company
Saurabh2e292062015-11-18 17:03:33 +0530498
Ankush Menat494bd9e2022-03-28 18:52:46 +0530499 warehouses = list(set(d.warehouse for d in self.get("items") if getattr(d, "warehouse", None)))
Saurabh2e292062015-11-18 17:03:33 +0530500
Ankush Menat494bd9e2022-03-28 18:52:46 +0530501 target_warehouses = list(
502 set([d.target_warehouse for d in self.get("items") if getattr(d, "target_warehouse", None)])
503 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530504
505 warehouses.extend(target_warehouses)
506
Ankush Menat494bd9e2022-03-28 18:52:46 +0530507 from_warehouse = list(
508 set([d.from_warehouse for d in self.get("items") if getattr(d, "from_warehouse", None)])
509 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530510
511 warehouses.extend(from_warehouse)
512
Saurabh2e292062015-11-18 17:03:33 +0530513 for w in warehouses:
Jannat Patel30c88732021-02-11 11:46:48 +0530514 validate_disabled_warehouse(w)
Saurabh2e292062015-11-18 17:03:33 +0530515 validate_warehouse_company(w, self.company)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530516
Anand Doshi6b71ef52016-01-06 16:32:06 +0530517 def update_billing_percentage(self, update_modified=True):
marinationd6596a12020-11-02 15:07:48 +0530518 target_ref_field = "amount"
519 if self.doctype == "Delivery Note":
520 target_ref_field = "amount - (returned_qty * rate)"
521
Ankush Menat494bd9e2022-03-28 18:52:46 +0530522 self._update_percent_field(
523 {
524 "target_dt": self.doctype + " Item",
525 "target_parent_dt": self.doctype,
526 "target_parent_field": "per_billed",
527 "target_ref_field": target_ref_field,
528 "target_field": "billed_amt",
529 "name": self.name,
530 },
531 update_modified,
532 )
Anand Doshia740f752014-06-25 13:31:02 +0530533
Nabin Hait8af429d2016-11-16 17:21:59 +0530534 def validate_inspection(self):
marination9ac9a4e2021-06-21 16:18:35 +0530535 """Checks if quality inspection is set/ is valid for Items that require inspection."""
536 inspection_fieldname_map = {
537 "Purchase Receipt": "inspection_required_before_purchase",
538 "Purchase Invoice": "inspection_required_before_purchase",
539 "Sales Invoice": "inspection_required_before_delivery",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530540 "Delivery Note": "inspection_required_before_delivery",
marination9ac9a4e2021-06-21 16:18:35 +0530541 }
542 inspection_required_fieldname = inspection_fieldname_map.get(self.doctype)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530543
marination9ac9a4e2021-06-21 16:18:35 +0530544 # return if inspection is not required on document level
Ankush Menat494bd9e2022-03-28 18:52:46 +0530545 if (
546 (not inspection_required_fieldname and self.doctype != "Stock Entry")
547 or (self.doctype == "Stock Entry" and not self.inspection_required)
548 or (self.doctype in ["Sales Invoice", "Purchase Invoice"] and not self.update_stock)
549 ):
550 return
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530551
Ankush Menat494bd9e2022-03-28 18:52:46 +0530552 for row in self.get("items"):
marination9ac9a4e2021-06-21 16:18:35 +0530553 qi_required = False
Ankush Menat494bd9e2022-03-28 18:52:46 +0530554 if inspection_required_fieldname and frappe.db.get_value(
555 "Item", row.item_code, inspection_required_fieldname
556 ):
marination9ac9a4e2021-06-21 16:18:35 +0530557 qi_required = True
558 elif self.doctype == "Stock Entry" and row.t_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530559 qi_required = True # inward stock needs inspection
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530560
Ankush Menat494bd9e2022-03-28 18:52:46 +0530561 if qi_required: # validate row only if inspection is required on item level
marination9ac9a4e2021-06-21 16:18:35 +0530562 self.validate_qi_presence(row)
563 if self.docstatus == 1:
564 self.validate_qi_submission(row)
565 self.validate_qi_rejection(row)
566
567 def validate_qi_presence(self, row):
568 """Check if QI is present on row level. Warn on save and stop on submit if missing."""
569 if not row.quality_inspection:
marination654e9d82021-06-21 16:51:12 +0530570 msg = f"Row #{row.idx}: Quality Inspection is required for Item {frappe.bold(row.item_code)}"
marination9ac9a4e2021-06-21 16:18:35 +0530571 if self.docstatus == 1:
marination654e9d82021-06-21 16:51:12 +0530572 frappe.throw(_(msg), title=_("Inspection Required"), exc=QualityInspectionRequiredError)
marination9ac9a4e2021-06-21 16:18:35 +0530573 else:
marination654e9d82021-06-21 16:51:12 +0530574 frappe.msgprint(_(msg), title=_("Inspection Required"), indicator="blue")
marination9ac9a4e2021-06-21 16:18:35 +0530575
576 def validate_qi_submission(self, row):
577 """Check if QI is submitted on row level, during submission"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530578 action = frappe.db.get_single_value(
579 "Stock Settings", "action_if_quality_inspection_is_not_submitted"
580 )
marination9ac9a4e2021-06-21 16:18:35 +0530581 qa_docstatus = frappe.db.get_value("Quality Inspection", row.quality_inspection, "docstatus")
582
583 if not qa_docstatus == 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530584 link = frappe.utils.get_link_to_form("Quality Inspection", row.quality_inspection)
585 msg = (
586 f"Row #{row.idx}: Quality Inspection {link} is not submitted for the item: {row.item_code}"
587 )
marination9ac9a4e2021-06-21 16:18:35 +0530588 if action == "Stop":
marination654e9d82021-06-21 16:51:12 +0530589 frappe.throw(_(msg), title=_("Inspection Submission"), exc=QualityInspectionNotSubmittedError)
marination9ac9a4e2021-06-21 16:18:35 +0530590 else:
Marica9ba3fce2021-06-22 11:20:17 +0530591 frappe.msgprint(_(msg), alert=True, indicator="orange")
marination9ac9a4e2021-06-21 16:18:35 +0530592
593 def validate_qi_rejection(self, row):
594 """Check if QI is rejected on row level, during submission"""
marinationf67f13c2021-07-10 18:24:24 +0530595 action = frappe.db.get_single_value("Stock Settings", "action_if_quality_inspection_is_rejected")
marination9ac9a4e2021-06-21 16:18:35 +0530596 qa_status = frappe.db.get_value("Quality Inspection", row.quality_inspection, "status")
597
598 if qa_status == "Rejected":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530599 link = frappe.utils.get_link_to_form("Quality Inspection", row.quality_inspection)
marination654e9d82021-06-21 16:51:12 +0530600 msg = f"Row #{row.idx}: Quality Inspection {link} was rejected for item {row.item_code}"
marination9ac9a4e2021-06-21 16:18:35 +0530601 if action == "Stop":
marination654e9d82021-06-21 16:51:12 +0530602 frappe.throw(_(msg), title=_("Inspection Rejected"), exc=QualityInspectionRejectedError)
marination9ac9a4e2021-06-21 16:18:35 +0530603 else:
marination654e9d82021-06-21 16:51:12 +0530604 frappe.msgprint(_(msg), alert=True, indicator="orange")
Manas Solankicc902412016-11-10 19:15:11 +0530605
Nabin Haitb2d3c0f2018-06-14 15:54:34 +0530606 def update_blanket_order(self):
Nabin Haitd1f40ad2018-06-14 17:09:55 +0530607 blanket_orders = list(set([d.blanket_order for d in self.items if d.blanket_order]))
Nabin Haitb2d3c0f2018-06-14 15:54:34 +0530608 for blanket_order in blanket_orders:
609 frappe.get_doc("Blanket Order", blanket_order).update_ordered_qty()
Manas Solankie5e87f72018-05-28 20:07:08 +0530610
marinationfd04e962020-04-03 15:46:48 +0530611 def validate_customer_provided_item(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530612 for d in self.get("items"):
marinationfd04e962020-04-03 15:46:48 +0530613 # Customer Provided parts will have zero valuation rate
Ankush Menat494bd9e2022-03-28 18:52:46 +0530614 if frappe.db.get_value("Item", d.item_code, "is_customer_provided_item"):
marinationfd04e962020-04-03 15:46:48 +0530615 d.allow_zero_valuation_rate = 1
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530616
Anupam Kumar7e1dcf92021-02-11 20:19:30 +0530617 def set_rate_of_stock_uom(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530618 if self.doctype in [
619 "Purchase Receipt",
620 "Purchase Invoice",
621 "Purchase Order",
622 "Sales Invoice",
623 "Sales Order",
624 "Delivery Note",
625 "Quotation",
626 ]:
Anupam Kumar7e1dcf92021-02-11 20:19:30 +0530627 for d in self.get("items"):
Rohit Waghchaure13584432021-03-26 14:11:50 +0530628 d.stock_uom_rate = d.rate / (d.conversion_factor or 1)
Anupam Kumar7e1dcf92021-02-11 20:19:30 +0530629
Deepesh Gargb4be2922021-01-28 13:09:56 +0530630 def validate_internal_transfer(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530631 if (
632 self.doctype in ("Sales Invoice", "Delivery Note", "Purchase Invoice", "Purchase Receipt")
633 and self.is_internal_transfer()
634 ):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530635 self.validate_in_transit_warehouses()
636 self.validate_multi_currency()
637 self.validate_packed_items()
638
639 def validate_in_transit_warehouses(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530640 if (
641 self.doctype == "Sales Invoice" and self.get("update_stock")
642 ) or self.doctype == "Delivery Note":
643 for item in self.get("items"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530644 if not item.target_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530645 frappe.throw(
646 _("Row {0}: Target Warehouse is mandatory for internal transfers").format(item.idx)
647 )
Deepesh Gargb4be2922021-01-28 13:09:56 +0530648
Ankush Menat494bd9e2022-03-28 18:52:46 +0530649 if (
650 self.doctype == "Purchase Invoice" and self.get("update_stock")
651 ) or self.doctype == "Purchase Receipt":
652 for item in self.get("items"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530653 if not item.from_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530654 frappe.throw(
655 _("Row {0}: From Warehouse is mandatory for internal transfers").format(item.idx)
656 )
Deepesh Gargb4be2922021-01-28 13:09:56 +0530657
658 def validate_multi_currency(self):
659 if self.currency != self.company_currency:
660 frappe.throw(_("Internal transfers can only be done in company's default currency"))
661
662 def validate_packed_items(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530663 if self.doctype in ("Sales Invoice", "Delivery Note Item") and self.get("packed_items"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530664 frappe.throw(_("Packed Items cannot be transferred internally"))
665
marinationfac40352020-12-07 21:35:49 +0530666 def validate_putaway_capacity(self):
667 # if over receipt is attempted while 'apply putaway rule' is disabled
668 # and if rule was applied on the transaction, validate it.
marination957615b2021-01-18 23:47:24 +0530669 from erpnext.stock.doctype.putaway_rule.putaway_rule import get_available_putaway_capacity
Ankush Menat494bd9e2022-03-28 18:52:46 +0530670
671 valid_doctype = self.doctype in (
672 "Purchase Receipt",
673 "Stock Entry",
674 "Purchase Invoice",
675 "Stock Reconciliation",
676 )
marinationfac40352020-12-07 21:35:49 +0530677
marination957615b2021-01-18 23:47:24 +0530678 if self.doctype == "Purchase Invoice" and self.get("update_stock") == 0:
679 valid_doctype = False
680
681 if valid_doctype:
marinationfac40352020-12-07 21:35:49 +0530682 rule_map = defaultdict(dict)
683 for item in self.get("items"):
marination957615b2021-01-18 23:47:24 +0530684 warehouse_field = "t_warehouse" if self.doctype == "Stock Entry" else "warehouse"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530685 rule = frappe.db.get_value(
686 "Putaway Rule",
687 {"item_code": item.get("item_code"), "warehouse": item.get(warehouse_field)},
688 ["name", "disable"],
689 as_dict=True,
690 )
marination957615b2021-01-18 23:47:24 +0530691 if rule:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530692 if rule.get("disabled"):
693 continue # dont validate for disabled rule
marination957615b2021-01-18 23:47:24 +0530694
695 if self.doctype == "Stock Reconciliation":
696 stock_qty = flt(item.qty)
697 else:
698 stock_qty = flt(item.transfer_qty) if self.doctype == "Stock Entry" else flt(item.stock_qty)
699
700 rule_name = rule.get("name")
701 if not rule_map[rule_name]:
702 rule_map[rule_name]["warehouse"] = item.get(warehouse_field)
703 rule_map[rule_name]["item"] = item.get("item_code")
704 rule_map[rule_name]["qty_put"] = 0
705 rule_map[rule_name]["capacity"] = get_available_putaway_capacity(rule_name)
706 rule_map[rule_name]["qty_put"] += flt(stock_qty)
marinationfac40352020-12-07 21:35:49 +0530707
708 for rule, values in rule_map.items():
709 if flt(values["qty_put"]) > flt(values["capacity"]):
marination957615b2021-01-18 23:47:24 +0530710 message = self.prepare_over_receipt_message(rule, values)
marinationfac40352020-12-07 21:35:49 +0530711 frappe.throw(msg=message, title=_("Over Receipt"))
marination957615b2021-01-18 23:47:24 +0530712
713 def prepare_over_receipt_message(self, rule, values):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530714 message = _(
715 "{0} qty of Item {1} is being received into Warehouse {2} with capacity {3}."
716 ).format(
717 frappe.bold(values["qty_put"]),
718 frappe.bold(values["item"]),
719 frappe.bold(values["warehouse"]),
720 frappe.bold(values["capacity"]),
721 )
marination957615b2021-01-18 23:47:24 +0530722 message += "<br><br>"
723 rule_link = frappe.utils.get_link_to_form("Putaway Rule", rule)
Ankush Menatad6a2652021-04-17 16:50:02 +0530724 message += _("Please adjust the qty or edit {0} to proceed.").format(rule_link)
marination957615b2021-01-18 23:47:24 +0530725 return message
marinationfac40352020-12-07 21:35:49 +0530726
Nabin Haita77b8c92020-12-21 14:45:50 +0530727 def repost_future_sle_and_gle(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530728 args = frappe._dict(
729 {
730 "posting_date": self.posting_date,
731 "posting_time": self.posting_time,
732 "voucher_type": self.doctype,
733 "voucher_no": self.name,
734 "company": self.company,
735 }
736 )
Ankush Menat3638fbf2022-03-01 18:17:14 +0530737
738 if future_sle_exists(args) or repost_required_for_queue(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530739 item_based_reposting = cint(
740 frappe.db.get_single_value("Stock Reposting Settings", "item_based_reposting")
741 )
Ankush Menat45dd46b2021-11-02 10:50:52 +0530742 if item_based_reposting:
743 create_item_wise_repost_entries(voucher_type=self.doctype, voucher_no=self.name)
744 else:
745 create_repost_item_valuation_entry(args)
746
Sagar Sharmaf4673942022-08-21 21:26:06 +0530747 def add_gl_entry(
748 self,
749 gl_entries,
750 account,
751 cost_center,
752 debit,
753 credit,
754 remarks,
755 against_account,
756 debit_in_account_currency=None,
757 credit_in_account_currency=None,
758 account_currency=None,
759 project=None,
760 voucher_detail_no=None,
761 item=None,
762 posting_date=None,
763 ):
764
765 gl_entry = {
766 "account": account,
767 "cost_center": cost_center,
768 "debit": debit,
769 "credit": credit,
770 "against": against_account,
771 "remarks": remarks,
772 }
773
774 if voucher_detail_no:
775 gl_entry.update({"voucher_detail_no": voucher_detail_no})
776
777 if debit_in_account_currency:
778 gl_entry.update({"debit_in_account_currency": debit_in_account_currency})
779
780 if credit_in_account_currency:
781 gl_entry.update({"credit_in_account_currency": credit_in_account_currency})
782
783 if posting_date:
784 gl_entry.update({"posting_date": posting_date})
785
786 gl_entries.append(self.get_gl_dict(gl_entry, item=item))
787
Ankush Menat494bd9e2022-03-28 18:52:46 +0530788
Ankush Menat3638fbf2022-03-01 18:17:14 +0530789def repost_required_for_queue(doc: StockController) -> bool:
790 """check if stock document contains repeated item-warehouse with queue based valuation.
791
792 if queue exists for repeated items then SLEs need to reprocessed in background again.
793 """
794
Ankush Menat494bd9e2022-03-28 18:52:46 +0530795 consuming_sles = frappe.db.get_all(
796 "Stock Ledger Entry",
Ankush Menat3638fbf2022-03-01 18:17:14 +0530797 filters={
798 "voucher_type": doc.doctype,
799 "voucher_no": doc.name,
800 "actual_qty": ("<", 0),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530801 "is_cancelled": 0,
Ankush Menat3638fbf2022-03-01 18:17:14 +0530802 },
Ankush Menat494bd9e2022-03-28 18:52:46 +0530803 fields=["item_code", "warehouse", "stock_queue"],
Ankush Menat3638fbf2022-03-01 18:17:14 +0530804 )
805 item_warehouses = [(sle.item_code, sle.warehouse) for sle in consuming_sles]
806
807 unique_item_warehouses = set(item_warehouses)
808
809 if len(unique_item_warehouses) == len(item_warehouses):
810 return False
811
812 for sle in consuming_sles:
813 if sle.stock_queue != "[]": # using FIFO/LIFO valuation
814 return True
815 return False
816
Nabin Hait19f8fa52021-02-22 22:27:22 +0530817
Rohan Bansal7f8b95e2021-04-14 14:12:03 +0530818@frappe.whitelist()
819def make_quality_inspections(doctype, docname, items):
Rohan Bansala06ec032021-06-02 14:55:31 +0530820 if isinstance(items, str):
821 items = json.loads(items)
Rohan Bansal7f8b95e2021-04-14 14:12:03 +0530822
Rohan Bansala06ec032021-06-02 14:55:31 +0530823 inspections = []
Rohan Bansal7f8b95e2021-04-14 14:12:03 +0530824 for item in items:
Rohan Bansal1cdf5a02021-05-26 14:42:15 +0530825 if flt(item.get("sample_size")) > flt(item.get("qty")):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530826 frappe.throw(
827 _(
828 "{item_name}'s Sample Size ({sample_size}) cannot be greater than the Accepted Quantity ({accepted_quantity})"
829 ).format(
830 item_name=item.get("item_name"),
831 sample_size=item.get("sample_size"),
832 accepted_quantity=item.get("qty"),
833 )
834 )
Rohan Bansal7f8b95e2021-04-14 14:12:03 +0530835
Ankush Menat494bd9e2022-03-28 18:52:46 +0530836 quality_inspection = frappe.get_doc(
837 {
838 "doctype": "Quality Inspection",
839 "inspection_type": "Incoming",
840 "inspected_by": frappe.session.user,
841 "reference_type": doctype,
842 "reference_name": docname,
843 "item_code": item.get("item_code"),
844 "description": item.get("description"),
845 "sample_size": flt(item.get("sample_size")),
846 "item_serial_no": item.get("serial_no").split("\n")[0] if item.get("serial_no") else None,
847 "batch_no": item.get("batch_no"),
848 }
849 ).insert()
Rohan Bansal7f8b95e2021-04-14 14:12:03 +0530850 quality_inspection.save()
Rohan Bansal1cdf5a02021-05-26 14:42:15 +0530851 inspections.append(quality_inspection.name)
Rohan Bansal7f8b95e2021-04-14 14:12:03 +0530852
Rohan Bansal1cdf5a02021-05-26 14:42:15 +0530853 return inspections
Rohan Bansal7f8b95e2021-04-14 14:12:03 +0530854
Ankush Menat494bd9e2022-03-28 18:52:46 +0530855
Nabin Haitb99c77b2020-12-25 18:12:35 +0530856def is_reposting_pending():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530857 return frappe.db.exists(
858 "Repost Item Valuation", {"docstatus": 1, "status": ["in", ["Queued", "In Progress"]]}
859 )
860
Nabin Haitb99c77b2020-12-25 18:12:35 +0530861
Rohit Waghchaure8520edc2021-06-15 10:21:44 +0530862def future_sle_exists(args, sl_entries=None):
863 key = (args.voucher_type, args.voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530864
Rohit Waghchaure8520edc2021-06-15 10:21:44 +0530865 if validate_future_sle_not_exists(args, key, sl_entries):
866 return False
867 elif get_cached_data(args, key):
868 return True
869
870 if not sl_entries:
871 sl_entries = get_sle_entries_against_voucher(args)
872 if not sl_entries:
873 return
874
875 or_conditions = get_conditions_to_validate_future_sle(sl_entries)
876
Ankush Menat494bd9e2022-03-28 18:52:46 +0530877 data = frappe.db.sql(
878 """
Rohit Waghchaure8520edc2021-06-15 10:21:44 +0530879 select item_code, warehouse, count(name) as total_row
Deepesh Garg6f107da2021-10-12 20:15:55 +0530880 from `tabStock Ledger Entry` force index (item_warehouse)
Rohit Waghchaure8520edc2021-06-15 10:21:44 +0530881 where
882 ({})
883 and timestamp(posting_date, posting_time)
884 >= timestamp(%(posting_date)s, %(posting_time)s)
885 and voucher_no != %(voucher_no)s
886 and is_cancelled = 0
887 GROUP BY
888 item_code, warehouse
Ankush Menat494bd9e2022-03-28 18:52:46 +0530889 """.format(
890 " or ".join(or_conditions)
891 ),
892 args,
893 as_dict=1,
894 )
Rohit Waghchaure8520edc2021-06-15 10:21:44 +0530895
896 for d in data:
897 frappe.local.future_sle[key][(d.item_code, d.warehouse)] = d.total_row
898
899 return len(data)
900
Rohit Waghchaure8520edc2021-06-15 10:21:44 +0530901
Ankush Menat494bd9e2022-03-28 18:52:46 +0530902def validate_future_sle_not_exists(args, key, sl_entries=None):
903 item_key = ""
904 if args.get("item_code"):
905 item_key = (args.get("item_code"), args.get("warehouse"))
906
907 if not sl_entries and hasattr(frappe.local, "future_sle"):
908 if not frappe.local.future_sle.get(key) or (
909 item_key and item_key not in frappe.local.future_sle.get(key)
910 ):
Rohit Waghchaure8520edc2021-06-15 10:21:44 +0530911 return True
912
Ankush Menat494bd9e2022-03-28 18:52:46 +0530913
Rohit Waghchaure8520edc2021-06-15 10:21:44 +0530914def get_cached_data(args, key):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530915 if not hasattr(frappe.local, "future_sle"):
Rohit Waghchaure8520edc2021-06-15 10:21:44 +0530916 frappe.local.future_sle = {}
917
918 if key not in frappe.local.future_sle:
919 frappe.local.future_sle[key] = frappe._dict({})
920
Ankush Menat494bd9e2022-03-28 18:52:46 +0530921 if args.get("item_code"):
922 item_key = (args.get("item_code"), args.get("warehouse"))
Rohit Waghchaure8520edc2021-06-15 10:21:44 +0530923 count = frappe.local.future_sle[key].get(item_key)
924
925 return True if (count or count == 0) else False
926 else:
927 return frappe.local.future_sle[key]
928
Ankush Menat494bd9e2022-03-28 18:52:46 +0530929
Rohit Waghchaure8520edc2021-06-15 10:21:44 +0530930def get_sle_entries_against_voucher(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530931 return frappe.get_all(
932 "Stock Ledger Entry",
Nabin Haita77b8c92020-12-21 14:45:50 +0530933 filters={"voucher_type": args.voucher_type, "voucher_no": args.voucher_no},
934 fields=["item_code", "warehouse"],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530935 order_by="creation asc",
936 )
937
Nabin Haita77b8c92020-12-21 14:45:50 +0530938
Rohit Waghchaure8520edc2021-06-15 10:21:44 +0530939def get_conditions_to_validate_future_sle(sl_entries):
Sagar Vora868c0bf2021-03-27 16:10:20 +0530940 warehouse_items_map = {}
941 for entry in sl_entries:
942 if entry.warehouse not in warehouse_items_map:
943 warehouse_items_map[entry.warehouse] = set()
Nabin Haita77b8c92020-12-21 14:45:50 +0530944
Sagar Vora868c0bf2021-03-27 16:10:20 +0530945 warehouse_items_map[entry.warehouse].add(entry.item_code)
946
947 or_conditions = []
948 for warehouse, items in warehouse_items_map.items():
949 or_conditions.append(
Noah Jacobb5a14912021-06-15 12:44:04 +0530950 f"""warehouse = {frappe.db.escape(warehouse)}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530951 and item_code in ({', '.join(frappe.db.escape(item) for item in items)})"""
952 )
Sagar Vora868c0bf2021-03-27 16:10:20 +0530953
Rohit Waghchaure8520edc2021-06-15 10:21:44 +0530954 return or_conditions
Nabin Haita77b8c92020-12-21 14:45:50 +0530955
Ankush Menat494bd9e2022-03-28 18:52:46 +0530956
Nabin Haita77b8c92020-12-21 14:45:50 +0530957def create_repost_item_valuation_entry(args):
958 args = frappe._dict(args)
959 repost_entry = frappe.new_doc("Repost Item Valuation")
960 repost_entry.based_on = args.based_on
961 if not args.based_on:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530962 repost_entry.based_on = "Transaction" if args.voucher_no else "Item and Warehouse"
Nabin Haita77b8c92020-12-21 14:45:50 +0530963 repost_entry.voucher_type = args.voucher_type
964 repost_entry.voucher_no = args.voucher_no
965 repost_entry.item_code = args.item_code
966 repost_entry.warehouse = args.warehouse
967 repost_entry.posting_date = args.posting_date
968 repost_entry.posting_time = args.posting_time
969 repost_entry.company = args.company
970 repost_entry.allow_zero_rate = args.allow_zero_rate
971 repost_entry.flags.ignore_links = True
Ankush Menataa024fc2021-11-18 12:51:26 +0530972 repost_entry.flags.ignore_permissions = True
Nabin Haita77b8c92020-12-21 14:45:50 +0530973 repost_entry.save()
Sagar Vora868c0bf2021-03-27 16:10:20 +0530974 repost_entry.submit()
Ankush Menat6dc9b822021-10-28 15:53:18 +0530975
976
977def create_item_wise_repost_entries(voucher_type, voucher_no, allow_zero_rate=False):
978 """Using a voucher create repost item valuation records for all item-warehouse pairs."""
979
Ankush Menatd220e082021-10-28 17:47:00 +0530980 stock_ledger_entries = get_items_to_be_repost(voucher_type, voucher_no)
981
Ankush Menat6dc9b822021-10-28 15:53:18 +0530982 distinct_item_warehouses = set()
Ankush Menat6dc9b822021-10-28 15:53:18 +0530983 repost_entries = []
984
985 for sle in stock_ledger_entries:
986 item_wh = (sle.item_code, sle.warehouse)
987 if item_wh in distinct_item_warehouses:
988 continue
989 distinct_item_warehouses.add(item_wh)
990
991 repost_entry = frappe.new_doc("Repost Item Valuation")
992 repost_entry.based_on = "Item and Warehouse"
993 repost_entry.voucher_type = voucher_type
994 repost_entry.voucher_no = voucher_no
995
996 repost_entry.item_code = sle.item_code
997 repost_entry.warehouse = sle.warehouse
998 repost_entry.posting_date = sle.posting_date
999 repost_entry.posting_time = sle.posting_time
1000 repost_entry.allow_zero_rate = allow_zero_rate
1001 repost_entry.flags.ignore_links = True
Ankush Menat0a2964d2021-11-24 15:55:31 +05301002 repost_entry.flags.ignore_permissions = True
Ankush Menat6dc9b822021-10-28 15:53:18 +05301003 repost_entry.submit()
1004 repost_entries.append(repost_entry)
1005
1006 return repost_entries