blob: 1b90086440fc3b92467f35900df55b6de5c4bb0d [file] [log] [blame]
Anand Doshi885e0742015-03-03 14:55:30 +05301# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
Rushabh Mehtae67d1fb2013-08-05 14:59:54 +05302# License: GNU General Public License v3. See license.txt
Nabin 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 Menateb8b4242022-02-12 13:08:28 +05306from typing import Optional
Chillar Anand915b3432021-09-02 16:44:59 +05307
8import frappe
9from frappe import _
10from frappe.model.meta import get_field_precision
Ankush Menat102fff22022-02-19 15:51:04 +053011from frappe.query_builder.functions import Sum
Ankush Menatcef84c22021-12-03 12:18:59 +053012from frappe.utils import cint, cstr, flt, get_link_to_form, getdate, now, nowdate
Ankush Menat102fff22022-02-19 15:51:04 +053013from pypika import CustomFunction
Achilles Rasquinha361366e2018-02-14 17:08:59 +053014
Chillar Anand915b3432021-09-02 16:44:59 +053015import erpnext
Ankush Menatcef84c22021-12-03 12:18:59 +053016from erpnext.stock.doctype.bin.bin import update_qty as update_bin_qty
Chillar Anand915b3432021-09-02 16:44:59 +053017from erpnext.stock.utils import (
Chillar Anand915b3432021-09-02 16:44:59 +053018 get_incoming_outgoing_rate_for_cancel,
Deepesh Garg6f107da2021-10-12 20:15:55 +053019 get_or_make_bin,
Chillar Anand915b3432021-09-02 16:44:59 +053020 get_valuation_method,
21)
Ankush Menatb534fee2022-02-19 20:58:36 +053022from erpnext.stock.valuation import FIFOValuation, LIFOValuation, round_off_if_near_zero
Chillar Anand915b3432021-09-02 16:44:59 +053023
Nabin Hait97bce3a2021-07-12 13:24:43 +053024
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053025class NegativeStockError(frappe.ValidationError): pass
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +053026class SerialNoExistsInFutureTransaction(frappe.ValidationError):
27 pass
Nabin Hait902e8602013-01-08 18:29:24 +053028
Anand Doshi5b004ff2013-09-25 19:55:41 +053029
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053030def make_sl_entries(sl_entries, allow_negative_stock=False, via_landed_cost_voucher=False):
Rohit Waghchaure4d81d452021-06-15 10:21:44 +053031 from erpnext.controllers.stock_controller import future_sle_exists
Nabin Haitca775742013-09-26 16:16:44 +053032 if sl_entries:
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053033 cancel = sl_entries[0].get("is_cancelled")
Nabin Haitca775742013-09-26 16:16:44 +053034 if cancel:
Nabin Hait186a0452021-02-18 14:14:21 +053035 validate_cancellation(sl_entries)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053036 set_as_cancel(sl_entries[0].get('voucher_type'), sl_entries[0].get('voucher_no'))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053037
Rohit Waghchaure4d81d452021-06-15 10:21:44 +053038 args = get_args_for_future_sle(sl_entries[0])
39 future_sle_exists(args, sl_entries)
40
Nabin Haitca775742013-09-26 16:16:44 +053041 for sle in sl_entries:
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +053042 if sle.serial_no:
43 validate_serial_no(sle)
44
Nabin Haita77b8c92020-12-21 14:45:50 +053045 if cancel:
46 sle['actual_qty'] = -flt(sle.get('actual_qty'))
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053047
Nabin Haita77b8c92020-12-21 14:45:50 +053048 if sle['actual_qty'] < 0 and not sle.get('outgoing_rate'):
49 sle['outgoing_rate'] = get_incoming_outgoing_rate_for_cancel(sle.item_code,
50 sle.voucher_type, sle.voucher_no, sle.voucher_detail_no)
51 sle['incoming_rate'] = 0.0
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053052
Nabin Haita77b8c92020-12-21 14:45:50 +053053 if sle['actual_qty'] > 0 and not sle.get('incoming_rate'):
54 sle['incoming_rate'] = get_incoming_outgoing_rate_for_cancel(sle.item_code,
55 sle.voucher_type, sle.voucher_no, sle.voucher_detail_no)
56 sle['outgoing_rate'] = 0.0
Nabin Haitdc82d4f2014-04-07 12:02:57 +053057
Nabin Hait5288bde2014-11-03 15:08:21 +053058 if sle.get("actual_qty") or sle.get("voucher_type")=="Stock Reconciliation":
Nabin Haita77b8c92020-12-21 14:45:50 +053059 sle_doc = make_entry(sle, allow_negative_stock, via_landed_cost_voucher)
Deepesh Gargb4be2922021-01-28 13:09:56 +053060
Nabin Haita77b8c92020-12-21 14:45:50 +053061 args = sle_doc.as_dict()
marination40389772021-07-02 17:13:45 +053062
63 if sle.get("voucher_type") == "Stock Reconciliation":
64 # preserve previous_qty_after_transaction for qty reposting
65 args.previous_qty_after_transaction = sle.get("previous_qty_after_transaction")
66
Ankush Menatcef84c22021-12-03 12:18:59 +053067 is_stock_item = frappe.get_cached_value('Item', args.get("item_code"), 'is_stock_item')
68 if is_stock_item:
69 bin_name = get_or_make_bin(args.get("item_code"), args.get("warehouse"))
Ankush Menatcef84c22021-12-03 12:18:59 +053070 repost_current_voucher(args, allow_negative_stock, via_landed_cost_voucher)
Ankush Menatff9a6e82021-12-20 15:07:41 +053071 update_bin_qty(bin_name, args)
Ankush Menatcef84c22021-12-03 12:18:59 +053072 else:
73 frappe.msgprint(_("Item {0} ignored since it is not a stock item").format(args.get("item_code")))
74
75def repost_current_voucher(args, allow_negative_stock=False, via_landed_cost_voucher=False):
76 if args.get("actual_qty") or args.get("voucher_type") == "Stock Reconciliation":
77 if not args.get("posting_date"):
78 args["posting_date"] = nowdate()
79
80 if args.get("is_cancelled") and via_landed_cost_voucher:
81 return
82
83 # Reposts only current voucher SL Entries
84 # Updates valuation rate, stock value, stock queue for current transaction
85 update_entries_after({
86 "item_code": args.get('item_code'),
87 "warehouse": args.get('warehouse'),
88 "posting_date": args.get("posting_date"),
89 "posting_time": args.get("posting_time"),
90 "voucher_type": args.get("voucher_type"),
91 "voucher_no": args.get("voucher_no"),
92 "sle_id": args.get('name'),
93 "creation": args.get('creation')
94 }, allow_negative_stock=allow_negative_stock, via_landed_cost_voucher=via_landed_cost_voucher)
95
96 # update qty in future sle and Validate negative qty
97 update_qty_in_future_sle(args, allow_negative_stock)
98
Nabin Haitadeb9762014-10-06 11:53:52 +053099
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530100def get_args_for_future_sle(row):
101 return frappe._dict({
102 'voucher_type': row.get('voucher_type'),
103 'voucher_no': row.get('voucher_no'),
104 'posting_date': row.get('posting_date'),
105 'posting_time': row.get('posting_time')
106 })
107
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530108def validate_serial_no(sle):
109 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
Ankush Menat66bf21f2022-01-16 20:45:59 +0530110
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530111 for sn in get_serial_nos(sle.serial_no):
112 args = copy.deepcopy(sle)
113 args.serial_no = sn
114 args.warehouse = ''
115
116 vouchers = []
117 for row in get_stock_ledger_entries(args, '>'):
118 voucher_type = frappe.bold(row.voucher_type)
119 voucher_no = frappe.bold(get_link_to_form(row.voucher_type, row.voucher_no))
120 vouchers.append(f'{voucher_type} {voucher_no}')
121
122 if vouchers:
123 serial_no = frappe.bold(sn)
124 msg = (f'''The serial no {serial_no} has been used in the future transactions so you need to cancel them first.
125 The list of the transactions are as below.''' + '<br><br><ul><li>')
126
127 msg += '</li><li>'.join(vouchers)
128 msg += '</li></ul>'
129
130 title = 'Cannot Submit' if not sle.get('is_cancelled') else 'Cannot Cancel'
131 frappe.throw(_(msg), title=_(title), exc=SerialNoExistsInFutureTransaction)
132
Nabin Hait186a0452021-02-18 14:14:21 +0530133def validate_cancellation(args):
134 if args[0].get("is_cancelled"):
135 repost_entry = frappe.db.get_value("Repost Item Valuation", {
136 'voucher_type': args[0].voucher_type,
137 'voucher_no': args[0].voucher_no,
138 'docstatus': 1
139 }, ['name', 'status'], as_dict=1)
140
141 if repost_entry:
142 if repost_entry.status == 'In Progress':
143 frappe.throw(_("Cannot cancel the transaction. Reposting of item valuation on submission is not completed yet."))
144 if repost_entry.status == 'Queued':
Nabin Haitd46b2362021-02-23 16:38:52 +0530145 doc = frappe.get_doc("Repost Item Valuation", repost_entry.name)
Ankush Menataa024fc2021-11-18 12:51:26 +0530146 doc.flags.ignore_permissions = True
Nabin Haitd46b2362021-02-23 16:38:52 +0530147 doc.cancel()
148 doc.delete()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530149
Nabin Hait9653f602013-08-20 15:37:33 +0530150def set_as_cancel(voucher_type, voucher_no):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530151 frappe.db.sql("""update `tabStock Ledger Entry` set is_cancelled=1,
Nabin Hait9653f602013-08-20 15:37:33 +0530152 modified=%s, modified_by=%s
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530153 where voucher_type=%s and voucher_no=%s and is_cancelled = 0""",
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530154 (now(), frappe.session.user, voucher_type, voucher_no))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530155
Nabin Hait54c865e2015-03-27 15:38:31 +0530156def make_entry(args, allow_negative_stock=False, via_landed_cost_voucher=False):
Saqib Ansaric7fc6092021-10-12 13:30:40 +0530157 args["doctype"] = "Stock Ledger Entry"
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530158 sle = frappe.get_doc(args)
Anand Doshi6dfd4302015-02-10 14:41:27 +0530159 sle.flags.ignore_permissions = 1
Nabin Hait4ccd8d32015-01-23 12:18:01 +0530160 sle.allow_negative_stock=allow_negative_stock
Nabin Hait54c865e2015-03-27 15:38:31 +0530161 sle.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Haitaeba24e2013-08-23 15:17:36 +0530162 sle.submit()
Nabin Haita77b8c92020-12-21 14:45:50 +0530163 return sle
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530164
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530165def repost_future_sle(args=None, voucher_type=None, voucher_no=None, allow_negative_stock=None, via_landed_cost_voucher=False, doc=None):
Nabin Haita77b8c92020-12-21 14:45:50 +0530166 if not args and voucher_type and voucher_no:
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530167 args = get_items_to_be_repost(voucher_type, voucher_no, doc)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530168
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530169 distinct_item_warehouses = get_distinct_item_warehouse(args, doc)
Nabin Haita77b8c92020-12-21 14:45:50 +0530170
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530171 i = get_current_index(doc) or 0
Nabin Haita77b8c92020-12-21 14:45:50 +0530172 while i < len(args):
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530173 validate_item_warehouse(args[i])
174
Nabin Haita77b8c92020-12-21 14:45:50 +0530175 obj = update_entries_after({
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530176 'item_code': args[i].get('item_code'),
177 'warehouse': args[i].get('warehouse'),
178 'posting_date': args[i].get('posting_date'),
179 'posting_time': args[i].get('posting_time'),
180 'creation': args[i].get('creation'),
181 'distinct_item_warehouses': distinct_item_warehouses
Nabin Haita77b8c92020-12-21 14:45:50 +0530182 }, allow_negative_stock=allow_negative_stock, via_landed_cost_voucher=via_landed_cost_voucher)
183
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530184 distinct_item_warehouses[(args[i].get('item_code'), args[i].get('warehouse'))].reposting_status = True
Deepesh Gargb4be2922021-01-28 13:09:56 +0530185
Nabin Hait97bce3a2021-07-12 13:24:43 +0530186 if obj.new_items_found:
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530187 for item_wh, data in distinct_item_warehouses.items():
Nabin Hait97bce3a2021-07-12 13:24:43 +0530188 if ('args_idx' not in data and not data.reposting_status) or (data.sle_changed and data.reposting_status):
189 data.args_idx = len(args)
190 args.append(data.sle)
191 elif data.sle_changed and not data.reposting_status:
192 args[data.args_idx] = data.sle
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530193
Nabin Hait97bce3a2021-07-12 13:24:43 +0530194 data.sle_changed = False
Nabin Haita77b8c92020-12-21 14:45:50 +0530195 i += 1
196
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530197 if doc and i % 2 == 0:
198 update_args_in_repost_item_valuation(doc, i, args, distinct_item_warehouses)
199
200 if doc and args:
201 update_args_in_repost_item_valuation(doc, i, args, distinct_item_warehouses)
202
203def validate_item_warehouse(args):
204 for field in ['item_code', 'warehouse', 'posting_date', 'posting_time']:
205 if not args.get(field):
206 validation_msg = f'The field {frappe.unscrub(args.get(field))} is required for the reposting'
207 frappe.throw(_(validation_msg))
208
209def update_args_in_repost_item_valuation(doc, index, args, distinct_item_warehouses):
210 frappe.db.set_value(doc.doctype, doc.name, {
211 'items_to_be_repost': json.dumps(args, default=str),
212 'distinct_item_and_warehouse': json.dumps({str(k): v for k,v in distinct_item_warehouses.items()}, default=str),
213 'current_index': index
214 })
215
216 frappe.db.commit()
217
218 frappe.publish_realtime('item_reposting_progress', {
219 'name': doc.name,
220 'items_to_be_repost': json.dumps(args, default=str),
221 'current_index': index
222 })
223
224def get_items_to_be_repost(voucher_type, voucher_no, doc=None):
225 if doc and doc.items_to_be_repost:
226 return json.loads(doc.items_to_be_repost) or []
227
Nabin Haita77b8c92020-12-21 14:45:50 +0530228 return frappe.db.get_all("Stock Ledger Entry",
229 filters={"voucher_type": voucher_type, "voucher_no": voucher_no},
Nabin Hait186a0452021-02-18 14:14:21 +0530230 fields=["item_code", "warehouse", "posting_date", "posting_time", "creation"],
Nabin Haita77b8c92020-12-21 14:45:50 +0530231 order_by="creation asc",
232 group_by="item_code, warehouse"
233 )
Nabin Hait74c281c2013-08-19 16:17:18 +0530234
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530235def get_distinct_item_warehouse(args=None, doc=None):
236 distinct_item_warehouses = {}
237 if doc and doc.distinct_item_and_warehouse:
238 distinct_item_warehouses = json.loads(doc.distinct_item_and_warehouse)
239 distinct_item_warehouses = {frappe.safe_eval(k): frappe._dict(v) for k, v in distinct_item_warehouses.items()}
240 else:
241 for i, d in enumerate(args):
242 distinct_item_warehouses.setdefault((d.item_code, d.warehouse), frappe._dict({
243 "reposting_status": False,
244 "sle": d,
245 "args_idx": i
246 }))
247
248 return distinct_item_warehouses
249
250def get_current_index(doc=None):
251 if doc and doc.current_index:
252 return doc.current_index
253
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530254class update_entries_after(object):
Nabin Hait902e8602013-01-08 18:29:24 +0530255 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530256 update valution rate and qty after transaction
Nabin Hait902e8602013-01-08 18:29:24 +0530257 from the current time-bucket onwards
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530258
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530259 :param args: args as dict
260
261 args = {
262 "item_code": "ABC",
263 "warehouse": "XYZ",
264 "posting_date": "2012-12-12",
265 "posting_time": "12:00"
266 }
Nabin Hait902e8602013-01-08 18:29:24 +0530267 """
Anand Doshi0dc79f42015-04-06 12:59:34 +0530268 def __init__(self, args, allow_zero_rate=False, allow_negative_stock=None, via_landed_cost_voucher=False, verbose=1):
Nabin Haita77b8c92020-12-21 14:45:50 +0530269 self.exceptions = {}
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530270 self.verbose = verbose
271 self.allow_zero_rate = allow_zero_rate
Anand Doshi0dc79f42015-04-06 12:59:34 +0530272 self.via_landed_cost_voucher = via_landed_cost_voucher
Ankush Menateb8b4242022-02-12 13:08:28 +0530273 self.item_code = args.get("item_code")
274 self.allow_negative_stock = allow_negative_stock or is_negative_stock_allowed(item_code=self.item_code)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530275
Nabin Haita77b8c92020-12-21 14:45:50 +0530276 self.args = frappe._dict(args)
Nabin Haita77b8c92020-12-21 14:45:50 +0530277 if self.args.sle_id:
278 self.args['name'] = self.args.sle_id
Nabin Haitd46b2362021-02-23 16:38:52 +0530279
Nabin Haita77b8c92020-12-21 14:45:50 +0530280 self.company = frappe.get_cached_value("Warehouse", self.args.warehouse, "company")
281 self.get_precision()
282 self.valuation_method = get_valuation_method(self.item_code)
Nabin Hait97bce3a2021-07-12 13:24:43 +0530283
284 self.new_items_found = False
285 self.distinct_item_warehouses = args.get("distinct_item_warehouses", frappe._dict())
Nabin Haita77b8c92020-12-21 14:45:50 +0530286
287 self.data = frappe._dict()
288 self.initialize_previous_data(self.args)
Nabin Haita77b8c92020-12-21 14:45:50 +0530289 self.build()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530290
Nabin Haita77b8c92020-12-21 14:45:50 +0530291 def get_precision(self):
292 company_base_currency = frappe.get_cached_value('Company', self.company, "default_currency")
293 self.precision = get_field_precision(frappe.get_meta("Stock Ledger Entry").get_field("stock_value"),
294 currency=company_base_currency)
295
296 def initialize_previous_data(self, args):
297 """
298 Get previous sl entries for current item for each related warehouse
299 and assigns into self.data dict
300
301 :Data Structure:
302
303 self.data = {
304 warehouse1: {
305 'previus_sle': {},
306 'qty_after_transaction': 10,
307 'valuation_rate': 100,
308 'stock_value': 1000,
309 'prev_stock_value': 1000,
310 'stock_queue': '[[10, 100]]',
311 'stock_value_difference': 1000
312 }
313 }
314
315 """
Ankush Menatc1d986a2021-08-31 19:43:42 +0530316 self.data.setdefault(args.warehouse, frappe._dict())
317 warehouse_dict = self.data[args.warehouse]
marination8418c4b2021-06-22 21:35:25 +0530318 previous_sle = get_previous_sle_of_current_voucher(args)
Ankush Menatc1d986a2021-08-31 19:43:42 +0530319 warehouse_dict.previous_sle = previous_sle
Nabin Haitbb777562013-08-29 18:19:37 +0530320
Ankush Menatc1d986a2021-08-31 19:43:42 +0530321 for key in ("qty_after_transaction", "valuation_rate", "stock_value"):
322 setattr(warehouse_dict, key, flt(previous_sle.get(key)))
323
324 warehouse_dict.update({
Nabin Haita77b8c92020-12-21 14:45:50 +0530325 "prev_stock_value": previous_sle.stock_value or 0.0,
326 "stock_queue": json.loads(previous_sle.stock_queue or "[]"),
327 "stock_value_difference": 0.0
328 })
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530329
Nabin Haita77b8c92020-12-21 14:45:50 +0530330 def build(self):
Sagar Vorae50324a2021-03-31 12:44:03 +0530331 from erpnext.controllers.stock_controller import future_sle_exists
Nabin Hait186a0452021-02-18 14:14:21 +0530332
Nabin Haita77b8c92020-12-21 14:45:50 +0530333 if self.args.get("sle_id"):
Nabin Hait186a0452021-02-18 14:14:21 +0530334 self.process_sle_against_current_timestamp()
Sagar Vorae50324a2021-03-31 12:44:03 +0530335 if not future_sle_exists(self.args):
Nabin Hait186a0452021-02-18 14:14:21 +0530336 self.update_bin()
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530337 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530338 entries_to_fix = self.get_future_entries_to_fix()
339
340 i = 0
341 while i < len(entries_to_fix):
342 sle = entries_to_fix[i]
343 i += 1
344
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530345 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530346
Nabin Haita77b8c92020-12-21 14:45:50 +0530347 if sle.dependant_sle_voucher_detail_no:
Nabin Hait243d59b2021-02-02 16:55:13 +0530348 entries_to_fix = self.get_dependent_entries_to_fix(entries_to_fix, sle)
Nabin Haitd46b2362021-02-23 16:38:52 +0530349
Nabin Hait186a0452021-02-18 14:14:21 +0530350 self.update_bin()
Nabin Haita77b8c92020-12-21 14:45:50 +0530351
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530352 if self.exceptions:
353 self.raise_exceptions()
354
Nabin Hait186a0452021-02-18 14:14:21 +0530355 def process_sle_against_current_timestamp(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530356 sl_entries = self.get_sle_against_current_voucher()
357 for sle in sl_entries:
358 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530359
Nabin Haita77b8c92020-12-21 14:45:50 +0530360 def get_sle_against_current_voucher(self):
Nabin Haitf2be0802021-02-15 19:27:49 +0530361 self.args['time_format'] = '%H:%i:%s'
362
Nabin Haita77b8c92020-12-21 14:45:50 +0530363 return frappe.db.sql("""
364 select
365 *, timestamp(posting_date, posting_time) as "timestamp"
366 from
367 `tabStock Ledger Entry`
368 where
369 item_code = %(item_code)s
370 and warehouse = %(warehouse)s
rohitwaghchaurefe4540d2021-08-26 12:52:36 +0530371 and is_cancelled = 0
Nabin Hait186a0452021-02-18 14:14:21 +0530372 and timestamp(posting_date, time_format(posting_time, %(time_format)s)) = timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
373
Nabin Haita77b8c92020-12-21 14:45:50 +0530374 order by
375 creation ASC
376 for update
377 """, self.args, as_dict=1)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530378
Nabin Haita77b8c92020-12-21 14:45:50 +0530379 def get_future_entries_to_fix(self):
380 # includes current entry!
381 args = self.data[self.args.warehouse].previous_sle \
382 or frappe._dict({"item_code": self.item_code, "warehouse": self.args.warehouse})
Deepesh Gargb4be2922021-01-28 13:09:56 +0530383
Nabin Haita77b8c92020-12-21 14:45:50 +0530384 return list(self.get_sle_after_datetime(args))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530385
Nabin Haita77b8c92020-12-21 14:45:50 +0530386 def get_dependent_entries_to_fix(self, entries_to_fix, sle):
387 dependant_sle = get_sle_by_voucher_detail_no(sle.dependant_sle_voucher_detail_no,
388 excluded_sle=sle.name)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530389
Nabin Haita77b8c92020-12-21 14:45:50 +0530390 if not dependant_sle:
Nabin Hait243d59b2021-02-02 16:55:13 +0530391 return entries_to_fix
Nabin Haita77b8c92020-12-21 14:45:50 +0530392 elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse == self.args.warehouse:
Nabin Hait243d59b2021-02-02 16:55:13 +0530393 return entries_to_fix
394 elif dependant_sle.item_code != self.item_code:
Nabin Hait97bce3a2021-07-12 13:24:43 +0530395 self.update_distinct_item_warehouses(dependant_sle)
Nabin Hait243d59b2021-02-02 16:55:13 +0530396 return entries_to_fix
397 elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse in self.data:
398 return entries_to_fix
Nabin Hait97bce3a2021-07-12 13:24:43 +0530399 else:
400 return self.append_future_sle_for_dependant(dependant_sle, entries_to_fix)
401
402 def update_distinct_item_warehouses(self, dependant_sle):
403 key = (dependant_sle.item_code, dependant_sle.warehouse)
404 val = frappe._dict({
405 "sle": dependant_sle
406 })
407 if key not in self.distinct_item_warehouses:
408 self.distinct_item_warehouses[key] = val
409 self.new_items_found = True
410 else:
411 existing_sle_posting_date = self.distinct_item_warehouses[key].get("sle", {}).get("posting_date")
412 if getdate(dependant_sle.posting_date) < getdate(existing_sle_posting_date):
413 val.sle_changed = True
414 self.distinct_item_warehouses[key] = val
415 self.new_items_found = True
416
417 def append_future_sle_for_dependant(self, dependant_sle, entries_to_fix):
Nabin Haita77b8c92020-12-21 14:45:50 +0530418 self.initialize_previous_data(dependant_sle)
419
420 args = self.data[dependant_sle.warehouse].previous_sle \
421 or frappe._dict({"item_code": self.item_code, "warehouse": dependant_sle.warehouse})
422 future_sle_for_dependant = list(self.get_sle_after_datetime(args))
423
424 entries_to_fix.extend(future_sle_for_dependant)
Nabin Hait243d59b2021-02-02 16:55:13 +0530425 return sorted(entries_to_fix, key=lambda k: k['timestamp'])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530426
427 def process_sle(self, sle):
Ankush Menat66bf21f2022-01-16 20:45:59 +0530428 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
429
Nabin Haita77b8c92020-12-21 14:45:50 +0530430 # previous sle data for this warehouse
431 self.wh_data = self.data[sle.warehouse]
432
Anand Doshi0dc79f42015-04-06 12:59:34 +0530433 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 +0530434 # validate negative stock for serialized items, fifo valuation
Nabin Hait902e8602013-01-08 18:29:24 +0530435 # or when negative stock is not allowed for moving average
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530436 if not self.validate_negative_stock(sle):
Nabin Haita77b8c92020-12-21 14:45:50 +0530437 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530438 return
Nabin Haitb96c0142014-10-07 11:25:04 +0530439
Nabin Haita77b8c92020-12-21 14:45:50 +0530440 # Get dynamic incoming/outgoing rate
rohitwaghchauree6a1ad82021-09-15 20:42:47 +0530441 if not self.args.get("sle_id"):
442 self.get_dynamic_incoming_outgoing_rate(sle)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530443
Ankush Menat66bf21f2022-01-16 20:45:59 +0530444 if get_serial_nos(sle.serial_no):
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530445 self.get_serialized_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530446 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530447 if sle.voucher_type == "Stock Reconciliation":
Nabin Haita77b8c92020-12-21 14:45:50 +0530448 self.wh_data.qty_after_transaction = sle.qty_after_transaction
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530449
Nabin Haita77b8c92020-12-21 14:45:50 +0530450 self.wh_data.stock_value = flt(self.wh_data.qty_after_transaction) * flt(self.wh_data.valuation_rate)
Ankush Menatce0514c2022-02-15 11:41:41 +0530451 elif sle.batch_no and frappe.db.get_value("Batch", sle.batch_no, "use_batchwise_valuation", cache=True):
452 self.update_batched_values(sle)
Nabin Haitb96c0142014-10-07 11:25:04 +0530453 else:
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530454 if sle.voucher_type=="Stock Reconciliation" and not sle.batch_no:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530455 # assert
Nabin Haita77b8c92020-12-21 14:45:50 +0530456 self.wh_data.valuation_rate = sle.valuation_rate
457 self.wh_data.qty_after_transaction = sle.qty_after_transaction
Nabin Haita77b8c92020-12-21 14:45:50 +0530458 self.wh_data.stock_value = flt(self.wh_data.qty_after_transaction) * flt(self.wh_data.valuation_rate)
Ankush Menatb0cf6192022-01-16 13:02:23 +0530459 if self.valuation_method != "Moving Average":
460 self.wh_data.stock_queue = [[self.wh_data.qty_after_transaction, self.wh_data.valuation_rate]]
Nabin Haitb96c0142014-10-07 11:25:04 +0530461 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530462 if self.valuation_method == "Moving Average":
463 self.get_moving_average_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530464 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
465 self.wh_data.stock_value = flt(self.wh_data.qty_after_transaction) * flt(self.wh_data.valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530466 else:
Ankush Menatf089d392022-02-02 12:51:21 +0530467 self.update_queue_values(sle)
Nabin Haitb96c0142014-10-07 11:25:04 +0530468
Rushabh Mehta54047782013-12-26 11:07:46 +0530469 # rounding as per precision
Nabin Haita77b8c92020-12-21 14:45:50 +0530470 self.wh_data.stock_value = flt(self.wh_data.stock_value, self.precision)
Ankush Menat609d2fc2022-02-20 11:35:53 +0530471 if not self.wh_data.qty_after_transaction:
472 self.wh_data.stock_value = 0.0
Nabin Haita77b8c92020-12-21 14:45:50 +0530473 stock_value_difference = self.wh_data.stock_value - self.wh_data.prev_stock_value
474 self.wh_data.prev_stock_value = self.wh_data.stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530475
Nabin Hait902e8602013-01-08 18:29:24 +0530476 # update current sle
Nabin Haita77b8c92020-12-21 14:45:50 +0530477 sle.qty_after_transaction = self.wh_data.qty_after_transaction
478 sle.valuation_rate = self.wh_data.valuation_rate
479 sle.stock_value = self.wh_data.stock_value
480 sle.stock_queue = json.dumps(self.wh_data.stock_queue)
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530481 sle.stock_value_difference = stock_value_difference
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530482 sle.doctype="Stock Ledger Entry"
483 frappe.get_doc(sle).db_update()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530484
rohitwaghchauree6a1ad82021-09-15 20:42:47 +0530485 if not self.args.get("sle_id"):
486 self.update_outgoing_rate_on_transaction(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530487
Ankush Menatce0514c2022-02-15 11:41:41 +0530488
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530489 def validate_negative_stock(self, sle):
490 """
491 validate negative stock for entries current datetime onwards
492 will not consider cancelled entries
493 """
Nabin Haita77b8c92020-12-21 14:45:50 +0530494 diff = self.wh_data.qty_after_transaction + flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530495
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530496 if diff < 0 and abs(diff) > 0.0001:
497 # negative stock!
498 exc = sle.copy().update({"diff": diff})
Nabin Haita77b8c92020-12-21 14:45:50 +0530499 self.exceptions.setdefault(sle.warehouse, []).append(exc)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530500 return False
Nabin Hait902e8602013-01-08 18:29:24 +0530501 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530502 return True
503
Nabin Haita77b8c92020-12-21 14:45:50 +0530504 def get_dynamic_incoming_outgoing_rate(self, sle):
505 # Get updated incoming/outgoing rate from transaction
506 if sle.recalculate_rate:
507 rate = self.get_incoming_outgoing_rate_from_transaction(sle)
508
509 if flt(sle.actual_qty) >= 0:
510 sle.incoming_rate = rate
511 else:
512 sle.outgoing_rate = rate
513
514 def get_incoming_outgoing_rate_from_transaction(self, sle):
515 rate = 0
516 # Material Transfer, Repack, Manufacturing
517 if sle.voucher_type == "Stock Entry":
Nabin Hait97bce3a2021-07-12 13:24:43 +0530518 self.recalculate_amounts_in_stock_entry(sle.voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530519 rate = frappe.db.get_value("Stock Entry Detail", sle.voucher_detail_no, "valuation_rate")
520 # Sales and Purchase Return
521 elif sle.voucher_type in ("Purchase Receipt", "Purchase Invoice", "Delivery Note", "Sales Invoice"):
522 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_return"):
Chillar Anand915b3432021-09-02 16:44:59 +0530523 from erpnext.controllers.sales_and_purchase_return import (
524 get_rate_for_return, # don't move this import to top
525 )
rohitwaghchaurece6c3b52021-04-13 20:55:52 +0530526 rate = get_rate_for_return(sle.voucher_type, sle.voucher_no, sle.item_code,
527 voucher_detail_no=sle.voucher_detail_no, sle = sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530528 else:
529 if sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530530 rate_field = "valuation_rate"
Nabin Haita77b8c92020-12-21 14:45:50 +0530531 else:
532 rate_field = "incoming_rate"
533
534 # check in item table
535 item_code, incoming_rate = frappe.db.get_value(sle.voucher_type + " Item",
536 sle.voucher_detail_no, ["item_code", rate_field])
537
538 if item_code == sle.item_code:
539 rate = incoming_rate
540 else:
541 if sle.voucher_type in ("Delivery Note", "Sales Invoice"):
542 ref_doctype = "Packed Item"
543 else:
544 ref_doctype = "Purchase Receipt Item Supplied"
Deepesh Gargb4be2922021-01-28 13:09:56 +0530545
Nabin Haita77b8c92020-12-21 14:45:50 +0530546 rate = frappe.db.get_value(ref_doctype, {"parent_detail_docname": sle.voucher_detail_no,
547 "item_code": sle.item_code}, rate_field)
548
549 return rate
550
551 def update_outgoing_rate_on_transaction(self, sle):
552 """
553 Update outgoing rate in Stock Entry, Delivery Note, Sales Invoice and Sales Return
554 In case of Stock Entry, also calculate FG Item rate and total incoming/outgoing amount
555 """
556 if sle.actual_qty and sle.voucher_detail_no:
557 outgoing_rate = abs(flt(sle.stock_value_difference)) / abs(sle.actual_qty)
558
559 if flt(sle.actual_qty) < 0 and sle.voucher_type == "Stock Entry":
560 self.update_rate_on_stock_entry(sle, outgoing_rate)
561 elif sle.voucher_type in ("Delivery Note", "Sales Invoice"):
562 self.update_rate_on_delivery_and_sales_return(sle, outgoing_rate)
563 elif flt(sle.actual_qty) < 0 and sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
564 self.update_rate_on_purchase_receipt(sle, outgoing_rate)
565
566 def update_rate_on_stock_entry(self, sle, outgoing_rate):
567 frappe.db.set_value("Stock Entry Detail", sle.voucher_detail_no, "basic_rate", outgoing_rate)
568
569 # Update outgoing item's rate, recalculate FG Item's rate and total incoming/outgoing amount
Nabin Hait97bce3a2021-07-12 13:24:43 +0530570 if not sle.dependant_sle_voucher_detail_no:
571 self.recalculate_amounts_in_stock_entry(sle.voucher_no)
572
573 def recalculate_amounts_in_stock_entry(self, voucher_no):
574 stock_entry = frappe.get_doc("Stock Entry", voucher_no, for_update=True)
Nabin Haita77b8c92020-12-21 14:45:50 +0530575 stock_entry.calculate_rate_and_amount(reset_outgoing_rate=False, raise_error_if_no_rate=False)
576 stock_entry.db_update()
577 for d in stock_entry.items:
578 d.db_update()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530579
Nabin Haita77b8c92020-12-21 14:45:50 +0530580 def update_rate_on_delivery_and_sales_return(self, sle, outgoing_rate):
581 # Update item's incoming rate on transaction
582 item_code = frappe.db.get_value(sle.voucher_type + " Item", sle.voucher_detail_no, "item_code")
583 if item_code == sle.item_code:
584 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "incoming_rate", outgoing_rate)
585 else:
586 # packed item
587 frappe.db.set_value("Packed Item",
588 {"parent_detail_docname": sle.voucher_detail_no, "item_code": sle.item_code},
589 "incoming_rate", outgoing_rate)
590
591 def update_rate_on_purchase_receipt(self, sle, outgoing_rate):
592 if frappe.db.exists(sle.voucher_type + " Item", sle.voucher_detail_no):
593 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "base_net_rate", outgoing_rate)
594 else:
595 frappe.db.set_value("Purchase Receipt Item Supplied", sle.voucher_detail_no, "rate", outgoing_rate)
596
597 # Recalculate subcontracted item's rate in case of subcontracted purchase receipt/invoice
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530598 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_subcontracted") == 'Yes':
Rohit Waghchauree5fb2392021-06-18 20:37:42 +0530599 doc = frappe.get_doc(sle.voucher_type, sle.voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530600 doc.update_valuation_rate(reset_outgoing_rate=False)
601 for d in (doc.items + doc.supplied_items):
602 d.db_update()
603
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530604 def get_serialized_values(self, sle):
605 incoming_rate = flt(sle.incoming_rate)
606 actual_qty = flt(sle.actual_qty)
Nabin Hait328c4f92020-01-02 19:00:32 +0530607 serial_nos = cstr(sle.serial_no).split("\n")
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530608
609 if incoming_rate < 0:
610 # wrong incoming rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530611 incoming_rate = self.wh_data.valuation_rate
Rushabh Mehta538607e2016-06-12 11:03:00 +0530612
Nabin Hait2620bf42016-02-29 11:30:27 +0530613 stock_value_change = 0
Ankush Menatb9642a12021-12-21 16:49:41 +0530614 if actual_qty > 0:
Nabin Hait2620bf42016-02-29 11:30:27 +0530615 stock_value_change = actual_qty * incoming_rate
Ankush Menatb9642a12021-12-21 16:49:41 +0530616 else:
Nabin Hait2620bf42016-02-29 11:30:27 +0530617 # In case of delivery/stock issue, get average purchase rate
618 # of serial nos of current entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530619 if not sle.is_cancelled:
620 outgoing_value = self.get_incoming_value_for_serial_nos(sle, serial_nos)
621 stock_value_change = -1 * outgoing_value
622 else:
623 stock_value_change = actual_qty * sle.outgoing_rate
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530624
Nabin Haita77b8c92020-12-21 14:45:50 +0530625 new_stock_qty = self.wh_data.qty_after_transaction + actual_qty
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530626
Nabin Hait2620bf42016-02-29 11:30:27 +0530627 if new_stock_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530628 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + stock_value_change
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530629 if new_stock_value >= 0:
Nabin Hait2620bf42016-02-29 11:30:27 +0530630 # calculate new valuation rate only if stock value is positive
631 # else it remains the same as that of previous entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530632 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530633
Nabin Haita77b8c92020-12-21 14:45:50 +0530634 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530635 allow_zero_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
636 if not allow_zero_rate:
Ankush Menatd7ca83e2022-02-19 19:35:33 +0530637 self.wh_data.valuation_rate = self.get_fallback_rate(sle)
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530638
Nabin Hait328c4f92020-01-02 19:00:32 +0530639 def get_incoming_value_for_serial_nos(self, sle, serial_nos):
640 # get rate from serial nos within same company
641 all_serial_nos = frappe.get_all("Serial No",
642 fields=["purchase_rate", "name", "company"],
643 filters = {'name': ('in', serial_nos)})
644
Ankush Menat98917802021-06-11 18:40:22 +0530645 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 +0530646
647 # Get rate for serial nos which has been transferred to other company
648 invalid_serial_nos = [d.name for d in all_serial_nos if d.company!=sle.company]
649 for serial_no in invalid_serial_nos:
650 incoming_rate = frappe.db.sql("""
651 select incoming_rate
652 from `tabStock Ledger Entry`
653 where
654 company = %s
655 and actual_qty > 0
Ankush Menat82ea9582022-01-16 20:19:04 +0530656 and is_cancelled = 0
Nabin Hait328c4f92020-01-02 19:00:32 +0530657 and (serial_no = %s
658 or serial_no like %s
659 or serial_no like %s
660 or serial_no like %s
661 )
662 order by posting_date desc
663 limit 1
664 """, (sle.company, serial_no, serial_no+'\n%', '%\n'+serial_no, '%\n'+serial_no+'\n%'))
665
666 incoming_values += flt(incoming_rate[0][0]) if incoming_rate else 0
667
668 return incoming_values
669
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530670 def get_moving_average_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530671 actual_qty = flt(sle.actual_qty)
Nabin Haita77b8c92020-12-21 14:45:50 +0530672 new_stock_qty = flt(self.wh_data.qty_after_transaction) + actual_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530673 if new_stock_qty >= 0:
674 if actual_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530675 if flt(self.wh_data.qty_after_transaction) <= 0:
676 self.wh_data.valuation_rate = sle.incoming_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530677 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530678 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530679 (actual_qty * sle.incoming_rate)
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530680
Nabin Haita77b8c92020-12-21 14:45:50 +0530681 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530682
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530683 elif sle.outgoing_rate:
684 if new_stock_qty:
Nabin Haita77b8c92020-12-21 14:45:50 +0530685 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530686 (actual_qty * sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530687
Nabin Haita77b8c92020-12-21 14:45:50 +0530688 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530689 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530690 self.wh_data.valuation_rate = sle.outgoing_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530691 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530692 if flt(self.wh_data.qty_after_transaction) >= 0 and sle.outgoing_rate:
693 self.wh_data.valuation_rate = sle.outgoing_rate
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530694
Nabin Haita77b8c92020-12-21 14:45:50 +0530695 if not self.wh_data.valuation_rate and actual_qty > 0:
696 self.wh_data.valuation_rate = sle.incoming_rate
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530697
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530698 # Get valuation rate from previous SLE or Item master, if item does not have the
Javier Wong9b11d9b2017-04-14 18:24:04 +0800699 # allow zero valuration rate flag set
Nabin Haita77b8c92020-12-21 14:45:50 +0530700 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
Javier Wong9b11d9b2017-04-14 18:24:04 +0800701 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
702 if not allow_zero_valuation_rate:
Ankush Menatd7ca83e2022-02-19 19:35:33 +0530703 self.wh_data.valuation_rate = self.get_fallback_rate(sle)
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530704
Ankush Menatf089d392022-02-02 12:51:21 +0530705 def update_queue_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530706 incoming_rate = flt(sle.incoming_rate)
707 actual_qty = flt(sle.actual_qty)
Nabin Haitada485f2015-07-17 15:09:56 +0530708 outgoing_rate = flt(sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530709
Ankush Menatb534fee2022-02-19 20:58:36 +0530710 self.wh_data.qty_after_transaction = round_off_if_near_zero(self.wh_data.qty_after_transaction + actual_qty)
711
Ankush Menat97e18a12022-01-15 17:42:25 +0530712 if self.valuation_method == "LIFO":
713 stock_queue = LIFOValuation(self.wh_data.stock_queue)
714 else:
715 stock_queue = FIFOValuation(self.wh_data.stock_queue)
716
Ankush Menatb534fee2022-02-19 20:58:36 +0530717 _prev_qty, prev_stock_value = stock_queue.get_total_stock_and_value()
718
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530719 if actual_qty > 0:
Ankush Menat97e18a12022-01-15 17:42:25 +0530720 stock_queue.add_stock(qty=actual_qty, rate=incoming_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530721 else:
Ankush Menat4b29fb62021-12-18 18:40:22 +0530722 def rate_generator() -> float:
723 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
724 if not allow_zero_valuation_rate:
Ankush Menatd7ca83e2022-02-19 19:35:33 +0530725 return self.get_fallback_rate(sle)
Nabin Haitada485f2015-07-17 15:09:56 +0530726 else:
Ankush Menat4b29fb62021-12-18 18:40:22 +0530727 return 0.0
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530728
Ankush Menat97e18a12022-01-15 17:42:25 +0530729 stock_queue.remove_stock(qty=abs(actual_qty), outgoing_rate=outgoing_rate, rate_generator=rate_generator)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530730
Ankush Menatb534fee2022-02-19 20:58:36 +0530731 _qty, stock_value = stock_queue.get_total_stock_and_value()
732
733 stock_value_difference = stock_value - prev_stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530734
Ankush Menat97e18a12022-01-15 17:42:25 +0530735 self.wh_data.stock_queue = stock_queue.state
Ankush Menatb534fee2022-02-19 20:58:36 +0530736 self.wh_data.stock_value = round_off_if_near_zero(self.wh_data.stock_value + stock_value_difference)
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530737
Nabin Haita77b8c92020-12-21 14:45:50 +0530738 if not self.wh_data.stock_queue:
739 self.wh_data.stock_queue.append([0, sle.incoming_rate or sle.outgoing_rate or self.wh_data.valuation_rate])
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530740
Ankush Menatb534fee2022-02-19 20:58:36 +0530741 if self.wh_data.qty_after_transaction:
742 self.wh_data.valuation_rate = self.wh_data.stock_value / self.wh_data.qty_after_transaction
743
Ankush Menatce0514c2022-02-15 11:41:41 +0530744 def update_batched_values(self, sle):
745 incoming_rate = flt(sle.incoming_rate)
746 actual_qty = flt(sle.actual_qty)
Ankush Menat4b29fb62021-12-18 18:40:22 +0530747
Ankush Menat35483242022-02-19 22:22:27 +0530748 self.wh_data.qty_after_transaction = round_off_if_near_zero(self.wh_data.qty_after_transaction + actual_qty)
Ankush Menatce0514c2022-02-15 11:41:41 +0530749
750 if actual_qty > 0:
751 stock_value_difference = incoming_rate * actual_qty
Ankush Menatce0514c2022-02-15 11:41:41 +0530752 else:
Ankush Menat35483242022-02-19 22:22:27 +0530753 outgoing_rate = get_batch_incoming_rate(item_code=sle.item_code,
754 warehouse=sle.warehouse, batch_no=sle.batch_no, posting_date=sle.posting_date,
755 posting_time=sle.posting_time, creation=sle.creation)
Ankush Menataba7a7c2022-02-19 19:36:28 +0530756 if outgoing_rate is None:
757 # This can *only* happen if qty available for the batch is zero.
758 # in such case fall back various other rates.
759 # future entries will correct the overall accounting as each
760 # batch individually uses moving average rates.
761 outgoing_rate = self.get_fallback_rate(sle)
Ankush Menatce0514c2022-02-15 11:41:41 +0530762 stock_value_difference = outgoing_rate * actual_qty
Ankush Menatce0514c2022-02-15 11:41:41 +0530763
Ankush Menat35483242022-02-19 22:22:27 +0530764 self.wh_data.stock_value = round_off_if_near_zero(self.wh_data.stock_value + stock_value_difference)
Ankush Menatce0514c2022-02-15 11:41:41 +0530765 if self.wh_data.qty_after_transaction:
766 self.wh_data.valuation_rate = self.wh_data.stock_value / self.wh_data.qty_after_transaction
Ankush Menat4b29fb62021-12-18 18:40:22 +0530767
Javier Wong9b11d9b2017-04-14 18:24:04 +0800768 def check_if_allow_zero_valuation_rate(self, voucher_type, voucher_detail_no):
deepeshgarg007f9c0ef32019-07-30 18:49:19 +0530769 ref_item_dt = ""
770
771 if voucher_type == "Stock Entry":
772 ref_item_dt = voucher_type + " Detail"
773 elif voucher_type in ["Purchase Invoice", "Sales Invoice", "Delivery Note", "Purchase Receipt"]:
774 ref_item_dt = voucher_type + " Item"
775
776 if ref_item_dt:
777 return frappe.db.get_value(ref_item_dt, voucher_detail_no, "allow_zero_valuation_rate")
778 else:
779 return 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530780
Ankush Menatd7ca83e2022-02-19 19:35:33 +0530781 def get_fallback_rate(self, sle) -> float:
782 """When exact incoming rate isn't available use any of other "average" rates as fallback.
783 This should only get used for negative stock."""
784 return get_valuation_rate(sle.item_code, sle.warehouse,
785 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
786 currency=erpnext.get_company_currency(sle.company), company=sle.company, batch_no=sle.batch_no)
787
Nabin Haita77b8c92020-12-21 14:45:50 +0530788 def get_sle_before_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530789 """get previous stock ledger entry before current time-bucket"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530790 sle = get_stock_ledger_entries(args, "<", "desc", "limit 1", for_update=False)
791 sle = sle[0] if sle else frappe._dict()
792 return sle
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530793
Nabin Haita77b8c92020-12-21 14:45:50 +0530794 def get_sle_after_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530795 """get Stock Ledger Entries after a particular datetime, for reposting"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530796 return get_stock_ledger_entries(args, ">", "asc", for_update=True, check_serial_no=False)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530797
798 def raise_exceptions(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530799 msg_list = []
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530800 for warehouse, exceptions in self.exceptions.items():
Nabin Haita77b8c92020-12-21 14:45:50 +0530801 deficiency = min(e["diff"] for e in exceptions)
Rushabh Mehta538607e2016-06-12 11:03:00 +0530802
Nabin Haita77b8c92020-12-21 14:45:50 +0530803 if ((exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]) in
804 frappe.local.flags.currently_saving):
Nabin Hait3edefb12016-07-20 16:13:18 +0530805
Nabin Haita77b8c92020-12-21 14:45:50 +0530806 msg = _("{0} units of {1} needed in {2} to complete this transaction.").format(
Nabin Hait243d59b2021-02-02 16:55:13 +0530807 abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]),
Nabin Haita77b8c92020-12-21 14:45:50 +0530808 frappe.get_desk_link('Warehouse', warehouse))
809 else:
810 msg = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
Nabin Hait243d59b2021-02-02 16:55:13 +0530811 abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]),
Nabin Haita77b8c92020-12-21 14:45:50 +0530812 frappe.get_desk_link('Warehouse', warehouse),
813 exceptions[0]["posting_date"], exceptions[0]["posting_time"],
814 frappe.get_desk_link(exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530815
Nabin Haita77b8c92020-12-21 14:45:50 +0530816 if msg:
817 msg_list.append(msg)
818
819 if msg_list:
820 message = "\n\n".join(msg_list)
821 if self.verbose:
822 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
823 else:
824 raise NegativeStockError(message)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530825
Nabin Haita77b8c92020-12-21 14:45:50 +0530826 def update_bin(self):
827 # update bin for each warehouse
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530828 for warehouse, data in self.data.items():
Ankush Menat97060c42021-12-03 11:50:38 +0530829 bin_name = get_or_make_bin(self.item_code, warehouse)
Deepesh Garg6f107da2021-10-12 20:15:55 +0530830
Ankush Menat97060c42021-12-03 11:50:38 +0530831 frappe.db.set_value('Bin', bin_name, {
Nabin Haita77b8c92020-12-21 14:45:50 +0530832 "valuation_rate": data.valuation_rate,
833 "actual_qty": data.qty_after_transaction,
834 "stock_value": data.stock_value
835 })
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530836
marination8418c4b2021-06-22 21:35:25 +0530837
838def get_previous_sle_of_current_voucher(args, exclude_current_voucher=False):
839 """get stock ledger entries filtered by specific posting datetime conditions"""
840
841 args['time_format'] = '%H:%i:%s'
842 if not args.get("posting_date"):
843 args["posting_date"] = "1900-01-01"
844 if not args.get("posting_time"):
845 args["posting_time"] = "00:00"
846
847 voucher_condition = ""
848 if exclude_current_voucher:
849 voucher_no = args.get("voucher_no")
850 voucher_condition = f"and voucher_no != '{voucher_no}'"
851
852 sle = frappe.db.sql("""
853 select *, timestamp(posting_date, posting_time) as "timestamp"
854 from `tabStock Ledger Entry`
855 where item_code = %(item_code)s
856 and warehouse = %(warehouse)s
857 and is_cancelled = 0
858 {voucher_condition}
859 and timestamp(posting_date, time_format(posting_time, %(time_format)s)) < timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
860 order by timestamp(posting_date, posting_time) desc, creation desc
861 limit 1
862 for update""".format(voucher_condition=voucher_condition), args, as_dict=1)
863
864 return sle[0] if sle else frappe._dict()
865
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530866def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530867 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530868 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530869 to get actual qty before transaction, this function
870 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530871
Anand Doshi1b531862013-01-10 19:29:51 +0530872 args = {
873 "item_code": "ABC",
874 "warehouse": "XYZ",
875 "posting_date": "2012-12-12",
876 "posting_time": "12:00",
877 "sle": "name of reference Stock Ledger Entry"
878 }
879 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530880 args["name"] = args.get("sle", None) or ""
881 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530882 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530883
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530884def get_stock_ledger_entries(previous_sle, operator=None,
885 order="desc", limit=None, for_update=False, debug=False, check_serial_no=True):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530886 """get stock ledger entries filtered by specific posting datetime conditions"""
Nabin Haitb9ce1042018-02-01 14:58:50 +0530887 conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
888 if previous_sle.get("warehouse"):
889 conditions += " and warehouse = %(warehouse)s"
890 elif previous_sle.get("warehouse_condition"):
891 conditions += " and " + previous_sle.get("warehouse_condition")
892
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530893 if check_serial_no and previous_sle.get("serial_no"):
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530894 # conditions += " and serial_no like {}".format(frappe.db.escape('%{0}%'.format(previous_sle.get("serial_no"))))
895 serial_no = previous_sle.get("serial_no")
896 conditions += (""" and
897 (
898 serial_no = {0}
899 or serial_no like {1}
900 or serial_no like {2}
901 or serial_no like {3}
902 )
903 """).format(frappe.db.escape(serial_no), frappe.db.escape('{}\n%'.format(serial_no)),
904 frappe.db.escape('%\n{}'.format(serial_no)), frappe.db.escape('%\n{}\n%'.format(serial_no)))
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530905
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530906 if not previous_sle.get("posting_date"):
907 previous_sle["posting_date"] = "1900-01-01"
908 if not previous_sle.get("posting_time"):
909 previous_sle["posting_time"] = "00:00"
910
911 if operator in (">", "<=") and previous_sle.get("name"):
912 conditions += " and name!=%(name)s"
913
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530914 return frappe.db.sql("""
915 select *, timestamp(posting_date, posting_time) as "timestamp"
916 from `tabStock Ledger Entry`
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530917 where item_code = %%(item_code)s
Nabin Haita77b8c92020-12-21 14:45:50 +0530918 and is_cancelled = 0
Nabin Haitb9ce1042018-02-01 14:58:50 +0530919 %(conditions)s
Aditya Hase0c164242019-01-07 22:07:13 +0530920 order by timestamp(posting_date, posting_time) %(order)s, creation %(order)s
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530921 %(limit)s %(for_update)s""" % {
922 "conditions": conditions,
923 "limit": limit or "",
924 "for_update": for_update and "for update" or "",
925 "order": order
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530926 }, previous_sle, as_dict=1, debug=debug)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530927
Nabin Haita77b8c92020-12-21 14:45:50 +0530928def get_sle_by_voucher_detail_no(voucher_detail_no, excluded_sle=None):
929 return frappe.db.get_value('Stock Ledger Entry',
930 {'voucher_detail_no': voucher_detail_no, 'name': ['!=', excluded_sle]},
931 ['item_code', 'warehouse', 'posting_date', 'posting_time', 'timestamp(posting_date, posting_time) as timestamp'],
932 as_dict=1)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530933
Ankush Menatab926522022-02-19 15:37:03 +0530934def get_batch_incoming_rate(item_code, warehouse, batch_no, posting_date, posting_time, creation=None):
Ankush Menatce0514c2022-02-15 11:41:41 +0530935
Ankush Menat102fff22022-02-19 15:51:04 +0530936 Timestamp = CustomFunction('timestamp', ['date', 'time'])
937
938 sle = frappe.qb.DocType("Stock Ledger Entry")
939
940 timestamp_condition = (Timestamp(sle.posting_date, sle.posting_time) < Timestamp(posting_date, posting_time))
941 if creation:
942 timestamp_condition |= (
943 (Timestamp(sle.posting_date, sle.posting_time) == Timestamp(posting_date, posting_time))
944 & (sle.creation < creation)
Ankush Menatce0514c2022-02-15 11:41:41 +0530945 )
Ankush Menat102fff22022-02-19 15:51:04 +0530946
947 batch_details = (
948 frappe.qb
949 .from_(sle)
950 .select(
951 Sum(sle.stock_value_difference).as_("batch_value"),
952 Sum(sle.actual_qty).as_("batch_qty")
953 )
954 .where(
955 (sle.item_code == item_code)
956 & (sle.warehouse == warehouse)
957 & (sle.batch_no == batch_no)
958 & (sle.is_cancelled == 0)
959 )
960 .where(timestamp_condition)
961 ).run(as_dict=True)
Ankush Menatce0514c2022-02-15 11:41:41 +0530962
963 if batch_details and batch_details[0].batch_qty:
964 return batch_details[0].batch_value / batch_details[0].batch_qty
965
966
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530967def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no,
Ankush Menat342d09a2022-02-19 14:28:51 +0530968 allow_zero_rate=False, currency=None, company=None, raise_error_if_no_rate=True, batch_no=None):
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530969
Ankush Menatf7ffe042021-11-01 13:21:14 +0530970 if not company:
971 company = frappe.get_cached_value("Warehouse", warehouse, "company")
972
Ankush Menat342d09a2022-02-19 14:28:51 +0530973 last_valuation_rate = None
974
975 # Get moving average rate of a specific batch number
976 if warehouse and batch_no and frappe.db.get_value("Batch", batch_no, "use_batchwise_valuation"):
977 last_valuation_rate = frappe.db.sql("""
978 select sum(stock_value_difference) / sum(actual_qty)
979 from `tabStock Ledger Entry`
980 where
981 item_code = %s
982 AND warehouse = %s
983 AND batch_no = %s
984 AND is_cancelled = 0
985 AND NOT (voucher_no = %s AND voucher_type = %s)
986 """,
987 (item_code, warehouse, batch_no, voucher_no, voucher_type))
988
Ankush Menatf7ffe042021-11-01 13:21:14 +0530989 # Get valuation rate from last sle for the same item and warehouse
Ankush Menat342d09a2022-02-19 14:28:51 +0530990 if not last_valuation_rate or last_valuation_rate[0][0] is None:
991 last_valuation_rate = frappe.db.sql("""select valuation_rate
992 from `tabStock Ledger Entry` force index (item_warehouse)
993 where
994 item_code = %s
995 AND warehouse = %s
996 AND valuation_rate >= 0
997 AND is_cancelled = 0
998 AND NOT (voucher_no = %s AND voucher_type = %s)
999 order by posting_date desc, posting_time desc, name desc limit 1""", (item_code, warehouse, voucher_no, voucher_type))
Nabin Haitfb6e4342014-10-15 11:34:40 +05301000
1001 if not last_valuation_rate:
Nabin Haita0b967f2017-01-18 18:35:58 +05301002 # Get valuation rate from last sle for the item against any warehouse
Nabin Haitfb6e4342014-10-15 11:34:40 +05301003 last_valuation_rate = frappe.db.sql("""select valuation_rate
Deepesh Garg6f107da2021-10-12 20:15:55 +05301004 from `tabStock Ledger Entry` force index (item_code)
Mangesh-Khairnar0df51342019-08-19 10:04:52 +05301005 where
1006 item_code = %s
1007 AND valuation_rate > 0
Ankush Menat82ea9582022-01-16 20:19:04 +05301008 AND is_cancelled = 0
Mangesh-Khairnar0df51342019-08-19 10:04:52 +05301009 AND NOT(voucher_no = %s AND voucher_type = %s)
1010 order by posting_date desc, posting_time desc, name desc limit 1""", (item_code, voucher_no, voucher_type))
Nabin Haitfb6e4342014-10-15 11:34:40 +05301011
Nabin Haita645f362018-03-01 10:31:24 +05301012 if last_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +05301013 return flt(last_valuation_rate[0][0])
Nabin Haita645f362018-03-01 10:31:24 +05301014
1015 # If negative stock allowed, and item delivered without any incoming entry,
1016 # system does not found any SLE, then take valuation rate from Item
1017 valuation_rate = frappe.db.get_value("Item", item_code, "valuation_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +05301018
1019 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +05301020 # try Item Standard rate
1021 valuation_rate = frappe.db.get_value("Item", item_code, "standard_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +05301022
Rushabh Mehtaaedaac62017-05-04 09:35:19 +05301023 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +05301024 # try in price list
1025 valuation_rate = frappe.db.get_value('Item Price',
1026 dict(item_code=item_code, buying=1, currency=currency),
1027 'price_list_rate')
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +05301028
Nabin Hait7ba092e2018-02-01 10:51:27 +05301029 if not allow_zero_rate and not valuation_rate and raise_error_if_no_rate \
Rohit Waghchauree9ff1912017-06-19 12:54:59 +05301030 and cint(erpnext.is_perpetual_inventory_enabled(company)):
Neil Trini Lasrado193c8912017-03-28 17:39:34 +05301031 frappe.local.message_log = []
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +05301032 form_link = get_link_to_form("Item", item_code)
Marica97715f22020-05-11 20:45:37 +05301033
1034 message = _("Valuation Rate for the Item {0}, is required to do accounting entries for {1} {2}.").format(form_link, voucher_type, voucher_no)
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +05301035 message += "<br><br>" + _("Here are the options to proceed:")
Marica97715f22020-05-11 20:45:37 +05301036 solutions = "<li>" + _("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.").format(voucher_type) + "</li>"
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +05301037 solutions += "<li>" + _("If not, you can Cancel / Submit this entry") + " {0} ".format(frappe.bold("after")) + _("performing either one below:") + "</li>"
Marica97715f22020-05-11 20:45:37 +05301038 sub_solutions = "<ul><li>" + _("Create an incoming stock transaction for the Item.") + "</li>"
1039 sub_solutions += "<li>" + _("Mention Valuation Rate in the Item master.") + "</li></ul>"
1040 msg = message + solutions + sub_solutions + "</li>"
1041
1042 frappe.throw(msg=msg, title=_("Valuation Rate Missing"))
Nabin Haitfb6e4342014-10-15 11:34:40 +05301043
1044 return valuation_rate
Nabin Haita77b8c92020-12-21 14:45:50 +05301045
Ankush Menate7109c12021-08-26 16:40:45 +05301046def update_qty_in_future_sle(args, allow_negative_stock=False):
marination8418c4b2021-06-22 21:35:25 +05301047 """Recalculate Qty after Transaction in future SLEs based on current SLE."""
marination40389772021-07-02 17:13:45 +05301048 datetime_limit_condition = ""
marination8418c4b2021-06-22 21:35:25 +05301049 qty_shift = args.actual_qty
1050
1051 # find difference/shift in qty caused by stock reconciliation
1052 if args.voucher_type == "Stock Reconciliation":
marination40389772021-07-02 17:13:45 +05301053 qty_shift = get_stock_reco_qty_shift(args)
1054
1055 # find the next nearest stock reco so that we only recalculate SLEs till that point
1056 next_stock_reco_detail = get_next_stock_reco(args)
1057 if next_stock_reco_detail:
1058 detail = next_stock_reco_detail[0]
1059 # add condition to update SLEs before this date & time
1060 datetime_limit_condition = get_datetime_limit_condition(detail)
marination8418c4b2021-06-22 21:35:25 +05301061
Nabin Hait186a0452021-02-18 14:14:21 +05301062 frappe.db.sql("""
1063 update `tabStock Ledger Entry`
marination8418c4b2021-06-22 21:35:25 +05301064 set qty_after_transaction = qty_after_transaction + {qty_shift}
Nabin Hait186a0452021-02-18 14:14:21 +05301065 where
1066 item_code = %(item_code)s
1067 and warehouse = %(warehouse)s
1068 and voucher_no != %(voucher_no)s
1069 and is_cancelled = 0
1070 and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)
1071 or (
1072 timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s)
1073 and creation > %(creation)s
1074 )
1075 )
marination40389772021-07-02 17:13:45 +05301076 {datetime_limit_condition}
1077 """.format(qty_shift=qty_shift, datetime_limit_condition=datetime_limit_condition), args)
Nabin Hait186a0452021-02-18 14:14:21 +05301078
1079 validate_negative_qty_in_future_sle(args, allow_negative_stock)
1080
marination40389772021-07-02 17:13:45 +05301081def get_stock_reco_qty_shift(args):
1082 stock_reco_qty_shift = 0
1083 if args.get("is_cancelled"):
1084 if args.get("previous_qty_after_transaction"):
1085 # get qty (balance) that was set at submission
1086 last_balance = args.get("previous_qty_after_transaction")
1087 stock_reco_qty_shift = flt(args.qty_after_transaction) - flt(last_balance)
1088 else:
1089 stock_reco_qty_shift = flt(args.actual_qty)
1090 else:
1091 # reco is being submitted
1092 last_balance = get_previous_sle_of_current_voucher(args,
1093 exclude_current_voucher=True).get("qty_after_transaction")
1094
1095 if last_balance is not None:
1096 stock_reco_qty_shift = flt(args.qty_after_transaction) - flt(last_balance)
1097 else:
1098 stock_reco_qty_shift = args.qty_after_transaction
1099
1100 return stock_reco_qty_shift
1101
1102def get_next_stock_reco(args):
1103 """Returns next nearest stock reconciliaton's details."""
1104
1105 return frappe.db.sql("""
1106 select
1107 name, posting_date, posting_time, creation, voucher_no
1108 from
marination8c441262021-07-02 17:46:05 +05301109 `tabStock Ledger Entry`
marination40389772021-07-02 17:13:45 +05301110 where
1111 item_code = %(item_code)s
1112 and warehouse = %(warehouse)s
1113 and voucher_type = 'Stock Reconciliation'
1114 and voucher_no != %(voucher_no)s
1115 and is_cancelled = 0
1116 and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)
1117 or (
1118 timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s)
1119 and creation > %(creation)s
1120 )
1121 )
1122 limit 1
1123 """, args, as_dict=1)
1124
1125def get_datetime_limit_condition(detail):
marination40389772021-07-02 17:13:45 +05301126 return f"""
1127 and
1128 (timestamp(posting_date, posting_time) < timestamp('{detail.posting_date}', '{detail.posting_time}')
1129 or (
1130 timestamp(posting_date, posting_time) = timestamp('{detail.posting_date}', '{detail.posting_time}')
1131 and creation < '{detail.creation}'
1132 )
1133 )"""
1134
Ankush Menate7109c12021-08-26 16:40:45 +05301135def validate_negative_qty_in_future_sle(args, allow_negative_stock=False):
Ankush Menateb8b4242022-02-12 13:08:28 +05301136 if allow_negative_stock or is_negative_stock_allowed(item_code=args.item_code):
Ankush Menat5eba5752021-12-07 23:03:52 +05301137 return
1138 if not (args.actual_qty < 0 or args.voucher_type == "Stock Reconciliation"):
1139 return
Deepesh Gargb4be2922021-01-28 13:09:56 +05301140
Ankush Menat5eba5752021-12-07 23:03:52 +05301141 neg_sle = get_future_sle_with_negative_qty(args)
1142 if neg_sle:
1143 message = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
1144 abs(neg_sle[0]["qty_after_transaction"]),
1145 frappe.get_desk_link('Item', args.item_code),
1146 frappe.get_desk_link('Warehouse', args.warehouse),
1147 neg_sle[0]["posting_date"], neg_sle[0]["posting_time"],
1148 frappe.get_desk_link(neg_sle[0]["voucher_type"], neg_sle[0]["voucher_no"]))
1149
1150 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
1151
1152
1153 if not args.batch_no:
1154 return
1155
1156 neg_batch_sle = get_future_sle_with_negative_batch_qty(args)
1157 if neg_batch_sle:
1158 message = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
1159 abs(neg_batch_sle[0]["cumulative_total"]),
1160 frappe.get_desk_link('Batch', args.batch_no),
1161 frappe.get_desk_link('Warehouse', args.warehouse),
1162 neg_batch_sle[0]["posting_date"], neg_batch_sle[0]["posting_time"],
1163 frappe.get_desk_link(neg_batch_sle[0]["voucher_type"], neg_batch_sle[0]["voucher_no"]))
1164 frappe.throw(message, NegativeStockError, title="Insufficient Stock for Batch")
1165
Nabin Haita77b8c92020-12-21 14:45:50 +05301166
1167def get_future_sle_with_negative_qty(args):
1168 return frappe.db.sql("""
1169 select
1170 qty_after_transaction, posting_date, posting_time,
1171 voucher_type, voucher_no
1172 from `tabStock Ledger Entry`
Deepesh Gargb4be2922021-01-28 13:09:56 +05301173 where
Nabin Haita77b8c92020-12-21 14:45:50 +05301174 item_code = %(item_code)s
1175 and warehouse = %(warehouse)s
1176 and voucher_no != %(voucher_no)s
1177 and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s)
1178 and is_cancelled = 0
Nabin Hait186a0452021-02-18 14:14:21 +05301179 and qty_after_transaction < 0
Nabin Hait243d59b2021-02-02 16:55:13 +05301180 order by timestamp(posting_date, posting_time) asc
Nabin Haita77b8c92020-12-21 14:45:50 +05301181 limit 1
Sagar Vorae50324a2021-03-31 12:44:03 +05301182 """, args, as_dict=1)
Ankush Menat6a014d12021-04-12 20:21:27 +05301183
Ankush Menat5eba5752021-12-07 23:03:52 +05301184
1185def get_future_sle_with_negative_batch_qty(args):
1186 return frappe.db.sql("""
1187 with batch_ledger as (
1188 select
1189 posting_date, posting_time, voucher_type, voucher_no,
1190 sum(actual_qty) over (order by posting_date, posting_time, creation) as cumulative_total
1191 from `tabStock Ledger Entry`
1192 where
1193 item_code = %(item_code)s
1194 and warehouse = %(warehouse)s
1195 and batch_no=%(batch_no)s
1196 and is_cancelled = 0
1197 order by posting_date, posting_time, creation
1198 )
1199 select * from batch_ledger
1200 where
1201 cumulative_total < 0.0
1202 and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s)
1203 limit 1
1204 """, args, as_dict=1)
Ankush Menateb8b4242022-02-12 13:08:28 +05301205
1206
1207def is_negative_stock_allowed(*, item_code: Optional[str] = None) -> bool:
1208 if cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock", cache=True)):
1209 return True
1210 if item_code and cint(frappe.db.get_value("Item", item_code, "allow_negative_stock", cache=True)):
1211 return True
1212 return False