blob: 499632a234084d0e20d17191e8fa9ddc340a424d [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
Chillar Anand915b3432021-09-02 16:44:59 +05306
7import frappe
8from frappe import _
9from frappe.model.meta import get_field_precision
Ankush Menatcef84c22021-12-03 12:18:59 +053010from frappe.utils import cint, cstr, flt, get_link_to_form, getdate, now, nowdate
Achilles Rasquinha361366e2018-02-14 17:08:59 +053011
Chillar Anand915b3432021-09-02 16:44:59 +053012import erpnext
Ankush Menatcef84c22021-12-03 12:18:59 +053013from erpnext.stock.doctype.bin.bin import update_qty as update_bin_qty
Chillar Anand915b3432021-09-02 16:44:59 +053014from erpnext.stock.utils import (
Chillar Anand915b3432021-09-02 16:44:59 +053015 get_incoming_outgoing_rate_for_cancel,
Deepesh Garg6f107da2021-10-12 20:15:55 +053016 get_or_make_bin,
Chillar Anand915b3432021-09-02 16:44:59 +053017 get_valuation_method,
18)
Ankush Menat107b4042021-12-19 20:47:08 +053019from erpnext.stock.valuation import FIFOValuation
Chillar Anand915b3432021-09-02 16:44:59 +053020
Nabin Hait97bce3a2021-07-12 13:24:43 +053021
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053022class NegativeStockError(frappe.ValidationError): pass
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +053023class SerialNoExistsInFutureTransaction(frappe.ValidationError):
24 pass
Nabin Hait902e8602013-01-08 18:29:24 +053025
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053026_exceptions = frappe.local('stockledger_exceptions')
Anand Doshi5b004ff2013-09-25 19:55:41 +053027
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053028def make_sl_entries(sl_entries, allow_negative_stock=False, via_landed_cost_voucher=False):
Rohit Waghchaure4d81d452021-06-15 10:21:44 +053029 from erpnext.controllers.stock_controller import future_sle_exists
Nabin Haitca775742013-09-26 16:16:44 +053030 if sl_entries:
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053031 cancel = sl_entries[0].get("is_cancelled")
Nabin Haitca775742013-09-26 16:16:44 +053032 if cancel:
Nabin Hait186a0452021-02-18 14:14:21 +053033 validate_cancellation(sl_entries)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053034 set_as_cancel(sl_entries[0].get('voucher_type'), sl_entries[0].get('voucher_no'))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053035
Rohit Waghchaure4d81d452021-06-15 10:21:44 +053036 args = get_args_for_future_sle(sl_entries[0])
37 future_sle_exists(args, sl_entries)
38
Nabin Haitca775742013-09-26 16:16:44 +053039 for sle in sl_entries:
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +053040 if sle.serial_no:
41 validate_serial_no(sle)
42
Nabin Haita77b8c92020-12-21 14:45:50 +053043 if cancel:
44 sle['actual_qty'] = -flt(sle.get('actual_qty'))
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053045
Nabin Haita77b8c92020-12-21 14:45:50 +053046 if sle['actual_qty'] < 0 and not sle.get('outgoing_rate'):
47 sle['outgoing_rate'] = get_incoming_outgoing_rate_for_cancel(sle.item_code,
48 sle.voucher_type, sle.voucher_no, sle.voucher_detail_no)
49 sle['incoming_rate'] = 0.0
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053050
Nabin Haita77b8c92020-12-21 14:45:50 +053051 if sle['actual_qty'] > 0 and not sle.get('incoming_rate'):
52 sle['incoming_rate'] = get_incoming_outgoing_rate_for_cancel(sle.item_code,
53 sle.voucher_type, sle.voucher_no, sle.voucher_detail_no)
54 sle['outgoing_rate'] = 0.0
Nabin Haitdc82d4f2014-04-07 12:02:57 +053055
Nabin Hait5288bde2014-11-03 15:08:21 +053056 if sle.get("actual_qty") or sle.get("voucher_type")=="Stock Reconciliation":
Nabin Haita77b8c92020-12-21 14:45:50 +053057 sle_doc = make_entry(sle, allow_negative_stock, via_landed_cost_voucher)
Deepesh Gargb4be2922021-01-28 13:09:56 +053058
Nabin Haita77b8c92020-12-21 14:45:50 +053059 args = sle_doc.as_dict()
marination40389772021-07-02 17:13:45 +053060
61 if sle.get("voucher_type") == "Stock Reconciliation":
62 # preserve previous_qty_after_transaction for qty reposting
63 args.previous_qty_after_transaction = sle.get("previous_qty_after_transaction")
64
Ankush Menatcef84c22021-12-03 12:18:59 +053065 is_stock_item = frappe.get_cached_value('Item', args.get("item_code"), 'is_stock_item')
66 if is_stock_item:
67 bin_name = get_or_make_bin(args.get("item_code"), args.get("warehouse"))
Ankush Menatcef84c22021-12-03 12:18:59 +053068 repost_current_voucher(args, allow_negative_stock, via_landed_cost_voucher)
Ankush Menatff9a6e82021-12-20 15:07:41 +053069 update_bin_qty(bin_name, args)
Ankush Menatcef84c22021-12-03 12:18:59 +053070 else:
71 frappe.msgprint(_("Item {0} ignored since it is not a stock item").format(args.get("item_code")))
72
73def repost_current_voucher(args, allow_negative_stock=False, via_landed_cost_voucher=False):
74 if args.get("actual_qty") or args.get("voucher_type") == "Stock Reconciliation":
75 if not args.get("posting_date"):
76 args["posting_date"] = nowdate()
77
78 if args.get("is_cancelled") and via_landed_cost_voucher:
79 return
80
81 # Reposts only current voucher SL Entries
82 # Updates valuation rate, stock value, stock queue for current transaction
83 update_entries_after({
84 "item_code": args.get('item_code'),
85 "warehouse": args.get('warehouse'),
86 "posting_date": args.get("posting_date"),
87 "posting_time": args.get("posting_time"),
88 "voucher_type": args.get("voucher_type"),
89 "voucher_no": args.get("voucher_no"),
90 "sle_id": args.get('name'),
91 "creation": args.get('creation')
92 }, allow_negative_stock=allow_negative_stock, via_landed_cost_voucher=via_landed_cost_voucher)
93
94 # update qty in future sle and Validate negative qty
95 update_qty_in_future_sle(args, allow_negative_stock)
96
Nabin Haitadeb9762014-10-06 11:53:52 +053097
Rohit Waghchaure4d81d452021-06-15 10:21:44 +053098def get_args_for_future_sle(row):
99 return frappe._dict({
100 'voucher_type': row.get('voucher_type'),
101 'voucher_no': row.get('voucher_no'),
102 'posting_date': row.get('posting_date'),
103 'posting_time': row.get('posting_time')
104 })
105
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530106def validate_serial_no(sle):
107 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
108 for sn in get_serial_nos(sle.serial_no):
109 args = copy.deepcopy(sle)
110 args.serial_no = sn
111 args.warehouse = ''
112
113 vouchers = []
114 for row in get_stock_ledger_entries(args, '>'):
115 voucher_type = frappe.bold(row.voucher_type)
116 voucher_no = frappe.bold(get_link_to_form(row.voucher_type, row.voucher_no))
117 vouchers.append(f'{voucher_type} {voucher_no}')
118
119 if vouchers:
120 serial_no = frappe.bold(sn)
121 msg = (f'''The serial no {serial_no} has been used in the future transactions so you need to cancel them first.
122 The list of the transactions are as below.''' + '<br><br><ul><li>')
123
124 msg += '</li><li>'.join(vouchers)
125 msg += '</li></ul>'
126
127 title = 'Cannot Submit' if not sle.get('is_cancelled') else 'Cannot Cancel'
128 frappe.throw(_(msg), title=_(title), exc=SerialNoExistsInFutureTransaction)
129
Nabin Hait186a0452021-02-18 14:14:21 +0530130def validate_cancellation(args):
131 if args[0].get("is_cancelled"):
132 repost_entry = frappe.db.get_value("Repost Item Valuation", {
133 'voucher_type': args[0].voucher_type,
134 'voucher_no': args[0].voucher_no,
135 'docstatus': 1
136 }, ['name', 'status'], as_dict=1)
137
138 if repost_entry:
139 if repost_entry.status == 'In Progress':
140 frappe.throw(_("Cannot cancel the transaction. Reposting of item valuation on submission is not completed yet."))
141 if repost_entry.status == 'Queued':
Nabin Haitd46b2362021-02-23 16:38:52 +0530142 doc = frappe.get_doc("Repost Item Valuation", repost_entry.name)
Ankush Menataa024fc2021-11-18 12:51:26 +0530143 doc.flags.ignore_permissions = True
Nabin Haitd46b2362021-02-23 16:38:52 +0530144 doc.cancel()
145 doc.delete()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530146
Nabin Hait9653f602013-08-20 15:37:33 +0530147def set_as_cancel(voucher_type, voucher_no):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530148 frappe.db.sql("""update `tabStock Ledger Entry` set is_cancelled=1,
Nabin Hait9653f602013-08-20 15:37:33 +0530149 modified=%s, modified_by=%s
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530150 where voucher_type=%s and voucher_no=%s and is_cancelled = 0""",
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530151 (now(), frappe.session.user, voucher_type, voucher_no))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530152
Nabin Hait54c865e2015-03-27 15:38:31 +0530153def make_entry(args, allow_negative_stock=False, via_landed_cost_voucher=False):
Saqib Ansaric7fc6092021-10-12 13:30:40 +0530154 args["doctype"] = "Stock Ledger Entry"
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530155 sle = frappe.get_doc(args)
Anand Doshi6dfd4302015-02-10 14:41:27 +0530156 sle.flags.ignore_permissions = 1
Nabin Hait4ccd8d32015-01-23 12:18:01 +0530157 sle.allow_negative_stock=allow_negative_stock
Nabin Hait54c865e2015-03-27 15:38:31 +0530158 sle.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Haitaeba24e2013-08-23 15:17:36 +0530159 sle.submit()
Nabin Haita77b8c92020-12-21 14:45:50 +0530160 return sle
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530161
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530162def 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 +0530163 if not args and voucher_type and voucher_no:
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530164 args = get_items_to_be_repost(voucher_type, voucher_no, doc)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530165
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530166 distinct_item_warehouses = get_distinct_item_warehouse(args, doc)
Nabin Haita77b8c92020-12-21 14:45:50 +0530167
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530168 i = get_current_index(doc) or 0
Nabin Haita77b8c92020-12-21 14:45:50 +0530169 while i < len(args):
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530170 validate_item_warehouse(args[i])
171
Nabin Haita77b8c92020-12-21 14:45:50 +0530172 obj = update_entries_after({
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530173 'item_code': args[i].get('item_code'),
174 'warehouse': args[i].get('warehouse'),
175 'posting_date': args[i].get('posting_date'),
176 'posting_time': args[i].get('posting_time'),
177 'creation': args[i].get('creation'),
178 'distinct_item_warehouses': distinct_item_warehouses
Nabin Haita77b8c92020-12-21 14:45:50 +0530179 }, allow_negative_stock=allow_negative_stock, via_landed_cost_voucher=via_landed_cost_voucher)
180
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530181 distinct_item_warehouses[(args[i].get('item_code'), args[i].get('warehouse'))].reposting_status = True
Deepesh Gargb4be2922021-01-28 13:09:56 +0530182
Nabin Hait97bce3a2021-07-12 13:24:43 +0530183 if obj.new_items_found:
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530184 for item_wh, data in distinct_item_warehouses.items():
Nabin Hait97bce3a2021-07-12 13:24:43 +0530185 if ('args_idx' not in data and not data.reposting_status) or (data.sle_changed and data.reposting_status):
186 data.args_idx = len(args)
187 args.append(data.sle)
188 elif data.sle_changed and not data.reposting_status:
189 args[data.args_idx] = data.sle
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530190
Nabin Hait97bce3a2021-07-12 13:24:43 +0530191 data.sle_changed = False
Nabin Haita77b8c92020-12-21 14:45:50 +0530192 i += 1
193
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530194 if doc and i % 2 == 0:
195 update_args_in_repost_item_valuation(doc, i, args, distinct_item_warehouses)
196
197 if doc and args:
198 update_args_in_repost_item_valuation(doc, i, args, distinct_item_warehouses)
199
200def validate_item_warehouse(args):
201 for field in ['item_code', 'warehouse', 'posting_date', 'posting_time']:
202 if not args.get(field):
203 validation_msg = f'The field {frappe.unscrub(args.get(field))} is required for the reposting'
204 frappe.throw(_(validation_msg))
205
206def update_args_in_repost_item_valuation(doc, index, args, distinct_item_warehouses):
207 frappe.db.set_value(doc.doctype, doc.name, {
208 'items_to_be_repost': json.dumps(args, default=str),
209 'distinct_item_and_warehouse': json.dumps({str(k): v for k,v in distinct_item_warehouses.items()}, default=str),
210 'current_index': index
211 })
212
213 frappe.db.commit()
214
215 frappe.publish_realtime('item_reposting_progress', {
216 'name': doc.name,
217 'items_to_be_repost': json.dumps(args, default=str),
218 'current_index': index
219 })
220
221def get_items_to_be_repost(voucher_type, voucher_no, doc=None):
222 if doc and doc.items_to_be_repost:
223 return json.loads(doc.items_to_be_repost) or []
224
Nabin Haita77b8c92020-12-21 14:45:50 +0530225 return frappe.db.get_all("Stock Ledger Entry",
226 filters={"voucher_type": voucher_type, "voucher_no": voucher_no},
Nabin Hait186a0452021-02-18 14:14:21 +0530227 fields=["item_code", "warehouse", "posting_date", "posting_time", "creation"],
Nabin Haita77b8c92020-12-21 14:45:50 +0530228 order_by="creation asc",
229 group_by="item_code, warehouse"
230 )
Nabin Hait74c281c2013-08-19 16:17:18 +0530231
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530232def get_distinct_item_warehouse(args=None, doc=None):
233 distinct_item_warehouses = {}
234 if doc and doc.distinct_item_and_warehouse:
235 distinct_item_warehouses = json.loads(doc.distinct_item_and_warehouse)
236 distinct_item_warehouses = {frappe.safe_eval(k): frappe._dict(v) for k, v in distinct_item_warehouses.items()}
237 else:
238 for i, d in enumerate(args):
239 distinct_item_warehouses.setdefault((d.item_code, d.warehouse), frappe._dict({
240 "reposting_status": False,
241 "sle": d,
242 "args_idx": i
243 }))
244
245 return distinct_item_warehouses
246
247def get_current_index(doc=None):
248 if doc and doc.current_index:
249 return doc.current_index
250
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530251class update_entries_after(object):
Nabin Hait902e8602013-01-08 18:29:24 +0530252 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530253 update valution rate and qty after transaction
Nabin Hait902e8602013-01-08 18:29:24 +0530254 from the current time-bucket onwards
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530255
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530256 :param args: args as dict
257
258 args = {
259 "item_code": "ABC",
260 "warehouse": "XYZ",
261 "posting_date": "2012-12-12",
262 "posting_time": "12:00"
263 }
Nabin Hait902e8602013-01-08 18:29:24 +0530264 """
Anand Doshi0dc79f42015-04-06 12:59:34 +0530265 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 +0530266 self.exceptions = {}
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530267 self.verbose = verbose
268 self.allow_zero_rate = allow_zero_rate
Anand Doshi0dc79f42015-04-06 12:59:34 +0530269 self.via_landed_cost_voucher = via_landed_cost_voucher
Ankush Menat7bafa112021-10-12 20:39:10 +0530270 self.allow_negative_stock = allow_negative_stock \
271 or cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530272
Nabin Haita77b8c92020-12-21 14:45:50 +0530273 self.args = frappe._dict(args)
274 self.item_code = args.get("item_code")
275 if self.args.sle_id:
276 self.args['name'] = self.args.sle_id
Nabin Haitd46b2362021-02-23 16:38:52 +0530277
Nabin Haita77b8c92020-12-21 14:45:50 +0530278 self.company = frappe.get_cached_value("Warehouse", self.args.warehouse, "company")
279 self.get_precision()
280 self.valuation_method = get_valuation_method(self.item_code)
Nabin Hait97bce3a2021-07-12 13:24:43 +0530281
282 self.new_items_found = False
283 self.distinct_item_warehouses = args.get("distinct_item_warehouses", frappe._dict())
Nabin Haita77b8c92020-12-21 14:45:50 +0530284
285 self.data = frappe._dict()
286 self.initialize_previous_data(self.args)
Nabin Haita77b8c92020-12-21 14:45:50 +0530287 self.build()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530288
Nabin Haita77b8c92020-12-21 14:45:50 +0530289 def get_precision(self):
290 company_base_currency = frappe.get_cached_value('Company', self.company, "default_currency")
291 self.precision = get_field_precision(frappe.get_meta("Stock Ledger Entry").get_field("stock_value"),
292 currency=company_base_currency)
293
294 def initialize_previous_data(self, args):
295 """
296 Get previous sl entries for current item for each related warehouse
297 and assigns into self.data dict
298
299 :Data Structure:
300
301 self.data = {
302 warehouse1: {
303 'previus_sle': {},
304 'qty_after_transaction': 10,
305 'valuation_rate': 100,
306 'stock_value': 1000,
307 'prev_stock_value': 1000,
308 'stock_queue': '[[10, 100]]',
309 'stock_value_difference': 1000
310 }
311 }
312
313 """
Ankush Menatc1d986a2021-08-31 19:43:42 +0530314 self.data.setdefault(args.warehouse, frappe._dict())
315 warehouse_dict = self.data[args.warehouse]
marination8418c4b2021-06-22 21:35:25 +0530316 previous_sle = get_previous_sle_of_current_voucher(args)
Ankush Menatc1d986a2021-08-31 19:43:42 +0530317 warehouse_dict.previous_sle = previous_sle
Nabin Haitbb777562013-08-29 18:19:37 +0530318
Ankush Menatc1d986a2021-08-31 19:43:42 +0530319 for key in ("qty_after_transaction", "valuation_rate", "stock_value"):
320 setattr(warehouse_dict, key, flt(previous_sle.get(key)))
321
322 warehouse_dict.update({
Nabin Haita77b8c92020-12-21 14:45:50 +0530323 "prev_stock_value": previous_sle.stock_value or 0.0,
324 "stock_queue": json.loads(previous_sle.stock_queue or "[]"),
325 "stock_value_difference": 0.0
326 })
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530327
Nabin Haita77b8c92020-12-21 14:45:50 +0530328 def build(self):
Sagar Vorae50324a2021-03-31 12:44:03 +0530329 from erpnext.controllers.stock_controller import future_sle_exists
Nabin Hait186a0452021-02-18 14:14:21 +0530330
Nabin Haita77b8c92020-12-21 14:45:50 +0530331 if self.args.get("sle_id"):
Nabin Hait186a0452021-02-18 14:14:21 +0530332 self.process_sle_against_current_timestamp()
Sagar Vorae50324a2021-03-31 12:44:03 +0530333 if not future_sle_exists(self.args):
Nabin Hait186a0452021-02-18 14:14:21 +0530334 self.update_bin()
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530335 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530336 entries_to_fix = self.get_future_entries_to_fix()
337
338 i = 0
339 while i < len(entries_to_fix):
340 sle = entries_to_fix[i]
341 i += 1
342
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530343 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530344
Nabin Haita77b8c92020-12-21 14:45:50 +0530345 if sle.dependant_sle_voucher_detail_no:
Nabin Hait243d59b2021-02-02 16:55:13 +0530346 entries_to_fix = self.get_dependent_entries_to_fix(entries_to_fix, sle)
Nabin Haitd46b2362021-02-23 16:38:52 +0530347
Nabin Hait186a0452021-02-18 14:14:21 +0530348 self.update_bin()
Nabin Haita77b8c92020-12-21 14:45:50 +0530349
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530350 if self.exceptions:
351 self.raise_exceptions()
352
Nabin Hait186a0452021-02-18 14:14:21 +0530353 def process_sle_against_current_timestamp(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530354 sl_entries = self.get_sle_against_current_voucher()
355 for sle in sl_entries:
356 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530357
Nabin Haita77b8c92020-12-21 14:45:50 +0530358 def get_sle_against_current_voucher(self):
Nabin Haitf2be0802021-02-15 19:27:49 +0530359 self.args['time_format'] = '%H:%i:%s'
360
Nabin Haita77b8c92020-12-21 14:45:50 +0530361 return frappe.db.sql("""
362 select
363 *, timestamp(posting_date, posting_time) as "timestamp"
364 from
365 `tabStock Ledger Entry`
366 where
367 item_code = %(item_code)s
368 and warehouse = %(warehouse)s
rohitwaghchaurefe4540d2021-08-26 12:52:36 +0530369 and is_cancelled = 0
Nabin Hait186a0452021-02-18 14:14:21 +0530370 and timestamp(posting_date, time_format(posting_time, %(time_format)s)) = timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
371
Nabin Haita77b8c92020-12-21 14:45:50 +0530372 order by
373 creation ASC
374 for update
375 """, self.args, as_dict=1)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530376
Nabin Haita77b8c92020-12-21 14:45:50 +0530377 def get_future_entries_to_fix(self):
378 # includes current entry!
379 args = self.data[self.args.warehouse].previous_sle \
380 or frappe._dict({"item_code": self.item_code, "warehouse": self.args.warehouse})
Deepesh Gargb4be2922021-01-28 13:09:56 +0530381
Nabin Haita77b8c92020-12-21 14:45:50 +0530382 return list(self.get_sle_after_datetime(args))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530383
Nabin Haita77b8c92020-12-21 14:45:50 +0530384 def get_dependent_entries_to_fix(self, entries_to_fix, sle):
385 dependant_sle = get_sle_by_voucher_detail_no(sle.dependant_sle_voucher_detail_no,
386 excluded_sle=sle.name)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530387
Nabin Haita77b8c92020-12-21 14:45:50 +0530388 if not dependant_sle:
Nabin Hait243d59b2021-02-02 16:55:13 +0530389 return entries_to_fix
Nabin Haita77b8c92020-12-21 14:45:50 +0530390 elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse == self.args.warehouse:
Nabin Hait243d59b2021-02-02 16:55:13 +0530391 return entries_to_fix
392 elif dependant_sle.item_code != self.item_code:
Nabin Hait97bce3a2021-07-12 13:24:43 +0530393 self.update_distinct_item_warehouses(dependant_sle)
Nabin Hait243d59b2021-02-02 16:55:13 +0530394 return entries_to_fix
395 elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse in self.data:
396 return entries_to_fix
Nabin Hait97bce3a2021-07-12 13:24:43 +0530397 else:
398 return self.append_future_sle_for_dependant(dependant_sle, entries_to_fix)
399
400 def update_distinct_item_warehouses(self, dependant_sle):
401 key = (dependant_sle.item_code, dependant_sle.warehouse)
402 val = frappe._dict({
403 "sle": dependant_sle
404 })
405 if key not in self.distinct_item_warehouses:
406 self.distinct_item_warehouses[key] = val
407 self.new_items_found = True
408 else:
409 existing_sle_posting_date = self.distinct_item_warehouses[key].get("sle", {}).get("posting_date")
410 if getdate(dependant_sle.posting_date) < getdate(existing_sle_posting_date):
411 val.sle_changed = True
412 self.distinct_item_warehouses[key] = val
413 self.new_items_found = True
414
415 def append_future_sle_for_dependant(self, dependant_sle, entries_to_fix):
Nabin Haita77b8c92020-12-21 14:45:50 +0530416 self.initialize_previous_data(dependant_sle)
417
418 args = self.data[dependant_sle.warehouse].previous_sle \
419 or frappe._dict({"item_code": self.item_code, "warehouse": dependant_sle.warehouse})
420 future_sle_for_dependant = list(self.get_sle_after_datetime(args))
421
422 entries_to_fix.extend(future_sle_for_dependant)
Nabin Hait243d59b2021-02-02 16:55:13 +0530423 return sorted(entries_to_fix, key=lambda k: k['timestamp'])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530424
425 def process_sle(self, sle):
Nabin Haita77b8c92020-12-21 14:45:50 +0530426 # previous sle data for this warehouse
427 self.wh_data = self.data[sle.warehouse]
428
Anand Doshi0dc79f42015-04-06 12:59:34 +0530429 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 +0530430 # validate negative stock for serialized items, fifo valuation
Nabin Hait902e8602013-01-08 18:29:24 +0530431 # or when negative stock is not allowed for moving average
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530432 if not self.validate_negative_stock(sle):
Nabin Haita77b8c92020-12-21 14:45:50 +0530433 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530434 return
Nabin Haitb96c0142014-10-07 11:25:04 +0530435
Nabin Haita77b8c92020-12-21 14:45:50 +0530436 # Get dynamic incoming/outgoing rate
rohitwaghchauree6a1ad82021-09-15 20:42:47 +0530437 if not self.args.get("sle_id"):
438 self.get_dynamic_incoming_outgoing_rate(sle)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530439
Anand Doshi1b531862013-01-10 19:29:51 +0530440 if sle.serial_no:
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530441 self.get_serialized_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530442 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530443 if sle.voucher_type == "Stock Reconciliation":
Nabin Haita77b8c92020-12-21 14:45:50 +0530444 self.wh_data.qty_after_transaction = sle.qty_after_transaction
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530445
Nabin Haita77b8c92020-12-21 14:45:50 +0530446 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 +0530447 else:
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530448 if sle.voucher_type=="Stock Reconciliation" and not sle.batch_no:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530449 # assert
Nabin Haita77b8c92020-12-21 14:45:50 +0530450 self.wh_data.valuation_rate = sle.valuation_rate
451 self.wh_data.qty_after_transaction = sle.qty_after_transaction
Nabin Haita77b8c92020-12-21 14:45:50 +0530452 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 +0530453 if self.valuation_method != "Moving Average":
454 self.wh_data.stock_queue = [[self.wh_data.qty_after_transaction, self.wh_data.valuation_rate]]
Nabin Haitb96c0142014-10-07 11:25:04 +0530455 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530456 if self.valuation_method == "Moving Average":
457 self.get_moving_average_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530458 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
459 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 +0530460 else:
Ankush Menat4b29fb62021-12-18 18:40:22 +0530461 self.update_fifo_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530462 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Nabin Haitb96c0142014-10-07 11:25:04 +0530463
Rushabh Mehta54047782013-12-26 11:07:46 +0530464 # rounding as per precision
Nabin Haita77b8c92020-12-21 14:45:50 +0530465 self.wh_data.stock_value = flt(self.wh_data.stock_value, self.precision)
466 stock_value_difference = self.wh_data.stock_value - self.wh_data.prev_stock_value
467 self.wh_data.prev_stock_value = self.wh_data.stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530468
Nabin Hait902e8602013-01-08 18:29:24 +0530469 # update current sle
Nabin Haita77b8c92020-12-21 14:45:50 +0530470 sle.qty_after_transaction = self.wh_data.qty_after_transaction
471 sle.valuation_rate = self.wh_data.valuation_rate
472 sle.stock_value = self.wh_data.stock_value
473 sle.stock_queue = json.dumps(self.wh_data.stock_queue)
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530474 sle.stock_value_difference = stock_value_difference
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530475 sle.doctype="Stock Ledger Entry"
476 frappe.get_doc(sle).db_update()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530477
rohitwaghchauree6a1ad82021-09-15 20:42:47 +0530478 if not self.args.get("sle_id"):
479 self.update_outgoing_rate_on_transaction(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530480
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530481 def validate_negative_stock(self, sle):
482 """
483 validate negative stock for entries current datetime onwards
484 will not consider cancelled entries
485 """
Nabin Haita77b8c92020-12-21 14:45:50 +0530486 diff = self.wh_data.qty_after_transaction + flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530487
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530488 if diff < 0 and abs(diff) > 0.0001:
489 # negative stock!
490 exc = sle.copy().update({"diff": diff})
Nabin Haita77b8c92020-12-21 14:45:50 +0530491 self.exceptions.setdefault(sle.warehouse, []).append(exc)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530492 return False
Nabin Hait902e8602013-01-08 18:29:24 +0530493 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530494 return True
495
Nabin Haita77b8c92020-12-21 14:45:50 +0530496 def get_dynamic_incoming_outgoing_rate(self, sle):
497 # Get updated incoming/outgoing rate from transaction
498 if sle.recalculate_rate:
499 rate = self.get_incoming_outgoing_rate_from_transaction(sle)
500
501 if flt(sle.actual_qty) >= 0:
502 sle.incoming_rate = rate
503 else:
504 sle.outgoing_rate = rate
505
506 def get_incoming_outgoing_rate_from_transaction(self, sle):
507 rate = 0
508 # Material Transfer, Repack, Manufacturing
509 if sle.voucher_type == "Stock Entry":
Nabin Hait97bce3a2021-07-12 13:24:43 +0530510 self.recalculate_amounts_in_stock_entry(sle.voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530511 rate = frappe.db.get_value("Stock Entry Detail", sle.voucher_detail_no, "valuation_rate")
512 # Sales and Purchase Return
513 elif sle.voucher_type in ("Purchase Receipt", "Purchase Invoice", "Delivery Note", "Sales Invoice"):
514 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_return"):
Chillar Anand915b3432021-09-02 16:44:59 +0530515 from erpnext.controllers.sales_and_purchase_return import (
516 get_rate_for_return, # don't move this import to top
517 )
rohitwaghchaurece6c3b52021-04-13 20:55:52 +0530518 rate = get_rate_for_return(sle.voucher_type, sle.voucher_no, sle.item_code,
519 voucher_detail_no=sle.voucher_detail_no, sle = sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530520 else:
521 if sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530522 rate_field = "valuation_rate"
Nabin Haita77b8c92020-12-21 14:45:50 +0530523 else:
524 rate_field = "incoming_rate"
525
526 # check in item table
527 item_code, incoming_rate = frappe.db.get_value(sle.voucher_type + " Item",
528 sle.voucher_detail_no, ["item_code", rate_field])
529
530 if item_code == sle.item_code:
531 rate = incoming_rate
532 else:
533 if sle.voucher_type in ("Delivery Note", "Sales Invoice"):
534 ref_doctype = "Packed Item"
535 else:
536 ref_doctype = "Purchase Receipt Item Supplied"
Deepesh Gargb4be2922021-01-28 13:09:56 +0530537
Nabin Haita77b8c92020-12-21 14:45:50 +0530538 rate = frappe.db.get_value(ref_doctype, {"parent_detail_docname": sle.voucher_detail_no,
539 "item_code": sle.item_code}, rate_field)
540
541 return rate
542
543 def update_outgoing_rate_on_transaction(self, sle):
544 """
545 Update outgoing rate in Stock Entry, Delivery Note, Sales Invoice and Sales Return
546 In case of Stock Entry, also calculate FG Item rate and total incoming/outgoing amount
547 """
548 if sle.actual_qty and sle.voucher_detail_no:
549 outgoing_rate = abs(flt(sle.stock_value_difference)) / abs(sle.actual_qty)
550
551 if flt(sle.actual_qty) < 0 and sle.voucher_type == "Stock Entry":
552 self.update_rate_on_stock_entry(sle, outgoing_rate)
553 elif sle.voucher_type in ("Delivery Note", "Sales Invoice"):
554 self.update_rate_on_delivery_and_sales_return(sle, outgoing_rate)
555 elif flt(sle.actual_qty) < 0 and sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
556 self.update_rate_on_purchase_receipt(sle, outgoing_rate)
557
558 def update_rate_on_stock_entry(self, sle, outgoing_rate):
559 frappe.db.set_value("Stock Entry Detail", sle.voucher_detail_no, "basic_rate", outgoing_rate)
560
561 # Update outgoing item's rate, recalculate FG Item's rate and total incoming/outgoing amount
Nabin Hait97bce3a2021-07-12 13:24:43 +0530562 if not sle.dependant_sle_voucher_detail_no:
563 self.recalculate_amounts_in_stock_entry(sle.voucher_no)
564
565 def recalculate_amounts_in_stock_entry(self, voucher_no):
566 stock_entry = frappe.get_doc("Stock Entry", voucher_no, for_update=True)
Nabin Haita77b8c92020-12-21 14:45:50 +0530567 stock_entry.calculate_rate_and_amount(reset_outgoing_rate=False, raise_error_if_no_rate=False)
568 stock_entry.db_update()
569 for d in stock_entry.items:
570 d.db_update()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530571
Nabin Haita77b8c92020-12-21 14:45:50 +0530572 def update_rate_on_delivery_and_sales_return(self, sle, outgoing_rate):
573 # Update item's incoming rate on transaction
574 item_code = frappe.db.get_value(sle.voucher_type + " Item", sle.voucher_detail_no, "item_code")
575 if item_code == sle.item_code:
576 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "incoming_rate", outgoing_rate)
577 else:
578 # packed item
579 frappe.db.set_value("Packed Item",
580 {"parent_detail_docname": sle.voucher_detail_no, "item_code": sle.item_code},
581 "incoming_rate", outgoing_rate)
582
583 def update_rate_on_purchase_receipt(self, sle, outgoing_rate):
584 if frappe.db.exists(sle.voucher_type + " Item", sle.voucher_detail_no):
585 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "base_net_rate", outgoing_rate)
586 else:
587 frappe.db.set_value("Purchase Receipt Item Supplied", sle.voucher_detail_no, "rate", outgoing_rate)
588
589 # Recalculate subcontracted item's rate in case of subcontracted purchase receipt/invoice
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530590 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_subcontracted") == 'Yes':
Rohit Waghchauree5fb2392021-06-18 20:37:42 +0530591 doc = frappe.get_doc(sle.voucher_type, sle.voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530592 doc.update_valuation_rate(reset_outgoing_rate=False)
593 for d in (doc.items + doc.supplied_items):
594 d.db_update()
595
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530596 def get_serialized_values(self, sle):
597 incoming_rate = flt(sle.incoming_rate)
598 actual_qty = flt(sle.actual_qty)
Nabin Hait328c4f92020-01-02 19:00:32 +0530599 serial_nos = cstr(sle.serial_no).split("\n")
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530600
601 if incoming_rate < 0:
602 # wrong incoming rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530603 incoming_rate = self.wh_data.valuation_rate
Rushabh Mehta538607e2016-06-12 11:03:00 +0530604
Nabin Hait2620bf42016-02-29 11:30:27 +0530605 stock_value_change = 0
606 if incoming_rate:
607 stock_value_change = actual_qty * incoming_rate
608 elif actual_qty < 0:
609 # In case of delivery/stock issue, get average purchase rate
610 # of serial nos of current entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530611 if not sle.is_cancelled:
612 outgoing_value = self.get_incoming_value_for_serial_nos(sle, serial_nos)
613 stock_value_change = -1 * outgoing_value
614 else:
615 stock_value_change = actual_qty * sle.outgoing_rate
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530616
Nabin Haita77b8c92020-12-21 14:45:50 +0530617 new_stock_qty = self.wh_data.qty_after_transaction + actual_qty
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530618
Nabin Hait2620bf42016-02-29 11:30:27 +0530619 if new_stock_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530620 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + stock_value_change
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530621 if new_stock_value >= 0:
Nabin Hait2620bf42016-02-29 11:30:27 +0530622 # calculate new valuation rate only if stock value is positive
623 # else it remains the same as that of previous entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530624 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530625
Nabin Haita77b8c92020-12-21 14:45:50 +0530626 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530627 allow_zero_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
628 if not allow_zero_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530629 self.wh_data.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530630 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
Ankush Menata0727b22021-11-01 13:17:40 +0530631 currency=erpnext.get_company_currency(sle.company), company=sle.company)
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530632
Nabin Hait328c4f92020-01-02 19:00:32 +0530633 def get_incoming_value_for_serial_nos(self, sle, serial_nos):
634 # get rate from serial nos within same company
635 all_serial_nos = frappe.get_all("Serial No",
636 fields=["purchase_rate", "name", "company"],
637 filters = {'name': ('in', serial_nos)})
638
Ankush Menat98917802021-06-11 18:40:22 +0530639 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 +0530640
641 # Get rate for serial nos which has been transferred to other company
642 invalid_serial_nos = [d.name for d in all_serial_nos if d.company!=sle.company]
643 for serial_no in invalid_serial_nos:
644 incoming_rate = frappe.db.sql("""
645 select incoming_rate
646 from `tabStock Ledger Entry`
647 where
648 company = %s
649 and actual_qty > 0
650 and (serial_no = %s
651 or serial_no like %s
652 or serial_no like %s
653 or serial_no like %s
654 )
655 order by posting_date desc
656 limit 1
657 """, (sle.company, serial_no, serial_no+'\n%', '%\n'+serial_no, '%\n'+serial_no+'\n%'))
658
659 incoming_values += flt(incoming_rate[0][0]) if incoming_rate else 0
660
661 return incoming_values
662
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530663 def get_moving_average_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530664 actual_qty = flt(sle.actual_qty)
Nabin Haita77b8c92020-12-21 14:45:50 +0530665 new_stock_qty = flt(self.wh_data.qty_after_transaction) + actual_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530666 if new_stock_qty >= 0:
667 if actual_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530668 if flt(self.wh_data.qty_after_transaction) <= 0:
669 self.wh_data.valuation_rate = sle.incoming_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530670 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530671 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530672 (actual_qty * sle.incoming_rate)
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530673
Nabin Haita77b8c92020-12-21 14:45:50 +0530674 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530675
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530676 elif sle.outgoing_rate:
677 if new_stock_qty:
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.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530680
Nabin Haita77b8c92020-12-21 14:45:50 +0530681 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530682 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530683 self.wh_data.valuation_rate = sle.outgoing_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530684 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530685 if flt(self.wh_data.qty_after_transaction) >= 0 and sle.outgoing_rate:
686 self.wh_data.valuation_rate = sle.outgoing_rate
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530687
Nabin Haita77b8c92020-12-21 14:45:50 +0530688 if not self.wh_data.valuation_rate and actual_qty > 0:
689 self.wh_data.valuation_rate = sle.incoming_rate
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530690
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530691 # Get valuation rate from previous SLE or Item master, if item does not have the
Javier Wong9b11d9b2017-04-14 18:24:04 +0800692 # allow zero valuration rate flag set
Nabin Haita77b8c92020-12-21 14:45:50 +0530693 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
Javier Wong9b11d9b2017-04-14 18:24:04 +0800694 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
695 if not allow_zero_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530696 self.wh_data.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530697 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
Ankush Menata0727b22021-11-01 13:17:40 +0530698 currency=erpnext.get_company_currency(sle.company), company=sle.company)
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530699
Ankush Menat4b29fb62021-12-18 18:40:22 +0530700 def update_fifo_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530701 incoming_rate = flt(sle.incoming_rate)
702 actual_qty = flt(sle.actual_qty)
Nabin Haitada485f2015-07-17 15:09:56 +0530703 outgoing_rate = flt(sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530704
Ankush Menat107b4042021-12-19 20:47:08 +0530705 fifo_queue = FIFOValuation(self.wh_data.stock_queue)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530706 if actual_qty > 0:
Ankush Menat4b29fb62021-12-18 18:40:22 +0530707 fifo_queue.add_stock(qty=actual_qty, rate=incoming_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530708 else:
Ankush Menat4b29fb62021-12-18 18:40:22 +0530709 def rate_generator() -> float:
710 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
711 if not allow_zero_valuation_rate:
712 return get_valuation_rate(sle.item_code, sle.warehouse,
713 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
714 currency=erpnext.get_company_currency(sle.company), company=sle.company)
Nabin Haitada485f2015-07-17 15:09:56 +0530715 else:
Ankush Menat4b29fb62021-12-18 18:40:22 +0530716 return 0.0
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530717
Ankush Menata00d8d02021-12-19 18:45:04 +0530718 fifo_queue.remove_stock(qty=abs(actual_qty), outgoing_rate=outgoing_rate, rate_generator=rate_generator)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530719
Ankush Menat4b29fb62021-12-18 18:40:22 +0530720 stock_qty, stock_value = fifo_queue.get_total_stock_and_value()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530721
Ankush Menat4b29fb62021-12-18 18:40:22 +0530722 self.wh_data.stock_queue = fifo_queue.get_state()
723 self.wh_data.stock_value = stock_value
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530724 if stock_qty:
Ankush Menat4b29fb62021-12-18 18:40:22 +0530725 self.wh_data.valuation_rate = stock_value / stock_qty
726
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530727
Nabin Haita77b8c92020-12-21 14:45:50 +0530728 if not self.wh_data.stock_queue:
729 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 +0530730
Ankush Menat4b29fb62021-12-18 18:40:22 +0530731
732
Javier Wong9b11d9b2017-04-14 18:24:04 +0800733 def check_if_allow_zero_valuation_rate(self, voucher_type, voucher_detail_no):
deepeshgarg007f9c0ef32019-07-30 18:49:19 +0530734 ref_item_dt = ""
735
736 if voucher_type == "Stock Entry":
737 ref_item_dt = voucher_type + " Detail"
738 elif voucher_type in ["Purchase Invoice", "Sales Invoice", "Delivery Note", "Purchase Receipt"]:
739 ref_item_dt = voucher_type + " Item"
740
741 if ref_item_dt:
742 return frappe.db.get_value(ref_item_dt, voucher_detail_no, "allow_zero_valuation_rate")
743 else:
744 return 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530745
Nabin Haita77b8c92020-12-21 14:45:50 +0530746 def get_sle_before_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530747 """get previous stock ledger entry before current time-bucket"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530748 sle = get_stock_ledger_entries(args, "<", "desc", "limit 1", for_update=False)
749 sle = sle[0] if sle else frappe._dict()
750 return sle
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530751
Nabin Haita77b8c92020-12-21 14:45:50 +0530752 def get_sle_after_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530753 """get Stock Ledger Entries after a particular datetime, for reposting"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530754 return get_stock_ledger_entries(args, ">", "asc", for_update=True, check_serial_no=False)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530755
756 def raise_exceptions(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530757 msg_list = []
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530758 for warehouse, exceptions in self.exceptions.items():
Nabin Haita77b8c92020-12-21 14:45:50 +0530759 deficiency = min(e["diff"] for e in exceptions)
Rushabh Mehta538607e2016-06-12 11:03:00 +0530760
Nabin Haita77b8c92020-12-21 14:45:50 +0530761 if ((exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]) in
762 frappe.local.flags.currently_saving):
Nabin Hait3edefb12016-07-20 16:13:18 +0530763
Nabin Haita77b8c92020-12-21 14:45:50 +0530764 msg = _("{0} units of {1} needed in {2} to complete this transaction.").format(
Nabin Hait243d59b2021-02-02 16:55:13 +0530765 abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]),
Nabin Haita77b8c92020-12-21 14:45:50 +0530766 frappe.get_desk_link('Warehouse', warehouse))
767 else:
768 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 +0530769 abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]),
Nabin Haita77b8c92020-12-21 14:45:50 +0530770 frappe.get_desk_link('Warehouse', warehouse),
771 exceptions[0]["posting_date"], exceptions[0]["posting_time"],
772 frappe.get_desk_link(exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530773
Nabin Haita77b8c92020-12-21 14:45:50 +0530774 if msg:
775 msg_list.append(msg)
776
777 if msg_list:
778 message = "\n\n".join(msg_list)
779 if self.verbose:
780 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
781 else:
782 raise NegativeStockError(message)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530783
Nabin Haita77b8c92020-12-21 14:45:50 +0530784 def update_bin(self):
785 # update bin for each warehouse
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530786 for warehouse, data in self.data.items():
Ankush Menat97060c42021-12-03 11:50:38 +0530787 bin_name = get_or_make_bin(self.item_code, warehouse)
Deepesh Garg6f107da2021-10-12 20:15:55 +0530788
Ankush Menat97060c42021-12-03 11:50:38 +0530789 frappe.db.set_value('Bin', bin_name, {
Nabin Haita77b8c92020-12-21 14:45:50 +0530790 "valuation_rate": data.valuation_rate,
791 "actual_qty": data.qty_after_transaction,
792 "stock_value": data.stock_value
793 })
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530794
marination8418c4b2021-06-22 21:35:25 +0530795
796def get_previous_sle_of_current_voucher(args, exclude_current_voucher=False):
797 """get stock ledger entries filtered by specific posting datetime conditions"""
798
799 args['time_format'] = '%H:%i:%s'
800 if not args.get("posting_date"):
801 args["posting_date"] = "1900-01-01"
802 if not args.get("posting_time"):
803 args["posting_time"] = "00:00"
804
805 voucher_condition = ""
806 if exclude_current_voucher:
807 voucher_no = args.get("voucher_no")
808 voucher_condition = f"and voucher_no != '{voucher_no}'"
809
810 sle = frappe.db.sql("""
811 select *, timestamp(posting_date, posting_time) as "timestamp"
812 from `tabStock Ledger Entry`
813 where item_code = %(item_code)s
814 and warehouse = %(warehouse)s
815 and is_cancelled = 0
816 {voucher_condition}
817 and timestamp(posting_date, time_format(posting_time, %(time_format)s)) < timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
818 order by timestamp(posting_date, posting_time) desc, creation desc
819 limit 1
820 for update""".format(voucher_condition=voucher_condition), args, as_dict=1)
821
822 return sle[0] if sle else frappe._dict()
823
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530824def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530825 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530826 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530827 to get actual qty before transaction, this function
828 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530829
Anand Doshi1b531862013-01-10 19:29:51 +0530830 args = {
831 "item_code": "ABC",
832 "warehouse": "XYZ",
833 "posting_date": "2012-12-12",
834 "posting_time": "12:00",
835 "sle": "name of reference Stock Ledger Entry"
836 }
837 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530838 args["name"] = args.get("sle", None) or ""
839 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530840 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530841
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530842def get_stock_ledger_entries(previous_sle, operator=None,
843 order="desc", limit=None, for_update=False, debug=False, check_serial_no=True):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530844 """get stock ledger entries filtered by specific posting datetime conditions"""
Nabin Haitb9ce1042018-02-01 14:58:50 +0530845 conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
846 if previous_sle.get("warehouse"):
847 conditions += " and warehouse = %(warehouse)s"
848 elif previous_sle.get("warehouse_condition"):
849 conditions += " and " + previous_sle.get("warehouse_condition")
850
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530851 if check_serial_no and previous_sle.get("serial_no"):
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530852 # conditions += " and serial_no like {}".format(frappe.db.escape('%{0}%'.format(previous_sle.get("serial_no"))))
853 serial_no = previous_sle.get("serial_no")
854 conditions += (""" and
855 (
856 serial_no = {0}
857 or serial_no like {1}
858 or serial_no like {2}
859 or serial_no like {3}
860 )
861 """).format(frappe.db.escape(serial_no), frappe.db.escape('{}\n%'.format(serial_no)),
862 frappe.db.escape('%\n{}'.format(serial_no)), frappe.db.escape('%\n{}\n%'.format(serial_no)))
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530863
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530864 if not previous_sle.get("posting_date"):
865 previous_sle["posting_date"] = "1900-01-01"
866 if not previous_sle.get("posting_time"):
867 previous_sle["posting_time"] = "00:00"
868
869 if operator in (">", "<=") and previous_sle.get("name"):
870 conditions += " and name!=%(name)s"
871
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530872 return frappe.db.sql("""
873 select *, timestamp(posting_date, posting_time) as "timestamp"
874 from `tabStock Ledger Entry`
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530875 where item_code = %%(item_code)s
Nabin Haita77b8c92020-12-21 14:45:50 +0530876 and is_cancelled = 0
Nabin Haitb9ce1042018-02-01 14:58:50 +0530877 %(conditions)s
Aditya Hase0c164242019-01-07 22:07:13 +0530878 order by timestamp(posting_date, posting_time) %(order)s, creation %(order)s
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530879 %(limit)s %(for_update)s""" % {
880 "conditions": conditions,
881 "limit": limit or "",
882 "for_update": for_update and "for update" or "",
883 "order": order
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530884 }, previous_sle, as_dict=1, debug=debug)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530885
Nabin Haita77b8c92020-12-21 14:45:50 +0530886def get_sle_by_voucher_detail_no(voucher_detail_no, excluded_sle=None):
887 return frappe.db.get_value('Stock Ledger Entry',
888 {'voucher_detail_no': voucher_detail_no, 'name': ['!=', excluded_sle]},
889 ['item_code', 'warehouse', 'posting_date', 'posting_time', 'timestamp(posting_date, posting_time) as timestamp'],
890 as_dict=1)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530891
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530892def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no,
Nabin Hait7ba092e2018-02-01 10:51:27 +0530893 allow_zero_rate=False, currency=None, company=None, raise_error_if_no_rate=True):
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530894
Ankush Menatf7ffe042021-11-01 13:21:14 +0530895 if not company:
896 company = frappe.get_cached_value("Warehouse", warehouse, "company")
897
898 # Get valuation rate from last sle for the same item and warehouse
Nabin Haitfb6e4342014-10-15 11:34:40 +0530899 last_valuation_rate = frappe.db.sql("""select valuation_rate
Deepesh Garg6f107da2021-10-12 20:15:55 +0530900 from `tabStock Ledger Entry` force index (item_warehouse)
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530901 where
902 item_code = %s
903 AND warehouse = %s
904 AND valuation_rate >= 0
905 AND NOT (voucher_no = %s AND voucher_type = %s)
906 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 +0530907
908 if not last_valuation_rate:
Nabin Haita0b967f2017-01-18 18:35:58 +0530909 # Get valuation rate from last sle for the item against any warehouse
Nabin Haitfb6e4342014-10-15 11:34:40 +0530910 last_valuation_rate = frappe.db.sql("""select valuation_rate
Deepesh Garg6f107da2021-10-12 20:15:55 +0530911 from `tabStock Ledger Entry` force index (item_code)
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530912 where
913 item_code = %s
914 AND valuation_rate > 0
915 AND NOT(voucher_no = %s AND voucher_type = %s)
916 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 +0530917
Nabin Haita645f362018-03-01 10:31:24 +0530918 if last_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530919 return flt(last_valuation_rate[0][0])
Nabin Haita645f362018-03-01 10:31:24 +0530920
921 # If negative stock allowed, and item delivered without any incoming entry,
922 # system does not found any SLE, then take valuation rate from Item
923 valuation_rate = frappe.db.get_value("Item", item_code, "valuation_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530924
925 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530926 # try Item Standard rate
927 valuation_rate = frappe.db.get_value("Item", item_code, "standard_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530928
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530929 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530930 # try in price list
931 valuation_rate = frappe.db.get_value('Item Price',
932 dict(item_code=item_code, buying=1, currency=currency),
933 'price_list_rate')
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530934
Nabin Hait7ba092e2018-02-01 10:51:27 +0530935 if not allow_zero_rate and not valuation_rate and raise_error_if_no_rate \
Rohit Waghchauree9ff1912017-06-19 12:54:59 +0530936 and cint(erpnext.is_perpetual_inventory_enabled(company)):
Neil Trini Lasrado193c8912017-03-28 17:39:34 +0530937 frappe.local.message_log = []
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530938 form_link = get_link_to_form("Item", item_code)
Marica97715f22020-05-11 20:45:37 +0530939
940 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 +0530941 message += "<br><br>" + _("Here are the options to proceed:")
Marica97715f22020-05-11 20:45:37 +0530942 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 +0530943 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 +0530944 sub_solutions = "<ul><li>" + _("Create an incoming stock transaction for the Item.") + "</li>"
945 sub_solutions += "<li>" + _("Mention Valuation Rate in the Item master.") + "</li></ul>"
946 msg = message + solutions + sub_solutions + "</li>"
947
948 frappe.throw(msg=msg, title=_("Valuation Rate Missing"))
Nabin Haitfb6e4342014-10-15 11:34:40 +0530949
950 return valuation_rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530951
Ankush Menate7109c12021-08-26 16:40:45 +0530952def update_qty_in_future_sle(args, allow_negative_stock=False):
marination8418c4b2021-06-22 21:35:25 +0530953 """Recalculate Qty after Transaction in future SLEs based on current SLE."""
marination40389772021-07-02 17:13:45 +0530954 datetime_limit_condition = ""
marination8418c4b2021-06-22 21:35:25 +0530955 qty_shift = args.actual_qty
956
957 # find difference/shift in qty caused by stock reconciliation
958 if args.voucher_type == "Stock Reconciliation":
marination40389772021-07-02 17:13:45 +0530959 qty_shift = get_stock_reco_qty_shift(args)
960
961 # find the next nearest stock reco so that we only recalculate SLEs till that point
962 next_stock_reco_detail = get_next_stock_reco(args)
963 if next_stock_reco_detail:
964 detail = next_stock_reco_detail[0]
965 # add condition to update SLEs before this date & time
966 datetime_limit_condition = get_datetime_limit_condition(detail)
marination8418c4b2021-06-22 21:35:25 +0530967
Nabin Hait186a0452021-02-18 14:14:21 +0530968 frappe.db.sql("""
969 update `tabStock Ledger Entry`
marination8418c4b2021-06-22 21:35:25 +0530970 set qty_after_transaction = qty_after_transaction + {qty_shift}
Nabin Hait186a0452021-02-18 14:14:21 +0530971 where
972 item_code = %(item_code)s
973 and warehouse = %(warehouse)s
974 and voucher_no != %(voucher_no)s
975 and is_cancelled = 0
976 and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)
977 or (
978 timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s)
979 and creation > %(creation)s
980 )
981 )
marination40389772021-07-02 17:13:45 +0530982 {datetime_limit_condition}
983 """.format(qty_shift=qty_shift, datetime_limit_condition=datetime_limit_condition), args)
Nabin Hait186a0452021-02-18 14:14:21 +0530984
985 validate_negative_qty_in_future_sle(args, allow_negative_stock)
986
marination40389772021-07-02 17:13:45 +0530987def get_stock_reco_qty_shift(args):
988 stock_reco_qty_shift = 0
989 if args.get("is_cancelled"):
990 if args.get("previous_qty_after_transaction"):
991 # get qty (balance) that was set at submission
992 last_balance = args.get("previous_qty_after_transaction")
993 stock_reco_qty_shift = flt(args.qty_after_transaction) - flt(last_balance)
994 else:
995 stock_reco_qty_shift = flt(args.actual_qty)
996 else:
997 # reco is being submitted
998 last_balance = get_previous_sle_of_current_voucher(args,
999 exclude_current_voucher=True).get("qty_after_transaction")
1000
1001 if last_balance is not None:
1002 stock_reco_qty_shift = flt(args.qty_after_transaction) - flt(last_balance)
1003 else:
1004 stock_reco_qty_shift = args.qty_after_transaction
1005
1006 return stock_reco_qty_shift
1007
1008def get_next_stock_reco(args):
1009 """Returns next nearest stock reconciliaton's details."""
1010
1011 return frappe.db.sql("""
1012 select
1013 name, posting_date, posting_time, creation, voucher_no
1014 from
marination8c441262021-07-02 17:46:05 +05301015 `tabStock Ledger Entry`
marination40389772021-07-02 17:13:45 +05301016 where
1017 item_code = %(item_code)s
1018 and warehouse = %(warehouse)s
1019 and voucher_type = 'Stock Reconciliation'
1020 and voucher_no != %(voucher_no)s
1021 and is_cancelled = 0
1022 and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)
1023 or (
1024 timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s)
1025 and creation > %(creation)s
1026 )
1027 )
1028 limit 1
1029 """, args, as_dict=1)
1030
1031def get_datetime_limit_condition(detail):
marination40389772021-07-02 17:13:45 +05301032 return f"""
1033 and
1034 (timestamp(posting_date, posting_time) < timestamp('{detail.posting_date}', '{detail.posting_time}')
1035 or (
1036 timestamp(posting_date, posting_time) = timestamp('{detail.posting_date}', '{detail.posting_time}')
1037 and creation < '{detail.creation}'
1038 )
1039 )"""
1040
Ankush Menate7109c12021-08-26 16:40:45 +05301041def validate_negative_qty_in_future_sle(args, allow_negative_stock=False):
1042 allow_negative_stock = cint(allow_negative_stock) \
Nabin Haita77b8c92020-12-21 14:45:50 +05301043 or cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
1044
Ankush Menat5eba5752021-12-07 23:03:52 +05301045 if allow_negative_stock:
1046 return
1047 if not (args.actual_qty < 0 or args.voucher_type == "Stock Reconciliation"):
1048 return
Deepesh Gargb4be2922021-01-28 13:09:56 +05301049
Ankush Menat5eba5752021-12-07 23:03:52 +05301050 neg_sle = get_future_sle_with_negative_qty(args)
1051 if neg_sle:
1052 message = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
1053 abs(neg_sle[0]["qty_after_transaction"]),
1054 frappe.get_desk_link('Item', args.item_code),
1055 frappe.get_desk_link('Warehouse', args.warehouse),
1056 neg_sle[0]["posting_date"], neg_sle[0]["posting_time"],
1057 frappe.get_desk_link(neg_sle[0]["voucher_type"], neg_sle[0]["voucher_no"]))
1058
1059 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
1060
1061
1062 if not args.batch_no:
1063 return
1064
1065 neg_batch_sle = get_future_sle_with_negative_batch_qty(args)
1066 if neg_batch_sle:
1067 message = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
1068 abs(neg_batch_sle[0]["cumulative_total"]),
1069 frappe.get_desk_link('Batch', args.batch_no),
1070 frappe.get_desk_link('Warehouse', args.warehouse),
1071 neg_batch_sle[0]["posting_date"], neg_batch_sle[0]["posting_time"],
1072 frappe.get_desk_link(neg_batch_sle[0]["voucher_type"], neg_batch_sle[0]["voucher_no"]))
1073 frappe.throw(message, NegativeStockError, title="Insufficient Stock for Batch")
1074
Nabin Haita77b8c92020-12-21 14:45:50 +05301075
1076def get_future_sle_with_negative_qty(args):
1077 return frappe.db.sql("""
1078 select
1079 qty_after_transaction, posting_date, posting_time,
1080 voucher_type, voucher_no
1081 from `tabStock Ledger Entry`
Deepesh Gargb4be2922021-01-28 13:09:56 +05301082 where
Nabin Haita77b8c92020-12-21 14:45:50 +05301083 item_code = %(item_code)s
1084 and warehouse = %(warehouse)s
1085 and voucher_no != %(voucher_no)s
1086 and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s)
1087 and is_cancelled = 0
Nabin Hait186a0452021-02-18 14:14:21 +05301088 and qty_after_transaction < 0
Nabin Hait243d59b2021-02-02 16:55:13 +05301089 order by timestamp(posting_date, posting_time) asc
Nabin Haita77b8c92020-12-21 14:45:50 +05301090 limit 1
Sagar Vorae50324a2021-03-31 12:44:03 +05301091 """, args, as_dict=1)
Ankush Menat6a014d12021-04-12 20:21:27 +05301092
Ankush Menat5eba5752021-12-07 23:03:52 +05301093
1094def get_future_sle_with_negative_batch_qty(args):
1095 return frappe.db.sql("""
1096 with batch_ledger as (
1097 select
1098 posting_date, posting_time, voucher_type, voucher_no,
1099 sum(actual_qty) over (order by posting_date, posting_time, creation) as cumulative_total
1100 from `tabStock Ledger Entry`
1101 where
1102 item_code = %(item_code)s
1103 and warehouse = %(warehouse)s
1104 and batch_no=%(batch_no)s
1105 and is_cancelled = 0
1106 order by posting_date, posting_time, creation
1107 )
1108 select * from batch_ledger
1109 where
1110 cumulative_total < 0.0
1111 and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s)
1112 limit 1
1113 """, args, as_dict=1)