blob: 498b9f51f621770d24bf0d969f2efecac1b75a0b [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 Menat4b29fb62021-12-18 18:40:22 +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"))
68 update_bin_qty(bin_name, args)
69 repost_current_voucher(args, allow_negative_stock, via_landed_cost_voucher)
70 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
452 self.wh_data.stock_queue = [[self.wh_data.qty_after_transaction, self.wh_data.valuation_rate]]
453 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 +0530454 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530455 if self.valuation_method == "Moving Average":
456 self.get_moving_average_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530457 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
458 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 +0530459 else:
Ankush Menat4b29fb62021-12-18 18:40:22 +0530460 self.update_fifo_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530461 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Nabin Haitb96c0142014-10-07 11:25:04 +0530462
Rushabh Mehta54047782013-12-26 11:07:46 +0530463 # rounding as per precision
Nabin Haita77b8c92020-12-21 14:45:50 +0530464 self.wh_data.stock_value = flt(self.wh_data.stock_value, self.precision)
465 stock_value_difference = self.wh_data.stock_value - self.wh_data.prev_stock_value
466 self.wh_data.prev_stock_value = self.wh_data.stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530467
Nabin Hait902e8602013-01-08 18:29:24 +0530468 # update current sle
Nabin Haita77b8c92020-12-21 14:45:50 +0530469 sle.qty_after_transaction = self.wh_data.qty_after_transaction
470 sle.valuation_rate = self.wh_data.valuation_rate
471 sle.stock_value = self.wh_data.stock_value
472 sle.stock_queue = json.dumps(self.wh_data.stock_queue)
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530473 sle.stock_value_difference = stock_value_difference
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530474 sle.doctype="Stock Ledger Entry"
475 frappe.get_doc(sle).db_update()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530476
rohitwaghchauree6a1ad82021-09-15 20:42:47 +0530477 if not self.args.get("sle_id"):
478 self.update_outgoing_rate_on_transaction(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530479
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530480 def validate_negative_stock(self, sle):
481 """
482 validate negative stock for entries current datetime onwards
483 will not consider cancelled entries
484 """
Nabin Haita77b8c92020-12-21 14:45:50 +0530485 diff = self.wh_data.qty_after_transaction + flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530486
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530487 if diff < 0 and abs(diff) > 0.0001:
488 # negative stock!
489 exc = sle.copy().update({"diff": diff})
Nabin Haita77b8c92020-12-21 14:45:50 +0530490 self.exceptions.setdefault(sle.warehouse, []).append(exc)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530491 return False
Nabin Hait902e8602013-01-08 18:29:24 +0530492 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530493 return True
494
Nabin Haita77b8c92020-12-21 14:45:50 +0530495 def get_dynamic_incoming_outgoing_rate(self, sle):
496 # Get updated incoming/outgoing rate from transaction
497 if sle.recalculate_rate:
498 rate = self.get_incoming_outgoing_rate_from_transaction(sle)
499
500 if flt(sle.actual_qty) >= 0:
501 sle.incoming_rate = rate
502 else:
503 sle.outgoing_rate = rate
504
505 def get_incoming_outgoing_rate_from_transaction(self, sle):
506 rate = 0
507 # Material Transfer, Repack, Manufacturing
508 if sle.voucher_type == "Stock Entry":
Nabin Hait97bce3a2021-07-12 13:24:43 +0530509 self.recalculate_amounts_in_stock_entry(sle.voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530510 rate = frappe.db.get_value("Stock Entry Detail", sle.voucher_detail_no, "valuation_rate")
511 # Sales and Purchase Return
512 elif sle.voucher_type in ("Purchase Receipt", "Purchase Invoice", "Delivery Note", "Sales Invoice"):
513 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_return"):
Chillar Anand915b3432021-09-02 16:44:59 +0530514 from erpnext.controllers.sales_and_purchase_return import (
515 get_rate_for_return, # don't move this import to top
516 )
rohitwaghchaurece6c3b52021-04-13 20:55:52 +0530517 rate = get_rate_for_return(sle.voucher_type, sle.voucher_no, sle.item_code,
518 voucher_detail_no=sle.voucher_detail_no, sle = sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530519 else:
520 if sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530521 rate_field = "valuation_rate"
Nabin Haita77b8c92020-12-21 14:45:50 +0530522 else:
523 rate_field = "incoming_rate"
524
525 # check in item table
526 item_code, incoming_rate = frappe.db.get_value(sle.voucher_type + " Item",
527 sle.voucher_detail_no, ["item_code", rate_field])
528
529 if item_code == sle.item_code:
530 rate = incoming_rate
531 else:
532 if sle.voucher_type in ("Delivery Note", "Sales Invoice"):
533 ref_doctype = "Packed Item"
534 else:
535 ref_doctype = "Purchase Receipt Item Supplied"
Deepesh Gargb4be2922021-01-28 13:09:56 +0530536
Nabin Haita77b8c92020-12-21 14:45:50 +0530537 rate = frappe.db.get_value(ref_doctype, {"parent_detail_docname": sle.voucher_detail_no,
538 "item_code": sle.item_code}, rate_field)
539
540 return rate
541
542 def update_outgoing_rate_on_transaction(self, sle):
543 """
544 Update outgoing rate in Stock Entry, Delivery Note, Sales Invoice and Sales Return
545 In case of Stock Entry, also calculate FG Item rate and total incoming/outgoing amount
546 """
547 if sle.actual_qty and sle.voucher_detail_no:
548 outgoing_rate = abs(flt(sle.stock_value_difference)) / abs(sle.actual_qty)
549
550 if flt(sle.actual_qty) < 0 and sle.voucher_type == "Stock Entry":
551 self.update_rate_on_stock_entry(sle, outgoing_rate)
552 elif sle.voucher_type in ("Delivery Note", "Sales Invoice"):
553 self.update_rate_on_delivery_and_sales_return(sle, outgoing_rate)
554 elif flt(sle.actual_qty) < 0 and sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
555 self.update_rate_on_purchase_receipt(sle, outgoing_rate)
556
557 def update_rate_on_stock_entry(self, sle, outgoing_rate):
558 frappe.db.set_value("Stock Entry Detail", sle.voucher_detail_no, "basic_rate", outgoing_rate)
559
560 # Update outgoing item's rate, recalculate FG Item's rate and total incoming/outgoing amount
Nabin Hait97bce3a2021-07-12 13:24:43 +0530561 if not sle.dependant_sle_voucher_detail_no:
562 self.recalculate_amounts_in_stock_entry(sle.voucher_no)
563
564 def recalculate_amounts_in_stock_entry(self, voucher_no):
565 stock_entry = frappe.get_doc("Stock Entry", voucher_no, for_update=True)
Nabin Haita77b8c92020-12-21 14:45:50 +0530566 stock_entry.calculate_rate_and_amount(reset_outgoing_rate=False, raise_error_if_no_rate=False)
567 stock_entry.db_update()
568 for d in stock_entry.items:
569 d.db_update()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530570
Nabin Haita77b8c92020-12-21 14:45:50 +0530571 def update_rate_on_delivery_and_sales_return(self, sle, outgoing_rate):
572 # Update item's incoming rate on transaction
573 item_code = frappe.db.get_value(sle.voucher_type + " Item", sle.voucher_detail_no, "item_code")
574 if item_code == sle.item_code:
575 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "incoming_rate", outgoing_rate)
576 else:
577 # packed item
578 frappe.db.set_value("Packed Item",
579 {"parent_detail_docname": sle.voucher_detail_no, "item_code": sle.item_code},
580 "incoming_rate", outgoing_rate)
581
582 def update_rate_on_purchase_receipt(self, sle, outgoing_rate):
583 if frappe.db.exists(sle.voucher_type + " Item", sle.voucher_detail_no):
584 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "base_net_rate", outgoing_rate)
585 else:
586 frappe.db.set_value("Purchase Receipt Item Supplied", sle.voucher_detail_no, "rate", outgoing_rate)
587
588 # Recalculate subcontracted item's rate in case of subcontracted purchase receipt/invoice
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530589 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_subcontracted") == 'Yes':
Rohit Waghchauree5fb2392021-06-18 20:37:42 +0530590 doc = frappe.get_doc(sle.voucher_type, sle.voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530591 doc.update_valuation_rate(reset_outgoing_rate=False)
592 for d in (doc.items + doc.supplied_items):
593 d.db_update()
594
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530595 def get_serialized_values(self, sle):
596 incoming_rate = flt(sle.incoming_rate)
597 actual_qty = flt(sle.actual_qty)
Nabin Hait328c4f92020-01-02 19:00:32 +0530598 serial_nos = cstr(sle.serial_no).split("\n")
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530599
600 if incoming_rate < 0:
601 # wrong incoming rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530602 incoming_rate = self.wh_data.valuation_rate
Rushabh Mehta538607e2016-06-12 11:03:00 +0530603
Nabin Hait2620bf42016-02-29 11:30:27 +0530604 stock_value_change = 0
605 if incoming_rate:
606 stock_value_change = actual_qty * incoming_rate
607 elif actual_qty < 0:
608 # In case of delivery/stock issue, get average purchase rate
609 # of serial nos of current entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530610 if not sle.is_cancelled:
611 outgoing_value = self.get_incoming_value_for_serial_nos(sle, serial_nos)
612 stock_value_change = -1 * outgoing_value
613 else:
614 stock_value_change = actual_qty * sle.outgoing_rate
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530615
Nabin Haita77b8c92020-12-21 14:45:50 +0530616 new_stock_qty = self.wh_data.qty_after_transaction + actual_qty
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530617
Nabin Hait2620bf42016-02-29 11:30:27 +0530618 if new_stock_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530619 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + stock_value_change
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530620 if new_stock_value >= 0:
Nabin Hait2620bf42016-02-29 11:30:27 +0530621 # calculate new valuation rate only if stock value is positive
622 # else it remains the same as that of previous entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530623 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530624
Nabin Haita77b8c92020-12-21 14:45:50 +0530625 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530626 allow_zero_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
627 if not allow_zero_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530628 self.wh_data.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530629 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
Ankush Menata0727b22021-11-01 13:17:40 +0530630 currency=erpnext.get_company_currency(sle.company), company=sle.company)
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530631
Nabin Hait328c4f92020-01-02 19:00:32 +0530632 def get_incoming_value_for_serial_nos(self, sle, serial_nos):
633 # get rate from serial nos within same company
634 all_serial_nos = frappe.get_all("Serial No",
635 fields=["purchase_rate", "name", "company"],
636 filters = {'name': ('in', serial_nos)})
637
Ankush Menat98917802021-06-11 18:40:22 +0530638 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 +0530639
640 # Get rate for serial nos which has been transferred to other company
641 invalid_serial_nos = [d.name for d in all_serial_nos if d.company!=sle.company]
642 for serial_no in invalid_serial_nos:
643 incoming_rate = frappe.db.sql("""
644 select incoming_rate
645 from `tabStock Ledger Entry`
646 where
647 company = %s
648 and actual_qty > 0
649 and (serial_no = %s
650 or serial_no like %s
651 or serial_no like %s
652 or serial_no like %s
653 )
654 order by posting_date desc
655 limit 1
656 """, (sle.company, serial_no, serial_no+'\n%', '%\n'+serial_no, '%\n'+serial_no+'\n%'))
657
658 incoming_values += flt(incoming_rate[0][0]) if incoming_rate else 0
659
660 return incoming_values
661
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530662 def get_moving_average_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530663 actual_qty = flt(sle.actual_qty)
Nabin Haita77b8c92020-12-21 14:45:50 +0530664 new_stock_qty = flt(self.wh_data.qty_after_transaction) + actual_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530665 if new_stock_qty >= 0:
666 if actual_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530667 if flt(self.wh_data.qty_after_transaction) <= 0:
668 self.wh_data.valuation_rate = sle.incoming_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530669 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530670 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530671 (actual_qty * sle.incoming_rate)
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530672
Nabin Haita77b8c92020-12-21 14:45:50 +0530673 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530674
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530675 elif sle.outgoing_rate:
676 if new_stock_qty:
Nabin Haita77b8c92020-12-21 14:45:50 +0530677 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530678 (actual_qty * sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530679
Nabin Haita77b8c92020-12-21 14:45:50 +0530680 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530681 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530682 self.wh_data.valuation_rate = sle.outgoing_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530683 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530684 if flt(self.wh_data.qty_after_transaction) >= 0 and sle.outgoing_rate:
685 self.wh_data.valuation_rate = sle.outgoing_rate
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530686
Nabin Haita77b8c92020-12-21 14:45:50 +0530687 if not self.wh_data.valuation_rate and actual_qty > 0:
688 self.wh_data.valuation_rate = sle.incoming_rate
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530689
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530690 # Get valuation rate from previous SLE or Item master, if item does not have the
Javier Wong9b11d9b2017-04-14 18:24:04 +0800691 # allow zero valuration rate flag set
Nabin Haita77b8c92020-12-21 14:45:50 +0530692 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
Javier Wong9b11d9b2017-04-14 18:24:04 +0800693 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
694 if not allow_zero_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530695 self.wh_data.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530696 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
Ankush Menata0727b22021-11-01 13:17:40 +0530697 currency=erpnext.get_company_currency(sle.company), company=sle.company)
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530698
Ankush Menat4b29fb62021-12-18 18:40:22 +0530699 def update_fifo_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530700 incoming_rate = flt(sle.incoming_rate)
701 actual_qty = flt(sle.actual_qty)
Nabin Haitada485f2015-07-17 15:09:56 +0530702 outgoing_rate = flt(sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530703
Ankush Menat4b29fb62021-12-18 18:40:22 +0530704 fifo_queue = FifoValuation(self.wh_data.stock_queue)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530705 if actual_qty > 0:
Ankush Menat4b29fb62021-12-18 18:40:22 +0530706 fifo_queue.add_stock(qty=actual_qty, rate=incoming_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530707 else:
Ankush Menat4b29fb62021-12-18 18:40:22 +0530708 def rate_generator() -> float:
709 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
710 if not allow_zero_valuation_rate:
711 return get_valuation_rate(sle.item_code, sle.warehouse,
712 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
713 currency=erpnext.get_company_currency(sle.company), company=sle.company)
Nabin Haitada485f2015-07-17 15:09:56 +0530714 else:
Ankush Menat4b29fb62021-12-18 18:40:22 +0530715 return 0.0
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530716
Ankush Menata00d8d02021-12-19 18:45:04 +0530717 fifo_queue.remove_stock(qty=abs(actual_qty), outgoing_rate=outgoing_rate, rate_generator=rate_generator)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530718
Ankush Menat4b29fb62021-12-18 18:40:22 +0530719 stock_qty, stock_value = fifo_queue.get_total_stock_and_value()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530720
Ankush Menat4b29fb62021-12-18 18:40:22 +0530721 self.wh_data.stock_queue = fifo_queue.get_state()
722 self.wh_data.stock_value = stock_value
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530723 if stock_qty:
Ankush Menat4b29fb62021-12-18 18:40:22 +0530724 self.wh_data.valuation_rate = stock_value / stock_qty
725
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530726
Nabin Haita77b8c92020-12-21 14:45:50 +0530727 if not self.wh_data.stock_queue:
728 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 +0530729
Ankush Menat4b29fb62021-12-18 18:40:22 +0530730
731
Javier Wong9b11d9b2017-04-14 18:24:04 +0800732 def check_if_allow_zero_valuation_rate(self, voucher_type, voucher_detail_no):
deepeshgarg007f9c0ef32019-07-30 18:49:19 +0530733 ref_item_dt = ""
734
735 if voucher_type == "Stock Entry":
736 ref_item_dt = voucher_type + " Detail"
737 elif voucher_type in ["Purchase Invoice", "Sales Invoice", "Delivery Note", "Purchase Receipt"]:
738 ref_item_dt = voucher_type + " Item"
739
740 if ref_item_dt:
741 return frappe.db.get_value(ref_item_dt, voucher_detail_no, "allow_zero_valuation_rate")
742 else:
743 return 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530744
Nabin Haita77b8c92020-12-21 14:45:50 +0530745 def get_sle_before_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530746 """get previous stock ledger entry before current time-bucket"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530747 sle = get_stock_ledger_entries(args, "<", "desc", "limit 1", for_update=False)
748 sle = sle[0] if sle else frappe._dict()
749 return sle
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530750
Nabin Haita77b8c92020-12-21 14:45:50 +0530751 def get_sle_after_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530752 """get Stock Ledger Entries after a particular datetime, for reposting"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530753 return get_stock_ledger_entries(args, ">", "asc", for_update=True, check_serial_no=False)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530754
755 def raise_exceptions(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530756 msg_list = []
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530757 for warehouse, exceptions in self.exceptions.items():
Nabin Haita77b8c92020-12-21 14:45:50 +0530758 deficiency = min(e["diff"] for e in exceptions)
Rushabh Mehta538607e2016-06-12 11:03:00 +0530759
Nabin Haita77b8c92020-12-21 14:45:50 +0530760 if ((exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]) in
761 frappe.local.flags.currently_saving):
Nabin Hait3edefb12016-07-20 16:13:18 +0530762
Nabin Haita77b8c92020-12-21 14:45:50 +0530763 msg = _("{0} units of {1} needed in {2} to complete this transaction.").format(
Nabin Hait243d59b2021-02-02 16:55:13 +0530764 abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]),
Nabin Haita77b8c92020-12-21 14:45:50 +0530765 frappe.get_desk_link('Warehouse', warehouse))
766 else:
767 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 +0530768 abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]),
Nabin Haita77b8c92020-12-21 14:45:50 +0530769 frappe.get_desk_link('Warehouse', warehouse),
770 exceptions[0]["posting_date"], exceptions[0]["posting_time"],
771 frappe.get_desk_link(exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530772
Nabin Haita77b8c92020-12-21 14:45:50 +0530773 if msg:
774 msg_list.append(msg)
775
776 if msg_list:
777 message = "\n\n".join(msg_list)
778 if self.verbose:
779 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
780 else:
781 raise NegativeStockError(message)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530782
Nabin Haita77b8c92020-12-21 14:45:50 +0530783 def update_bin(self):
784 # update bin for each warehouse
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530785 for warehouse, data in self.data.items():
Ankush Menat97060c42021-12-03 11:50:38 +0530786 bin_name = get_or_make_bin(self.item_code, warehouse)
Deepesh Garg6f107da2021-10-12 20:15:55 +0530787
Ankush Menat97060c42021-12-03 11:50:38 +0530788 frappe.db.set_value('Bin', bin_name, {
Nabin Haita77b8c92020-12-21 14:45:50 +0530789 "valuation_rate": data.valuation_rate,
790 "actual_qty": data.qty_after_transaction,
791 "stock_value": data.stock_value
792 })
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530793
marination8418c4b2021-06-22 21:35:25 +0530794
795def get_previous_sle_of_current_voucher(args, exclude_current_voucher=False):
796 """get stock ledger entries filtered by specific posting datetime conditions"""
797
798 args['time_format'] = '%H:%i:%s'
799 if not args.get("posting_date"):
800 args["posting_date"] = "1900-01-01"
801 if not args.get("posting_time"):
802 args["posting_time"] = "00:00"
803
804 voucher_condition = ""
805 if exclude_current_voucher:
806 voucher_no = args.get("voucher_no")
807 voucher_condition = f"and voucher_no != '{voucher_no}'"
808
809 sle = frappe.db.sql("""
810 select *, timestamp(posting_date, posting_time) as "timestamp"
811 from `tabStock Ledger Entry`
812 where item_code = %(item_code)s
813 and warehouse = %(warehouse)s
814 and is_cancelled = 0
815 {voucher_condition}
816 and timestamp(posting_date, time_format(posting_time, %(time_format)s)) < timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
817 order by timestamp(posting_date, posting_time) desc, creation desc
818 limit 1
819 for update""".format(voucher_condition=voucher_condition), args, as_dict=1)
820
821 return sle[0] if sle else frappe._dict()
822
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530823def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530824 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530825 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530826 to get actual qty before transaction, this function
827 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530828
Anand Doshi1b531862013-01-10 19:29:51 +0530829 args = {
830 "item_code": "ABC",
831 "warehouse": "XYZ",
832 "posting_date": "2012-12-12",
833 "posting_time": "12:00",
834 "sle": "name of reference Stock Ledger Entry"
835 }
836 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530837 args["name"] = args.get("sle", None) or ""
838 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530839 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530840
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530841def get_stock_ledger_entries(previous_sle, operator=None,
842 order="desc", limit=None, for_update=False, debug=False, check_serial_no=True):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530843 """get stock ledger entries filtered by specific posting datetime conditions"""
Nabin Haitb9ce1042018-02-01 14:58:50 +0530844 conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
845 if previous_sle.get("warehouse"):
846 conditions += " and warehouse = %(warehouse)s"
847 elif previous_sle.get("warehouse_condition"):
848 conditions += " and " + previous_sle.get("warehouse_condition")
849
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530850 if check_serial_no and previous_sle.get("serial_no"):
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530851 # conditions += " and serial_no like {}".format(frappe.db.escape('%{0}%'.format(previous_sle.get("serial_no"))))
852 serial_no = previous_sle.get("serial_no")
853 conditions += (""" and
854 (
855 serial_no = {0}
856 or serial_no like {1}
857 or serial_no like {2}
858 or serial_no like {3}
859 )
860 """).format(frappe.db.escape(serial_no), frappe.db.escape('{}\n%'.format(serial_no)),
861 frappe.db.escape('%\n{}'.format(serial_no)), frappe.db.escape('%\n{}\n%'.format(serial_no)))
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530862
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530863 if not previous_sle.get("posting_date"):
864 previous_sle["posting_date"] = "1900-01-01"
865 if not previous_sle.get("posting_time"):
866 previous_sle["posting_time"] = "00:00"
867
868 if operator in (">", "<=") and previous_sle.get("name"):
869 conditions += " and name!=%(name)s"
870
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530871 return frappe.db.sql("""
872 select *, timestamp(posting_date, posting_time) as "timestamp"
873 from `tabStock Ledger Entry`
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530874 where item_code = %%(item_code)s
Nabin Haita77b8c92020-12-21 14:45:50 +0530875 and is_cancelled = 0
Nabin Haitb9ce1042018-02-01 14:58:50 +0530876 %(conditions)s
Aditya Hase0c164242019-01-07 22:07:13 +0530877 order by timestamp(posting_date, posting_time) %(order)s, creation %(order)s
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530878 %(limit)s %(for_update)s""" % {
879 "conditions": conditions,
880 "limit": limit or "",
881 "for_update": for_update and "for update" or "",
882 "order": order
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530883 }, previous_sle, as_dict=1, debug=debug)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530884
Nabin Haita77b8c92020-12-21 14:45:50 +0530885def get_sle_by_voucher_detail_no(voucher_detail_no, excluded_sle=None):
886 return frappe.db.get_value('Stock Ledger Entry',
887 {'voucher_detail_no': voucher_detail_no, 'name': ['!=', excluded_sle]},
888 ['item_code', 'warehouse', 'posting_date', 'posting_time', 'timestamp(posting_date, posting_time) as timestamp'],
889 as_dict=1)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530890
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530891def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no,
Nabin Hait7ba092e2018-02-01 10:51:27 +0530892 allow_zero_rate=False, currency=None, company=None, raise_error_if_no_rate=True):
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530893
Ankush Menatf7ffe042021-11-01 13:21:14 +0530894 if not company:
895 company = frappe.get_cached_value("Warehouse", warehouse, "company")
896
897 # Get valuation rate from last sle for the same item and warehouse
Nabin Haitfb6e4342014-10-15 11:34:40 +0530898 last_valuation_rate = frappe.db.sql("""select valuation_rate
Deepesh Garg6f107da2021-10-12 20:15:55 +0530899 from `tabStock Ledger Entry` force index (item_warehouse)
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530900 where
901 item_code = %s
902 AND warehouse = %s
903 AND valuation_rate >= 0
904 AND NOT (voucher_no = %s AND voucher_type = %s)
905 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 +0530906
907 if not last_valuation_rate:
Nabin Haita0b967f2017-01-18 18:35:58 +0530908 # Get valuation rate from last sle for the item against any warehouse
Nabin Haitfb6e4342014-10-15 11:34:40 +0530909 last_valuation_rate = frappe.db.sql("""select valuation_rate
Deepesh Garg6f107da2021-10-12 20:15:55 +0530910 from `tabStock Ledger Entry` force index (item_code)
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530911 where
912 item_code = %s
913 AND valuation_rate > 0
914 AND NOT(voucher_no = %s AND voucher_type = %s)
915 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 +0530916
Nabin Haita645f362018-03-01 10:31:24 +0530917 if last_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530918 return flt(last_valuation_rate[0][0])
Nabin Haita645f362018-03-01 10:31:24 +0530919
920 # If negative stock allowed, and item delivered without any incoming entry,
921 # system does not found any SLE, then take valuation rate from Item
922 valuation_rate = frappe.db.get_value("Item", item_code, "valuation_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530923
924 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530925 # try Item Standard rate
926 valuation_rate = frappe.db.get_value("Item", item_code, "standard_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530927
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530928 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530929 # try in price list
930 valuation_rate = frappe.db.get_value('Item Price',
931 dict(item_code=item_code, buying=1, currency=currency),
932 'price_list_rate')
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530933
Nabin Hait7ba092e2018-02-01 10:51:27 +0530934 if not allow_zero_rate and not valuation_rate and raise_error_if_no_rate \
Rohit Waghchauree9ff1912017-06-19 12:54:59 +0530935 and cint(erpnext.is_perpetual_inventory_enabled(company)):
Neil Trini Lasrado193c8912017-03-28 17:39:34 +0530936 frappe.local.message_log = []
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530937 form_link = get_link_to_form("Item", item_code)
Marica97715f22020-05-11 20:45:37 +0530938
939 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 +0530940 message += "<br><br>" + _("Here are the options to proceed:")
Marica97715f22020-05-11 20:45:37 +0530941 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 +0530942 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 +0530943 sub_solutions = "<ul><li>" + _("Create an incoming stock transaction for the Item.") + "</li>"
944 sub_solutions += "<li>" + _("Mention Valuation Rate in the Item master.") + "</li></ul>"
945 msg = message + solutions + sub_solutions + "</li>"
946
947 frappe.throw(msg=msg, title=_("Valuation Rate Missing"))
Nabin Haitfb6e4342014-10-15 11:34:40 +0530948
949 return valuation_rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530950
Ankush Menate7109c12021-08-26 16:40:45 +0530951def update_qty_in_future_sle(args, allow_negative_stock=False):
marination8418c4b2021-06-22 21:35:25 +0530952 """Recalculate Qty after Transaction in future SLEs based on current SLE."""
marination40389772021-07-02 17:13:45 +0530953 datetime_limit_condition = ""
marination8418c4b2021-06-22 21:35:25 +0530954 qty_shift = args.actual_qty
955
956 # find difference/shift in qty caused by stock reconciliation
957 if args.voucher_type == "Stock Reconciliation":
marination40389772021-07-02 17:13:45 +0530958 qty_shift = get_stock_reco_qty_shift(args)
959
960 # find the next nearest stock reco so that we only recalculate SLEs till that point
961 next_stock_reco_detail = get_next_stock_reco(args)
962 if next_stock_reco_detail:
963 detail = next_stock_reco_detail[0]
964 # add condition to update SLEs before this date & time
965 datetime_limit_condition = get_datetime_limit_condition(detail)
marination8418c4b2021-06-22 21:35:25 +0530966
Nabin Hait186a0452021-02-18 14:14:21 +0530967 frappe.db.sql("""
968 update `tabStock Ledger Entry`
marination8418c4b2021-06-22 21:35:25 +0530969 set qty_after_transaction = qty_after_transaction + {qty_shift}
Nabin Hait186a0452021-02-18 14:14:21 +0530970 where
971 item_code = %(item_code)s
972 and warehouse = %(warehouse)s
973 and voucher_no != %(voucher_no)s
974 and is_cancelled = 0
975 and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)
976 or (
977 timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s)
978 and creation > %(creation)s
979 )
980 )
marination40389772021-07-02 17:13:45 +0530981 {datetime_limit_condition}
982 """.format(qty_shift=qty_shift, datetime_limit_condition=datetime_limit_condition), args)
Nabin Hait186a0452021-02-18 14:14:21 +0530983
984 validate_negative_qty_in_future_sle(args, allow_negative_stock)
985
marination40389772021-07-02 17:13:45 +0530986def get_stock_reco_qty_shift(args):
987 stock_reco_qty_shift = 0
988 if args.get("is_cancelled"):
989 if args.get("previous_qty_after_transaction"):
990 # get qty (balance) that was set at submission
991 last_balance = args.get("previous_qty_after_transaction")
992 stock_reco_qty_shift = flt(args.qty_after_transaction) - flt(last_balance)
993 else:
994 stock_reco_qty_shift = flt(args.actual_qty)
995 else:
996 # reco is being submitted
997 last_balance = get_previous_sle_of_current_voucher(args,
998 exclude_current_voucher=True).get("qty_after_transaction")
999
1000 if last_balance is not None:
1001 stock_reco_qty_shift = flt(args.qty_after_transaction) - flt(last_balance)
1002 else:
1003 stock_reco_qty_shift = args.qty_after_transaction
1004
1005 return stock_reco_qty_shift
1006
1007def get_next_stock_reco(args):
1008 """Returns next nearest stock reconciliaton's details."""
1009
1010 return frappe.db.sql("""
1011 select
1012 name, posting_date, posting_time, creation, voucher_no
1013 from
marination8c441262021-07-02 17:46:05 +05301014 `tabStock Ledger Entry`
marination40389772021-07-02 17:13:45 +05301015 where
1016 item_code = %(item_code)s
1017 and warehouse = %(warehouse)s
1018 and voucher_type = 'Stock Reconciliation'
1019 and voucher_no != %(voucher_no)s
1020 and is_cancelled = 0
1021 and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)
1022 or (
1023 timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s)
1024 and creation > %(creation)s
1025 )
1026 )
1027 limit 1
1028 """, args, as_dict=1)
1029
1030def get_datetime_limit_condition(detail):
marination40389772021-07-02 17:13:45 +05301031 return f"""
1032 and
1033 (timestamp(posting_date, posting_time) < timestamp('{detail.posting_date}', '{detail.posting_time}')
1034 or (
1035 timestamp(posting_date, posting_time) = timestamp('{detail.posting_date}', '{detail.posting_time}')
1036 and creation < '{detail.creation}'
1037 )
1038 )"""
1039
Ankush Menate7109c12021-08-26 16:40:45 +05301040def validate_negative_qty_in_future_sle(args, allow_negative_stock=False):
1041 allow_negative_stock = cint(allow_negative_stock) \
Nabin Haita77b8c92020-12-21 14:45:50 +05301042 or cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
1043
Ankush Menat5eba5752021-12-07 23:03:52 +05301044 if allow_negative_stock:
1045 return
1046 if not (args.actual_qty < 0 or args.voucher_type == "Stock Reconciliation"):
1047 return
Deepesh Gargb4be2922021-01-28 13:09:56 +05301048
Ankush Menat5eba5752021-12-07 23:03:52 +05301049 neg_sle = get_future_sle_with_negative_qty(args)
1050 if neg_sle:
1051 message = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
1052 abs(neg_sle[0]["qty_after_transaction"]),
1053 frappe.get_desk_link('Item', args.item_code),
1054 frappe.get_desk_link('Warehouse', args.warehouse),
1055 neg_sle[0]["posting_date"], neg_sle[0]["posting_time"],
1056 frappe.get_desk_link(neg_sle[0]["voucher_type"], neg_sle[0]["voucher_no"]))
1057
1058 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
1059
1060
1061 if not args.batch_no:
1062 return
1063
1064 neg_batch_sle = get_future_sle_with_negative_batch_qty(args)
1065 if neg_batch_sle:
1066 message = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
1067 abs(neg_batch_sle[0]["cumulative_total"]),
1068 frappe.get_desk_link('Batch', args.batch_no),
1069 frappe.get_desk_link('Warehouse', args.warehouse),
1070 neg_batch_sle[0]["posting_date"], neg_batch_sle[0]["posting_time"],
1071 frappe.get_desk_link(neg_batch_sle[0]["voucher_type"], neg_batch_sle[0]["voucher_no"]))
1072 frappe.throw(message, NegativeStockError, title="Insufficient Stock for Batch")
1073
Nabin Haita77b8c92020-12-21 14:45:50 +05301074
1075def get_future_sle_with_negative_qty(args):
1076 return frappe.db.sql("""
1077 select
1078 qty_after_transaction, posting_date, posting_time,
1079 voucher_type, voucher_no
1080 from `tabStock Ledger Entry`
Deepesh Gargb4be2922021-01-28 13:09:56 +05301081 where
Nabin Haita77b8c92020-12-21 14:45:50 +05301082 item_code = %(item_code)s
1083 and warehouse = %(warehouse)s
1084 and voucher_no != %(voucher_no)s
1085 and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s)
1086 and is_cancelled = 0
Nabin Hait186a0452021-02-18 14:14:21 +05301087 and qty_after_transaction < 0
Nabin Hait243d59b2021-02-02 16:55:13 +05301088 order by timestamp(posting_date, posting_time) asc
Nabin Haita77b8c92020-12-21 14:45:50 +05301089 limit 1
Sagar Vorae50324a2021-03-31 12:44:03 +05301090 """, args, as_dict=1)
Ankush Menat6a014d12021-04-12 20:21:27 +05301091
Ankush Menat5eba5752021-12-07 23:03:52 +05301092
1093def get_future_sle_with_negative_batch_qty(args):
1094 return frappe.db.sql("""
1095 with batch_ledger as (
1096 select
1097 posting_date, posting_time, voucher_type, voucher_no,
1098 sum(actual_qty) over (order by posting_date, posting_time, creation) as cumulative_total
1099 from `tabStock Ledger Entry`
1100 where
1101 item_code = %(item_code)s
1102 and warehouse = %(warehouse)s
1103 and batch_no=%(batch_no)s
1104 and is_cancelled = 0
1105 order by posting_date, posting_time, creation
1106 )
1107 select * from batch_ledger
1108 where
1109 cumulative_total < 0.0
1110 and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s)
1111 limit 1
1112 """, args, as_dict=1)