blob: 335f2b0ea68477f6428ac374dd16ccc095e08b0f [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 _
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)
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(
Daizy Modi4efc9472022-11-07 09:21:03 +053060 frappe.get_cached_value(
Ankush Menat494bd9e2022-03-28 18:52:46 +053061 "Company", self.company, "enable_provisional_accounting_for_non_stock_items"
62 )
63 )
Deepesh Garg528c7132022-02-01 14:42:55 +053064
Deepesh Gargd1ec0a62023-10-23 00:16:40 +053065 is_asset_pr = any(d.get("is_fixed_asset") for d in self.get("items"))
66
Ankush Menat494bd9e2022-03-28 18:52:46 +053067 if (
68 cint(erpnext.is_perpetual_inventory_enabled(self.company))
69 or provisional_accounting_for_non_stock_items
Deepesh Gargd1ec0a62023-10-23 00:16:40 +053070 or is_asset_pr
Ankush Menat494bd9e2022-03-28 18:52:46 +053071 ):
Rohit Waghchaure6b33c9b2019-03-08 11:13:35 +053072 warehouse_account = get_warehouse_account_map(self.company)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053073
Ankush Menat494bd9e2022-03-28 18:52:46 +053074 if self.docstatus == 1:
Nabin Hait9784d272016-12-30 16:21:35 +053075 if not gl_entries:
76 gl_entries = self.get_gl_entries(warehouse_account)
Nabin Haita77b8c92020-12-21 14:45:50 +053077 make_gl_entries(gl_entries, from_repost=from_repost)
Nabin Hait145e5e22013-10-22 23:51:41 +053078
rohitwaghchaure9af557f2019-12-30 13:26:47 +053079 def validate_serialized_batch(self):
80 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
Ankush Menat494bd9e2022-03-28 18:52:46 +053081
Rohit Waghchaure795c9432022-08-17 13:48:56 +053082 is_material_issue = False
83 if self.doctype == "Stock Entry" and self.purpose == "Material Issue":
84 is_material_issue = True
85
rohitwaghchaure9af557f2019-12-30 13:26:47 +053086 for d in self.get("items"):
Ankush Menat494bd9e2022-03-28 18:52:46 +053087 if hasattr(d, "serial_no") and hasattr(d, "batch_no") and d.serial_no and d.batch_no:
88 serial_nos = frappe.get_all(
89 "Serial No",
Rohit Waghchaure6b482eb2021-07-23 16:40:45 +053090 fields=["batch_no", "name", "warehouse"],
Ankush Menat494bd9e2022-03-28 18:52:46 +053091 filters={"name": ("in", get_serial_nos(d.serial_no))},
Rohit Waghchaure6b482eb2021-07-23 16:40:45 +053092 )
93
94 for row in serial_nos:
95 if row.warehouse and row.batch_no != d.batch_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +053096 frappe.throw(
97 _("Row #{0}: Serial No {1} does not belong to Batch {2}").format(
98 d.idx, row.name, d.batch_no
99 )
100 )
rohitwaghchaure9af557f2019-12-30 13:26:47 +0530101
Rohit Waghchaure795c9432022-08-17 13:48:56 +0530102 if is_material_issue:
103 continue
104
Saqib Ansari903055b2020-10-20 11:59:06 +0530105 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 +0530106 expiry_date = frappe.get_cached_value("Batch", d.get("batch_no"), "expiry_date")
107
108 if expiry_date and getdate(expiry_date) < getdate(self.posting_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530109 frappe.throw(
110 _("Row #{0}: The batch {1} has already expired.").format(
111 d.idx, get_link_to_form("Batch", d.get("batch_no"))
Rohit Waghchaure795c9432022-08-17 13:48:56 +0530112 ),
113 BatchExpiredError,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530114 )
rohitwaghchaure28a48802020-04-28 13:01:43 +0530115
marinationeecfc4c2021-07-22 13:23:54 +0530116 def clean_serial_nos(self):
Ankush Menatb20df372022-01-24 19:19:58 +0530117 from erpnext.stock.doctype.serial_no.serial_no import clean_serial_no_string
118
marinationeecfc4c2021-07-22 13:23:54 +0530119 for row in self.get("items"):
120 if hasattr(row, "serial_no") and row.serial_no:
Ankush Menatb20df372022-01-24 19:19:58 +0530121 # remove extra whitespace and store one serial no on each line
122 row.serial_no = clean_serial_no_string(row.serial_no)
marinationeecfc4c2021-07-22 13:23:54 +0530123
Ankush Menat494bd9e2022-03-28 18:52:46 +0530124 for row in self.get("packed_items") or []:
Ankush Menate177c522022-01-24 19:28:26 +0530125 if hasattr(row, "serial_no") and row.serial_no:
126 # remove extra whitespace and store one serial no on each line
127 row.serial_no = clean_serial_no_string(row.serial_no)
128
Ankush Menat494bd9e2022-03-28 18:52:46 +0530129 def get_gl_entries(
130 self, warehouse_account=None, default_expense_account=None, default_cost_center=None
131 ):
Nabin Haitadeb9762014-10-06 11:53:52 +0530132
Nabin Hait142007a2013-09-17 15:15:16 +0530133 if not warehouse_account:
Rohit Waghchaure6b33c9b2019-03-08 11:13:35 +0530134 warehouse_account = get_warehouse_account_map(self.company)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530135
Anand Doshide1a97d2014-04-17 11:37:46 +0530136 sle_map = self.get_stock_ledger_details()
137 voucher_details = self.get_voucher_details(default_expense_account, default_cost_center, sle_map)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530138
Nabin Hait2e296fa2013-08-28 18:53:11 +0530139 gl_list = []
Nabin Hait7a75e102013-09-17 10:21:20 +0530140 warehouse_with_no_account = []
Nabin Hait19f8fa52021-02-22 22:27:22 +0530141 precision = self.get_debit_field_precision()
Nabin Hait8c61f342016-12-15 13:46:03 +0530142 for item_row in voucher_details:
143 sle_list = sle_map.get(item_row.name)
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530144 sle_rounding_diff = 0.0
Nabin Hait2e296fa2013-08-28 18:53:11 +0530145 if sle_list:
146 for sle in sle_list:
147 if warehouse_account.get(sle.warehouse):
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530148 # from warehouse account
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530149
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530150 sle_rounding_diff += flt(sle.stock_value_difference)
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530151
Nabin Hait8c61f342016-12-15 13:46:03 +0530152 self.check_expense_account(item_row)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530153
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530154 # expense account/ target_warehouse / source_warehouse
Ankush Menat494bd9e2022-03-28 18:52:46 +0530155 if item_row.get("target_warehouse"):
156 warehouse = item_row.get("target_warehouse")
Deepesh Gargf17ea2c2020-12-11 21:30:39 +0530157 expense_account = warehouse_account[warehouse]["account"]
158 else:
159 expense_account = item_row.expense_account
160
Ankush Menat494bd9e2022-03-28 18:52:46 +0530161 gl_list.append(
162 self.get_gl_dict(
163 {
164 "account": warehouse_account[sle.warehouse]["account"],
Gursheen Anand4ea43eb2023-09-25 20:01:13 +0530165 "against_type": "Account",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530166 "against": expense_account,
167 "cost_center": item_row.cost_center,
168 "project": item_row.project or self.get("project"),
169 "remarks": self.get("remarks") or _("Accounting Entry for Stock"),
170 "debit": flt(sle.stock_value_difference, precision),
171 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
172 },
173 warehouse_account[sle.warehouse]["account_currency"],
174 item=item_row,
175 )
176 )
Nabin Hait27994c22013-08-26 16:53:30 +0530177
Ankush Menat494bd9e2022-03-28 18:52:46 +0530178 gl_list.append(
179 self.get_gl_dict(
180 {
181 "account": expense_account,
Gursheen Anand4ea43eb2023-09-25 20:01:13 +0530182 "against_type": "Account",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530183 "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 Garg9aa5e202022-10-12 15:53:28 +0530196 if abs(sle_rounding_diff) > (1.0 / (10**precision)) and self.is_internal_transfer():
Deepesh Garg1c05c002022-10-12 14:19:09 +0530197 warehouse_asset_account = ""
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530198 if self.get("is_internal_customer"):
Deepesh Garg1c05c002022-10-12 14:19:09 +0530199 warehouse_asset_account = warehouse_account[item_row.get("target_warehouse")]["account"]
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530200 elif self.get("is_internal_supplier"):
Deepesh Garg1c05c002022-10-12 14:19:09 +0530201 warehouse_asset_account = warehouse_account[item_row.get("warehouse")]["account"]
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530202
Daizy Modi4efc9472022-11-07 09:21:03 +0530203 expense_account = frappe.get_cached_value("Company", self.company, "default_expense_account")
Deepesh Gargce9164e2023-07-11 12:03:38 +0530204 if not expense_account:
205 frappe.throw(
206 _(
207 "Please set default cost of goods sold account in company {0} for booking rounding gain and loss during stock transfer"
208 ).format(frappe.bold(self.company))
209 )
Deepesh Garg1c05c002022-10-12 14:19:09 +0530210
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530211 gl_list.append(
212 self.get_gl_dict(
213 {
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530214 "account": expense_account,
Gursheen Anand4ea43eb2023-09-25 20:01:13 +0530215 "against_type": "Account",
Deepesh Garg1c05c002022-10-12 14:19:09 +0530216 "against": warehouse_asset_account,
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530217 "cost_center": item_row.cost_center,
218 "project": item_row.project or self.get("project"),
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530219 "remarks": _("Rounding gain/loss Entry for Stock Transfer"),
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530220 "debit": sle_rounding_diff,
221 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
222 },
223 warehouse_account[sle.warehouse]["account_currency"],
224 item=item_row,
225 )
226 )
227
228 gl_list.append(
229 self.get_gl_dict(
230 {
Deepesh Garg1c05c002022-10-12 14:19:09 +0530231 "account": warehouse_asset_account,
Gursheen Anand4ea43eb2023-09-25 20:01:13 +0530232 "against_type": "Account",
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530233 "against": expense_account,
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530234 "cost_center": item_row.cost_center,
Deepesh Gargdf2a0e22022-10-11 14:55:09 +0530235 "remarks": _("Rounding gain/loss Entry for Stock Transfer"),
236 "credit": sle_rounding_diff,
Deepesh Garg6e47fd52022-09-26 21:15:57 +0530237 "project": item_row.get("project") or self.get("project"),
238 "is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
239 },
240 item=item_row,
241 )
242 )
243
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530244 if warehouse_with_no_account:
Nabin Haitd6625022016-10-24 18:17:57 +0530245 for wh in warehouse_with_no_account:
Daizy Modi4efc9472022-11-07 09:21:03 +0530246 if frappe.get_cached_value("Warehouse", wh, "company"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530247 frappe.throw(
248 _(
249 "Warehouse {0} is not linked to any account, please mention the account in the warehouse record or set default inventory account in company {1}."
250 ).format(wh, self.company)
251 )
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530252
Nabin Hait19f8fa52021-02-22 22:27:22 +0530253 return process_gl_map(gl_list, precision=precision)
254
255 def get_debit_field_precision(self):
256 if not frappe.flags.debit_field_precision:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530257 frappe.flags.debit_field_precision = frappe.get_precision(
258 "GL Entry", "debit_in_account_currency"
259 )
Nabin Hait19f8fa52021-02-22 22:27:22 +0530260
261 return frappe.flags.debit_field_precision
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530262
Anand Doshide1a97d2014-04-17 11:37:46 +0530263 def get_voucher_details(self, default_expense_account, default_cost_center, sle_map):
264 if self.doctype == "Stock Reconciliation":
Nabin Hait3f119ec2019-05-16 17:28:39 +0530265 reconciliation_purpose = frappe.db.get_value(self.doctype, self.name, "purpose")
266 is_opening = "Yes" if reconciliation_purpose == "Opening Stock" else "No"
267 details = []
Nabin Hait34c551d2019-07-03 10:34:31 +0530268 for voucher_detail_no in sle_map:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530269 details.append(
270 frappe._dict(
271 {
272 "name": voucher_detail_no,
273 "expense_account": default_expense_account,
274 "cost_center": default_cost_center,
275 "is_opening": is_opening,
276 }
277 )
278 )
Nabin Hait3f119ec2019-05-16 17:28:39 +0530279 return details
Anand Doshide1a97d2014-04-17 11:37:46 +0530280 else:
Nabin Haitdd38a262014-12-26 13:15:21 +0530281 details = self.get("items")
Anand Doshi094610d2014-04-16 19:56:53 +0530282
Anand Doshide1a97d2014-04-17 11:37:46 +0530283 if default_expense_account or default_cost_center:
284 for d in details:
285 if default_expense_account and not d.get("expense_account"):
286 d.expense_account = default_expense_account
287 if default_cost_center and not d.get("cost_center"):
288 d.cost_center = default_cost_center
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530289
Anand Doshide1a97d2014-04-17 11:37:46 +0530290 return details
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530291
Ankush Menate6ab8df2022-02-06 13:02:34 +0530292 def get_items_and_warehouses(self) -> Tuple[List[str], List[str]]:
293 """Get list of items and warehouses affected by a transaction"""
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530294
Ankush Menate6ab8df2022-02-06 13:02:34 +0530295 if not (hasattr(self, "items") or hasattr(self, "packed_items")):
296 return [], []
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530297
Ankush Menate6ab8df2022-02-06 13:02:34 +0530298 item_rows = (self.get("items") or []) + (self.get("packed_items") or [])
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530299
Ankush Menate6ab8df2022-02-06 13:02:34 +0530300 items = {d.item_code for d in item_rows if d.item_code}
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530301
Ankush Menate6ab8df2022-02-06 13:02:34 +0530302 warehouses = set()
303 for d in item_rows:
304 if d.get("warehouse"):
305 warehouses.add(d.warehouse)
Nabin Haitbecf75d2014-03-27 17:18:29 +0530306
Ankush Menate6ab8df2022-02-06 13:02:34 +0530307 if self.doctype == "Stock Entry":
308 if d.get("s_warehouse"):
309 warehouses.add(d.s_warehouse)
310 if d.get("t_warehouse"):
311 warehouses.add(d.t_warehouse)
312
313 return list(items), list(warehouses)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530314
Nabin Hait2e296fa2013-08-28 18:53:11 +0530315 def get_stock_ledger_details(self):
316 stock_ledger = {}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530317 stock_ledger_entries = frappe.db.sql(
318 """
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530319 select
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530320 name, warehouse, stock_value_difference, valuation_rate,
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530321 voucher_detail_no, item_code, posting_date, posting_time,
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530322 actual_qty, qty_after_transaction
Nabin Haitea8fab52017-02-06 17:13:39 +0530323 from
324 `tabStock Ledger Entry`
325 where
Ankush Menat0ca60af2022-02-08 10:24:19 +0530326 voucher_type=%s and voucher_no=%s and is_cancelled = 0
Ankush Menat494bd9e2022-03-28 18:52:46 +0530327 """,
328 (self.doctype, self.name),
329 as_dict=True,
330 )
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530331
Nabin Haitea8fab52017-02-06 17:13:39 +0530332 for sle in stock_ledger_entries:
Deepesh Gargb4be2922021-01-28 13:09:56 +0530333 stock_ledger.setdefault(sle.voucher_detail_no, []).append(sle)
Nabin Hait2e296fa2013-08-28 18:53:11 +0530334 return stock_ledger
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530335
Nabin Hait27994c22013-08-26 16:53:30 +0530336 def check_expense_account(self, item):
Rushabh Mehta052fe822014-04-16 19:20:11 +0530337 if not item.get("expense_account"):
Rohit Waghchaureceab6922020-11-18 17:57:35 +0530338 msg = _("Please set an Expense Account in the Items table")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530339 frappe.throw(
340 _("Row #{0}: Expense Account not set for the Item {1}. {2}").format(
341 item.idx, frappe.bold(item.item_code), msg
342 ),
343 title=_("Expense Account Missing"),
344 )
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530345
Anand Doshi496123a2014-06-19 19:25:19 +0530346 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530347 is_expense_account = (
348 frappe.get_cached_value("Account", item.get("expense_account"), "report_type")
349 == "Profit and Loss"
350 )
351 if (
352 self.doctype
Sagar Sharma2d04e712022-08-17 15:57:41 +0530353 not in (
354 "Purchase Receipt",
355 "Purchase Invoice",
356 "Stock Reconciliation",
357 "Stock Entry",
358 "Subcontracting Receipt",
359 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530360 and not is_expense_account
361 ):
362 frappe.throw(
363 _("Expense / Difference account ({0}) must be a 'Profit or Loss' account").format(
364 item.get("expense_account")
365 )
366 )
Anand Doshi496123a2014-06-19 19:25:19 +0530367 if is_expense_account and not item.get("cost_center"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530368 frappe.throw(
369 _("{0} {1}: Cost Center is mandatory for Item {2}").format(
370 _(self.doctype), self.name, item.get("item_code")
371 )
372 )
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530373
Rohit Waghchaure8996b7d2020-01-23 17:36:52 +0530374 def delete_auto_created_batches(self):
Rohit Waghchaurebc75a7e2022-10-10 13:28:19 +0530375 for row in self.items:
376 if row.serial_and_batch_bundle:
377 frappe.db.set_value(
378 "Serial and Batch Bundle", row.serial_and_batch_bundle, {"is_cancelled": 1}
379 )
Rohit Waghchaure8996b7d2020-01-23 17:36:52 +0530380
Rohit Waghchaurebc75a7e2022-10-10 13:28:19 +0530381 row.db_set("serial_and_batch_bundle", None)
Saqibe9ac3e02020-03-02 15:02:58 +0530382
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530383 def set_serial_and_batch_bundle(self, table_name=None, ignore_validate=False):
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530384 if not table_name:
385 table_name = "items"
Rohit Waghchaure8996b7d2020-01-23 17:36:52 +0530386
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530387 QTY_FIELD = {
388 "serial_and_batch_bundle": "qty",
389 "current_serial_and_batch_bundle": "current_qty",
390 "rejected_serial_and_batch_bundle": "rejected_qty",
391 }
392
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530393 for row in self.get(table_name):
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530394 for field in [
395 "serial_and_batch_bundle",
396 "current_serial_and_batch_bundle",
397 "rejected_serial_and_batch_bundle",
398 ]:
399 if row.get(field):
400 frappe.get_doc("Serial and Batch Bundle", row.get(field)).set_serial_and_batch_values(
401 self, row, qty_field=QTY_FIELD[field]
402 )
Rohit Waghchaure648efca2023-03-28 12:16:27 +0530403
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530404 def make_package_for_transfer(
405 self, serial_and_batch_bundle, warehouse, type_of_transaction=None, do_not_submit=None
406 ):
407 bundle_doc = frappe.get_doc("Serial and Batch Bundle", serial_and_batch_bundle)
408
409 if not type_of_transaction:
410 type_of_transaction = "Inward"
411
412 bundle_doc = frappe.copy_doc(bundle_doc)
413 bundle_doc.warehouse = warehouse
414 bundle_doc.type_of_transaction = type_of_transaction
415 bundle_doc.voucher_type = self.doctype
416 bundle_doc.voucher_no = self.name
417 bundle_doc.is_cancelled = 0
418
Rohit Waghchaure5bb31732023-03-21 10:54:41 +0530419 for row in bundle_doc.entries:
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530420 row.is_outward = 0
421 row.qty = abs(row.qty)
422 row.stock_value_difference = abs(row.stock_value_difference)
423 if type_of_transaction == "Outward":
424 row.qty *= -1
425 row.stock_value_difference *= row.stock_value_difference
426 row.is_outward = 1
427
428 row.warehouse = warehouse
429
Rohit Waghchaure5bb31732023-03-21 10:54:41 +0530430 bundle_doc.calculate_qty_and_amount()
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530431 bundle_doc.flags.ignore_permissions = True
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530432 bundle_doc.save(ignore_permissions=True)
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530433
Rohit Waghchaure86da3062023-03-20 14:15:34 +0530434 return bundle_doc.name
Rohit Waghchaure4f4dbf12020-01-23 12:42:42 +0530435
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530436 def get_sl_entries(self, d, args):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530437 sl_dict = frappe._dict(
438 {
439 "item_code": d.get("item_code", None),
440 "warehouse": d.get("warehouse", None),
Rohit Waghchaurebc75a7e2022-10-10 13:28:19 +0530441 "serial_and_batch_bundle": d.get("serial_and_batch_bundle"),
Ankush Menat494bd9e2022-03-28 18:52:46 +0530442 "posting_date": self.posting_date,
443 "posting_time": self.posting_time,
444 "fiscal_year": get_fiscal_year(self.posting_date, company=self.company)[0],
445 "voucher_type": self.doctype,
446 "voucher_no": self.name,
447 "voucher_detail_no": d.name,
448 "actual_qty": (self.docstatus == 1 and 1 or -1) * flt(d.get("stock_qty")),
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +0530449 "stock_uom": frappe.get_cached_value(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530450 "Item", args.get("item_code") or d.get("item_code"), "stock_uom"
451 ),
452 "incoming_rate": 0,
453 "company": self.company,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530454 "project": d.get("project") or self.get("project"),
455 "is_cancelled": 1 if self.docstatus == 2 else 0,
456 }
457 )
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530458
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530459 sl_dict.update(args)
Rohit Waghchauree576f7f2022-06-30 19:12:06 +0530460 self.update_inventory_dimensions(d, sl_dict)
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530461
Nabin Hait1e2f20a2013-08-02 11:42:11 +0530462 return sl_dict
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530463
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530464 def update_inventory_dimensions(self, row, sl_dict) -> None:
Rohit Waghchaure23729992022-09-02 18:43:55 +0530465 # To handle delivery note and sales invoice
466 if row.get("item_row"):
467 row = row.get("item_row")
468
Rohit Waghchaure289e6cd2022-07-15 15:43:38 +0530469 dimensions = get_evaluated_inventory_dimension(row, sl_dict, parent_doc=self)
470 for dimension in dimensions:
Rohit Waghchaure0b39a012022-08-17 11:56:13 +0530471 if not dimension:
472 continue
473
Rohit Waghchaure6798b902023-05-09 16:07:14 +0530474 if self.doctype in [
475 "Purchase Invoice",
476 "Purchase Receipt",
477 "Sales Invoice",
478 "Delivery Note",
479 "Stock Entry",
480 ]:
Rohit Waghchaure38aaba52023-05-13 13:00:05 +0530481 if (
482 (
483 sl_dict.actual_qty > 0
484 and not self.get("is_return")
485 or sl_dict.actual_qty < 0
486 and self.get("is_return")
487 )
488 and self.doctype in ["Purchase Invoice", "Purchase Receipt"]
489 ) or (
490 (
491 sl_dict.actual_qty < 0
492 and not self.get("is_return")
493 or sl_dict.actual_qty > 0
494 and self.get("is_return")
495 )
496 and self.doctype in ["Sales Invoice", "Delivery Note", "Stock Entry"]
Rohit Waghchaure6798b902023-05-09 16:07:14 +0530497 ):
498 sl_dict[dimension.target_fieldname] = row.get(dimension.source_fieldname)
499 else:
500 fieldname_start_with = "to"
501 if self.doctype in ["Purchase Invoice", "Purchase Receipt"]:
502 fieldname_start_with = "from"
503
504 fieldname = f"{fieldname_start_with}_{dimension.source_fieldname}"
505 sl_dict[dimension.target_fieldname] = row.get(fieldname)
506
507 if not sl_dict.get(dimension.target_fieldname):
508 sl_dict[dimension.target_fieldname] = row.get(dimension.source_fieldname)
509
510 elif row.get(dimension.source_fieldname):
Rohit Waghchaure289e6cd2022-07-15 15:43:38 +0530511 sl_dict[dimension.target_fieldname] = row.get(dimension.source_fieldname)
Rohit Waghchauredbec5cf2022-06-22 12:24:08 +0530512
Rohit Waghchaure0b39a012022-08-17 11:56:13 +0530513 if not sl_dict.get(dimension.target_fieldname) and dimension.fetch_from_parent:
514 sl_dict[dimension.target_fieldname] = self.get(dimension.fetch_from_parent)
515
516 # Get value based on doctype name
517 if not sl_dict.get(dimension.target_fieldname):
Daizy Modi4efc9472022-11-07 09:21:03 +0530518 fieldname = next(
519 (
520 field.fieldname
521 for field in frappe.get_meta(self.doctype).fields
522 if field.options == dimension.fetch_from_parent
523 ),
524 None,
Rohit Waghchaure0b39a012022-08-17 11:56:13 +0530525 )
526
527 if fieldname and self.get(fieldname):
528 sl_dict[dimension.target_fieldname] = self.get(fieldname)
529
Rohit Waghchaure75fcab02022-09-03 17:09:24 +0530530 if sl_dict[dimension.target_fieldname] and self.docstatus == 1:
531 row.db_set(dimension.source_fieldname, sl_dict[dimension.target_fieldname])
Rohit Waghchaure23729992022-09-02 18:43:55 +0530532
Ankush Menat494bd9e2022-03-28 18:52:46 +0530533 def make_sl_entries(self, sl_entries, allow_negative_stock=False, via_landed_cost_voucher=False):
Rushabh Mehta1f847992013-12-12 19:12:19 +0530534 from erpnext.stock.stock_ledger import make_sl_entries
Ankush Menat494bd9e2022-03-28 18:52:46 +0530535
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530536 make_sl_entries(sl_entries, allow_negative_stock, via_landed_cost_voucher)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530537
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530538 def make_gl_entries_on_cancel(self):
ruthra kumar46ea8142023-07-28 08:29:19 +0530539 cancel_exchange_gain_loss_journal(frappe._dict(doctype=self.doctype, name=self.name))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530540 if frappe.db.sql(
541 """select name from `tabGL Entry` where voucher_type=%s
542 and voucher_no=%s""",
543 (self.doctype, self.name),
544 ):
545 self.make_gl_entries()
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530546
Anand Doshia740f752014-06-25 13:31:02 +0530547 def get_serialized_items(self):
548 serialized_items = []
Ankush Menata9c84f72021-06-11 16:00:48 +0530549 item_codes = list(set(d.item_code for d in self.get("items")))
Anand Doshia740f752014-06-25 13:31:02 +0530550 if item_codes:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530551 serialized_items = frappe.db.sql_list(
552 """select name from `tabItem`
553 where has_serial_no=1 and name in ({})""".format(
554 ", ".join(["%s"] * len(item_codes))
555 ),
556 tuple(item_codes),
557 )
Anand Doshia740f752014-06-25 13:31:02 +0530558
559 return serialized_items
Rushabh Mehtab16b9cd2015-08-03 16:13:33 +0530560
Saurabh2e292062015-11-18 17:03:33 +0530561 def validate_warehouse(self):
Rohan Bansal7f8b95e2021-04-14 14:12:03 +0530562 from erpnext.stock.utils import validate_disabled_warehouse, validate_warehouse_company
Saurabh2e292062015-11-18 17:03:33 +0530563
Ankush Menat494bd9e2022-03-28 18:52:46 +0530564 warehouses = list(set(d.warehouse for d in self.get("items") if getattr(d, "warehouse", None)))
Saurabh2e292062015-11-18 17:03:33 +0530565
Ankush Menat494bd9e2022-03-28 18:52:46 +0530566 target_warehouses = list(
567 set([d.target_warehouse for d in self.get("items") if getattr(d, "target_warehouse", None)])
568 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530569
570 warehouses.extend(target_warehouses)
571
Ankush Menat494bd9e2022-03-28 18:52:46 +0530572 from_warehouse = list(
573 set([d.from_warehouse for d in self.get("items") if getattr(d, "from_warehouse", None)])
574 )
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530575
576 warehouses.extend(from_warehouse)
577
Saurabh2e292062015-11-18 17:03:33 +0530578 for w in warehouses:
Jannat Patel30c88732021-02-11 11:46:48 +0530579 validate_disabled_warehouse(w)
Saurabh2e292062015-11-18 17:03:33 +0530580 validate_warehouse_company(w, self.company)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530581
Anand Doshi6b71ef52016-01-06 16:32:06 +0530582 def update_billing_percentage(self, update_modified=True):
marinationd6596a12020-11-02 15:07:48 +0530583 target_ref_field = "amount"
584 if self.doctype == "Delivery Note":
585 target_ref_field = "amount - (returned_qty * rate)"
586
Ankush Menat494bd9e2022-03-28 18:52:46 +0530587 self._update_percent_field(
588 {
589 "target_dt": self.doctype + " Item",
590 "target_parent_dt": self.doctype,
591 "target_parent_field": "per_billed",
592 "target_ref_field": target_ref_field,
593 "target_field": "billed_amt",
594 "name": self.name,
595 },
596 update_modified,
597 )
Anand Doshia740f752014-06-25 13:31:02 +0530598
Nabin Hait8af429d2016-11-16 17:21:59 +0530599 def validate_inspection(self):
marination9ac9a4e2021-06-21 16:18:35 +0530600 """Checks if quality inspection is set/ is valid for Items that require inspection."""
601 inspection_fieldname_map = {
602 "Purchase Receipt": "inspection_required_before_purchase",
603 "Purchase Invoice": "inspection_required_before_purchase",
s-aga-r3fdcd332023-08-23 12:15:35 +0530604 "Subcontracting Receipt": "inspection_required_before_purchase",
marination9ac9a4e2021-06-21 16:18:35 +0530605 "Sales Invoice": "inspection_required_before_delivery",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530606 "Delivery Note": "inspection_required_before_delivery",
marination9ac9a4e2021-06-21 16:18:35 +0530607 }
608 inspection_required_fieldname = inspection_fieldname_map.get(self.doctype)
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530609
marination9ac9a4e2021-06-21 16:18:35 +0530610 # return if inspection is not required on document level
Ankush Menat494bd9e2022-03-28 18:52:46 +0530611 if (
612 (not inspection_required_fieldname and self.doctype != "Stock Entry")
613 or (self.doctype == "Stock Entry" and not self.inspection_required)
614 or (self.doctype in ["Sales Invoice", "Purchase Invoice"] and not self.update_stock)
615 ):
616 return
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530617
Ankush Menat494bd9e2022-03-28 18:52:46 +0530618 for row in self.get("items"):
marination9ac9a4e2021-06-21 16:18:35 +0530619 qi_required = False
Ankush Menat494bd9e2022-03-28 18:52:46 +0530620 if inspection_required_fieldname and frappe.db.get_value(
621 "Item", row.item_code, inspection_required_fieldname
622 ):
marination9ac9a4e2021-06-21 16:18:35 +0530623 qi_required = True
624 elif self.doctype == "Stock Entry" and row.t_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530625 qi_required = True # inward stock needs inspection
Rushabh Mehtaffd80a62017-01-16 17:23:20 +0530626
Ankush Menat494bd9e2022-03-28 18:52:46 +0530627 if qi_required: # validate row only if inspection is required on item level
marination9ac9a4e2021-06-21 16:18:35 +0530628 self.validate_qi_presence(row)
629 if self.docstatus == 1:
630 self.validate_qi_submission(row)
631 self.validate_qi_rejection(row)
632
633 def validate_qi_presence(self, row):
634 """Check if QI is present on row level. Warn on save and stop on submit if missing."""
635 if not row.quality_inspection:
marination654e9d82021-06-21 16:51:12 +0530636 msg = f"Row #{row.idx}: Quality Inspection is required for Item {frappe.bold(row.item_code)}"
marination9ac9a4e2021-06-21 16:18:35 +0530637 if self.docstatus == 1:
marination654e9d82021-06-21 16:51:12 +0530638 frappe.throw(_(msg), title=_("Inspection Required"), exc=QualityInspectionRequiredError)
marination9ac9a4e2021-06-21 16:18:35 +0530639 else:
marination654e9d82021-06-21 16:51:12 +0530640 frappe.msgprint(_(msg), title=_("Inspection Required"), indicator="blue")
marination9ac9a4e2021-06-21 16:18:35 +0530641
642 def validate_qi_submission(self, row):
643 """Check if QI is submitted on row level, during submission"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530644 action = frappe.db.get_single_value(
645 "Stock Settings", "action_if_quality_inspection_is_not_submitted"
646 )
marination9ac9a4e2021-06-21 16:18:35 +0530647 qa_docstatus = frappe.db.get_value("Quality Inspection", row.quality_inspection, "docstatus")
648
649 if not qa_docstatus == 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530650 link = frappe.utils.get_link_to_form("Quality Inspection", row.quality_inspection)
651 msg = (
652 f"Row #{row.idx}: Quality Inspection {link} is not submitted for the item: {row.item_code}"
653 )
marination9ac9a4e2021-06-21 16:18:35 +0530654 if action == "Stop":
marination654e9d82021-06-21 16:51:12 +0530655 frappe.throw(_(msg), title=_("Inspection Submission"), exc=QualityInspectionNotSubmittedError)
marination9ac9a4e2021-06-21 16:18:35 +0530656 else:
Marica9ba3fce2021-06-22 11:20:17 +0530657 frappe.msgprint(_(msg), alert=True, indicator="orange")
marination9ac9a4e2021-06-21 16:18:35 +0530658
659 def validate_qi_rejection(self, row):
660 """Check if QI is rejected on row level, during submission"""
marinationf67f13c2021-07-10 18:24:24 +0530661 action = frappe.db.get_single_value("Stock Settings", "action_if_quality_inspection_is_rejected")
marination9ac9a4e2021-06-21 16:18:35 +0530662 qa_status = frappe.db.get_value("Quality Inspection", row.quality_inspection, "status")
663
664 if qa_status == "Rejected":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530665 link = frappe.utils.get_link_to_form("Quality Inspection", row.quality_inspection)
marination654e9d82021-06-21 16:51:12 +0530666 msg = f"Row #{row.idx}: Quality Inspection {link} was rejected for item {row.item_code}"
marination9ac9a4e2021-06-21 16:18:35 +0530667 if action == "Stop":
marination654e9d82021-06-21 16:51:12 +0530668 frappe.throw(_(msg), title=_("Inspection Rejected"), exc=QualityInspectionRejectedError)
marination9ac9a4e2021-06-21 16:18:35 +0530669 else:
marination654e9d82021-06-21 16:51:12 +0530670 frappe.msgprint(_(msg), alert=True, indicator="orange")
Manas Solankicc902412016-11-10 19:15:11 +0530671
Nabin Haitb2d3c0f2018-06-14 15:54:34 +0530672 def update_blanket_order(self):
Nabin Haitd1f40ad2018-06-14 17:09:55 +0530673 blanket_orders = list(set([d.blanket_order for d in self.items if d.blanket_order]))
Nabin Haitb2d3c0f2018-06-14 15:54:34 +0530674 for blanket_order in blanket_orders:
675 frappe.get_doc("Blanket Order", blanket_order).update_ordered_qty()
Manas Solankie5e87f72018-05-28 20:07:08 +0530676
marinationfd04e962020-04-03 15:46:48 +0530677 def validate_customer_provided_item(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530678 for d in self.get("items"):
marinationfd04e962020-04-03 15:46:48 +0530679 # Customer Provided parts will have zero valuation rate
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +0530680 if frappe.get_cached_value("Item", d.item_code, "is_customer_provided_item"):
marinationfd04e962020-04-03 15:46:48 +0530681 d.allow_zero_valuation_rate = 1
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530682
Anupam Kumar7e1dcf92021-02-11 20:19:30 +0530683 def set_rate_of_stock_uom(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530684 if self.doctype in [
685 "Purchase Receipt",
686 "Purchase Invoice",
687 "Purchase Order",
688 "Sales Invoice",
689 "Sales Order",
690 "Delivery Note",
691 "Quotation",
692 ]:
Anupam Kumar7e1dcf92021-02-11 20:19:30 +0530693 for d in self.get("items"):
Rohit Waghchaure13584432021-03-26 14:11:50 +0530694 d.stock_uom_rate = d.rate / (d.conversion_factor or 1)
Anupam Kumar7e1dcf92021-02-11 20:19:30 +0530695
Deepesh Gargb4be2922021-01-28 13:09:56 +0530696 def validate_internal_transfer(self):
rohitwaghchaure5136fe12023-10-22 20:03:02 +0530697 if self.doctype in ("Sales Invoice", "Delivery Note", "Purchase Invoice", "Purchase Receipt"):
698 if self.is_internal_transfer():
699 self.validate_in_transit_warehouses()
700 self.validate_multi_currency()
701 self.validate_packed_items()
702 else:
703 self.validate_internal_transfer_warehouse()
704
705 def validate_internal_transfer_warehouse(self):
706 for row in self.items:
707 if row.get("target_warehouse"):
708 row.target_warehouse = None
709
710 if row.get("from_warehouse"):
711 row.from_warehouse = None
Deepesh Gargb4be2922021-01-28 13:09:56 +0530712
713 def validate_in_transit_warehouses(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530714 if (
715 self.doctype == "Sales Invoice" and self.get("update_stock")
716 ) or self.doctype == "Delivery Note":
717 for item in self.get("items"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530718 if not item.target_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530719 frappe.throw(
720 _("Row {0}: Target Warehouse is mandatory for internal transfers").format(item.idx)
721 )
Deepesh Gargb4be2922021-01-28 13:09:56 +0530722
Ankush Menat494bd9e2022-03-28 18:52:46 +0530723 if (
724 self.doctype == "Purchase Invoice" and self.get("update_stock")
725 ) or self.doctype == "Purchase Receipt":
726 for item in self.get("items"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530727 if not item.from_warehouse:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530728 frappe.throw(
729 _("Row {0}: From Warehouse is mandatory for internal transfers").format(item.idx)
730 )
Deepesh Gargb4be2922021-01-28 13:09:56 +0530731
732 def validate_multi_currency(self):
733 if self.currency != self.company_currency:
734 frappe.throw(_("Internal transfers can only be done in company's default currency"))
735
736 def validate_packed_items(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530737 if self.doctype in ("Sales Invoice", "Delivery Note Item") and self.get("packed_items"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530738 frappe.throw(_("Packed Items cannot be transferred internally"))
739
marinationfac40352020-12-07 21:35:49 +0530740 def validate_putaway_capacity(self):
741 # if over receipt is attempted while 'apply putaway rule' is disabled
742 # and if rule was applied on the transaction, validate it.
marination957615b2021-01-18 23:47:24 +0530743 from erpnext.stock.doctype.putaway_rule.putaway_rule import get_available_putaway_capacity
Ankush Menat494bd9e2022-03-28 18:52:46 +0530744
745 valid_doctype = self.doctype in (
746 "Purchase Receipt",
747 "Stock Entry",
748 "Purchase Invoice",
749 "Stock Reconciliation",
750 )
marinationfac40352020-12-07 21:35:49 +0530751
marination957615b2021-01-18 23:47:24 +0530752 if self.doctype == "Purchase Invoice" and self.get("update_stock") == 0:
753 valid_doctype = False
754
755 if valid_doctype:
marinationfac40352020-12-07 21:35:49 +0530756 rule_map = defaultdict(dict)
757 for item in self.get("items"):
marination957615b2021-01-18 23:47:24 +0530758 warehouse_field = "t_warehouse" if self.doctype == "Stock Entry" else "warehouse"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530759 rule = frappe.db.get_value(
760 "Putaway Rule",
761 {"item_code": item.get("item_code"), "warehouse": item.get(warehouse_field)},
762 ["name", "disable"],
763 as_dict=True,
764 )
marination957615b2021-01-18 23:47:24 +0530765 if rule:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530766 if rule.get("disabled"):
767 continue # dont validate for disabled rule
marination957615b2021-01-18 23:47:24 +0530768
769 if self.doctype == "Stock Reconciliation":
770 stock_qty = flt(item.qty)
771 else:
772 stock_qty = flt(item.transfer_qty) if self.doctype == "Stock Entry" else flt(item.stock_qty)
773
774 rule_name = rule.get("name")
775 if not rule_map[rule_name]:
776 rule_map[rule_name]["warehouse"] = item.get(warehouse_field)
777 rule_map[rule_name]["item"] = item.get("item_code")
778 rule_map[rule_name]["qty_put"] = 0
779 rule_map[rule_name]["capacity"] = get_available_putaway_capacity(rule_name)
780 rule_map[rule_name]["qty_put"] += flt(stock_qty)
marinationfac40352020-12-07 21:35:49 +0530781
782 for rule, values in rule_map.items():
783 if flt(values["qty_put"]) > flt(values["capacity"]):
marination957615b2021-01-18 23:47:24 +0530784 message = self.prepare_over_receipt_message(rule, values)
marinationfac40352020-12-07 21:35:49 +0530785 frappe.throw(msg=message, title=_("Over Receipt"))
marination957615b2021-01-18 23:47:24 +0530786
787 def prepare_over_receipt_message(self, rule, values):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530788 message = _(
789 "{0} qty of Item {1} is being received into Warehouse {2} with capacity {3}."
790 ).format(
791 frappe.bold(values["qty_put"]),
792 frappe.bold(values["item"]),
793 frappe.bold(values["warehouse"]),
794 frappe.bold(values["capacity"]),
795 )
marination957615b2021-01-18 23:47:24 +0530796 message += "<br><br>"
797 rule_link = frappe.utils.get_link_to_form("Putaway Rule", rule)
Ankush Menatad6a2652021-04-17 16:50:02 +0530798 message += _("Please adjust the qty or edit {0} to proceed.").format(rule_link)
marination957615b2021-01-18 23:47:24 +0530799 return message
marinationfac40352020-12-07 21:35:49 +0530800
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +0530801 def repost_future_sle_and_gle(self, force=False):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530802 args = frappe._dict(
803 {
804 "posting_date": self.posting_date,
805 "posting_time": self.posting_time,
806 "voucher_type": self.doctype,
807 "voucher_no": self.name,
808 "company": self.company,
809 }
810 )
Ankush Menat3638fbf2022-03-01 18:17:14 +0530811
Rohit Waghchaure6e661e72023-05-16 16:23:52 +0530812 if self.docstatus == 2:
813 force = True
814
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +0530815 if force or future_sle_exists(args) or repost_required_for_queue(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530816 item_based_reposting = cint(
817 frappe.db.get_single_value("Stock Reposting Settings", "item_based_reposting")
818 )
Ankush Menat45dd46b2021-11-02 10:50:52 +0530819 if item_based_reposting:
820 create_item_wise_repost_entries(voucher_type=self.doctype, voucher_no=self.name)
821 else:
822 create_repost_item_valuation_entry(args)
823
Sagar Sharmaf4673942022-08-21 21:26:06 +0530824 def add_gl_entry(
825 self,
826 gl_entries,
827 account,
828 cost_center,
829 debit,
830 credit,
831 remarks,
832 against_account,
Gursheen Anandfcfdb9b2023-10-03 15:19:33 +0530833 against_type="Account",
Sagar Sharmaf4673942022-08-21 21:26:06 +0530834 debit_in_account_currency=None,
835 credit_in_account_currency=None,
836 account_currency=None,
837 project=None,
838 voucher_detail_no=None,
839 item=None,
840 posting_date=None,
841 ):
842
843 gl_entry = {
844 "account": account,
845 "cost_center": cost_center,
846 "debit": debit,
847 "credit": credit,
Gursheen Anandfcfdb9b2023-10-03 15:19:33 +0530848 "against_type": against_type,
Sagar Sharmaf4673942022-08-21 21:26:06 +0530849 "against": against_account,
850 "remarks": remarks,
851 }
852
853 if voucher_detail_no:
854 gl_entry.update({"voucher_detail_no": voucher_detail_no})
855
856 if debit_in_account_currency:
857 gl_entry.update({"debit_in_account_currency": debit_in_account_currency})
858
859 if credit_in_account_currency:
860 gl_entry.update({"credit_in_account_currency": credit_in_account_currency})
861
862 if posting_date:
863 gl_entry.update({"posting_date": posting_date})
864
865 gl_entries.append(self.get_gl_dict(gl_entry, item=item))
866
Ankush Menat494bd9e2022-03-28 18:52:46 +0530867
Deepesh Garg2e52a632023-06-04 19:20:28 +0530868@frappe.whitelist()
Deepesh Garg0e68da52023-06-22 15:43:32 +0530869def show_accounting_ledger_preview(company, doctype, docname):
Smit Vora77cc91d2023-10-19 22:35:55 +0530870 filters = frappe._dict(company=company, include_dimensions=1)
Deepesh Garg0e68da52023-06-22 15:43:32 +0530871 doc = frappe.get_doc(doctype, docname)
Smit Vora77cc91d2023-10-19 22:35:55 +0530872 doc.run_method("before_gl_preview")
Deepesh Garg0e68da52023-06-22 15:43:32 +0530873
874 gl_columns, gl_data = get_accounting_ledger_preview(doc, filters)
875
Deepesh Gargd9e7bc52023-06-22 16:07:32 +0530876 frappe.db.rollback()
Deepesh Garg0e68da52023-06-22 15:43:32 +0530877
878 return {"gl_columns": gl_columns, "gl_data": gl_data}
879
880
881@frappe.whitelist()
882def show_stock_ledger_preview(company, doctype, docname):
Smit Vora77cc91d2023-10-19 22:35:55 +0530883 filters = frappe._dict(company=company)
Deepesh Garg2e52a632023-06-04 19:20:28 +0530884 doc = frappe.get_doc(doctype, docname)
Smit Vora77cc91d2023-10-19 22:35:55 +0530885 doc.run_method("before_sl_preview")
Deepesh Garge30c3ea2023-06-12 11:46:51 +0530886
Deepesh Garg011ac132023-06-12 18:42:49 +0530887 sl_columns, sl_data = get_stock_ledger_preview(doc, filters)
Deepesh Garge30c3ea2023-06-12 11:46:51 +0530888
Deepesh Gargd9e7bc52023-06-22 16:07:32 +0530889 frappe.db.rollback()
Deepesh Garge30c3ea2023-06-12 11:46:51 +0530890
Deepesh Garg2e52a632023-06-04 19:20:28 +0530891 return {
Deepesh Garg011ac132023-06-12 18:42:49 +0530892 "sl_columns": sl_columns,
893 "sl_data": sl_data,
Deepesh Garg2e52a632023-06-04 19:20:28 +0530894 }
895
896
Deepesh Garg011ac132023-06-12 18:42:49 +0530897def get_accounting_ledger_preview(doc, filters):
898 from erpnext.accounts.report.general_ledger.general_ledger import get_columns as get_gl_columns
899
900 gl_columns, gl_data = [], []
901 fields = [
902 "posting_date",
903 "account",
904 "debit",
905 "credit",
906 "against",
907 "party",
908 "party_type",
Deepesh Garg0e68da52023-06-22 15:43:32 +0530909 "cost_center",
Deepesh Garg011ac132023-06-12 18:42:49 +0530910 "against_voucher_type",
911 "against_voucher",
912 ]
913
914 doc.docstatus = 1
Deepesh Garg0e68da52023-06-22 15:43:32 +0530915
916 if doc.get("update_stock") or doc.doctype in ("Purchase Receipt", "Delivery Note"):
917 doc.update_stock_ledger()
918
Deepesh Garg011ac132023-06-12 18:42:49 +0530919 doc.make_gl_entries()
920 columns = get_gl_columns(filters)
921 gl_entries = get_gl_entries_for_preview(doc.doctype, doc.name, fields)
922
923 gl_columns = get_columns(columns, fields)
924 gl_data = get_data(fields, gl_entries)
925
926 return gl_columns, gl_data
927
928
929def get_stock_ledger_preview(doc, filters):
930 from erpnext.stock.report.stock_ledger.stock_ledger import get_columns as get_sl_columns
931
932 sl_columns, sl_data = [], []
933 fields = [
934 "item_code",
935 "stock_uom",
936 "actual_qty",
937 "qty_after_transaction",
938 "warehouse",
939 "incoming_rate",
940 "valuation_rate",
941 "stock_value",
942 "stock_value_difference",
943 ]
944 columns_fields = [
945 "item_code",
946 "stock_uom",
947 "in_qty",
948 "out_qty",
949 "qty_after_transaction",
950 "warehouse",
951 "incoming_rate",
Deepesh Garg0e68da52023-06-22 15:43:32 +0530952 "in_out_rate",
Deepesh Garg011ac132023-06-12 18:42:49 +0530953 "stock_value",
954 "stock_value_difference",
955 ]
956
Deepesh Garg0e68da52023-06-22 15:43:32 +0530957 if doc.get("update_stock") or doc.doctype in ("Purchase Receipt", "Delivery Note"):
Deepesh Garg011ac132023-06-12 18:42:49 +0530958 doc.docstatus = 1
959 doc.update_stock_ledger()
960 columns = get_sl_columns(filters)
961 sl_entries = get_sl_entries_for_preview(doc.doctype, doc.name, fields)
962
963 sl_columns = get_columns(columns, columns_fields)
964 sl_data = get_data(columns_fields, sl_entries)
965
966 return sl_columns, sl_data
967
968
969def get_sl_entries_for_preview(doctype, docname, fields):
970 sl_entries = frappe.get_all(
971 "Stock Ledger Entry", filters={"voucher_type": doctype, "voucher_no": docname}, fields=fields
972 )
973
974 for entry in sl_entries:
975 if entry.actual_qty > 0:
976 entry["in_qty"] = entry.actual_qty
977 entry["out_qty"] = 0
978 else:
979 entry["out_qty"] = abs(entry.actual_qty)
980 entry["in_qty"] = 0
981
Deepesh Garg0e68da52023-06-22 15:43:32 +0530982 entry["in_out_rate"] = entry["valuation_rate"]
983
Deepesh Garg011ac132023-06-12 18:42:49 +0530984 return sl_entries
985
986
987def get_gl_entries_for_preview(doctype, docname, fields):
Deepesh Garge30c3ea2023-06-12 11:46:51 +0530988 return frappe.get_all(
Deepesh Garg011ac132023-06-12 18:42:49 +0530989 "GL Entry", filters={"voucher_type": doctype, "voucher_no": docname}, fields=fields
Deepesh Garge30c3ea2023-06-12 11:46:51 +0530990 )
991
992
Deepesh Garg011ac132023-06-12 18:42:49 +0530993def get_columns(raw_columns, fields):
Deepesh Garge30c3ea2023-06-12 11:46:51 +0530994 return [
Deepesh Garg011ac132023-06-12 18:42:49 +0530995 {"name": d.get("label"), "editable": False, "width": 110}
Deepesh Garge30c3ea2023-06-12 11:46:51 +0530996 for d in raw_columns
Deepesh Garg011ac132023-06-12 18:42:49 +0530997 if not d.get("hidden") and d.get("fieldname") in fields
Deepesh Garge30c3ea2023-06-12 11:46:51 +0530998 ]
999
1000
1001def get_data(raw_columns, raw_data):
1002 datatable_data = []
1003 for row in raw_data:
1004 data_row = []
1005 for column in raw_columns:
Deepesh Garg011ac132023-06-12 18:42:49 +05301006 data_row.append(row.get(column) or "")
Deepesh Garge30c3ea2023-06-12 11:46:51 +05301007
1008 datatable_data.append(data_row)
1009
1010 return datatable_data
1011
1012
Ankush Menat3638fbf2022-03-01 18:17:14 +05301013def repost_required_for_queue(doc: StockController) -> bool:
1014 """check if stock document contains repeated item-warehouse with queue based valuation.
1015
1016 if queue exists for repeated items then SLEs need to reprocessed in background again.
1017 """
1018
Ankush Menat494bd9e2022-03-28 18:52:46 +05301019 consuming_sles = frappe.db.get_all(
1020 "Stock Ledger Entry",
Ankush Menat3638fbf2022-03-01 18:17:14 +05301021 filters={
1022 "voucher_type": doc.doctype,
1023 "voucher_no": doc.name,
1024 "actual_qty": ("<", 0),
Ankush Menat494bd9e2022-03-28 18:52:46 +05301025 "is_cancelled": 0,
Ankush Menat3638fbf2022-03-01 18:17:14 +05301026 },
Ankush Menat494bd9e2022-03-28 18:52:46 +05301027 fields=["item_code", "warehouse", "stock_queue"],
Ankush Menat3638fbf2022-03-01 18:17:14 +05301028 )
1029 item_warehouses = [(sle.item_code, sle.warehouse) for sle in consuming_sles]
1030
1031 unique_item_warehouses = set(item_warehouses)
1032
1033 if len(unique_item_warehouses) == len(item_warehouses):
1034 return False
1035
1036 for sle in consuming_sles:
1037 if sle.stock_queue != "[]": # using FIFO/LIFO valuation
1038 return True
1039 return False
1040
Nabin Hait19f8fa52021-02-22 22:27:22 +05301041
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301042@frappe.whitelist()
1043def make_quality_inspections(doctype, docname, items):
Rohan Bansala06ec032021-06-02 14:55:31 +05301044 if isinstance(items, str):
1045 items = json.loads(items)
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301046
Rohan Bansala06ec032021-06-02 14:55:31 +05301047 inspections = []
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301048 for item in items:
Rohan Bansal1cdf5a02021-05-26 14:42:15 +05301049 if flt(item.get("sample_size")) > flt(item.get("qty")):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301050 frappe.throw(
1051 _(
1052 "{item_name}'s Sample Size ({sample_size}) cannot be greater than the Accepted Quantity ({accepted_quantity})"
1053 ).format(
1054 item_name=item.get("item_name"),
1055 sample_size=item.get("sample_size"),
1056 accepted_quantity=item.get("qty"),
1057 )
1058 )
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301059
Ankush Menat494bd9e2022-03-28 18:52:46 +05301060 quality_inspection = frappe.get_doc(
1061 {
1062 "doctype": "Quality Inspection",
1063 "inspection_type": "Incoming",
1064 "inspected_by": frappe.session.user,
1065 "reference_type": doctype,
1066 "reference_name": docname,
1067 "item_code": item.get("item_code"),
1068 "description": item.get("description"),
1069 "sample_size": flt(item.get("sample_size")),
1070 "item_serial_no": item.get("serial_no").split("\n")[0] if item.get("serial_no") else None,
1071 "batch_no": item.get("batch_no"),
1072 }
1073 ).insert()
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301074 quality_inspection.save()
Rohan Bansal1cdf5a02021-05-26 14:42:15 +05301075 inspections.append(quality_inspection.name)
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301076
Rohan Bansal1cdf5a02021-05-26 14:42:15 +05301077 return inspections
Rohan Bansal7f8b95e2021-04-14 14:12:03 +05301078
Ankush Menat494bd9e2022-03-28 18:52:46 +05301079
Nabin Haitb99c77b2020-12-25 18:12:35 +05301080def is_reposting_pending():
Ankush Menat494bd9e2022-03-28 18:52:46 +05301081 return frappe.db.exists(
1082 "Repost Item Valuation", {"docstatus": 1, "status": ["in", ["Queued", "In Progress"]]}
1083 )
1084
Nabin Haitb99c77b2020-12-25 18:12:35 +05301085
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301086def future_sle_exists(args, sl_entries=None):
1087 key = (args.voucher_type, args.voucher_no)
Rohit Waghchaured9dd64b2023-04-14 13:00:12 +05301088 if not hasattr(frappe.local, "future_sle"):
1089 frappe.local.future_sle = {}
Nabin Haita77b8c92020-12-21 14:45:50 +05301090
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301091 if validate_future_sle_not_exists(args, key, sl_entries):
1092 return False
1093 elif get_cached_data(args, key):
1094 return True
1095
1096 if not sl_entries:
1097 sl_entries = get_sle_entries_against_voucher(args)
1098 if not sl_entries:
1099 return
1100
1101 or_conditions = get_conditions_to_validate_future_sle(sl_entries)
1102
Ankush Menat494bd9e2022-03-28 18:52:46 +05301103 data = frappe.db.sql(
1104 """
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301105 select item_code, warehouse, count(name) as total_row
Deepesh Garg6f107da2021-10-12 20:15:55 +05301106 from `tabStock Ledger Entry` force index (item_warehouse)
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301107 where
1108 ({})
1109 and timestamp(posting_date, posting_time)
1110 >= timestamp(%(posting_date)s, %(posting_time)s)
1111 and voucher_no != %(voucher_no)s
1112 and is_cancelled = 0
1113 GROUP BY
1114 item_code, warehouse
Ankush Menat494bd9e2022-03-28 18:52:46 +05301115 """.format(
1116 " or ".join(or_conditions)
1117 ),
1118 args,
1119 as_dict=1,
1120 )
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301121
1122 for d in data:
1123 frappe.local.future_sle[key][(d.item_code, d.warehouse)] = d.total_row
1124
1125 return len(data)
1126
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301127
Ankush Menat494bd9e2022-03-28 18:52:46 +05301128def validate_future_sle_not_exists(args, key, sl_entries=None):
1129 item_key = ""
1130 if args.get("item_code"):
1131 item_key = (args.get("item_code"), args.get("warehouse"))
1132
1133 if not sl_entries and hasattr(frappe.local, "future_sle"):
Rohit Waghchaured9dd64b2023-04-14 13:00:12 +05301134 if key not in frappe.local.future_sle:
1135 return False
1136
Ankush Menat494bd9e2022-03-28 18:52:46 +05301137 if not frappe.local.future_sle.get(key) or (
1138 item_key and item_key not in frappe.local.future_sle.get(key)
1139 ):
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301140 return True
1141
Ankush Menat494bd9e2022-03-28 18:52:46 +05301142
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301143def get_cached_data(args, key):
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301144 if key not in frappe.local.future_sle:
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +05301145 frappe.local.future_sle[key] = frappe._dict({})
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301146
Ankush Menat494bd9e2022-03-28 18:52:46 +05301147 if args.get("item_code"):
1148 item_key = (args.get("item_code"), args.get("warehouse"))
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301149 count = frappe.local.future_sle[key].get(item_key)
1150
1151 return True if (count or count == 0) else False
1152 else:
1153 return frappe.local.future_sle[key]
1154
Ankush Menat494bd9e2022-03-28 18:52:46 +05301155
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301156def get_sle_entries_against_voucher(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301157 return frappe.get_all(
1158 "Stock Ledger Entry",
Nabin Haita77b8c92020-12-21 14:45:50 +05301159 filters={"voucher_type": args.voucher_type, "voucher_no": args.voucher_no},
1160 fields=["item_code", "warehouse"],
Ankush Menat494bd9e2022-03-28 18:52:46 +05301161 order_by="creation asc",
1162 )
1163
Nabin Haita77b8c92020-12-21 14:45:50 +05301164
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301165def get_conditions_to_validate_future_sle(sl_entries):
Sagar Vora868c0bf2021-03-27 16:10:20 +05301166 warehouse_items_map = {}
1167 for entry in sl_entries:
1168 if entry.warehouse not in warehouse_items_map:
1169 warehouse_items_map[entry.warehouse] = set()
Nabin Haita77b8c92020-12-21 14:45:50 +05301170
Sagar Vora868c0bf2021-03-27 16:10:20 +05301171 warehouse_items_map[entry.warehouse].add(entry.item_code)
1172
1173 or_conditions = []
1174 for warehouse, items in warehouse_items_map.items():
1175 or_conditions.append(
Noah Jacobb5a14912021-06-15 12:44:04 +05301176 f"""warehouse = {frappe.db.escape(warehouse)}
Ankush Menat494bd9e2022-03-28 18:52:46 +05301177 and item_code in ({', '.join(frappe.db.escape(item) for item in items)})"""
1178 )
Sagar Vora868c0bf2021-03-27 16:10:20 +05301179
Rohit Waghchaure8520edc2021-06-15 10:21:44 +05301180 return or_conditions
Nabin Haita77b8c92020-12-21 14:45:50 +05301181
Ankush Menat494bd9e2022-03-28 18:52:46 +05301182
Nabin Haita77b8c92020-12-21 14:45:50 +05301183def create_repost_item_valuation_entry(args):
1184 args = frappe._dict(args)
1185 repost_entry = frappe.new_doc("Repost Item Valuation")
1186 repost_entry.based_on = args.based_on
1187 if not args.based_on:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301188 repost_entry.based_on = "Transaction" if args.voucher_no else "Item and Warehouse"
Nabin Haita77b8c92020-12-21 14:45:50 +05301189 repost_entry.voucher_type = args.voucher_type
1190 repost_entry.voucher_no = args.voucher_no
1191 repost_entry.item_code = args.item_code
1192 repost_entry.warehouse = args.warehouse
1193 repost_entry.posting_date = args.posting_date
1194 repost_entry.posting_time = args.posting_time
1195 repost_entry.company = args.company
1196 repost_entry.allow_zero_rate = args.allow_zero_rate
1197 repost_entry.flags.ignore_links = True
Ankush Menataa024fc2021-11-18 12:51:26 +05301198 repost_entry.flags.ignore_permissions = True
Nabin Haita77b8c92020-12-21 14:45:50 +05301199 repost_entry.save()
Sagar Vora868c0bf2021-03-27 16:10:20 +05301200 repost_entry.submit()
Ankush Menat6dc9b822021-10-28 15:53:18 +05301201
1202
1203def create_item_wise_repost_entries(voucher_type, voucher_no, allow_zero_rate=False):
1204 """Using a voucher create repost item valuation records for all item-warehouse pairs."""
1205
Ankush Menatd220e082021-10-28 17:47:00 +05301206 stock_ledger_entries = get_items_to_be_repost(voucher_type, voucher_no)
1207
Ankush Menat6dc9b822021-10-28 15:53:18 +05301208 distinct_item_warehouses = set()
Ankush Menat6dc9b822021-10-28 15:53:18 +05301209 repost_entries = []
1210
1211 for sle in stock_ledger_entries:
1212 item_wh = (sle.item_code, sle.warehouse)
1213 if item_wh in distinct_item_warehouses:
1214 continue
1215 distinct_item_warehouses.add(item_wh)
1216
1217 repost_entry = frappe.new_doc("Repost Item Valuation")
1218 repost_entry.based_on = "Item and Warehouse"
Ankush Menat6dc9b822021-10-28 15:53:18 +05301219
1220 repost_entry.item_code = sle.item_code
1221 repost_entry.warehouse = sle.warehouse
1222 repost_entry.posting_date = sle.posting_date
1223 repost_entry.posting_time = sle.posting_time
1224 repost_entry.allow_zero_rate = allow_zero_rate
1225 repost_entry.flags.ignore_links = True
Ankush Menat0a2964d2021-11-24 15:55:31 +05301226 repost_entry.flags.ignore_permissions = True
Ankush Menat6dc9b822021-10-28 15:53:18 +05301227 repost_entry.submit()
1228 repost_entries.append(repost_entry)
1229
1230 return repost_entries