blob: 2945c3d731406e64fea6f716546a39650dc209d5 [file] [log] [blame]
Maricad6078aa2022-06-17 15:13:13 +05301# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors
Rushabh Mehtae67d1fb2013-08-05 14:59:54 +05302# License: GNU General Public License v3. See license.txt
Nabin Hait902e8602013-01-08 18:29:24 +05303
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +05304import copy
Nabin Hait26d46552013-01-09 15:23:05 +05305import json
Ankush Menatecdb4932022-04-17 19:06:13 +05306from typing import Optional, Set, Tuple
Chillar Anand915b3432021-09-02 16:44:59 +05307
8import frappe
Rohit Waghchaurefb1a40c2023-05-31 14:11:15 +05309from frappe import _, scrub
Chillar Anand915b3432021-09-02 16:44:59 +053010from frappe.model.meta import get_field_precision
Ankush Menate1c16872022-04-21 20:01:48 +053011from frappe.query_builder.functions import CombineDatetime, Sum
Rohit Waghchaurefb1a40c2023-05-31 14:11:15 +053012from frappe.utils import (
13 cint,
14 cstr,
15 flt,
16 get_link_to_form,
17 getdate,
18 gzip_compress,
19 gzip_decompress,
20 now,
21 nowdate,
22 parse_json,
23)
Achilles Rasquinha361366e2018-02-14 17:08:59 +053024
Chillar Anand915b3432021-09-02 16:44:59 +053025import erpnext
Ankush Menatcef84c22021-12-03 12:18:59 +053026from erpnext.stock.doctype.bin.bin import update_qty as update_bin_qty
s-aga-rf0acb202023-04-12 14:13:54 +053027from erpnext.stock.doctype.stock_reservation_entry.stock_reservation_entry import (
28 get_sre_reserved_qty_for_item_and_warehouse as get_reserved_stock,
29)
Chillar Anand915b3432021-09-02 16:44:59 +053030from erpnext.stock.utils import (
Chillar Anand915b3432021-09-02 16:44:59 +053031 get_incoming_outgoing_rate_for_cancel,
Deepesh Garg6f107da2021-10-12 20:15:55 +053032 get_or_make_bin,
Chillar Anand915b3432021-09-02 16:44:59 +053033 get_valuation_method,
34)
Ankush Menatb534fee2022-02-19 20:58:36 +053035from erpnext.stock.valuation import FIFOValuation, LIFOValuation, round_off_if_near_zero
Chillar Anand915b3432021-09-02 16:44:59 +053036
Nabin Hait97bce3a2021-07-12 13:24:43 +053037
Ankush Menat494bd9e2022-03-28 18:52:46 +053038class NegativeStockError(frappe.ValidationError):
39 pass
40
41
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +053042class SerialNoExistsInFutureTransaction(frappe.ValidationError):
43 pass
Nabin Hait902e8602013-01-08 18:29:24 +053044
Anand Doshi5b004ff2013-09-25 19:55:41 +053045
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053046def make_sl_entries(sl_entries, allow_negative_stock=False, via_landed_cost_voucher=False):
Ankush Menat494bd9e2022-03-28 18:52:46 +053047 """Create SL entries from SL entry dicts
Ankush Menateb8495a2022-03-02 12:01:51 +053048
Ankush Menat494bd9e2022-03-28 18:52:46 +053049 args:
50 - allow_negative_stock: disable negative stock valiations if true
51 - via_landed_cost_voucher: landed cost voucher cancels and reposts
52 entries of purchase document. This flag is used to identify if
53 cancellation and repost is happening via landed cost voucher, in
54 such cases certain validations need to be ignored (like negative
55 stock)
Ankush Menateb8495a2022-03-02 12:01:51 +053056 """
Rohit Waghchaure4d81d452021-06-15 10:21:44 +053057 from erpnext.controllers.stock_controller import future_sle_exists
Ankush Menat494bd9e2022-03-28 18:52:46 +053058
Nabin Haitca775742013-09-26 16:16:44 +053059 if sl_entries:
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053060 cancel = sl_entries[0].get("is_cancelled")
Nabin Haitca775742013-09-26 16:16:44 +053061 if cancel:
Nabin Hait186a0452021-02-18 14:14:21 +053062 validate_cancellation(sl_entries)
Ankush Menat494bd9e2022-03-28 18:52:46 +053063 set_as_cancel(sl_entries[0].get("voucher_type"), sl_entries[0].get("voucher_no"))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053064
Rohit Waghchaure4d81d452021-06-15 10:21:44 +053065 args = get_args_for_future_sle(sl_entries[0])
66 future_sle_exists(args, sl_entries)
67
Nabin Haitca775742013-09-26 16:16:44 +053068 for sle in sl_entries:
Ankush Menatefc4b942022-03-02 11:19:12 +053069 if sle.serial_no and not via_landed_cost_voucher:
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +053070 validate_serial_no(sle)
71
Nabin Haita77b8c92020-12-21 14:45:50 +053072 if cancel:
Ankush Menat494bd9e2022-03-28 18:52:46 +053073 sle["actual_qty"] = -flt(sle.get("actual_qty"))
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053074
Ankush Menat494bd9e2022-03-28 18:52:46 +053075 if sle["actual_qty"] < 0 and not sle.get("outgoing_rate"):
76 sle["outgoing_rate"] = get_incoming_outgoing_rate_for_cancel(
77 sle.item_code, sle.voucher_type, sle.voucher_no, sle.voucher_detail_no
78 )
79 sle["incoming_rate"] = 0.0
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053080
Ankush Menat494bd9e2022-03-28 18:52:46 +053081 if sle["actual_qty"] > 0 and not sle.get("incoming_rate"):
82 sle["incoming_rate"] = get_incoming_outgoing_rate_for_cancel(
83 sle.item_code, sle.voucher_type, sle.voucher_no, sle.voucher_detail_no
84 )
85 sle["outgoing_rate"] = 0.0
Nabin Haitdc82d4f2014-04-07 12:02:57 +053086
Ankush Menat494bd9e2022-03-28 18:52:46 +053087 if sle.get("actual_qty") or sle.get("voucher_type") == "Stock Reconciliation":
Nabin Haita77b8c92020-12-21 14:45:50 +053088 sle_doc = make_entry(sle, allow_negative_stock, via_landed_cost_voucher)
Deepesh Gargb4be2922021-01-28 13:09:56 +053089
Nabin Haita77b8c92020-12-21 14:45:50 +053090 args = sle_doc.as_dict()
marination40389772021-07-02 17:13:45 +053091
92 if sle.get("voucher_type") == "Stock Reconciliation":
93 # preserve previous_qty_after_transaction for qty reposting
94 args.previous_qty_after_transaction = sle.get("previous_qty_after_transaction")
95
Ankush Menat494bd9e2022-03-28 18:52:46 +053096 is_stock_item = frappe.get_cached_value("Item", args.get("item_code"), "is_stock_item")
Ankush Menatcef84c22021-12-03 12:18:59 +053097 if is_stock_item:
98 bin_name = get_or_make_bin(args.get("item_code"), args.get("warehouse"))
Ankush Menatcef84c22021-12-03 12:18:59 +053099 repost_current_voucher(args, allow_negative_stock, via_landed_cost_voucher)
Ankush Menatff9a6e82021-12-20 15:07:41 +0530100 update_bin_qty(bin_name, args)
Ankush Menatcef84c22021-12-03 12:18:59 +0530101 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530102 frappe.msgprint(
103 _("Item {0} ignored since it is not a stock item").format(args.get("item_code"))
104 )
105
Ankush Menatcef84c22021-12-03 12:18:59 +0530106
107def repost_current_voucher(args, allow_negative_stock=False, via_landed_cost_voucher=False):
108 if args.get("actual_qty") or args.get("voucher_type") == "Stock Reconciliation":
109 if not args.get("posting_date"):
110 args["posting_date"] = nowdate()
111
marination7a5fd712022-07-04 17:46:54 +0530112 if not (args.get("is_cancelled") and via_landed_cost_voucher):
113 # Reposts only current voucher SL Entries
114 # Updates valuation rate, stock value, stock queue for current transaction
115 update_entries_after(
116 {
117 "item_code": args.get("item_code"),
118 "warehouse": args.get("warehouse"),
119 "posting_date": args.get("posting_date"),
120 "posting_time": args.get("posting_time"),
121 "voucher_type": args.get("voucher_type"),
122 "voucher_no": args.get("voucher_no"),
123 "sle_id": args.get("name"),
124 "creation": args.get("creation"),
125 },
126 allow_negative_stock=allow_negative_stock,
127 via_landed_cost_voucher=via_landed_cost_voucher,
128 )
Ankush Menatcef84c22021-12-03 12:18:59 +0530129
130 # update qty in future sle and Validate negative qty
marination7a5fd712022-07-04 17:46:54 +0530131 # For LCV: update future balances with -ve LCV SLE, which will be balanced by +ve LCV SLE
Ankush Menatcef84c22021-12-03 12:18:59 +0530132 update_qty_in_future_sle(args, allow_negative_stock)
133
Nabin Haitadeb9762014-10-06 11:53:52 +0530134
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530135def get_args_for_future_sle(row):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530136 return frappe._dict(
137 {
138 "voucher_type": row.get("voucher_type"),
139 "voucher_no": row.get("voucher_no"),
140 "posting_date": row.get("posting_date"),
141 "posting_time": row.get("posting_time"),
142 }
143 )
144
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530145
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530146def validate_serial_no(sle):
147 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
Ankush Menat66bf21f2022-01-16 20:45:59 +0530148
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530149 for sn in get_serial_nos(sle.serial_no):
150 args = copy.deepcopy(sle)
151 args.serial_no = sn
Ankush Menat494bd9e2022-03-28 18:52:46 +0530152 args.warehouse = ""
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530153
154 vouchers = []
Ankush Menat494bd9e2022-03-28 18:52:46 +0530155 for row in get_stock_ledger_entries(args, ">"):
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530156 voucher_type = frappe.bold(row.voucher_type)
157 voucher_no = frappe.bold(get_link_to_form(row.voucher_type, row.voucher_no))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530158 vouchers.append(f"{voucher_type} {voucher_no}")
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530159
160 if vouchers:
161 serial_no = frappe.bold(sn)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530162 msg = (
163 f"""The serial no {serial_no} has been used in the future transactions so you need to cancel them first.
164 The list of the transactions are as below."""
165 + "<br><br><ul><li>"
166 )
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530167
Ankush Menat494bd9e2022-03-28 18:52:46 +0530168 msg += "</li><li>".join(vouchers)
169 msg += "</li></ul>"
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530170
Ankush Menat494bd9e2022-03-28 18:52:46 +0530171 title = "Cannot Submit" if not sle.get("is_cancelled") else "Cannot Cancel"
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530172 frappe.throw(_(msg), title=_(title), exc=SerialNoExistsInFutureTransaction)
173
Ankush Menat494bd9e2022-03-28 18:52:46 +0530174
Nabin Hait186a0452021-02-18 14:14:21 +0530175def validate_cancellation(args):
176 if args[0].get("is_cancelled"):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530177 repost_entry = frappe.db.get_value(
178 "Repost Item Valuation",
179 {"voucher_type": args[0].voucher_type, "voucher_no": args[0].voucher_no, "docstatus": 1},
180 ["name", "status"],
181 as_dict=1,
182 )
Nabin Hait186a0452021-02-18 14:14:21 +0530183
184 if repost_entry:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530185 if repost_entry.status == "In Progress":
186 frappe.throw(
187 _(
188 "Cannot cancel the transaction. Reposting of item valuation on submission is not completed yet."
189 )
190 )
191 if repost_entry.status == "Queued":
Nabin Haitd46b2362021-02-23 16:38:52 +0530192 doc = frappe.get_doc("Repost Item Valuation", repost_entry.name)
Ankush Menata2819982022-04-08 13:20:25 +0530193 doc.status = "Skipped"
Ankush Menataa024fc2021-11-18 12:51:26 +0530194 doc.flags.ignore_permissions = True
Nabin Haitd46b2362021-02-23 16:38:52 +0530195 doc.cancel()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530196
Ankush Menat494bd9e2022-03-28 18:52:46 +0530197
Nabin Hait9653f602013-08-20 15:37:33 +0530198def set_as_cancel(voucher_type, voucher_no):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530199 frappe.db.sql(
200 """update `tabStock Ledger Entry` set is_cancelled=1,
Nabin Hait9653f602013-08-20 15:37:33 +0530201 modified=%s, modified_by=%s
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530202 where voucher_type=%s and voucher_no=%s and is_cancelled = 0""",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530203 (now(), frappe.session.user, voucher_type, voucher_no),
204 )
205
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530206
Nabin Hait54c865e2015-03-27 15:38:31 +0530207def make_entry(args, allow_negative_stock=False, via_landed_cost_voucher=False):
Saqib Ansaric7fc6092021-10-12 13:30:40 +0530208 args["doctype"] = "Stock Ledger Entry"
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530209 sle = frappe.get_doc(args)
Anand Doshi6dfd4302015-02-10 14:41:27 +0530210 sle.flags.ignore_permissions = 1
Ankush Menat494bd9e2022-03-28 18:52:46 +0530211 sle.allow_negative_stock = allow_negative_stock
Nabin Hait54c865e2015-03-27 15:38:31 +0530212 sle.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Haitaeba24e2013-08-23 15:17:36 +0530213 sle.submit()
Nabin Haita77b8c92020-12-21 14:45:50 +0530214 return sle
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530215
Ankush Menat494bd9e2022-03-28 18:52:46 +0530216
217def repost_future_sle(
218 args=None,
219 voucher_type=None,
220 voucher_no=None,
221 allow_negative_stock=None,
222 via_landed_cost_voucher=False,
223 doc=None,
224):
Nabin Haite1fa7232022-07-20 15:19:09 +0530225 if not args:
226 args = [] # set args to empty list if None to avoid enumerate error
Rohit Waghchaure1d80d372022-07-19 16:36:22 +0530227
Rohit Waghchaurefb1a40c2023-05-31 14:11:15 +0530228 reposting_data = {}
229 if doc and doc.reposting_data_file:
230 reposting_data = get_reposting_data(doc.reposting_data_file)
231
Rohit Waghchaure1d80d372022-07-19 16:36:22 +0530232 items_to_be_repost = get_items_to_be_repost(
Rohit Waghchaurefb1a40c2023-05-31 14:11:15 +0530233 voucher_type=voucher_type, voucher_no=voucher_no, doc=doc, reposting_data=reposting_data
Rohit Waghchaure1d80d372022-07-19 16:36:22 +0530234 )
235 if items_to_be_repost:
236 args = items_to_be_repost
Deepesh Gargb4be2922021-01-28 13:09:56 +0530237
Rohit Waghchaurefb1a40c2023-05-31 14:11:15 +0530238 distinct_item_warehouses = get_distinct_item_warehouse(args, doc, reposting_data=reposting_data)
239 affected_transactions = get_affected_transactions(doc, reposting_data=reposting_data)
Nabin Haita77b8c92020-12-21 14:45:50 +0530240
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530241 i = get_current_index(doc) or 0
Nabin Haita77b8c92020-12-21 14:45:50 +0530242 while i < len(args):
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530243 validate_item_warehouse(args[i])
244
Ankush Menat494bd9e2022-03-28 18:52:46 +0530245 obj = update_entries_after(
246 {
247 "item_code": args[i].get("item_code"),
248 "warehouse": args[i].get("warehouse"),
249 "posting_date": args[i].get("posting_date"),
250 "posting_time": args[i].get("posting_time"),
251 "creation": args[i].get("creation"),
252 "distinct_item_warehouses": distinct_item_warehouses,
253 },
254 allow_negative_stock=allow_negative_stock,
255 via_landed_cost_voucher=via_landed_cost_voucher,
256 )
Ankush Menatecdb4932022-04-17 19:06:13 +0530257 affected_transactions.update(obj.affected_transactions)
Nabin Haita77b8c92020-12-21 14:45:50 +0530258
Ankush Menat494bd9e2022-03-28 18:52:46 +0530259 distinct_item_warehouses[
260 (args[i].get("item_code"), args[i].get("warehouse"))
261 ].reposting_status = True
Deepesh Gargb4be2922021-01-28 13:09:56 +0530262
Nabin Hait97bce3a2021-07-12 13:24:43 +0530263 if obj.new_items_found:
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530264 for item_wh, data in distinct_item_warehouses.items():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530265 if ("args_idx" not in data and not data.reposting_status) or (
266 data.sle_changed and data.reposting_status
267 ):
Nabin Hait97bce3a2021-07-12 13:24:43 +0530268 data.args_idx = len(args)
269 args.append(data.sle)
270 elif data.sle_changed and not data.reposting_status:
271 args[data.args_idx] = data.sle
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530272
Nabin Hait97bce3a2021-07-12 13:24:43 +0530273 data.sle_changed = False
Nabin Haita77b8c92020-12-21 14:45:50 +0530274 i += 1
275
Rohit Waghchaure78c8bb22022-07-04 20:24:18 +0530276 if doc:
Ankush Menatecdb4932022-04-17 19:06:13 +0530277 update_args_in_repost_item_valuation(
278 doc, i, args, distinct_item_warehouses, affected_transactions
279 )
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530280
Ankush Menat494bd9e2022-03-28 18:52:46 +0530281
Rohit Waghchaurefb1a40c2023-05-31 14:11:15 +0530282def get_reposting_data(file_path) -> dict:
283 file_name = frappe.db.get_value(
284 "File",
285 {
286 "file_url": file_path,
287 "attached_to_field": "reposting_data_file",
288 },
289 "name",
290 )
291
292 if not file_name:
293 return frappe._dict()
294
295 attached_file = frappe.get_doc("File", file_name)
296
297 data = gzip_decompress(attached_file.get_content())
298 if data := json.loads(data.decode("utf-8")):
299 data = data
300
301 return parse_json(data)
302
303
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530304def validate_item_warehouse(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530305 for field in ["item_code", "warehouse", "posting_date", "posting_time"]:
s-aga-reeda2642022-01-12 20:55:30 +0530306 if args.get(field) in [None, ""]:
s-aga-rba77da02022-11-28 18:01:30 +0530307 validation_msg = f"The field {frappe.unscrub(field)} is required for the reposting"
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530308 frappe.throw(_(validation_msg))
309
Ankush Menat494bd9e2022-03-28 18:52:46 +0530310
Ankush Menatecdb4932022-04-17 19:06:13 +0530311def update_args_in_repost_item_valuation(
312 doc, index, args, distinct_item_warehouses, affected_transactions
313):
Rohit Waghchaurefb1a40c2023-05-31 14:11:15 +0530314 if not doc.items_to_be_repost:
315 file_name = ""
316 if doc.reposting_data_file:
317 file_name = get_reposting_file_name(doc.doctype, doc.name)
318 # frappe.delete_doc("File", file_name, ignore_permissions=True, delete_permanently=True)
319
320 doc.reposting_data_file = create_json_gz_file(
321 {
322 "items_to_be_repost": args,
323 "distinct_item_and_warehouse": {str(k): v for k, v in distinct_item_warehouses.items()},
324 "affected_transactions": affected_transactions,
325 },
326 doc,
327 file_name,
328 )
329
330 doc.db_set(
331 {
332 "current_index": index,
333 "total_reposting_count": len(args),
334 "reposting_data_file": doc.reposting_data_file,
335 }
336 )
337
338 else:
339 doc.db_set(
340 {
341 "items_to_be_repost": json.dumps(args, default=str),
342 "distinct_item_and_warehouse": json.dumps(
343 {str(k): v for k, v in distinct_item_warehouses.items()}, default=str
344 ),
345 "current_index": index,
346 "affected_transactions": frappe.as_json(affected_transactions),
347 }
348 )
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530349
Ankush Menatecdb4932022-04-17 19:06:13 +0530350 if not frappe.flags.in_test:
351 frappe.db.commit()
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530352
Ankush Menat494bd9e2022-03-28 18:52:46 +0530353 frappe.publish_realtime(
354 "item_reposting_progress",
Rohit Waghchaurefb1a40c2023-05-31 14:11:15 +0530355 {
356 "name": doc.name,
357 "items_to_be_repost": json.dumps(args, default=str),
358 "current_index": index,
359 "total_reposting_count": len(args),
360 },
Ankush Menat494bd9e2022-03-28 18:52:46 +0530361 )
362
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530363
Rohit Waghchaurefb1a40c2023-05-31 14:11:15 +0530364def get_reposting_file_name(dt, dn):
365 return frappe.db.get_value(
366 "File",
367 {
368 "attached_to_doctype": dt,
369 "attached_to_name": dn,
370 "attached_to_field": "reposting_data_file",
371 },
372 "name",
373 )
374
375
376def create_json_gz_file(data, doc, file_name=None) -> str:
377 encoded_content = frappe.safe_encode(frappe.as_json(data))
378 compressed_content = gzip_compress(encoded_content)
379
380 if not file_name:
381 json_filename = f"{scrub(doc.doctype)}-{scrub(doc.name)}.json.gz"
382 _file = frappe.get_doc(
383 {
384 "doctype": "File",
385 "file_name": json_filename,
386 "attached_to_doctype": doc.doctype,
387 "attached_to_name": doc.name,
388 "attached_to_field": "reposting_data_file",
389 "content": compressed_content,
390 "is_private": 1,
391 }
392 )
393 _file.save(ignore_permissions=True)
394
395 return _file.file_url
396 else:
397 file_doc = frappe.get_doc("File", file_name)
398 path = file_doc.get_full_path()
399
400 with open(path, "wb") as f:
401 f.write(compressed_content)
402
403 return doc.reposting_data_file
404
405
406def get_items_to_be_repost(voucher_type=None, voucher_no=None, doc=None, reposting_data=None):
407 if not reposting_data and doc and doc.reposting_data_file:
408 reposting_data = get_reposting_data(doc.reposting_data_file)
409
410 if reposting_data and reposting_data.items_to_be_repost:
411 return reposting_data.items_to_be_repost
412
Rohit Waghchaure1d80d372022-07-19 16:36:22 +0530413 items_to_be_repost = []
Rohit Waghchaurefb1a40c2023-05-31 14:11:15 +0530414
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530415 if doc and doc.items_to_be_repost:
Rohit Waghchaure1d80d372022-07-19 16:36:22 +0530416 items_to_be_repost = json.loads(doc.items_to_be_repost) or []
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530417
Rohit Waghchaure1d80d372022-07-19 16:36:22 +0530418 if not items_to_be_repost and voucher_type and voucher_no:
419 items_to_be_repost = frappe.db.get_all(
420 "Stock Ledger Entry",
421 filters={"voucher_type": voucher_type, "voucher_no": voucher_no},
422 fields=["item_code", "warehouse", "posting_date", "posting_time", "creation"],
423 order_by="creation asc",
424 group_by="item_code, warehouse",
425 )
426
Nabin Haite1fa7232022-07-20 15:19:09 +0530427 return items_to_be_repost or []
Nabin Hait74c281c2013-08-19 16:17:18 +0530428
Ankush Menat494bd9e2022-03-28 18:52:46 +0530429
Rohit Waghchaurefb1a40c2023-05-31 14:11:15 +0530430def get_distinct_item_warehouse(args=None, doc=None, reposting_data=None):
431 if not reposting_data and doc and doc.reposting_data_file:
432 reposting_data = get_reposting_data(doc.reposting_data_file)
433
434 if reposting_data and reposting_data.distinct_item_and_warehouse:
435 return reposting_data.distinct_item_and_warehouse
436
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530437 distinct_item_warehouses = {}
Rohit Waghchaurefb1a40c2023-05-31 14:11:15 +0530438
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530439 if doc and doc.distinct_item_and_warehouse:
440 distinct_item_warehouses = json.loads(doc.distinct_item_and_warehouse)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530441 distinct_item_warehouses = {
442 frappe.safe_eval(k): frappe._dict(v) for k, v in distinct_item_warehouses.items()
443 }
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530444 else:
445 for i, d in enumerate(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530446 distinct_item_warehouses.setdefault(
447 (d.item_code, d.warehouse), frappe._dict({"reposting_status": False, "sle": d, "args_idx": i})
448 )
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530449
450 return distinct_item_warehouses
451
Ankush Menat494bd9e2022-03-28 18:52:46 +0530452
Rohit Waghchaurefb1a40c2023-05-31 14:11:15 +0530453def get_affected_transactions(doc, reposting_data=None) -> Set[Tuple[str, str]]:
454 if not reposting_data and doc and doc.reposting_data_file:
455 reposting_data = get_reposting_data(doc.reposting_data_file)
456
457 if reposting_data and reposting_data.affected_transactions:
458 return {tuple(transaction) for transaction in reposting_data.affected_transactions}
459
Ankush Menatecdb4932022-04-17 19:06:13 +0530460 if not doc.affected_transactions:
461 return set()
462
463 transactions = frappe.parse_json(doc.affected_transactions)
464 return {tuple(transaction) for transaction in transactions}
465
466
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530467def get_current_index(doc=None):
468 if doc and doc.current_index:
469 return doc.current_index
470
Ankush Menat494bd9e2022-03-28 18:52:46 +0530471
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530472class update_entries_after(object):
Nabin Hait902e8602013-01-08 18:29:24 +0530473 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530474 update valution rate and qty after transaction
475 from the current time-bucket onwards
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530476
Ankush Menat494bd9e2022-03-28 18:52:46 +0530477 :param args: args as dict
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530478
Ankush Menat494bd9e2022-03-28 18:52:46 +0530479 args = {
480 "item_code": "ABC",
481 "warehouse": "XYZ",
482 "posting_date": "2012-12-12",
483 "posting_time": "12:00"
484 }
Nabin Hait902e8602013-01-08 18:29:24 +0530485 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530486
487 def __init__(
488 self,
489 args,
490 allow_zero_rate=False,
491 allow_negative_stock=None,
492 via_landed_cost_voucher=False,
493 verbose=1,
494 ):
Nabin Haita77b8c92020-12-21 14:45:50 +0530495 self.exceptions = {}
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530496 self.verbose = verbose
497 self.allow_zero_rate = allow_zero_rate
Anand Doshi0dc79f42015-04-06 12:59:34 +0530498 self.via_landed_cost_voucher = via_landed_cost_voucher
Ankush Menateb8b4242022-02-12 13:08:28 +0530499 self.item_code = args.get("item_code")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530500 self.allow_negative_stock = allow_negative_stock or is_negative_stock_allowed(
501 item_code=self.item_code
502 )
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530503
Nabin Haita77b8c92020-12-21 14:45:50 +0530504 self.args = frappe._dict(args)
Nabin Haita77b8c92020-12-21 14:45:50 +0530505 if self.args.sle_id:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530506 self.args["name"] = self.args.sle_id
Nabin Haitd46b2362021-02-23 16:38:52 +0530507
Nabin Haita77b8c92020-12-21 14:45:50 +0530508 self.company = frappe.get_cached_value("Warehouse", self.args.warehouse, "company")
Maricad6078aa2022-06-17 15:13:13 +0530509 self.set_precision()
Nabin Haita77b8c92020-12-21 14:45:50 +0530510 self.valuation_method = get_valuation_method(self.item_code)
Nabin Hait97bce3a2021-07-12 13:24:43 +0530511
512 self.new_items_found = False
513 self.distinct_item_warehouses = args.get("distinct_item_warehouses", frappe._dict())
Ankush Menatecdb4932022-04-17 19:06:13 +0530514 self.affected_transactions: Set[Tuple[str, str]] = set()
s-aga-rf0acb202023-04-12 14:13:54 +0530515 self.reserved_stock = get_reserved_stock(self.args.item_code, self.args.warehouse)
Nabin Haita77b8c92020-12-21 14:45:50 +0530516
517 self.data = frappe._dict()
518 self.initialize_previous_data(self.args)
Nabin Haita77b8c92020-12-21 14:45:50 +0530519 self.build()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530520
Maricad6078aa2022-06-17 15:13:13 +0530521 def set_precision(self):
522 self.flt_precision = cint(frappe.db.get_default("float_precision")) or 2
523 self.currency_precision = get_field_precision(
524 frappe.get_meta("Stock Ledger Entry").get_field("stock_value")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530525 )
Nabin Haita77b8c92020-12-21 14:45:50 +0530526
527 def initialize_previous_data(self, args):
528 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530529 Get previous sl entries for current item for each related warehouse
530 and assigns into self.data dict
Nabin Haita77b8c92020-12-21 14:45:50 +0530531
Ankush Menat494bd9e2022-03-28 18:52:46 +0530532 :Data Structure:
Nabin Haita77b8c92020-12-21 14:45:50 +0530533
Ankush Menat494bd9e2022-03-28 18:52:46 +0530534 self.data = {
535 warehouse1: {
536 'previus_sle': {},
537 'qty_after_transaction': 10,
538 'valuation_rate': 100,
539 'stock_value': 1000,
540 'prev_stock_value': 1000,
541 'stock_queue': '[[10, 100]]',
542 'stock_value_difference': 1000
543 }
544 }
Nabin Haita77b8c92020-12-21 14:45:50 +0530545
546 """
Ankush Menatc1d986a2021-08-31 19:43:42 +0530547 self.data.setdefault(args.warehouse, frappe._dict())
548 warehouse_dict = self.data[args.warehouse]
marination8418c4b2021-06-22 21:35:25 +0530549 previous_sle = get_previous_sle_of_current_voucher(args)
Ankush Menatc1d986a2021-08-31 19:43:42 +0530550 warehouse_dict.previous_sle = previous_sle
Nabin Haitbb777562013-08-29 18:19:37 +0530551
Ankush Menatc1d986a2021-08-31 19:43:42 +0530552 for key in ("qty_after_transaction", "valuation_rate", "stock_value"):
553 setattr(warehouse_dict, key, flt(previous_sle.get(key)))
554
Ankush Menat494bd9e2022-03-28 18:52:46 +0530555 warehouse_dict.update(
556 {
557 "prev_stock_value": previous_sle.stock_value or 0.0,
558 "stock_queue": json.loads(previous_sle.stock_queue or "[]"),
559 "stock_value_difference": 0.0,
560 }
561 )
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530562
Nabin Haita77b8c92020-12-21 14:45:50 +0530563 def build(self):
Sagar Vorae50324a2021-03-31 12:44:03 +0530564 from erpnext.controllers.stock_controller import future_sle_exists
Nabin Hait186a0452021-02-18 14:14:21 +0530565
Nabin Haita77b8c92020-12-21 14:45:50 +0530566 if self.args.get("sle_id"):
Nabin Hait186a0452021-02-18 14:14:21 +0530567 self.process_sle_against_current_timestamp()
Sagar Vorae50324a2021-03-31 12:44:03 +0530568 if not future_sle_exists(self.args):
Nabin Hait186a0452021-02-18 14:14:21 +0530569 self.update_bin()
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530570 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530571 entries_to_fix = self.get_future_entries_to_fix()
572
573 i = 0
574 while i < len(entries_to_fix):
575 sle = entries_to_fix[i]
576 i += 1
577
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530578 self.process_sle(sle)
Rohit Waghchaure9e5e2de2023-05-25 23:41:56 +0530579 self.update_bin_data(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530580
Nabin Haita77b8c92020-12-21 14:45:50 +0530581 if sle.dependant_sle_voucher_detail_no:
Nabin Hait243d59b2021-02-02 16:55:13 +0530582 entries_to_fix = self.get_dependent_entries_to_fix(entries_to_fix, sle)
Nabin Haitd46b2362021-02-23 16:38:52 +0530583
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530584 if self.exceptions:
585 self.raise_exceptions()
586
Nabin Hait186a0452021-02-18 14:14:21 +0530587 def process_sle_against_current_timestamp(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530588 sl_entries = self.get_sle_against_current_voucher()
589 for sle in sl_entries:
590 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530591
Nabin Haita77b8c92020-12-21 14:45:50 +0530592 def get_sle_against_current_voucher(self):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530593 self.args["time_format"] = "%H:%i:%s"
Nabin Haitf2be0802021-02-15 19:27:49 +0530594
Ankush Menat494bd9e2022-03-28 18:52:46 +0530595 return frappe.db.sql(
596 """
Nabin Haita77b8c92020-12-21 14:45:50 +0530597 select
598 *, timestamp(posting_date, posting_time) as "timestamp"
599 from
600 `tabStock Ledger Entry`
601 where
602 item_code = %(item_code)s
603 and warehouse = %(warehouse)s
rohitwaghchaurefe4540d2021-08-26 12:52:36 +0530604 and is_cancelled = 0
Rohit Waghchaurea05c47e2022-12-22 10:24:04 +0530605 and (
606 posting_date = %(posting_date)s and
607 time_format(posting_time, %(time_format)s) = time_format(%(posting_time)s, %(time_format)s)
608 )
Nabin Haita77b8c92020-12-21 14:45:50 +0530609 order by
610 creation ASC
611 for update
Ankush Menat494bd9e2022-03-28 18:52:46 +0530612 """,
613 self.args,
614 as_dict=1,
615 )
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530616
Nabin Haita77b8c92020-12-21 14:45:50 +0530617 def get_future_entries_to_fix(self):
618 # includes current entry!
Ankush Menat494bd9e2022-03-28 18:52:46 +0530619 args = self.data[self.args.warehouse].previous_sle or frappe._dict(
620 {"item_code": self.item_code, "warehouse": self.args.warehouse}
621 )
Deepesh Gargb4be2922021-01-28 13:09:56 +0530622
Nabin Haita77b8c92020-12-21 14:45:50 +0530623 return list(self.get_sle_after_datetime(args))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530624
Nabin Haita77b8c92020-12-21 14:45:50 +0530625 def get_dependent_entries_to_fix(self, entries_to_fix, sle):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530626 dependant_sle = get_sle_by_voucher_detail_no(
627 sle.dependant_sle_voucher_detail_no, excluded_sle=sle.name
628 )
Deepesh Gargb4be2922021-01-28 13:09:56 +0530629
Nabin Haita77b8c92020-12-21 14:45:50 +0530630 if not dependant_sle:
Nabin Hait243d59b2021-02-02 16:55:13 +0530631 return entries_to_fix
Ankush Menat494bd9e2022-03-28 18:52:46 +0530632 elif (
633 dependant_sle.item_code == self.item_code and dependant_sle.warehouse == self.args.warehouse
634 ):
Nabin Hait243d59b2021-02-02 16:55:13 +0530635 return entries_to_fix
636 elif dependant_sle.item_code != self.item_code:
Nabin Hait97bce3a2021-07-12 13:24:43 +0530637 self.update_distinct_item_warehouses(dependant_sle)
Nabin Hait243d59b2021-02-02 16:55:13 +0530638 return entries_to_fix
639 elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse in self.data:
640 return entries_to_fix
Nabin Hait97bce3a2021-07-12 13:24:43 +0530641 else:
Rohit Waghchaure1d80d372022-07-19 16:36:22 +0530642 self.initialize_previous_data(dependant_sle)
643 self.update_distinct_item_warehouses(dependant_sle)
Rohit Waghchaure78c8bb22022-07-04 20:24:18 +0530644 return entries_to_fix
Nabin Hait97bce3a2021-07-12 13:24:43 +0530645
646 def update_distinct_item_warehouses(self, dependant_sle):
647 key = (dependant_sle.item_code, dependant_sle.warehouse)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530648 val = frappe._dict({"sle": dependant_sle})
Nabin Hait97bce3a2021-07-12 13:24:43 +0530649 if key not in self.distinct_item_warehouses:
650 self.distinct_item_warehouses[key] = val
651 self.new_items_found = True
652 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530653 existing_sle_posting_date = (
654 self.distinct_item_warehouses[key].get("sle", {}).get("posting_date")
655 )
Nabin Hait97bce3a2021-07-12 13:24:43 +0530656 if getdate(dependant_sle.posting_date) < getdate(existing_sle_posting_date):
657 val.sle_changed = True
658 self.distinct_item_warehouses[key] = val
659 self.new_items_found = True
660
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530661 def process_sle(self, sle):
Ankush Menat66bf21f2022-01-16 20:45:59 +0530662 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
663
Nabin Haita77b8c92020-12-21 14:45:50 +0530664 # previous sle data for this warehouse
665 self.wh_data = self.data[sle.warehouse]
Ankush Menatecdb4932022-04-17 19:06:13 +0530666 self.affected_transactions.add((sle.voucher_type, sle.voucher_no))
Nabin Haita77b8c92020-12-21 14:45:50 +0530667
Anand Doshi0dc79f42015-04-06 12:59:34 +0530668 if (sle.serial_no and not self.via_landed_cost_voucher) or not cint(self.allow_negative_stock):
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530669 # validate negative stock for serialized items, fifo valuation
Nabin Hait902e8602013-01-08 18:29:24 +0530670 # or when negative stock is not allowed for moving average
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530671 if not self.validate_negative_stock(sle):
Nabin Haita77b8c92020-12-21 14:45:50 +0530672 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530673 return
Nabin Haitb96c0142014-10-07 11:25:04 +0530674
Nabin Haita77b8c92020-12-21 14:45:50 +0530675 # Get dynamic incoming/outgoing rate
Ankush Menat701878f2022-03-01 18:08:29 +0530676 if not self.args.get("sle_id"):
677 self.get_dynamic_incoming_outgoing_rate(sle)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530678
Rohit Waghchaure3266e542022-10-12 15:09:50 +0530679 if (
Rohit Waghchaure7bfc8f12023-04-14 12:22:19 +0530680 sle.voucher_type == "Stock Reconciliation"
681 and sle.batch_no
682 and sle.voucher_detail_no
683 and sle.actual_qty < 0
684 ):
685 self.reset_actual_qty_for_stock_reco(sle)
686
687 if (
Rohit Waghchaure3266e542022-10-12 15:09:50 +0530688 sle.voucher_type in ["Purchase Receipt", "Purchase Invoice"]
689 and sle.voucher_detail_no
690 and sle.actual_qty < 0
Rohit Waghchaureb5a2ccf2023-05-04 15:38:35 +0530691 and is_internal_transfer(sle)
Rohit Waghchaure3266e542022-10-12 15:09:50 +0530692 ):
693 sle.outgoing_rate = get_incoming_rate_for_inter_company_transfer(sle)
694
Ankush Menat66bf21f2022-01-16 20:45:59 +0530695 if get_serial_nos(sle.serial_no):
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530696 self.get_serialized_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530697 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530698 if sle.voucher_type == "Stock Reconciliation":
Nabin Haita77b8c92020-12-21 14:45:50 +0530699 self.wh_data.qty_after_transaction = sle.qty_after_transaction
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530700
Ankush Menat494bd9e2022-03-28 18:52:46 +0530701 self.wh_data.stock_value = flt(self.wh_data.qty_after_transaction) * flt(
702 self.wh_data.valuation_rate
703 )
704 elif sle.batch_no and frappe.db.get_value(
705 "Batch", sle.batch_no, "use_batchwise_valuation", cache=True
706 ):
Ankush Menatce0514c2022-02-15 11:41:41 +0530707 self.update_batched_values(sle)
Nabin Haitb96c0142014-10-07 11:25:04 +0530708 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530709 if sle.voucher_type == "Stock Reconciliation" and not sle.batch_no:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530710 # assert
Nabin Haita77b8c92020-12-21 14:45:50 +0530711 self.wh_data.valuation_rate = sle.valuation_rate
712 self.wh_data.qty_after_transaction = sle.qty_after_transaction
Ankush Menat494bd9e2022-03-28 18:52:46 +0530713 self.wh_data.stock_value = flt(self.wh_data.qty_after_transaction) * flt(
714 self.wh_data.valuation_rate
715 )
Ankush Menatb0cf6192022-01-16 13:02:23 +0530716 if self.valuation_method != "Moving Average":
717 self.wh_data.stock_queue = [[self.wh_data.qty_after_transaction, self.wh_data.valuation_rate]]
Nabin Haitb96c0142014-10-07 11:25:04 +0530718 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530719 if self.valuation_method == "Moving Average":
720 self.get_moving_average_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530721 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530722 self.wh_data.stock_value = flt(self.wh_data.qty_after_transaction) * flt(
723 self.wh_data.valuation_rate
724 )
Nabin Haitb96c0142014-10-07 11:25:04 +0530725 else:
Ankush Menatf089d392022-02-02 12:51:21 +0530726 self.update_queue_values(sle)
Nabin Haitb96c0142014-10-07 11:25:04 +0530727
Rushabh Mehta54047782013-12-26 11:07:46 +0530728 # rounding as per precision
Maricad6078aa2022-06-17 15:13:13 +0530729 self.wh_data.stock_value = flt(self.wh_data.stock_value, self.currency_precision)
Ankush Menat609d2fc2022-02-20 11:35:53 +0530730 if not self.wh_data.qty_after_transaction:
731 self.wh_data.stock_value = 0.0
Nabin Haita77b8c92020-12-21 14:45:50 +0530732 stock_value_difference = self.wh_data.stock_value - self.wh_data.prev_stock_value
733 self.wh_data.prev_stock_value = self.wh_data.stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530734
Nabin Hait902e8602013-01-08 18:29:24 +0530735 # update current sle
Nabin Haita77b8c92020-12-21 14:45:50 +0530736 sle.qty_after_transaction = self.wh_data.qty_after_transaction
737 sle.valuation_rate = self.wh_data.valuation_rate
738 sle.stock_value = self.wh_data.stock_value
739 sle.stock_queue = json.dumps(self.wh_data.stock_queue)
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530740 sle.stock_value_difference = stock_value_difference
Ankush Menat494bd9e2022-03-28 18:52:46 +0530741 sle.doctype = "Stock Ledger Entry"
Rohit Waghchaure683a47f2022-10-11 15:11:39 +0530742
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530743 frappe.get_doc(sle).db_update()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530744
Ankush Menat701878f2022-03-01 18:08:29 +0530745 if not self.args.get("sle_id"):
746 self.update_outgoing_rate_on_transaction(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530747
Rohit Waghchaure7bfc8f12023-04-14 12:22:19 +0530748 def reset_actual_qty_for_stock_reco(self, sle):
749 current_qty = frappe.get_cached_value(
750 "Stock Reconciliation Item", sle.voucher_detail_no, "current_qty"
751 )
752
753 if current_qty:
754 sle.actual_qty = current_qty * -1
755 elif current_qty == 0:
756 sle.is_cancelled = 1
757
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530758 def validate_negative_stock(self, sle):
759 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530760 validate negative stock for entries current datetime onwards
761 will not consider cancelled entries
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530762 """
s-aga-rf0acb202023-04-12 14:13:54 +0530763 diff = self.wh_data.qty_after_transaction + flt(sle.actual_qty) - flt(self.reserved_stock)
Maricad6078aa2022-06-17 15:13:13 +0530764 diff = flt(diff, self.flt_precision) # respect system precision
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530765
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530766 if diff < 0 and abs(diff) > 0.0001:
767 # negative stock!
768 exc = sle.copy().update({"diff": diff})
Nabin Haita77b8c92020-12-21 14:45:50 +0530769 self.exceptions.setdefault(sle.warehouse, []).append(exc)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530770 return False
Nabin Hait902e8602013-01-08 18:29:24 +0530771 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530772 return True
773
Nabin Haita77b8c92020-12-21 14:45:50 +0530774 def get_dynamic_incoming_outgoing_rate(self, sle):
775 # Get updated incoming/outgoing rate from transaction
776 if sle.recalculate_rate:
777 rate = self.get_incoming_outgoing_rate_from_transaction(sle)
778
779 if flt(sle.actual_qty) >= 0:
780 sle.incoming_rate = rate
781 else:
782 sle.outgoing_rate = rate
783
784 def get_incoming_outgoing_rate_from_transaction(self, sle):
785 rate = 0
786 # Material Transfer, Repack, Manufacturing
787 if sle.voucher_type == "Stock Entry":
Nabin Hait97bce3a2021-07-12 13:24:43 +0530788 self.recalculate_amounts_in_stock_entry(sle.voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530789 rate = frappe.db.get_value("Stock Entry Detail", sle.voucher_detail_no, "valuation_rate")
790 # Sales and Purchase Return
Ankush Menat494bd9e2022-03-28 18:52:46 +0530791 elif sle.voucher_type in (
792 "Purchase Receipt",
793 "Purchase Invoice",
794 "Delivery Note",
795 "Sales Invoice",
Sagar Sharma323bdf82022-05-17 15:14:07 +0530796 "Subcontracting Receipt",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530797 ):
Nabin Haita77b8c92020-12-21 14:45:50 +0530798 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_return"):
Chillar Anand915b3432021-09-02 16:44:59 +0530799 from erpnext.controllers.sales_and_purchase_return import (
800 get_rate_for_return, # don't move this import to top
801 )
Ankush Menat494bd9e2022-03-28 18:52:46 +0530802
803 rate = get_rate_for_return(
804 sle.voucher_type,
805 sle.voucher_no,
806 sle.item_code,
807 voucher_detail_no=sle.voucher_detail_no,
808 sle=sle,
809 )
Rohit Waghchaureddd24ea2022-08-09 14:50:20 +0530810
811 elif (
812 sle.voucher_type in ["Purchase Receipt", "Purchase Invoice"]
Rohit Waghchaurea03b4ce2022-09-08 19:16:00 +0530813 and sle.voucher_detail_no
Rohit Waghchaureb5a2ccf2023-05-04 15:38:35 +0530814 and is_internal_transfer(sle)
Rohit Waghchaureddd24ea2022-08-09 14:50:20 +0530815 ):
Rohit Waghchaure683a47f2022-10-11 15:11:39 +0530816 rate = get_incoming_rate_for_inter_company_transfer(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530817 else:
818 if sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530819 rate_field = "valuation_rate"
Sagar Sharma323bdf82022-05-17 15:14:07 +0530820 elif sle.voucher_type == "Subcontracting Receipt":
821 rate_field = "rate"
Nabin Haita77b8c92020-12-21 14:45:50 +0530822 else:
823 rate_field = "incoming_rate"
824
825 # check in item table
Ankush Menat494bd9e2022-03-28 18:52:46 +0530826 item_code, incoming_rate = frappe.db.get_value(
827 sle.voucher_type + " Item", sle.voucher_detail_no, ["item_code", rate_field]
828 )
Nabin Haita77b8c92020-12-21 14:45:50 +0530829
830 if item_code == sle.item_code:
831 rate = incoming_rate
832 else:
833 if sle.voucher_type in ("Delivery Note", "Sales Invoice"):
834 ref_doctype = "Packed Item"
Sagar Sharma323bdf82022-05-17 15:14:07 +0530835 elif sle == "Subcontracting Receipt":
836 ref_doctype = "Subcontracting Receipt Supplied Item"
Nabin Haita77b8c92020-12-21 14:45:50 +0530837 else:
838 ref_doctype = "Purchase Receipt Item Supplied"
Deepesh Gargb4be2922021-01-28 13:09:56 +0530839
Ankush Menat494bd9e2022-03-28 18:52:46 +0530840 rate = frappe.db.get_value(
841 ref_doctype,
842 {"parent_detail_docname": sle.voucher_detail_no, "item_code": sle.item_code},
843 rate_field,
844 )
Nabin Haita77b8c92020-12-21 14:45:50 +0530845
846 return rate
847
848 def update_outgoing_rate_on_transaction(self, sle):
849 """
Ankush Menat494bd9e2022-03-28 18:52:46 +0530850 Update outgoing rate in Stock Entry, Delivery Note, Sales Invoice and Sales Return
851 In case of Stock Entry, also calculate FG Item rate and total incoming/outgoing amount
Nabin Haita77b8c92020-12-21 14:45:50 +0530852 """
853 if sle.actual_qty and sle.voucher_detail_no:
854 outgoing_rate = abs(flt(sle.stock_value_difference)) / abs(sle.actual_qty)
855
856 if flt(sle.actual_qty) < 0 and sle.voucher_type == "Stock Entry":
857 self.update_rate_on_stock_entry(sle, outgoing_rate)
858 elif sle.voucher_type in ("Delivery Note", "Sales Invoice"):
859 self.update_rate_on_delivery_and_sales_return(sle, outgoing_rate)
860 elif flt(sle.actual_qty) < 0 and sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
861 self.update_rate_on_purchase_receipt(sle, outgoing_rate)
Sagar Sharma323bdf82022-05-17 15:14:07 +0530862 elif flt(sle.actual_qty) < 0 and sle.voucher_type == "Subcontracting Receipt":
863 self.update_rate_on_subcontracting_receipt(sle, outgoing_rate)
s-aga-r88a3f652023-05-30 16:54:28 +0530864 elif sle.voucher_type == "Stock Reconciliation":
865 self.update_rate_on_stock_reconciliation(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530866
867 def update_rate_on_stock_entry(self, sle, outgoing_rate):
868 frappe.db.set_value("Stock Entry Detail", sle.voucher_detail_no, "basic_rate", outgoing_rate)
869
Ankush Menat701878f2022-03-01 18:08:29 +0530870 # Update outgoing item's rate, recalculate FG Item's rate and total incoming/outgoing amount
871 if not sle.dependant_sle_voucher_detail_no:
872 self.recalculate_amounts_in_stock_entry(sle.voucher_no)
Nabin Hait97bce3a2021-07-12 13:24:43 +0530873
874 def recalculate_amounts_in_stock_entry(self, voucher_no):
875 stock_entry = frappe.get_doc("Stock Entry", voucher_no, for_update=True)
Nabin Haita77b8c92020-12-21 14:45:50 +0530876 stock_entry.calculate_rate_and_amount(reset_outgoing_rate=False, raise_error_if_no_rate=False)
877 stock_entry.db_update()
878 for d in stock_entry.items:
879 d.db_update()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530880
Nabin Haita77b8c92020-12-21 14:45:50 +0530881 def update_rate_on_delivery_and_sales_return(self, sle, outgoing_rate):
882 # Update item's incoming rate on transaction
883 item_code = frappe.db.get_value(sle.voucher_type + " Item", sle.voucher_detail_no, "item_code")
884 if item_code == sle.item_code:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530885 frappe.db.set_value(
886 sle.voucher_type + " Item", sle.voucher_detail_no, "incoming_rate", outgoing_rate
887 )
Nabin Haita77b8c92020-12-21 14:45:50 +0530888 else:
889 # packed item
Ankush Menat494bd9e2022-03-28 18:52:46 +0530890 frappe.db.set_value(
891 "Packed Item",
Nabin Haita77b8c92020-12-21 14:45:50 +0530892 {"parent_detail_docname": sle.voucher_detail_no, "item_code": sle.item_code},
Ankush Menat494bd9e2022-03-28 18:52:46 +0530893 "incoming_rate",
894 outgoing_rate,
895 )
Nabin Haita77b8c92020-12-21 14:45:50 +0530896
897 def update_rate_on_purchase_receipt(self, sle, outgoing_rate):
898 if frappe.db.exists(sle.voucher_type + " Item", sle.voucher_detail_no):
Rohit Waghchaure683a47f2022-10-11 15:11:39 +0530899 if sle.voucher_type in ["Purchase Receipt", "Purchase Invoice"] and frappe.get_cached_value(
900 sle.voucher_type, sle.voucher_no, "is_internal_supplier"
901 ):
902 frappe.db.set_value(
903 f"{sle.voucher_type} Item", sle.voucher_detail_no, "valuation_rate", sle.outgoing_rate
904 )
Nabin Haita77b8c92020-12-21 14:45:50 +0530905 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530906 frappe.db.set_value(
907 "Purchase Receipt Item Supplied", sle.voucher_detail_no, "rate", outgoing_rate
908 )
Nabin Haita77b8c92020-12-21 14:45:50 +0530909
910 # Recalculate subcontracted item's rate in case of subcontracted purchase receipt/invoice
Sagar Sharmad074c932022-03-31 19:57:42 +0530911 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_subcontracted"):
Rohit Waghchauree5fb2392021-06-18 20:37:42 +0530912 doc = frappe.get_doc(sle.voucher_type, sle.voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530913 doc.update_valuation_rate(reset_outgoing_rate=False)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530914 for d in doc.items + doc.supplied_items:
Nabin Haita77b8c92020-12-21 14:45:50 +0530915 d.db_update()
916
Sagar Sharma323bdf82022-05-17 15:14:07 +0530917 def update_rate_on_subcontracting_receipt(self, sle, outgoing_rate):
s-aga-ra6cb6c62023-05-03 09:51:58 +0530918 if frappe.db.exists("Subcontracting Receipt Item", sle.voucher_detail_no):
919 frappe.db.set_value("Subcontracting Receipt Item", sle.voucher_detail_no, "rate", outgoing_rate)
Sagar Sharma323bdf82022-05-17 15:14:07 +0530920 else:
921 frappe.db.set_value(
Sagar Sharma9c72c2a2023-05-12 11:46:32 +0530922 "Subcontracting Receipt Supplied Item",
923 sle.voucher_detail_no,
924 {"rate": outgoing_rate, "amount": abs(sle.actual_qty) * outgoing_rate},
Sagar Sharma323bdf82022-05-17 15:14:07 +0530925 )
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530926
s-aga-ra6cb6c62023-05-03 09:51:58 +0530927 scr = frappe.get_doc("Subcontracting Receipt", sle.voucher_no, for_update=True)
Sagar Sharma9c72c2a2023-05-12 11:46:32 +0530928 scr.calculate_items_qty_and_amount()
s-aga-ra6cb6c62023-05-03 09:51:58 +0530929 scr.db_update()
Sagar Sharma9c72c2a2023-05-12 11:46:32 +0530930 for d in scr.items:
s-aga-ra6cb6c62023-05-03 09:51:58 +0530931 d.db_update()
932
s-aga-r88a3f652023-05-30 16:54:28 +0530933 def update_rate_on_stock_reconciliation(self, sle):
934 if not sle.serial_no and not sle.batch_no:
935 sr = frappe.get_doc("Stock Reconciliation", sle.voucher_no, for_update=True)
936
937 for item in sr.items:
938 # Skip for Serial and Batch Items
939 if item.serial_no or item.batch_no:
940 continue
941
942 previous_sle = get_previous_sle(
943 {
944 "item_code": item.item_code,
945 "warehouse": item.warehouse,
946 "posting_date": sr.posting_date,
947 "posting_time": sr.posting_time,
948 "sle": sle.name,
949 }
950 )
951
952 item.current_qty = previous_sle.get("qty_after_transaction") or 0.0
953 item.current_valuation_rate = previous_sle.get("valuation_rate") or 0.0
954 item.current_amount = flt(item.current_qty) * flt(item.current_valuation_rate)
955
956 item.amount = flt(item.qty) * flt(item.valuation_rate)
957 item.amount_difference = item.amount - item.current_amount
958 else:
959 sr.difference_amount = sum([item.amount_difference for item in sr.items])
960 sr.db_update()
961
962 for item in sr.items:
963 item.db_update()
964
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530965 def get_serialized_values(self, sle):
966 incoming_rate = flt(sle.incoming_rate)
967 actual_qty = flt(sle.actual_qty)
Nabin Hait328c4f92020-01-02 19:00:32 +0530968 serial_nos = cstr(sle.serial_no).split("\n")
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530969
970 if incoming_rate < 0:
971 # wrong incoming rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530972 incoming_rate = self.wh_data.valuation_rate
Rushabh Mehta538607e2016-06-12 11:03:00 +0530973
Nabin Hait2620bf42016-02-29 11:30:27 +0530974 stock_value_change = 0
Ankush Menatb9642a12021-12-21 16:49:41 +0530975 if actual_qty > 0:
Nabin Hait2620bf42016-02-29 11:30:27 +0530976 stock_value_change = actual_qty * incoming_rate
Ankush Menatb9642a12021-12-21 16:49:41 +0530977 else:
Nabin Hait2620bf42016-02-29 11:30:27 +0530978 # In case of delivery/stock issue, get average purchase rate
979 # of serial nos of current entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530980 if not sle.is_cancelled:
981 outgoing_value = self.get_incoming_value_for_serial_nos(sle, serial_nos)
982 stock_value_change = -1 * outgoing_value
983 else:
984 stock_value_change = actual_qty * sle.outgoing_rate
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530985
Nabin Haita77b8c92020-12-21 14:45:50 +0530986 new_stock_qty = self.wh_data.qty_after_transaction + actual_qty
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530987
Nabin Hait2620bf42016-02-29 11:30:27 +0530988 if new_stock_qty > 0:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530989 new_stock_value = (
990 self.wh_data.qty_after_transaction * self.wh_data.valuation_rate
991 ) + stock_value_change
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530992 if new_stock_value >= 0:
Nabin Hait2620bf42016-02-29 11:30:27 +0530993 # calculate new valuation rate only if stock value is positive
994 # else it remains the same as that of previous entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530995 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530996
Nabin Haita77b8c92020-12-21 14:45:50 +0530997 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530998 allow_zero_rate = self.check_if_allow_zero_valuation_rate(
999 sle.voucher_type, sle.voucher_detail_no
1000 )
rohitwaghchaureb1ac9792017-12-01 16:09:02 +05301001 if not allow_zero_rate:
Ankush Menatd7ca83e2022-02-19 19:35:33 +05301002 self.wh_data.valuation_rate = self.get_fallback_rate(sle)
rohitwaghchaureb1ac9792017-12-01 16:09:02 +05301003
Nabin Hait328c4f92020-01-02 19:00:32 +05301004 def get_incoming_value_for_serial_nos(self, sle, serial_nos):
1005 # get rate from serial nos within same company
Ankush Menat494bd9e2022-03-28 18:52:46 +05301006 all_serial_nos = frappe.get_all(
1007 "Serial No", fields=["purchase_rate", "name", "company"], filters={"name": ("in", serial_nos)}
1008 )
Nabin Hait328c4f92020-01-02 19:00:32 +05301009
Ankush Menat494bd9e2022-03-28 18:52:46 +05301010 incoming_values = sum(flt(d.purchase_rate) for d in all_serial_nos if d.company == sle.company)
Nabin Hait328c4f92020-01-02 19:00:32 +05301011
1012 # Get rate for serial nos which has been transferred to other company
Ankush Menat494bd9e2022-03-28 18:52:46 +05301013 invalid_serial_nos = [d.name for d in all_serial_nos if d.company != sle.company]
Nabin Hait328c4f92020-01-02 19:00:32 +05301014 for serial_no in invalid_serial_nos:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301015 incoming_rate = frappe.db.sql(
1016 """
Nabin Hait328c4f92020-01-02 19:00:32 +05301017 select incoming_rate
1018 from `tabStock Ledger Entry`
1019 where
1020 company = %s
1021 and actual_qty > 0
Ankush Menat82ea9582022-01-16 20:19:04 +05301022 and is_cancelled = 0
Nabin Hait328c4f92020-01-02 19:00:32 +05301023 and (serial_no = %s
1024 or serial_no like %s
1025 or serial_no like %s
1026 or serial_no like %s
1027 )
1028 order by posting_date desc
1029 limit 1
Ankush Menat494bd9e2022-03-28 18:52:46 +05301030 """,
1031 (sle.company, serial_no, serial_no + "\n%", "%\n" + serial_no, "%\n" + serial_no + "\n%"),
1032 )
Nabin Hait328c4f92020-01-02 19:00:32 +05301033
1034 incoming_values += flt(incoming_rate[0][0]) if incoming_rate else 0
1035
1036 return incoming_values
1037
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +05301038 def get_moving_average_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +05301039 actual_qty = flt(sle.actual_qty)
Nabin Haita77b8c92020-12-21 14:45:50 +05301040 new_stock_qty = flt(self.wh_data.qty_after_transaction) + actual_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +05301041 if new_stock_qty >= 0:
1042 if actual_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +05301043 if flt(self.wh_data.qty_after_transaction) <= 0:
1044 self.wh_data.valuation_rate = sle.incoming_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +05301045 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301046 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + (
1047 actual_qty * sle.incoming_rate
1048 )
Rushabh Mehta14a908b2015-10-15 12:28:20 +05301049
Nabin Haita77b8c92020-12-21 14:45:50 +05301050 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehta14a908b2015-10-15 12:28:20 +05301051
Nabin Hait6dfc78b2016-06-24 12:28:55 +05301052 elif sle.outgoing_rate:
1053 if new_stock_qty:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301054 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + (
1055 actual_qty * sle.outgoing_rate
1056 )
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +05301057
Nabin Haita77b8c92020-12-21 14:45:50 +05301058 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +05301059 else:
Nabin Haita77b8c92020-12-21 14:45:50 +05301060 self.wh_data.valuation_rate = sle.outgoing_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +05301061 else:
Nabin Haita77b8c92020-12-21 14:45:50 +05301062 if flt(self.wh_data.qty_after_transaction) >= 0 and sle.outgoing_rate:
1063 self.wh_data.valuation_rate = sle.outgoing_rate
Rushabh Mehta14a908b2015-10-15 12:28:20 +05301064
Nabin Haita77b8c92020-12-21 14:45:50 +05301065 if not self.wh_data.valuation_rate and actual_qty > 0:
1066 self.wh_data.valuation_rate = sle.incoming_rate
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +05301067
Rushabh Mehtaaedaac62017-05-04 09:35:19 +05301068 # Get valuation rate from previous SLE or Item master, if item does not have the
Javier Wong9b11d9b2017-04-14 18:24:04 +08001069 # allow zero valuration rate flag set
Nabin Haita77b8c92020-12-21 14:45:50 +05301070 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301071 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(
1072 sle.voucher_type, sle.voucher_detail_no
1073 )
Javier Wong9b11d9b2017-04-14 18:24:04 +08001074 if not allow_zero_valuation_rate:
Ankush Menatd7ca83e2022-02-19 19:35:33 +05301075 self.wh_data.valuation_rate = self.get_fallback_rate(sle)
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +05301076
Ankush Menatf089d392022-02-02 12:51:21 +05301077 def update_queue_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +05301078 incoming_rate = flt(sle.incoming_rate)
1079 actual_qty = flt(sle.actual_qty)
Nabin Haitada485f2015-07-17 15:09:56 +05301080 outgoing_rate = flt(sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +05301081
Ankush Menat494bd9e2022-03-28 18:52:46 +05301082 self.wh_data.qty_after_transaction = round_off_if_near_zero(
1083 self.wh_data.qty_after_transaction + actual_qty
1084 )
Ankush Menatb534fee2022-02-19 20:58:36 +05301085
Ankush Menat97e18a12022-01-15 17:42:25 +05301086 if self.valuation_method == "LIFO":
1087 stock_queue = LIFOValuation(self.wh_data.stock_queue)
1088 else:
1089 stock_queue = FIFOValuation(self.wh_data.stock_queue)
1090
Ankush Menatb534fee2022-02-19 20:58:36 +05301091 _prev_qty, prev_stock_value = stock_queue.get_total_stock_and_value()
1092
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +05301093 if actual_qty > 0:
Ankush Menat97e18a12022-01-15 17:42:25 +05301094 stock_queue.add_stock(qty=actual_qty, rate=incoming_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +05301095 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301096
Ankush Menat4b29fb62021-12-18 18:40:22 +05301097 def rate_generator() -> float:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301098 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(
1099 sle.voucher_type, sle.voucher_detail_no
1100 )
Ankush Menat4b29fb62021-12-18 18:40:22 +05301101 if not allow_zero_valuation_rate:
Ankush Menatd7ca83e2022-02-19 19:35:33 +05301102 return self.get_fallback_rate(sle)
Nabin Haitada485f2015-07-17 15:09:56 +05301103 else:
Ankush Menat4b29fb62021-12-18 18:40:22 +05301104 return 0.0
Rushabh Mehtacca33b22016-07-08 18:24:46 +05301105
Ankush Menat494bd9e2022-03-28 18:52:46 +05301106 stock_queue.remove_stock(
1107 qty=abs(actual_qty), outgoing_rate=outgoing_rate, rate_generator=rate_generator
1108 )
Nabin Haitdc82d4f2014-04-07 12:02:57 +05301109
Ankush Menatb534fee2022-02-19 20:58:36 +05301110 _qty, stock_value = stock_queue.get_total_stock_and_value()
1111
1112 stock_value_difference = stock_value - prev_stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +05301113
Ankush Menat97e18a12022-01-15 17:42:25 +05301114 self.wh_data.stock_queue = stock_queue.state
Ankush Menat494bd9e2022-03-28 18:52:46 +05301115 self.wh_data.stock_value = round_off_if_near_zero(
1116 self.wh_data.stock_value + stock_value_difference
1117 )
Rushabh Mehtacca33b22016-07-08 18:24:46 +05301118
Nabin Haita77b8c92020-12-21 14:45:50 +05301119 if not self.wh_data.stock_queue:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301120 self.wh_data.stock_queue.append(
1121 [0, sle.incoming_rate or sle.outgoing_rate or self.wh_data.valuation_rate]
1122 )
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +05301123
Ankush Menatb534fee2022-02-19 20:58:36 +05301124 if self.wh_data.qty_after_transaction:
1125 self.wh_data.valuation_rate = self.wh_data.stock_value / self.wh_data.qty_after_transaction
1126
Ankush Menatce0514c2022-02-15 11:41:41 +05301127 def update_batched_values(self, sle):
1128 incoming_rate = flt(sle.incoming_rate)
1129 actual_qty = flt(sle.actual_qty)
Ankush Menat4b29fb62021-12-18 18:40:22 +05301130
Ankush Menat494bd9e2022-03-28 18:52:46 +05301131 self.wh_data.qty_after_transaction = round_off_if_near_zero(
1132 self.wh_data.qty_after_transaction + actual_qty
1133 )
Ankush Menatce0514c2022-02-15 11:41:41 +05301134
1135 if actual_qty > 0:
1136 stock_value_difference = incoming_rate * actual_qty
Ankush Menatce0514c2022-02-15 11:41:41 +05301137 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301138 outgoing_rate = get_batch_incoming_rate(
1139 item_code=sle.item_code,
1140 warehouse=sle.warehouse,
1141 batch_no=sle.batch_no,
1142 posting_date=sle.posting_date,
1143 posting_time=sle.posting_time,
1144 creation=sle.creation,
1145 )
Ankush Menataba7a7c2022-02-19 19:36:28 +05301146 if outgoing_rate is None:
1147 # This can *only* happen if qty available for the batch is zero.
1148 # in such case fall back various other rates.
1149 # future entries will correct the overall accounting as each
1150 # batch individually uses moving average rates.
1151 outgoing_rate = self.get_fallback_rate(sle)
Ankush Menatce0514c2022-02-15 11:41:41 +05301152 stock_value_difference = outgoing_rate * actual_qty
Ankush Menatce0514c2022-02-15 11:41:41 +05301153
Ankush Menat494bd9e2022-03-28 18:52:46 +05301154 self.wh_data.stock_value = round_off_if_near_zero(
1155 self.wh_data.stock_value + stock_value_difference
1156 )
Ankush Menatce0514c2022-02-15 11:41:41 +05301157 if self.wh_data.qty_after_transaction:
1158 self.wh_data.valuation_rate = self.wh_data.stock_value / self.wh_data.qty_after_transaction
Ankush Menat4b29fb62021-12-18 18:40:22 +05301159
Javier Wong9b11d9b2017-04-14 18:24:04 +08001160 def check_if_allow_zero_valuation_rate(self, voucher_type, voucher_detail_no):
deepeshgarg007f9c0ef32019-07-30 18:49:19 +05301161 ref_item_dt = ""
1162
1163 if voucher_type == "Stock Entry":
1164 ref_item_dt = voucher_type + " Detail"
1165 elif voucher_type in ["Purchase Invoice", "Sales Invoice", "Delivery Note", "Purchase Receipt"]:
1166 ref_item_dt = voucher_type + " Item"
1167
1168 if ref_item_dt:
1169 return frappe.db.get_value(ref_item_dt, voucher_detail_no, "allow_zero_valuation_rate")
1170 else:
1171 return 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +05301172
Ankush Menatd7ca83e2022-02-19 19:35:33 +05301173 def get_fallback_rate(self, sle) -> float:
1174 """When exact incoming rate isn't available use any of other "average" rates as fallback.
Ankush Menat494bd9e2022-03-28 18:52:46 +05301175 This should only get used for negative stock."""
1176 return get_valuation_rate(
1177 sle.item_code,
1178 sle.warehouse,
1179 sle.voucher_type,
1180 sle.voucher_no,
1181 self.allow_zero_rate,
1182 currency=erpnext.get_company_currency(sle.company),
1183 company=sle.company,
1184 batch_no=sle.batch_no,
1185 )
Ankush Menatd7ca83e2022-02-19 19:35:33 +05301186
Nabin Haita77b8c92020-12-21 14:45:50 +05301187 def get_sle_before_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +05301188 """get previous stock ledger entry before current time-bucket"""
Nabin Haita77b8c92020-12-21 14:45:50 +05301189 sle = get_stock_ledger_entries(args, "<", "desc", "limit 1", for_update=False)
1190 sle = sle[0] if sle else frappe._dict()
1191 return sle
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301192
Nabin Haita77b8c92020-12-21 14:45:50 +05301193 def get_sle_after_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +05301194 """get Stock Ledger Entries after a particular datetime, for reposting"""
Nabin Haita77b8c92020-12-21 14:45:50 +05301195 return get_stock_ledger_entries(args, ">", "asc", for_update=True, check_serial_no=False)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +05301196
1197 def raise_exceptions(self):
Nabin Haita77b8c92020-12-21 14:45:50 +05301198 msg_list = []
Ankush Menat8fe5feb2021-11-04 19:48:32 +05301199 for warehouse, exceptions in self.exceptions.items():
Nabin Haita77b8c92020-12-21 14:45:50 +05301200 deficiency = min(e["diff"] for e in exceptions)
Rushabh Mehta538607e2016-06-12 11:03:00 +05301201
Ankush Menat494bd9e2022-03-28 18:52:46 +05301202 if (
1203 exceptions[0]["voucher_type"],
1204 exceptions[0]["voucher_no"],
1205 ) in frappe.local.flags.currently_saving:
Nabin Hait3edefb12016-07-20 16:13:18 +05301206
Nabin Haita77b8c92020-12-21 14:45:50 +05301207 msg = _("{0} units of {1} needed in {2} to complete this transaction.").format(
s-aga-rf0acb202023-04-12 14:13:54 +05301208 frappe.bold(abs(deficiency)),
Ankush Menat494bd9e2022-03-28 18:52:46 +05301209 frappe.get_desk_link("Item", exceptions[0]["item_code"]),
1210 frappe.get_desk_link("Warehouse", warehouse),
1211 )
Nabin Haita77b8c92020-12-21 14:45:50 +05301212 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301213 msg = _(
1214 "{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction."
1215 ).format(
s-aga-rf0acb202023-04-12 14:13:54 +05301216 frappe.bold(abs(deficiency)),
Ankush Menat494bd9e2022-03-28 18:52:46 +05301217 frappe.get_desk_link("Item", exceptions[0]["item_code"]),
1218 frappe.get_desk_link("Warehouse", warehouse),
1219 exceptions[0]["posting_date"],
1220 exceptions[0]["posting_time"],
1221 frappe.get_desk_link(exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]),
1222 )
Rushabh Mehta538607e2016-06-12 11:03:00 +05301223
Nabin Haita77b8c92020-12-21 14:45:50 +05301224 if msg:
s-aga-rf0acb202023-04-12 14:13:54 +05301225 if self.reserved_stock:
s-aga-r7e8fd8f2023-04-21 17:44:44 +05301226 allowed_qty = abs(exceptions[0]["actual_qty"]) - abs(exceptions[0]["diff"])
1227 msg = "{0} As {1} units are reserved, you are allowed to consume only {2} units.".format(
1228 msg, frappe.bold(self.reserved_stock), frappe.bold(allowed_qty)
1229 )
s-aga-rf0acb202023-04-12 14:13:54 +05301230
Nabin Haita77b8c92020-12-21 14:45:50 +05301231 msg_list.append(msg)
1232
1233 if msg_list:
1234 message = "\n\n".join(msg_list)
1235 if self.verbose:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301236 frappe.throw(message, NegativeStockError, title=_("Insufficient Stock"))
Nabin Haita77b8c92020-12-21 14:45:50 +05301237 else:
1238 raise NegativeStockError(message)
Deepesh Gargb4be2922021-01-28 13:09:56 +05301239
Rohit Waghchaure9e5e2de2023-05-25 23:41:56 +05301240 def update_bin_data(self, sle):
1241 bin_name = get_or_make_bin(sle.item_code, sle.warehouse)
Rohit Waghchaure718ad3f2023-05-26 11:29:22 +05301242 values_to_update = {
1243 "actual_qty": sle.qty_after_transaction,
1244 "stock_value": sle.stock_value,
1245 }
1246
1247 if sle.valuation_rate is not None:
1248 values_to_update["valuation_rate"] = sle.valuation_rate
1249
1250 frappe.db.set_value("Bin", bin_name, values_to_update)
Rohit Waghchaure9e5e2de2023-05-25 23:41:56 +05301251
Nabin Haita77b8c92020-12-21 14:45:50 +05301252 def update_bin(self):
1253 # update bin for each warehouse
Ankush Menat8fe5feb2021-11-04 19:48:32 +05301254 for warehouse, data in self.data.items():
Ankush Menat97060c42021-12-03 11:50:38 +05301255 bin_name = get_or_make_bin(self.item_code, warehouse)
Deepesh Garg6f107da2021-10-12 20:15:55 +05301256
Ankush Menat494bd9e2022-03-28 18:52:46 +05301257 updated_values = {"actual_qty": data.qty_after_transaction, "stock_value": data.stock_value}
Ankush Menat7dd10362022-03-10 17:07:57 +05301258 if data.valuation_rate is not None:
1259 updated_values["valuation_rate"] = data.valuation_rate
Ankush Menat8376fbc2022-10-06 20:35:33 +05301260 frappe.db.set_value("Bin", bin_name, updated_values, update_modified=True)
Nabin Haitdc82d4f2014-04-07 12:02:57 +05301261
marination8418c4b2021-06-22 21:35:25 +05301262
Rohit Waghchaure6d513e22023-02-02 18:40:15 +05301263def get_previous_sle_of_current_voucher(args, operator="<", exclude_current_voucher=False):
marination8418c4b2021-06-22 21:35:25 +05301264 """get stock ledger entries filtered by specific posting datetime conditions"""
1265
Ankush Menat494bd9e2022-03-28 18:52:46 +05301266 args["time_format"] = "%H:%i:%s"
marination8418c4b2021-06-22 21:35:25 +05301267 if not args.get("posting_date"):
1268 args["posting_date"] = "1900-01-01"
1269 if not args.get("posting_time"):
1270 args["posting_time"] = "00:00"
1271
1272 voucher_condition = ""
1273 if exclude_current_voucher:
1274 voucher_no = args.get("voucher_no")
1275 voucher_condition = f"and voucher_no != '{voucher_no}'"
1276
Ankush Menat494bd9e2022-03-28 18:52:46 +05301277 sle = frappe.db.sql(
1278 """
marination8418c4b2021-06-22 21:35:25 +05301279 select *, timestamp(posting_date, posting_time) as "timestamp"
1280 from `tabStock Ledger Entry`
1281 where item_code = %(item_code)s
1282 and warehouse = %(warehouse)s
1283 and is_cancelled = 0
1284 {voucher_condition}
Rohit Waghchaurea05c47e2022-12-22 10:24:04 +05301285 and (
1286 posting_date < %(posting_date)s or
1287 (
1288 posting_date = %(posting_date)s and
Rohit Waghchaure6d513e22023-02-02 18:40:15 +05301289 time_format(posting_time, %(time_format)s) {operator} time_format(%(posting_time)s, %(time_format)s)
Rohit Waghchaurea05c47e2022-12-22 10:24:04 +05301290 )
1291 )
marination8418c4b2021-06-22 21:35:25 +05301292 order by timestamp(posting_date, posting_time) desc, creation desc
1293 limit 1
Ankush Menat494bd9e2022-03-28 18:52:46 +05301294 for update""".format(
Rohit Waghchaure6d513e22023-02-02 18:40:15 +05301295 operator=operator, voucher_condition=voucher_condition
Ankush Menat494bd9e2022-03-28 18:52:46 +05301296 ),
1297 args,
1298 as_dict=1,
1299 )
marination8418c4b2021-06-22 21:35:25 +05301300
1301 return sle[0] if sle else frappe._dict()
1302
Ankush Menat494bd9e2022-03-28 18:52:46 +05301303
Anand Doshi4dc7caa2013-01-11 11:44:49 +05301304def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +05301305 """
Ankush Menat494bd9e2022-03-28 18:52:46 +05301306 get the last sle on or before the current time-bucket,
1307 to get actual qty before transaction, this function
1308 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +05301309
Ankush Menat494bd9e2022-03-28 18:52:46 +05301310 args = {
1311 "item_code": "ABC",
1312 "warehouse": "XYZ",
1313 "posting_date": "2012-12-12",
1314 "posting_time": "12:00",
1315 "sle": "name of reference Stock Ledger Entry"
1316 }
Anand Doshi1b531862013-01-10 19:29:51 +05301317 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +05301318 args["name"] = args.get("sle", None) or ""
1319 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +05301320 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +05301321
Ankush Menat494bd9e2022-03-28 18:52:46 +05301322
1323def get_stock_ledger_entries(
1324 previous_sle,
1325 operator=None,
1326 order="desc",
1327 limit=None,
1328 for_update=False,
1329 debug=False,
1330 check_serial_no=True,
1331):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +05301332 """get stock ledger entries filtered by specific posting datetime conditions"""
Ankush Menat494bd9e2022-03-28 18:52:46 +05301333 conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(
1334 operator
1335 )
Nabin Haitb9ce1042018-02-01 14:58:50 +05301336 if previous_sle.get("warehouse"):
1337 conditions += " and warehouse = %(warehouse)s"
1338 elif previous_sle.get("warehouse_condition"):
1339 conditions += " and " + previous_sle.get("warehouse_condition")
1340
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +05301341 if check_serial_no and previous_sle.get("serial_no"):
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +05301342 # conditions += " and serial_no like {}".format(frappe.db.escape('%{0}%'.format(previous_sle.get("serial_no"))))
1343 serial_no = previous_sle.get("serial_no")
Ankush Menat494bd9e2022-03-28 18:52:46 +05301344 conditions += (
1345 """ and
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +05301346 (
1347 serial_no = {0}
1348 or serial_no like {1}
1349 or serial_no like {2}
1350 or serial_no like {3}
1351 )
Ankush Menat494bd9e2022-03-28 18:52:46 +05301352 """
1353 ).format(
1354 frappe.db.escape(serial_no),
1355 frappe.db.escape("{}\n%".format(serial_no)),
1356 frappe.db.escape("%\n{}".format(serial_no)),
1357 frappe.db.escape("%\n{}\n%".format(serial_no)),
1358 )
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +05301359
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +05301360 if not previous_sle.get("posting_date"):
1361 previous_sle["posting_date"] = "1900-01-01"
1362 if not previous_sle.get("posting_time"):
1363 previous_sle["posting_time"] = "00:00"
1364
1365 if operator in (">", "<=") and previous_sle.get("name"):
1366 conditions += " and name!=%(name)s"
1367
Ankush Menat494bd9e2022-03-28 18:52:46 +05301368 return frappe.db.sql(
1369 """
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301370 select *, timestamp(posting_date, posting_time) as "timestamp"
1371 from `tabStock Ledger Entry`
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +05301372 where item_code = %%(item_code)s
Nabin Haita77b8c92020-12-21 14:45:50 +05301373 and is_cancelled = 0
Nabin Haitb9ce1042018-02-01 14:58:50 +05301374 %(conditions)s
Aditya Hase0c164242019-01-07 22:07:13 +05301375 order by timestamp(posting_date, posting_time) %(order)s, creation %(order)s
Ankush Menat494bd9e2022-03-28 18:52:46 +05301376 %(limit)s %(for_update)s"""
1377 % {
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +05301378 "conditions": conditions,
1379 "limit": limit or "",
1380 "for_update": for_update and "for update" or "",
Ankush Menat494bd9e2022-03-28 18:52:46 +05301381 "order": order,
1382 },
1383 previous_sle,
1384 as_dict=1,
1385 debug=debug,
1386 )
1387
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +05301388
Nabin Haita77b8c92020-12-21 14:45:50 +05301389def get_sle_by_voucher_detail_no(voucher_detail_no, excluded_sle=None):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301390 return frappe.db.get_value(
1391 "Stock Ledger Entry",
Rohit Waghchauref8c852c2023-02-01 15:38:12 +05301392 {"voucher_detail_no": voucher_detail_no, "name": ["!=", excluded_sle], "is_cancelled": 0},
Ankush Menat494bd9e2022-03-28 18:52:46 +05301393 [
1394 "item_code",
1395 "warehouse",
1396 "posting_date",
1397 "posting_time",
1398 "timestamp(posting_date, posting_time) as timestamp",
1399 ],
1400 as_dict=1,
1401 )
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05301402
Ankush Menatce0514c2022-02-15 11:41:41 +05301403
Ankush Menat494bd9e2022-03-28 18:52:46 +05301404def get_batch_incoming_rate(
1405 item_code, warehouse, batch_no, posting_date, posting_time, creation=None
1406):
1407
Ankush Menat102fff22022-02-19 15:51:04 +05301408 sle = frappe.qb.DocType("Stock Ledger Entry")
1409
Ankush Menate1c16872022-04-21 20:01:48 +05301410 timestamp_condition = CombineDatetime(sle.posting_date, sle.posting_time) < CombineDatetime(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301411 posting_date, posting_time
1412 )
Ankush Menat102fff22022-02-19 15:51:04 +05301413 if creation:
1414 timestamp_condition |= (
Ankush Menate1c16872022-04-21 20:01:48 +05301415 CombineDatetime(sle.posting_date, sle.posting_time)
1416 == CombineDatetime(posting_date, posting_time)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301417 ) & (sle.creation < creation)
Ankush Menat102fff22022-02-19 15:51:04 +05301418
1419 batch_details = (
Ankush Menat494bd9e2022-03-28 18:52:46 +05301420 frappe.qb.from_(sle)
1421 .select(Sum(sle.stock_value_difference).as_("batch_value"), Sum(sle.actual_qty).as_("batch_qty"))
1422 .where(
1423 (sle.item_code == item_code)
1424 & (sle.warehouse == warehouse)
1425 & (sle.batch_no == batch_no)
1426 & (sle.is_cancelled == 0)
1427 )
1428 .where(timestamp_condition)
Ankush Menat102fff22022-02-19 15:51:04 +05301429 ).run(as_dict=True)
Ankush Menatce0514c2022-02-15 11:41:41 +05301430
1431 if batch_details and batch_details[0].batch_qty:
1432 return batch_details[0].batch_value / batch_details[0].batch_qty
1433
1434
Ankush Menat494bd9e2022-03-28 18:52:46 +05301435def get_valuation_rate(
1436 item_code,
1437 warehouse,
1438 voucher_type,
1439 voucher_no,
1440 allow_zero_rate=False,
1441 currency=None,
1442 company=None,
1443 raise_error_if_no_rate=True,
1444 batch_no=None,
1445):
Rohit Waghchaurea5f40942017-06-16 15:21:36 +05301446
Ankush Menatf7ffe042021-11-01 13:21:14 +05301447 if not company:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301448 company = frappe.get_cached_value("Warehouse", warehouse, "company")
Ankush Menatf7ffe042021-11-01 13:21:14 +05301449
Ankush Menat342d09a2022-02-19 14:28:51 +05301450 last_valuation_rate = None
1451
1452 # Get moving average rate of a specific batch number
1453 if warehouse and batch_no and frappe.db.get_value("Batch", batch_no, "use_batchwise_valuation"):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301454 last_valuation_rate = frappe.db.sql(
1455 """
Ankush Menat342d09a2022-02-19 14:28:51 +05301456 select sum(stock_value_difference) / sum(actual_qty)
1457 from `tabStock Ledger Entry`
1458 where
1459 item_code = %s
1460 AND warehouse = %s
1461 AND batch_no = %s
1462 AND is_cancelled = 0
1463 AND NOT (voucher_no = %s AND voucher_type = %s)
1464 """,
Ankush Menat494bd9e2022-03-28 18:52:46 +05301465 (item_code, warehouse, batch_no, voucher_no, voucher_type),
1466 )
Ankush Menat342d09a2022-02-19 14:28:51 +05301467
Ankush Menatf7ffe042021-11-01 13:21:14 +05301468 # Get valuation rate from last sle for the same item and warehouse
Ankush Menat342d09a2022-02-19 14:28:51 +05301469 if not last_valuation_rate or last_valuation_rate[0][0] is None:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301470 last_valuation_rate = frappe.db.sql(
1471 """select valuation_rate
Ankush Menat342d09a2022-02-19 14:28:51 +05301472 from `tabStock Ledger Entry` force index (item_warehouse)
1473 where
1474 item_code = %s
1475 AND warehouse = %s
1476 AND valuation_rate >= 0
1477 AND is_cancelled = 0
1478 AND NOT (voucher_no = %s AND voucher_type = %s)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301479 order by posting_date desc, posting_time desc, name desc limit 1""",
1480 (item_code, warehouse, voucher_no, voucher_type),
1481 )
Nabin Haitfb6e4342014-10-15 11:34:40 +05301482
Nabin Haita645f362018-03-01 10:31:24 +05301483 if last_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +05301484 return flt(last_valuation_rate[0][0])
Nabin Haita645f362018-03-01 10:31:24 +05301485
1486 # If negative stock allowed, and item delivered without any incoming entry,
1487 # system does not found any SLE, then take valuation rate from Item
1488 valuation_rate = frappe.db.get_value("Item", item_code, "valuation_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +05301489
1490 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +05301491 # try Item Standard rate
1492 valuation_rate = frappe.db.get_value("Item", item_code, "standard_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +05301493
Rushabh Mehtaaedaac62017-05-04 09:35:19 +05301494 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +05301495 # try in price list
Ankush Menat494bd9e2022-03-28 18:52:46 +05301496 valuation_rate = frappe.db.get_value(
1497 "Item Price", dict(item_code=item_code, buying=1, currency=currency), "price_list_rate"
1498 )
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +05301499
Ankush Menat494bd9e2022-03-28 18:52:46 +05301500 if (
1501 not allow_zero_rate
1502 and not valuation_rate
1503 and raise_error_if_no_rate
1504 and cint(erpnext.is_perpetual_inventory_enabled(company))
1505 ):
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +05301506 form_link = get_link_to_form("Item", item_code)
Marica97715f22020-05-11 20:45:37 +05301507
Ankush Menat494bd9e2022-03-28 18:52:46 +05301508 message = _(
1509 "Valuation Rate for the Item {0}, is required to do accounting entries for {1} {2}."
1510 ).format(form_link, voucher_type, voucher_no)
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +05301511 message += "<br><br>" + _("Here are the options to proceed:")
Ankush Menat494bd9e2022-03-28 18:52:46 +05301512 solutions = (
1513 "<li>"
1514 + _(
1515 "If the item is transacting as a Zero Valuation Rate item in this entry, please enable 'Allow Zero Valuation Rate' in the {0} Item table."
1516 ).format(voucher_type)
1517 + "</li>"
1518 )
1519 solutions += (
1520 "<li>"
1521 + _("If not, you can Cancel / Submit this entry")
1522 + " {0} ".format(frappe.bold("after"))
1523 + _("performing either one below:")
1524 + "</li>"
1525 )
Marica97715f22020-05-11 20:45:37 +05301526 sub_solutions = "<ul><li>" + _("Create an incoming stock transaction for the Item.") + "</li>"
1527 sub_solutions += "<li>" + _("Mention Valuation Rate in the Item master.") + "</li></ul>"
1528 msg = message + solutions + sub_solutions + "</li>"
1529
1530 frappe.throw(msg=msg, title=_("Valuation Rate Missing"))
Nabin Haitfb6e4342014-10-15 11:34:40 +05301531
1532 return valuation_rate
Nabin Haita77b8c92020-12-21 14:45:50 +05301533
Ankush Menat494bd9e2022-03-28 18:52:46 +05301534
Ankush Menate7109c12021-08-26 16:40:45 +05301535def update_qty_in_future_sle(args, allow_negative_stock=False):
marination8418c4b2021-06-22 21:35:25 +05301536 """Recalculate Qty after Transaction in future SLEs based on current SLE."""
marination40389772021-07-02 17:13:45 +05301537 datetime_limit_condition = ""
marination8418c4b2021-06-22 21:35:25 +05301538 qty_shift = args.actual_qty
1539
Ankush Menat7c839c42022-05-06 12:09:08 +05301540 args["time_format"] = "%H:%i:%s"
1541
marination8418c4b2021-06-22 21:35:25 +05301542 # find difference/shift in qty caused by stock reconciliation
1543 if args.voucher_type == "Stock Reconciliation":
marination40389772021-07-02 17:13:45 +05301544 qty_shift = get_stock_reco_qty_shift(args)
1545
1546 # find the next nearest stock reco so that we only recalculate SLEs till that point
1547 next_stock_reco_detail = get_next_stock_reco(args)
1548 if next_stock_reco_detail:
1549 detail = next_stock_reco_detail[0]
Rohit Waghchaureef4bd772023-04-04 23:56:57 +05301550 if detail.batch_no:
1551 regenerate_sle_for_batch_stock_reco(detail)
1552
marination40389772021-07-02 17:13:45 +05301553 # add condition to update SLEs before this date & time
1554 datetime_limit_condition = get_datetime_limit_condition(detail)
marination8418c4b2021-06-22 21:35:25 +05301555
Ankush Menat494bd9e2022-03-28 18:52:46 +05301556 frappe.db.sql(
Ankush Menat7e2fbc02022-05-09 11:13:31 +05301557 f"""
Nabin Hait186a0452021-02-18 14:14:21 +05301558 update `tabStock Ledger Entry`
marination8418c4b2021-06-22 21:35:25 +05301559 set qty_after_transaction = qty_after_transaction + {qty_shift}
Nabin Hait186a0452021-02-18 14:14:21 +05301560 where
1561 item_code = %(item_code)s
1562 and warehouse = %(warehouse)s
1563 and voucher_no != %(voucher_no)s
1564 and is_cancelled = 0
Rohit Waghchaurea05c47e2022-12-22 10:24:04 +05301565 and (
1566 posting_date > %(posting_date)s or
1567 (
1568 posting_date = %(posting_date)s and
1569 time_format(posting_time, %(time_format)s) > time_format(%(posting_time)s, %(time_format)s)
1570 )
1571 )
marination40389772021-07-02 17:13:45 +05301572 {datetime_limit_condition}
Ankush Menat7e2fbc02022-05-09 11:13:31 +05301573 """,
Ankush Menat494bd9e2022-03-28 18:52:46 +05301574 args,
1575 )
Nabin Hait186a0452021-02-18 14:14:21 +05301576
1577 validate_negative_qty_in_future_sle(args, allow_negative_stock)
1578
Ankush Menat494bd9e2022-03-28 18:52:46 +05301579
Rohit Waghchaureef4bd772023-04-04 23:56:57 +05301580def regenerate_sle_for_batch_stock_reco(detail):
1581 doc = frappe.get_cached_doc("Stock Reconciliation", detail.voucher_no)
Rohit Waghchaureef4bd772023-04-04 23:56:57 +05301582 doc.recalculate_current_qty(detail.item_code, detail.batch_no)
Rohit Waghchauref2253dd2023-04-22 11:16:12 +05301583
1584 if not frappe.db.exists(
1585 "Repost Item Valuation", {"voucher_no": doc.name, "status": "Queued", "docstatus": "1"}
1586 ):
Rohit Waghchaure2d5ccc02023-05-01 21:17:18 +05301587 doc.repost_future_sle_and_gle(force=True)
Rohit Waghchaureef4bd772023-04-04 23:56:57 +05301588
1589
marination40389772021-07-02 17:13:45 +05301590def get_stock_reco_qty_shift(args):
1591 stock_reco_qty_shift = 0
1592 if args.get("is_cancelled"):
1593 if args.get("previous_qty_after_transaction"):
1594 # get qty (balance) that was set at submission
1595 last_balance = args.get("previous_qty_after_transaction")
1596 stock_reco_qty_shift = flt(args.qty_after_transaction) - flt(last_balance)
1597 else:
1598 stock_reco_qty_shift = flt(args.actual_qty)
1599 else:
1600 # reco is being submitted
Rohit Waghchaure6d513e22023-02-02 18:40:15 +05301601 last_balance = get_previous_sle_of_current_voucher(args, "<=", exclude_current_voucher=True).get(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301602 "qty_after_transaction"
1603 )
marination40389772021-07-02 17:13:45 +05301604
1605 if last_balance is not None:
1606 stock_reco_qty_shift = flt(args.qty_after_transaction) - flt(last_balance)
1607 else:
1608 stock_reco_qty_shift = args.qty_after_transaction
1609
1610 return stock_reco_qty_shift
1611
Ankush Menat494bd9e2022-03-28 18:52:46 +05301612
Rohit Waghchaured9dd64b2023-04-14 13:00:12 +05301613def get_next_stock_reco(kwargs):
marination40389772021-07-02 17:13:45 +05301614 """Returns next nearest stock reconciliaton's details."""
1615
Rohit Waghchaured9dd64b2023-04-14 13:00:12 +05301616 sle = frappe.qb.DocType("Stock Ledger Entry")
1617
1618 query = (
1619 frappe.qb.from_(sle)
1620 .select(
1621 sle.name,
1622 sle.posting_date,
1623 sle.posting_time,
1624 sle.creation,
1625 sle.voucher_no,
1626 sle.item_code,
1627 sle.batch_no,
1628 sle.actual_qty,
1629 )
1630 .where(
1631 (sle.item_code == kwargs.get("item_code"))
1632 & (sle.warehouse == kwargs.get("warehouse"))
1633 & (sle.voucher_type == "Stock Reconciliation")
1634 & (sle.voucher_no != kwargs.get("voucher_no"))
1635 & (sle.is_cancelled == 0)
1636 & (
1637 (
1638 CombineDatetime(sle.posting_date, sle.posting_time)
1639 > CombineDatetime(kwargs.get("posting_date"), kwargs.get("posting_time"))
Rohit Waghchaure379b2152023-04-24 17:32:32 +05301640 )
1641 | (
1642 (
1643 CombineDatetime(sle.posting_date, sle.posting_time)
1644 == CombineDatetime(kwargs.get("posting_date"), kwargs.get("posting_time"))
Rohit Waghchaured9dd64b2023-04-14 13:00:12 +05301645 )
Rohit Waghchaure379b2152023-04-24 17:32:32 +05301646 & (sle.creation > kwargs.get("creation"))
marination40389772021-07-02 17:13:45 +05301647 )
1648 )
Rohit Waghchaured9dd64b2023-04-14 13:00:12 +05301649 )
Rohit Waghchaure6bccd862023-04-17 14:22:27 +05301650 .orderby(CombineDatetime(sle.posting_date, sle.posting_time))
1651 .orderby(sle.creation)
Rohit Waghchaurefcfa8842023-04-20 09:48:15 +05301652 .limit(1)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301653 )
1654
Rohit Waghchaured9dd64b2023-04-14 13:00:12 +05301655 if kwargs.get("batch_no"):
Deepesh Gargea6eeac2023-04-20 12:48:44 +05301656 query = query.where(sle.batch_no == kwargs.get("batch_no"))
Rohit Waghchaured9dd64b2023-04-14 13:00:12 +05301657
1658 return query.run(as_dict=True)
1659
marination40389772021-07-02 17:13:45 +05301660
1661def get_datetime_limit_condition(detail):
marination40389772021-07-02 17:13:45 +05301662 return f"""
1663 and
1664 (timestamp(posting_date, posting_time) < timestamp('{detail.posting_date}', '{detail.posting_time}')
1665 or (
1666 timestamp(posting_date, posting_time) = timestamp('{detail.posting_date}', '{detail.posting_time}')
1667 and creation < '{detail.creation}'
1668 )
1669 )"""
1670
Ankush Menat494bd9e2022-03-28 18:52:46 +05301671
Ankush Menate7109c12021-08-26 16:40:45 +05301672def validate_negative_qty_in_future_sle(args, allow_negative_stock=False):
Ankush Menateb8b4242022-02-12 13:08:28 +05301673 if allow_negative_stock or is_negative_stock_allowed(item_code=args.item_code):
Ankush Menat5eba5752021-12-07 23:03:52 +05301674 return
1675 if not (args.actual_qty < 0 or args.voucher_type == "Stock Reconciliation"):
1676 return
Deepesh Gargb4be2922021-01-28 13:09:56 +05301677
Ankush Menat5eba5752021-12-07 23:03:52 +05301678 neg_sle = get_future_sle_with_negative_qty(args)
Maricad6078aa2022-06-17 15:13:13 +05301679
1680 if is_negative_with_precision(neg_sle):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301681 message = _(
1682 "{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction."
1683 ).format(
Ankush Menat5eba5752021-12-07 23:03:52 +05301684 abs(neg_sle[0]["qty_after_transaction"]),
Ankush Menat494bd9e2022-03-28 18:52:46 +05301685 frappe.get_desk_link("Item", args.item_code),
1686 frappe.get_desk_link("Warehouse", args.warehouse),
1687 neg_sle[0]["posting_date"],
1688 neg_sle[0]["posting_time"],
1689 frappe.get_desk_link(neg_sle[0]["voucher_type"], neg_sle[0]["voucher_no"]),
1690 )
Ankush Menat5eba5752021-12-07 23:03:52 +05301691
Ankush Menat494bd9e2022-03-28 18:52:46 +05301692 frappe.throw(message, NegativeStockError, title=_("Insufficient Stock"))
Ankush Menat5eba5752021-12-07 23:03:52 +05301693
1694 if not args.batch_no:
1695 return
1696
1697 neg_batch_sle = get_future_sle_with_negative_batch_qty(args)
Maricad6078aa2022-06-17 15:13:13 +05301698 if is_negative_with_precision(neg_batch_sle, is_batch=True):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301699 message = _(
1700 "{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction."
1701 ).format(
Ankush Menat5eba5752021-12-07 23:03:52 +05301702 abs(neg_batch_sle[0]["cumulative_total"]),
Ankush Menat494bd9e2022-03-28 18:52:46 +05301703 frappe.get_desk_link("Batch", args.batch_no),
1704 frappe.get_desk_link("Warehouse", args.warehouse),
1705 neg_batch_sle[0]["posting_date"],
1706 neg_batch_sle[0]["posting_time"],
1707 frappe.get_desk_link(neg_batch_sle[0]["voucher_type"], neg_batch_sle[0]["voucher_no"]),
1708 )
mergify[bot]7a3d3012022-03-08 10:42:30 +05301709 frappe.throw(message, NegativeStockError, title=_("Insufficient Stock for Batch"))
Ankush Menat5eba5752021-12-07 23:03:52 +05301710
Nabin Haita77b8c92020-12-21 14:45:50 +05301711
Maricad6078aa2022-06-17 15:13:13 +05301712def is_negative_with_precision(neg_sle, is_batch=False):
1713 """
1714 Returns whether system precision rounded qty is insufficient.
1715 E.g: -0.0003 in precision 3 (0.000) is sufficient for the user.
1716 """
1717
1718 if not neg_sle:
1719 return False
1720
1721 field = "cumulative_total" if is_batch else "qty_after_transaction"
1722 precision = cint(frappe.db.get_default("float_precision")) or 2
1723 qty_deficit = flt(neg_sle[0][field], precision)
1724
1725 return qty_deficit < 0 and abs(qty_deficit) > 0.0001
1726
1727
Nabin Haita77b8c92020-12-21 14:45:50 +05301728def get_future_sle_with_negative_qty(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301729 return frappe.db.sql(
1730 """
Nabin Haita77b8c92020-12-21 14:45:50 +05301731 select
1732 qty_after_transaction, posting_date, posting_time,
1733 voucher_type, voucher_no
1734 from `tabStock Ledger Entry`
Deepesh Gargb4be2922021-01-28 13:09:56 +05301735 where
Nabin Haita77b8c92020-12-21 14:45:50 +05301736 item_code = %(item_code)s
1737 and warehouse = %(warehouse)s
1738 and voucher_no != %(voucher_no)s
1739 and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s)
1740 and is_cancelled = 0
Nabin Hait186a0452021-02-18 14:14:21 +05301741 and qty_after_transaction < 0
Nabin Hait243d59b2021-02-02 16:55:13 +05301742 order by timestamp(posting_date, posting_time) asc
Nabin Haita77b8c92020-12-21 14:45:50 +05301743 limit 1
Ankush Menat494bd9e2022-03-28 18:52:46 +05301744 """,
1745 args,
1746 as_dict=1,
1747 )
Ankush Menat6a014d12021-04-12 20:21:27 +05301748
Ankush Menat5eba5752021-12-07 23:03:52 +05301749
1750def get_future_sle_with_negative_batch_qty(args):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301751 return frappe.db.sql(
1752 """
Ankush Menat5eba5752021-12-07 23:03:52 +05301753 with batch_ledger as (
1754 select
1755 posting_date, posting_time, voucher_type, voucher_no,
1756 sum(actual_qty) over (order by posting_date, posting_time, creation) as cumulative_total
1757 from `tabStock Ledger Entry`
1758 where
1759 item_code = %(item_code)s
1760 and warehouse = %(warehouse)s
1761 and batch_no=%(batch_no)s
1762 and is_cancelled = 0
1763 order by posting_date, posting_time, creation
1764 )
1765 select * from batch_ledger
1766 where
1767 cumulative_total < 0.0
1768 and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s)
1769 limit 1
Ankush Menat494bd9e2022-03-28 18:52:46 +05301770 """,
1771 args,
1772 as_dict=1,
1773 )
Ankush Menateb8b4242022-02-12 13:08:28 +05301774
1775
1776def is_negative_stock_allowed(*, item_code: Optional[str] = None) -> bool:
1777 if cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock", cache=True)):
1778 return True
1779 if item_code and cint(frappe.db.get_value("Item", item_code, "allow_negative_stock", cache=True)):
1780 return True
1781 return False
Rohit Waghchaure683a47f2022-10-11 15:11:39 +05301782
1783
1784def get_incoming_rate_for_inter_company_transfer(sle) -> float:
1785 """
1786 For inter company transfer, incoming rate is the average of the outgoing rate
1787 """
1788 rate = 0.0
1789
1790 field = "delivery_note_item" if sle.voucher_type == "Purchase Receipt" else "sales_invoice_item"
1791
1792 doctype = "Delivery Note Item" if sle.voucher_type == "Purchase Receipt" else "Sales Invoice Item"
1793
1794 reference_name = frappe.get_cached_value(sle.voucher_type + " Item", sle.voucher_detail_no, field)
1795
1796 if reference_name:
1797 rate = frappe.get_cached_value(
1798 doctype,
1799 reference_name,
1800 "incoming_rate",
1801 )
1802
1803 return rate
Rohit Waghchaureb5a2ccf2023-05-04 15:38:35 +05301804
1805
1806def is_internal_transfer(sle):
1807 data = frappe.get_cached_value(
1808 sle.voucher_type,
1809 sle.voucher_no,
1810 ["is_internal_supplier", "represents_company", "company"],
1811 as_dict=True,
1812 )
1813
1814 if data.is_internal_supplier and data.represents_company == data.company:
1815 return True