blob: 0a7ab4009c0ed53edb0df46a5ad3cac0036a0678 [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
Ankush Menat66bf21f2022-01-16 20:45:59 +0530108
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530109 for sn in get_serial_nos(sle.serial_no):
110 args = copy.deepcopy(sle)
111 args.serial_no = sn
112 args.warehouse = ''
113
114 vouchers = []
115 for row in get_stock_ledger_entries(args, '>'):
116 voucher_type = frappe.bold(row.voucher_type)
117 voucher_no = frappe.bold(get_link_to_form(row.voucher_type, row.voucher_no))
118 vouchers.append(f'{voucher_type} {voucher_no}')
119
120 if vouchers:
121 serial_no = frappe.bold(sn)
122 msg = (f'''The serial no {serial_no} has been used in the future transactions so you need to cancel them first.
123 The list of the transactions are as below.''' + '<br><br><ul><li>')
124
125 msg += '</li><li>'.join(vouchers)
126 msg += '</li></ul>'
127
128 title = 'Cannot Submit' if not sle.get('is_cancelled') else 'Cannot Cancel'
129 frappe.throw(_(msg), title=_(title), exc=SerialNoExistsInFutureTransaction)
130
Nabin Hait186a0452021-02-18 14:14:21 +0530131def validate_cancellation(args):
132 if args[0].get("is_cancelled"):
133 repost_entry = frappe.db.get_value("Repost Item Valuation", {
134 'voucher_type': args[0].voucher_type,
135 'voucher_no': args[0].voucher_no,
136 'docstatus': 1
137 }, ['name', 'status'], as_dict=1)
138
139 if repost_entry:
140 if repost_entry.status == 'In Progress':
141 frappe.throw(_("Cannot cancel the transaction. Reposting of item valuation on submission is not completed yet."))
142 if repost_entry.status == 'Queued':
Nabin Haitd46b2362021-02-23 16:38:52 +0530143 doc = frappe.get_doc("Repost Item Valuation", repost_entry.name)
Ankush Menataa024fc2021-11-18 12:51:26 +0530144 doc.flags.ignore_permissions = True
Nabin Haitd46b2362021-02-23 16:38:52 +0530145 doc.cancel()
146 doc.delete()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530147
Nabin Hait9653f602013-08-20 15:37:33 +0530148def set_as_cancel(voucher_type, voucher_no):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530149 frappe.db.sql("""update `tabStock Ledger Entry` set is_cancelled=1,
Nabin Hait9653f602013-08-20 15:37:33 +0530150 modified=%s, modified_by=%s
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530151 where voucher_type=%s and voucher_no=%s and is_cancelled = 0""",
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530152 (now(), frappe.session.user, voucher_type, voucher_no))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530153
Nabin Hait54c865e2015-03-27 15:38:31 +0530154def make_entry(args, allow_negative_stock=False, via_landed_cost_voucher=False):
Saqib Ansaric7fc6092021-10-12 13:30:40 +0530155 args["doctype"] = "Stock Ledger Entry"
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530156 sle = frappe.get_doc(args)
Anand Doshi6dfd4302015-02-10 14:41:27 +0530157 sle.flags.ignore_permissions = 1
Nabin Hait4ccd8d32015-01-23 12:18:01 +0530158 sle.allow_negative_stock=allow_negative_stock
Nabin Hait54c865e2015-03-27 15:38:31 +0530159 sle.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Haitaeba24e2013-08-23 15:17:36 +0530160 sle.submit()
Nabin Haita77b8c92020-12-21 14:45:50 +0530161 return sle
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530162
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530163def 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 +0530164 if not args and voucher_type and voucher_no:
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530165 args = get_items_to_be_repost(voucher_type, voucher_no, doc)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530166
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530167 distinct_item_warehouses = get_distinct_item_warehouse(args, doc)
Nabin Haita77b8c92020-12-21 14:45:50 +0530168
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530169 i = get_current_index(doc) or 0
Nabin Haita77b8c92020-12-21 14:45:50 +0530170 while i < len(args):
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530171 validate_item_warehouse(args[i])
172
Nabin Haita77b8c92020-12-21 14:45:50 +0530173 obj = update_entries_after({
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530174 'item_code': args[i].get('item_code'),
175 'warehouse': args[i].get('warehouse'),
176 'posting_date': args[i].get('posting_date'),
177 'posting_time': args[i].get('posting_time'),
178 'creation': args[i].get('creation'),
179 'distinct_item_warehouses': distinct_item_warehouses
Nabin Haita77b8c92020-12-21 14:45:50 +0530180 }, allow_negative_stock=allow_negative_stock, via_landed_cost_voucher=via_landed_cost_voucher)
181
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530182 distinct_item_warehouses[(args[i].get('item_code'), args[i].get('warehouse'))].reposting_status = True
Deepesh Gargb4be2922021-01-28 13:09:56 +0530183
Nabin Hait97bce3a2021-07-12 13:24:43 +0530184 if obj.new_items_found:
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530185 for item_wh, data in distinct_item_warehouses.items():
Nabin Hait97bce3a2021-07-12 13:24:43 +0530186 if ('args_idx' not in data and not data.reposting_status) or (data.sle_changed and data.reposting_status):
187 data.args_idx = len(args)
188 args.append(data.sle)
189 elif data.sle_changed and not data.reposting_status:
190 args[data.args_idx] = data.sle
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530191
Nabin Hait97bce3a2021-07-12 13:24:43 +0530192 data.sle_changed = False
Nabin Haita77b8c92020-12-21 14:45:50 +0530193 i += 1
194
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530195 if doc and i % 2 == 0:
196 update_args_in_repost_item_valuation(doc, i, args, distinct_item_warehouses)
197
198 if doc and args:
199 update_args_in_repost_item_valuation(doc, i, args, distinct_item_warehouses)
200
201def validate_item_warehouse(args):
202 for field in ['item_code', 'warehouse', 'posting_date', 'posting_time']:
203 if not args.get(field):
204 validation_msg = f'The field {frappe.unscrub(args.get(field))} is required for the reposting'
205 frappe.throw(_(validation_msg))
206
207def update_args_in_repost_item_valuation(doc, index, args, distinct_item_warehouses):
208 frappe.db.set_value(doc.doctype, doc.name, {
209 'items_to_be_repost': json.dumps(args, default=str),
210 'distinct_item_and_warehouse': json.dumps({str(k): v for k,v in distinct_item_warehouses.items()}, default=str),
211 'current_index': index
212 })
213
214 frappe.db.commit()
215
216 frappe.publish_realtime('item_reposting_progress', {
217 'name': doc.name,
218 'items_to_be_repost': json.dumps(args, default=str),
219 'current_index': index
220 })
221
222def get_items_to_be_repost(voucher_type, voucher_no, doc=None):
223 if doc and doc.items_to_be_repost:
224 return json.loads(doc.items_to_be_repost) or []
225
Nabin Haita77b8c92020-12-21 14:45:50 +0530226 return frappe.db.get_all("Stock Ledger Entry",
227 filters={"voucher_type": voucher_type, "voucher_no": voucher_no},
Nabin Hait186a0452021-02-18 14:14:21 +0530228 fields=["item_code", "warehouse", "posting_date", "posting_time", "creation"],
Nabin Haita77b8c92020-12-21 14:45:50 +0530229 order_by="creation asc",
230 group_by="item_code, warehouse"
231 )
Nabin Hait74c281c2013-08-19 16:17:18 +0530232
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530233def get_distinct_item_warehouse(args=None, doc=None):
234 distinct_item_warehouses = {}
235 if doc and doc.distinct_item_and_warehouse:
236 distinct_item_warehouses = json.loads(doc.distinct_item_and_warehouse)
237 distinct_item_warehouses = {frappe.safe_eval(k): frappe._dict(v) for k, v in distinct_item_warehouses.items()}
238 else:
239 for i, d in enumerate(args):
240 distinct_item_warehouses.setdefault((d.item_code, d.warehouse), frappe._dict({
241 "reposting_status": False,
242 "sle": d,
243 "args_idx": i
244 }))
245
246 return distinct_item_warehouses
247
248def get_current_index(doc=None):
249 if doc and doc.current_index:
250 return doc.current_index
251
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530252class update_entries_after(object):
Nabin Hait902e8602013-01-08 18:29:24 +0530253 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530254 update valution rate and qty after transaction
Nabin Hait902e8602013-01-08 18:29:24 +0530255 from the current time-bucket onwards
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530256
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530257 :param args: args as dict
258
259 args = {
260 "item_code": "ABC",
261 "warehouse": "XYZ",
262 "posting_date": "2012-12-12",
263 "posting_time": "12:00"
264 }
Nabin Hait902e8602013-01-08 18:29:24 +0530265 """
Anand Doshi0dc79f42015-04-06 12:59:34 +0530266 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 +0530267 self.exceptions = {}
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530268 self.verbose = verbose
269 self.allow_zero_rate = allow_zero_rate
Anand Doshi0dc79f42015-04-06 12:59:34 +0530270 self.via_landed_cost_voucher = via_landed_cost_voucher
Ankush Menat7bafa112021-10-12 20:39:10 +0530271 self.allow_negative_stock = allow_negative_stock \
272 or cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530273
Nabin Haita77b8c92020-12-21 14:45:50 +0530274 self.args = frappe._dict(args)
275 self.item_code = args.get("item_code")
276 if self.args.sle_id:
277 self.args['name'] = self.args.sle_id
Nabin Haitd46b2362021-02-23 16:38:52 +0530278
Nabin Haita77b8c92020-12-21 14:45:50 +0530279 self.company = frappe.get_cached_value("Warehouse", self.args.warehouse, "company")
280 self.get_precision()
281 self.valuation_method = get_valuation_method(self.item_code)
Nabin Hait97bce3a2021-07-12 13:24:43 +0530282
283 self.new_items_found = False
284 self.distinct_item_warehouses = args.get("distinct_item_warehouses", frappe._dict())
Nabin Haita77b8c92020-12-21 14:45:50 +0530285
286 self.data = frappe._dict()
287 self.initialize_previous_data(self.args)
Nabin Haita77b8c92020-12-21 14:45:50 +0530288 self.build()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530289
Nabin Haita77b8c92020-12-21 14:45:50 +0530290 def get_precision(self):
291 company_base_currency = frappe.get_cached_value('Company', self.company, "default_currency")
292 self.precision = get_field_precision(frappe.get_meta("Stock Ledger Entry").get_field("stock_value"),
293 currency=company_base_currency)
294
295 def initialize_previous_data(self, args):
296 """
297 Get previous sl entries for current item for each related warehouse
298 and assigns into self.data dict
299
300 :Data Structure:
301
302 self.data = {
303 warehouse1: {
304 'previus_sle': {},
305 'qty_after_transaction': 10,
306 'valuation_rate': 100,
307 'stock_value': 1000,
308 'prev_stock_value': 1000,
309 'stock_queue': '[[10, 100]]',
310 'stock_value_difference': 1000
311 }
312 }
313
314 """
Ankush Menatc1d986a2021-08-31 19:43:42 +0530315 self.data.setdefault(args.warehouse, frappe._dict())
316 warehouse_dict = self.data[args.warehouse]
marination8418c4b2021-06-22 21:35:25 +0530317 previous_sle = get_previous_sle_of_current_voucher(args)
Ankush Menatc1d986a2021-08-31 19:43:42 +0530318 warehouse_dict.previous_sle = previous_sle
Nabin Haitbb777562013-08-29 18:19:37 +0530319
Ankush Menatc1d986a2021-08-31 19:43:42 +0530320 for key in ("qty_after_transaction", "valuation_rate", "stock_value"):
321 setattr(warehouse_dict, key, flt(previous_sle.get(key)))
322
323 warehouse_dict.update({
Nabin Haita77b8c92020-12-21 14:45:50 +0530324 "prev_stock_value": previous_sle.stock_value or 0.0,
325 "stock_queue": json.loads(previous_sle.stock_queue or "[]"),
326 "stock_value_difference": 0.0
327 })
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530328
Nabin Haita77b8c92020-12-21 14:45:50 +0530329 def build(self):
Sagar Vorae50324a2021-03-31 12:44:03 +0530330 from erpnext.controllers.stock_controller import future_sle_exists
Nabin Hait186a0452021-02-18 14:14:21 +0530331
Nabin Haita77b8c92020-12-21 14:45:50 +0530332 if self.args.get("sle_id"):
Nabin Hait186a0452021-02-18 14:14:21 +0530333 self.process_sle_against_current_timestamp()
Sagar Vorae50324a2021-03-31 12:44:03 +0530334 if not future_sle_exists(self.args):
Nabin Hait186a0452021-02-18 14:14:21 +0530335 self.update_bin()
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530336 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530337 entries_to_fix = self.get_future_entries_to_fix()
338
339 i = 0
340 while i < len(entries_to_fix):
341 sle = entries_to_fix[i]
342 i += 1
343
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530344 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530345
Nabin Haita77b8c92020-12-21 14:45:50 +0530346 if sle.dependant_sle_voucher_detail_no:
Nabin Hait243d59b2021-02-02 16:55:13 +0530347 entries_to_fix = self.get_dependent_entries_to_fix(entries_to_fix, sle)
Nabin Haitd46b2362021-02-23 16:38:52 +0530348
Nabin Hait186a0452021-02-18 14:14:21 +0530349 self.update_bin()
Nabin Haita77b8c92020-12-21 14:45:50 +0530350
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530351 if self.exceptions:
352 self.raise_exceptions()
353
Nabin Hait186a0452021-02-18 14:14:21 +0530354 def process_sle_against_current_timestamp(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530355 sl_entries = self.get_sle_against_current_voucher()
356 for sle in sl_entries:
357 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530358
Nabin Haita77b8c92020-12-21 14:45:50 +0530359 def get_sle_against_current_voucher(self):
Nabin Haitf2be0802021-02-15 19:27:49 +0530360 self.args['time_format'] = '%H:%i:%s'
361
Nabin Haita77b8c92020-12-21 14:45:50 +0530362 return frappe.db.sql("""
363 select
364 *, timestamp(posting_date, posting_time) as "timestamp"
365 from
366 `tabStock Ledger Entry`
367 where
368 item_code = %(item_code)s
369 and warehouse = %(warehouse)s
rohitwaghchaurefe4540d2021-08-26 12:52:36 +0530370 and is_cancelled = 0
Nabin Hait186a0452021-02-18 14:14:21 +0530371 and timestamp(posting_date, time_format(posting_time, %(time_format)s)) = timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
372
Nabin Haita77b8c92020-12-21 14:45:50 +0530373 order by
374 creation ASC
375 for update
376 """, self.args, as_dict=1)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530377
Nabin Haita77b8c92020-12-21 14:45:50 +0530378 def get_future_entries_to_fix(self):
379 # includes current entry!
380 args = self.data[self.args.warehouse].previous_sle \
381 or frappe._dict({"item_code": self.item_code, "warehouse": self.args.warehouse})
Deepesh Gargb4be2922021-01-28 13:09:56 +0530382
Nabin Haita77b8c92020-12-21 14:45:50 +0530383 return list(self.get_sle_after_datetime(args))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530384
Nabin Haita77b8c92020-12-21 14:45:50 +0530385 def get_dependent_entries_to_fix(self, entries_to_fix, sle):
386 dependant_sle = get_sle_by_voucher_detail_no(sle.dependant_sle_voucher_detail_no,
387 excluded_sle=sle.name)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530388
Nabin Haita77b8c92020-12-21 14:45:50 +0530389 if not dependant_sle:
Nabin Hait243d59b2021-02-02 16:55:13 +0530390 return entries_to_fix
Nabin Haita77b8c92020-12-21 14:45:50 +0530391 elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse == self.args.warehouse:
Nabin Hait243d59b2021-02-02 16:55:13 +0530392 return entries_to_fix
393 elif dependant_sle.item_code != self.item_code:
Nabin Hait97bce3a2021-07-12 13:24:43 +0530394 self.update_distinct_item_warehouses(dependant_sle)
Nabin Hait243d59b2021-02-02 16:55:13 +0530395 return entries_to_fix
396 elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse in self.data:
397 return entries_to_fix
Nabin Hait97bce3a2021-07-12 13:24:43 +0530398 else:
399 return self.append_future_sle_for_dependant(dependant_sle, entries_to_fix)
400
401 def update_distinct_item_warehouses(self, dependant_sle):
402 key = (dependant_sle.item_code, dependant_sle.warehouse)
403 val = frappe._dict({
404 "sle": dependant_sle
405 })
406 if key not in self.distinct_item_warehouses:
407 self.distinct_item_warehouses[key] = val
408 self.new_items_found = True
409 else:
410 existing_sle_posting_date = self.distinct_item_warehouses[key].get("sle", {}).get("posting_date")
411 if getdate(dependant_sle.posting_date) < getdate(existing_sle_posting_date):
412 val.sle_changed = True
413 self.distinct_item_warehouses[key] = val
414 self.new_items_found = True
415
416 def append_future_sle_for_dependant(self, dependant_sle, entries_to_fix):
Nabin Haita77b8c92020-12-21 14:45:50 +0530417 self.initialize_previous_data(dependant_sle)
418
419 args = self.data[dependant_sle.warehouse].previous_sle \
420 or frappe._dict({"item_code": self.item_code, "warehouse": dependant_sle.warehouse})
421 future_sle_for_dependant = list(self.get_sle_after_datetime(args))
422
423 entries_to_fix.extend(future_sle_for_dependant)
Nabin Hait243d59b2021-02-02 16:55:13 +0530424 return sorted(entries_to_fix, key=lambda k: k['timestamp'])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530425
426 def process_sle(self, sle):
Ankush Menat66bf21f2022-01-16 20:45:59 +0530427 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
428
Nabin Haita77b8c92020-12-21 14:45:50 +0530429 # previous sle data for this warehouse
430 self.wh_data = self.data[sle.warehouse]
431
Anand Doshi0dc79f42015-04-06 12:59:34 +0530432 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 +0530433 # validate negative stock for serialized items, fifo valuation
Nabin Hait902e8602013-01-08 18:29:24 +0530434 # or when negative stock is not allowed for moving average
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530435 if not self.validate_negative_stock(sle):
Nabin Haita77b8c92020-12-21 14:45:50 +0530436 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530437 return
Nabin Haitb96c0142014-10-07 11:25:04 +0530438
Nabin Haita77b8c92020-12-21 14:45:50 +0530439 # Get dynamic incoming/outgoing rate
rohitwaghchauree6a1ad82021-09-15 20:42:47 +0530440 if not self.args.get("sle_id"):
441 self.get_dynamic_incoming_outgoing_rate(sle)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530442
Ankush Menat66bf21f2022-01-16 20:45:59 +0530443 if get_serial_nos(sle.serial_no):
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530444 self.get_serialized_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530445 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530446 if sle.voucher_type == "Stock Reconciliation":
Nabin Haita77b8c92020-12-21 14:45:50 +0530447 self.wh_data.qty_after_transaction = sle.qty_after_transaction
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530448
Nabin Haita77b8c92020-12-21 14:45:50 +0530449 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 +0530450 else:
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530451 if sle.voucher_type=="Stock Reconciliation" and not sle.batch_no:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530452 # assert
Nabin Haita77b8c92020-12-21 14:45:50 +0530453 self.wh_data.valuation_rate = sle.valuation_rate
454 self.wh_data.qty_after_transaction = sle.qty_after_transaction
Nabin Haita77b8c92020-12-21 14:45:50 +0530455 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 +0530456 if self.valuation_method != "Moving Average":
457 self.wh_data.stock_queue = [[self.wh_data.qty_after_transaction, self.wh_data.valuation_rate]]
Nabin Haitb96c0142014-10-07 11:25:04 +0530458 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530459 if self.valuation_method == "Moving Average":
460 self.get_moving_average_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530461 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
462 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 +0530463 else:
Ankush Menat4b29fb62021-12-18 18:40:22 +0530464 self.update_fifo_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530465 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Nabin Haitb96c0142014-10-07 11:25:04 +0530466
Rushabh Mehta54047782013-12-26 11:07:46 +0530467 # rounding as per precision
Nabin Haita77b8c92020-12-21 14:45:50 +0530468 self.wh_data.stock_value = flt(self.wh_data.stock_value, self.precision)
469 stock_value_difference = self.wh_data.stock_value - self.wh_data.prev_stock_value
470 self.wh_data.prev_stock_value = self.wh_data.stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530471
Nabin Hait902e8602013-01-08 18:29:24 +0530472 # update current sle
Nabin Haita77b8c92020-12-21 14:45:50 +0530473 sle.qty_after_transaction = self.wh_data.qty_after_transaction
474 sle.valuation_rate = self.wh_data.valuation_rate
475 sle.stock_value = self.wh_data.stock_value
476 sle.stock_queue = json.dumps(self.wh_data.stock_queue)
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530477 sle.stock_value_difference = stock_value_difference
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530478 sle.doctype="Stock Ledger Entry"
479 frappe.get_doc(sle).db_update()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530480
rohitwaghchauree6a1ad82021-09-15 20:42:47 +0530481 if not self.args.get("sle_id"):
482 self.update_outgoing_rate_on_transaction(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530483
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530484 def validate_negative_stock(self, sle):
485 """
486 validate negative stock for entries current datetime onwards
487 will not consider cancelled entries
488 """
Nabin Haita77b8c92020-12-21 14:45:50 +0530489 diff = self.wh_data.qty_after_transaction + flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530490
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530491 if diff < 0 and abs(diff) > 0.0001:
492 # negative stock!
493 exc = sle.copy().update({"diff": diff})
Nabin Haita77b8c92020-12-21 14:45:50 +0530494 self.exceptions.setdefault(sle.warehouse, []).append(exc)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530495 return False
Nabin Hait902e8602013-01-08 18:29:24 +0530496 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530497 return True
498
Nabin Haita77b8c92020-12-21 14:45:50 +0530499 def get_dynamic_incoming_outgoing_rate(self, sle):
500 # Get updated incoming/outgoing rate from transaction
501 if sle.recalculate_rate:
502 rate = self.get_incoming_outgoing_rate_from_transaction(sle)
503
504 if flt(sle.actual_qty) >= 0:
505 sle.incoming_rate = rate
506 else:
507 sle.outgoing_rate = rate
508
509 def get_incoming_outgoing_rate_from_transaction(self, sle):
510 rate = 0
511 # Material Transfer, Repack, Manufacturing
512 if sle.voucher_type == "Stock Entry":
Nabin Hait97bce3a2021-07-12 13:24:43 +0530513 self.recalculate_amounts_in_stock_entry(sle.voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530514 rate = frappe.db.get_value("Stock Entry Detail", sle.voucher_detail_no, "valuation_rate")
515 # Sales and Purchase Return
516 elif sle.voucher_type in ("Purchase Receipt", "Purchase Invoice", "Delivery Note", "Sales Invoice"):
517 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_return"):
Chillar Anand915b3432021-09-02 16:44:59 +0530518 from erpnext.controllers.sales_and_purchase_return import (
519 get_rate_for_return, # don't move this import to top
520 )
rohitwaghchaurece6c3b52021-04-13 20:55:52 +0530521 rate = get_rate_for_return(sle.voucher_type, sle.voucher_no, sle.item_code,
522 voucher_detail_no=sle.voucher_detail_no, sle = sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530523 else:
524 if sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530525 rate_field = "valuation_rate"
Nabin Haita77b8c92020-12-21 14:45:50 +0530526 else:
527 rate_field = "incoming_rate"
528
529 # check in item table
530 item_code, incoming_rate = frappe.db.get_value(sle.voucher_type + " Item",
531 sle.voucher_detail_no, ["item_code", rate_field])
532
533 if item_code == sle.item_code:
534 rate = incoming_rate
535 else:
536 if sle.voucher_type in ("Delivery Note", "Sales Invoice"):
537 ref_doctype = "Packed Item"
538 else:
539 ref_doctype = "Purchase Receipt Item Supplied"
Deepesh Gargb4be2922021-01-28 13:09:56 +0530540
Nabin Haita77b8c92020-12-21 14:45:50 +0530541 rate = frappe.db.get_value(ref_doctype, {"parent_detail_docname": sle.voucher_detail_no,
542 "item_code": sle.item_code}, rate_field)
543
544 return rate
545
546 def update_outgoing_rate_on_transaction(self, sle):
547 """
548 Update outgoing rate in Stock Entry, Delivery Note, Sales Invoice and Sales Return
549 In case of Stock Entry, also calculate FG Item rate and total incoming/outgoing amount
550 """
551 if sle.actual_qty and sle.voucher_detail_no:
552 outgoing_rate = abs(flt(sle.stock_value_difference)) / abs(sle.actual_qty)
553
554 if flt(sle.actual_qty) < 0 and sle.voucher_type == "Stock Entry":
555 self.update_rate_on_stock_entry(sle, outgoing_rate)
556 elif sle.voucher_type in ("Delivery Note", "Sales Invoice"):
557 self.update_rate_on_delivery_and_sales_return(sle, outgoing_rate)
558 elif flt(sle.actual_qty) < 0 and sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
559 self.update_rate_on_purchase_receipt(sle, outgoing_rate)
560
561 def update_rate_on_stock_entry(self, sle, outgoing_rate):
562 frappe.db.set_value("Stock Entry Detail", sle.voucher_detail_no, "basic_rate", outgoing_rate)
563
564 # Update outgoing item's rate, recalculate FG Item's rate and total incoming/outgoing amount
Nabin Hait97bce3a2021-07-12 13:24:43 +0530565 if not sle.dependant_sle_voucher_detail_no:
566 self.recalculate_amounts_in_stock_entry(sle.voucher_no)
567
568 def recalculate_amounts_in_stock_entry(self, voucher_no):
569 stock_entry = frappe.get_doc("Stock Entry", voucher_no, for_update=True)
Nabin Haita77b8c92020-12-21 14:45:50 +0530570 stock_entry.calculate_rate_and_amount(reset_outgoing_rate=False, raise_error_if_no_rate=False)
571 stock_entry.db_update()
572 for d in stock_entry.items:
573 d.db_update()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530574
Nabin Haita77b8c92020-12-21 14:45:50 +0530575 def update_rate_on_delivery_and_sales_return(self, sle, outgoing_rate):
576 # Update item's incoming rate on transaction
577 item_code = frappe.db.get_value(sle.voucher_type + " Item", sle.voucher_detail_no, "item_code")
578 if item_code == sle.item_code:
579 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "incoming_rate", outgoing_rate)
580 else:
581 # packed item
582 frappe.db.set_value("Packed Item",
583 {"parent_detail_docname": sle.voucher_detail_no, "item_code": sle.item_code},
584 "incoming_rate", outgoing_rate)
585
586 def update_rate_on_purchase_receipt(self, sle, outgoing_rate):
587 if frappe.db.exists(sle.voucher_type + " Item", sle.voucher_detail_no):
588 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "base_net_rate", outgoing_rate)
589 else:
590 frappe.db.set_value("Purchase Receipt Item Supplied", sle.voucher_detail_no, "rate", outgoing_rate)
591
592 # Recalculate subcontracted item's rate in case of subcontracted purchase receipt/invoice
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530593 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_subcontracted") == 'Yes':
Rohit Waghchauree5fb2392021-06-18 20:37:42 +0530594 doc = frappe.get_doc(sle.voucher_type, sle.voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530595 doc.update_valuation_rate(reset_outgoing_rate=False)
596 for d in (doc.items + doc.supplied_items):
597 d.db_update()
598
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530599 def get_serialized_values(self, sle):
600 incoming_rate = flt(sle.incoming_rate)
601 actual_qty = flt(sle.actual_qty)
Nabin Hait328c4f92020-01-02 19:00:32 +0530602 serial_nos = cstr(sle.serial_no).split("\n")
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530603
604 if incoming_rate < 0:
605 # wrong incoming rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530606 incoming_rate = self.wh_data.valuation_rate
Rushabh Mehta538607e2016-06-12 11:03:00 +0530607
Nabin Hait2620bf42016-02-29 11:30:27 +0530608 stock_value_change = 0
Ankush Menatb9642a12021-12-21 16:49:41 +0530609 if actual_qty > 0:
Nabin Hait2620bf42016-02-29 11:30:27 +0530610 stock_value_change = actual_qty * incoming_rate
Ankush Menatb9642a12021-12-21 16:49:41 +0530611 else:
Nabin Hait2620bf42016-02-29 11:30:27 +0530612 # In case of delivery/stock issue, get average purchase rate
613 # of serial nos of current entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530614 if not sle.is_cancelled:
615 outgoing_value = self.get_incoming_value_for_serial_nos(sle, serial_nos)
616 stock_value_change = -1 * outgoing_value
617 else:
618 stock_value_change = actual_qty * sle.outgoing_rate
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530619
Nabin Haita77b8c92020-12-21 14:45:50 +0530620 new_stock_qty = self.wh_data.qty_after_transaction + actual_qty
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530621
Nabin Hait2620bf42016-02-29 11:30:27 +0530622 if new_stock_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530623 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + stock_value_change
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530624 if new_stock_value >= 0:
Nabin Hait2620bf42016-02-29 11:30:27 +0530625 # calculate new valuation rate only if stock value is positive
626 # else it remains the same as that of previous entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530627 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530628
Nabin Haita77b8c92020-12-21 14:45:50 +0530629 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530630 allow_zero_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
631 if not allow_zero_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530632 self.wh_data.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530633 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
Ankush Menata0727b22021-11-01 13:17:40 +0530634 currency=erpnext.get_company_currency(sle.company), company=sle.company)
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530635
Nabin Hait328c4f92020-01-02 19:00:32 +0530636 def get_incoming_value_for_serial_nos(self, sle, serial_nos):
637 # get rate from serial nos within same company
638 all_serial_nos = frappe.get_all("Serial No",
639 fields=["purchase_rate", "name", "company"],
640 filters = {'name': ('in', serial_nos)})
641
Ankush Menat98917802021-06-11 18:40:22 +0530642 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 +0530643
644 # Get rate for serial nos which has been transferred to other company
645 invalid_serial_nos = [d.name for d in all_serial_nos if d.company!=sle.company]
646 for serial_no in invalid_serial_nos:
647 incoming_rate = frappe.db.sql("""
648 select incoming_rate
649 from `tabStock Ledger Entry`
650 where
651 company = %s
652 and actual_qty > 0
Ankush Menat82ea9582022-01-16 20:19:04 +0530653 and is_cancelled = 0
Nabin Hait328c4f92020-01-02 19:00:32 +0530654 and (serial_no = %s
655 or serial_no like %s
656 or serial_no like %s
657 or serial_no like %s
658 )
659 order by posting_date desc
660 limit 1
661 """, (sle.company, serial_no, serial_no+'\n%', '%\n'+serial_no, '%\n'+serial_no+'\n%'))
662
663 incoming_values += flt(incoming_rate[0][0]) if incoming_rate else 0
664
665 return incoming_values
666
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530667 def get_moving_average_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530668 actual_qty = flt(sle.actual_qty)
Nabin Haita77b8c92020-12-21 14:45:50 +0530669 new_stock_qty = flt(self.wh_data.qty_after_transaction) + actual_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530670 if new_stock_qty >= 0:
671 if actual_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530672 if flt(self.wh_data.qty_after_transaction) <= 0:
673 self.wh_data.valuation_rate = sle.incoming_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530674 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530675 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530676 (actual_qty * sle.incoming_rate)
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530677
Nabin Haita77b8c92020-12-21 14:45:50 +0530678 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530679
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530680 elif sle.outgoing_rate:
681 if new_stock_qty:
Nabin Haita77b8c92020-12-21 14:45:50 +0530682 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530683 (actual_qty * sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530684
Nabin Haita77b8c92020-12-21 14:45:50 +0530685 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530686 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530687 self.wh_data.valuation_rate = sle.outgoing_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530688 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530689 if flt(self.wh_data.qty_after_transaction) >= 0 and sle.outgoing_rate:
690 self.wh_data.valuation_rate = sle.outgoing_rate
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530691
Nabin Haita77b8c92020-12-21 14:45:50 +0530692 if not self.wh_data.valuation_rate and actual_qty > 0:
693 self.wh_data.valuation_rate = sle.incoming_rate
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530694
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530695 # Get valuation rate from previous SLE or Item master, if item does not have the
Javier Wong9b11d9b2017-04-14 18:24:04 +0800696 # allow zero valuration rate flag set
Nabin Haita77b8c92020-12-21 14:45:50 +0530697 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
Javier Wong9b11d9b2017-04-14 18:24:04 +0800698 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
699 if not allow_zero_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530700 self.wh_data.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530701 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
Ankush Menata0727b22021-11-01 13:17:40 +0530702 currency=erpnext.get_company_currency(sle.company), company=sle.company)
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530703
Ankush Menat4b29fb62021-12-18 18:40:22 +0530704 def update_fifo_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530705 incoming_rate = flt(sle.incoming_rate)
706 actual_qty = flt(sle.actual_qty)
Nabin Haitada485f2015-07-17 15:09:56 +0530707 outgoing_rate = flt(sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530708
Ankush Menat107b4042021-12-19 20:47:08 +0530709 fifo_queue = FIFOValuation(self.wh_data.stock_queue)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530710 if actual_qty > 0:
Ankush Menat4b29fb62021-12-18 18:40:22 +0530711 fifo_queue.add_stock(qty=actual_qty, rate=incoming_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530712 else:
Ankush Menat4b29fb62021-12-18 18:40:22 +0530713 def rate_generator() -> float:
714 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
715 if not allow_zero_valuation_rate:
716 return get_valuation_rate(sle.item_code, sle.warehouse,
717 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
718 currency=erpnext.get_company_currency(sle.company), company=sle.company)
Nabin Haitada485f2015-07-17 15:09:56 +0530719 else:
Ankush Menat4b29fb62021-12-18 18:40:22 +0530720 return 0.0
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530721
Ankush Menata00d8d02021-12-19 18:45:04 +0530722 fifo_queue.remove_stock(qty=abs(actual_qty), outgoing_rate=outgoing_rate, rate_generator=rate_generator)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530723
Ankush Menat4b29fb62021-12-18 18:40:22 +0530724 stock_qty, stock_value = fifo_queue.get_total_stock_and_value()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530725
Ankush Menat4b29fb62021-12-18 18:40:22 +0530726 self.wh_data.stock_queue = fifo_queue.get_state()
727 self.wh_data.stock_value = stock_value
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530728 if stock_qty:
Ankush Menat4b29fb62021-12-18 18:40:22 +0530729 self.wh_data.valuation_rate = stock_value / stock_qty
730
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530731
Nabin Haita77b8c92020-12-21 14:45:50 +0530732 if not self.wh_data.stock_queue:
733 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 +0530734
Ankush Menat4b29fb62021-12-18 18:40:22 +0530735
736
Javier Wong9b11d9b2017-04-14 18:24:04 +0800737 def check_if_allow_zero_valuation_rate(self, voucher_type, voucher_detail_no):
deepeshgarg007f9c0ef32019-07-30 18:49:19 +0530738 ref_item_dt = ""
739
740 if voucher_type == "Stock Entry":
741 ref_item_dt = voucher_type + " Detail"
742 elif voucher_type in ["Purchase Invoice", "Sales Invoice", "Delivery Note", "Purchase Receipt"]:
743 ref_item_dt = voucher_type + " Item"
744
745 if ref_item_dt:
746 return frappe.db.get_value(ref_item_dt, voucher_detail_no, "allow_zero_valuation_rate")
747 else:
748 return 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530749
Nabin Haita77b8c92020-12-21 14:45:50 +0530750 def get_sle_before_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530751 """get previous stock ledger entry before current time-bucket"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530752 sle = get_stock_ledger_entries(args, "<", "desc", "limit 1", for_update=False)
753 sle = sle[0] if sle else frappe._dict()
754 return sle
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530755
Nabin Haita77b8c92020-12-21 14:45:50 +0530756 def get_sle_after_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530757 """get Stock Ledger Entries after a particular datetime, for reposting"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530758 return get_stock_ledger_entries(args, ">", "asc", for_update=True, check_serial_no=False)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530759
760 def raise_exceptions(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530761 msg_list = []
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530762 for warehouse, exceptions in self.exceptions.items():
Nabin Haita77b8c92020-12-21 14:45:50 +0530763 deficiency = min(e["diff"] for e in exceptions)
Rushabh Mehta538607e2016-06-12 11:03:00 +0530764
Nabin Haita77b8c92020-12-21 14:45:50 +0530765 if ((exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]) in
766 frappe.local.flags.currently_saving):
Nabin Hait3edefb12016-07-20 16:13:18 +0530767
Nabin Haita77b8c92020-12-21 14:45:50 +0530768 msg = _("{0} units of {1} needed in {2} 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 else:
772 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 +0530773 abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]),
Nabin Haita77b8c92020-12-21 14:45:50 +0530774 frappe.get_desk_link('Warehouse', warehouse),
775 exceptions[0]["posting_date"], exceptions[0]["posting_time"],
776 frappe.get_desk_link(exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530777
Nabin Haita77b8c92020-12-21 14:45:50 +0530778 if msg:
779 msg_list.append(msg)
780
781 if msg_list:
782 message = "\n\n".join(msg_list)
783 if self.verbose:
784 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
785 else:
786 raise NegativeStockError(message)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530787
Nabin Haita77b8c92020-12-21 14:45:50 +0530788 def update_bin(self):
789 # update bin for each warehouse
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530790 for warehouse, data in self.data.items():
Ankush Menat97060c42021-12-03 11:50:38 +0530791 bin_name = get_or_make_bin(self.item_code, warehouse)
Deepesh Garg6f107da2021-10-12 20:15:55 +0530792
Ankush Menat97060c42021-12-03 11:50:38 +0530793 frappe.db.set_value('Bin', bin_name, {
Nabin Haita77b8c92020-12-21 14:45:50 +0530794 "valuation_rate": data.valuation_rate,
795 "actual_qty": data.qty_after_transaction,
796 "stock_value": data.stock_value
797 })
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530798
marination8418c4b2021-06-22 21:35:25 +0530799
800def get_previous_sle_of_current_voucher(args, exclude_current_voucher=False):
801 """get stock ledger entries filtered by specific posting datetime conditions"""
802
803 args['time_format'] = '%H:%i:%s'
804 if not args.get("posting_date"):
805 args["posting_date"] = "1900-01-01"
806 if not args.get("posting_time"):
807 args["posting_time"] = "00:00"
808
809 voucher_condition = ""
810 if exclude_current_voucher:
811 voucher_no = args.get("voucher_no")
812 voucher_condition = f"and voucher_no != '{voucher_no}'"
813
814 sle = frappe.db.sql("""
815 select *, timestamp(posting_date, posting_time) as "timestamp"
816 from `tabStock Ledger Entry`
817 where item_code = %(item_code)s
818 and warehouse = %(warehouse)s
819 and is_cancelled = 0
820 {voucher_condition}
821 and timestamp(posting_date, time_format(posting_time, %(time_format)s)) < timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
822 order by timestamp(posting_date, posting_time) desc, creation desc
823 limit 1
824 for update""".format(voucher_condition=voucher_condition), args, as_dict=1)
825
826 return sle[0] if sle else frappe._dict()
827
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530828def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530829 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530830 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530831 to get actual qty before transaction, this function
832 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530833
Anand Doshi1b531862013-01-10 19:29:51 +0530834 args = {
835 "item_code": "ABC",
836 "warehouse": "XYZ",
837 "posting_date": "2012-12-12",
838 "posting_time": "12:00",
839 "sle": "name of reference Stock Ledger Entry"
840 }
841 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530842 args["name"] = args.get("sle", None) or ""
843 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530844 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530845
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530846def get_stock_ledger_entries(previous_sle, operator=None,
847 order="desc", limit=None, for_update=False, debug=False, check_serial_no=True):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530848 """get stock ledger entries filtered by specific posting datetime conditions"""
Nabin Haitb9ce1042018-02-01 14:58:50 +0530849 conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
850 if previous_sle.get("warehouse"):
851 conditions += " and warehouse = %(warehouse)s"
852 elif previous_sle.get("warehouse_condition"):
853 conditions += " and " + previous_sle.get("warehouse_condition")
854
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530855 if check_serial_no and previous_sle.get("serial_no"):
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530856 # conditions += " and serial_no like {}".format(frappe.db.escape('%{0}%'.format(previous_sle.get("serial_no"))))
857 serial_no = previous_sle.get("serial_no")
858 conditions += (""" and
859 (
860 serial_no = {0}
861 or serial_no like {1}
862 or serial_no like {2}
863 or serial_no like {3}
864 )
865 """).format(frappe.db.escape(serial_no), frappe.db.escape('{}\n%'.format(serial_no)),
866 frappe.db.escape('%\n{}'.format(serial_no)), frappe.db.escape('%\n{}\n%'.format(serial_no)))
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530867
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530868 if not previous_sle.get("posting_date"):
869 previous_sle["posting_date"] = "1900-01-01"
870 if not previous_sle.get("posting_time"):
871 previous_sle["posting_time"] = "00:00"
872
873 if operator in (">", "<=") and previous_sle.get("name"):
874 conditions += " and name!=%(name)s"
875
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530876 return frappe.db.sql("""
877 select *, timestamp(posting_date, posting_time) as "timestamp"
878 from `tabStock Ledger Entry`
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530879 where item_code = %%(item_code)s
Nabin Haita77b8c92020-12-21 14:45:50 +0530880 and is_cancelled = 0
Nabin Haitb9ce1042018-02-01 14:58:50 +0530881 %(conditions)s
Aditya Hase0c164242019-01-07 22:07:13 +0530882 order by timestamp(posting_date, posting_time) %(order)s, creation %(order)s
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530883 %(limit)s %(for_update)s""" % {
884 "conditions": conditions,
885 "limit": limit or "",
886 "for_update": for_update and "for update" or "",
887 "order": order
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530888 }, previous_sle, as_dict=1, debug=debug)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530889
Nabin Haita77b8c92020-12-21 14:45:50 +0530890def get_sle_by_voucher_detail_no(voucher_detail_no, excluded_sle=None):
891 return frappe.db.get_value('Stock Ledger Entry',
892 {'voucher_detail_no': voucher_detail_no, 'name': ['!=', excluded_sle]},
893 ['item_code', 'warehouse', 'posting_date', 'posting_time', 'timestamp(posting_date, posting_time) as timestamp'],
894 as_dict=1)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530895
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530896def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no,
Nabin Hait7ba092e2018-02-01 10:51:27 +0530897 allow_zero_rate=False, currency=None, company=None, raise_error_if_no_rate=True):
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530898
Ankush Menatf7ffe042021-11-01 13:21:14 +0530899 if not company:
900 company = frappe.get_cached_value("Warehouse", warehouse, "company")
901
902 # Get valuation rate from last sle for the same item and warehouse
Nabin Haitfb6e4342014-10-15 11:34:40 +0530903 last_valuation_rate = frappe.db.sql("""select valuation_rate
Deepesh Garg6f107da2021-10-12 20:15:55 +0530904 from `tabStock Ledger Entry` force index (item_warehouse)
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530905 where
906 item_code = %s
907 AND warehouse = %s
908 AND valuation_rate >= 0
Ankush Menat82ea9582022-01-16 20:19:04 +0530909 AND is_cancelled = 0
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530910 AND NOT (voucher_no = %s AND voucher_type = %s)
911 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 +0530912
913 if not last_valuation_rate:
Nabin Haita0b967f2017-01-18 18:35:58 +0530914 # Get valuation rate from last sle for the item against any warehouse
Nabin Haitfb6e4342014-10-15 11:34:40 +0530915 last_valuation_rate = frappe.db.sql("""select valuation_rate
Deepesh Garg6f107da2021-10-12 20:15:55 +0530916 from `tabStock Ledger Entry` force index (item_code)
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530917 where
918 item_code = %s
919 AND valuation_rate > 0
Ankush Menat82ea9582022-01-16 20:19:04 +0530920 AND is_cancelled = 0
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530921 AND NOT(voucher_no = %s AND voucher_type = %s)
922 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 +0530923
Nabin Haita645f362018-03-01 10:31:24 +0530924 if last_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530925 return flt(last_valuation_rate[0][0])
Nabin Haita645f362018-03-01 10:31:24 +0530926
927 # If negative stock allowed, and item delivered without any incoming entry,
928 # system does not found any SLE, then take valuation rate from Item
929 valuation_rate = frappe.db.get_value("Item", item_code, "valuation_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530930
931 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530932 # try Item Standard rate
933 valuation_rate = frappe.db.get_value("Item", item_code, "standard_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530934
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530935 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530936 # try in price list
937 valuation_rate = frappe.db.get_value('Item Price',
938 dict(item_code=item_code, buying=1, currency=currency),
939 'price_list_rate')
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530940
Nabin Hait7ba092e2018-02-01 10:51:27 +0530941 if not allow_zero_rate and not valuation_rate and raise_error_if_no_rate \
Rohit Waghchauree9ff1912017-06-19 12:54:59 +0530942 and cint(erpnext.is_perpetual_inventory_enabled(company)):
Neil Trini Lasrado193c8912017-03-28 17:39:34 +0530943 frappe.local.message_log = []
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530944 form_link = get_link_to_form("Item", item_code)
Marica97715f22020-05-11 20:45:37 +0530945
946 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 +0530947 message += "<br><br>" + _("Here are the options to proceed:")
Marica97715f22020-05-11 20:45:37 +0530948 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 +0530949 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 +0530950 sub_solutions = "<ul><li>" + _("Create an incoming stock transaction for the Item.") + "</li>"
951 sub_solutions += "<li>" + _("Mention Valuation Rate in the Item master.") + "</li></ul>"
952 msg = message + solutions + sub_solutions + "</li>"
953
954 frappe.throw(msg=msg, title=_("Valuation Rate Missing"))
Nabin Haitfb6e4342014-10-15 11:34:40 +0530955
956 return valuation_rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530957
Ankush Menate7109c12021-08-26 16:40:45 +0530958def update_qty_in_future_sle(args, allow_negative_stock=False):
marination8418c4b2021-06-22 21:35:25 +0530959 """Recalculate Qty after Transaction in future SLEs based on current SLE."""
marination40389772021-07-02 17:13:45 +0530960 datetime_limit_condition = ""
marination8418c4b2021-06-22 21:35:25 +0530961 qty_shift = args.actual_qty
962
963 # find difference/shift in qty caused by stock reconciliation
964 if args.voucher_type == "Stock Reconciliation":
marination40389772021-07-02 17:13:45 +0530965 qty_shift = get_stock_reco_qty_shift(args)
966
967 # find the next nearest stock reco so that we only recalculate SLEs till that point
968 next_stock_reco_detail = get_next_stock_reco(args)
969 if next_stock_reco_detail:
970 detail = next_stock_reco_detail[0]
971 # add condition to update SLEs before this date & time
972 datetime_limit_condition = get_datetime_limit_condition(detail)
marination8418c4b2021-06-22 21:35:25 +0530973
Nabin Hait186a0452021-02-18 14:14:21 +0530974 frappe.db.sql("""
975 update `tabStock Ledger Entry`
marination8418c4b2021-06-22 21:35:25 +0530976 set qty_after_transaction = qty_after_transaction + {qty_shift}
Nabin Hait186a0452021-02-18 14:14:21 +0530977 where
978 item_code = %(item_code)s
979 and warehouse = %(warehouse)s
980 and voucher_no != %(voucher_no)s
981 and is_cancelled = 0
982 and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)
983 or (
984 timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s)
985 and creation > %(creation)s
986 )
987 )
marination40389772021-07-02 17:13:45 +0530988 {datetime_limit_condition}
989 """.format(qty_shift=qty_shift, datetime_limit_condition=datetime_limit_condition), args)
Nabin Hait186a0452021-02-18 14:14:21 +0530990
991 validate_negative_qty_in_future_sle(args, allow_negative_stock)
992
marination40389772021-07-02 17:13:45 +0530993def get_stock_reco_qty_shift(args):
994 stock_reco_qty_shift = 0
995 if args.get("is_cancelled"):
996 if args.get("previous_qty_after_transaction"):
997 # get qty (balance) that was set at submission
998 last_balance = args.get("previous_qty_after_transaction")
999 stock_reco_qty_shift = flt(args.qty_after_transaction) - flt(last_balance)
1000 else:
1001 stock_reco_qty_shift = flt(args.actual_qty)
1002 else:
1003 # reco is being submitted
1004 last_balance = get_previous_sle_of_current_voucher(args,
1005 exclude_current_voucher=True).get("qty_after_transaction")
1006
1007 if last_balance is not None:
1008 stock_reco_qty_shift = flt(args.qty_after_transaction) - flt(last_balance)
1009 else:
1010 stock_reco_qty_shift = args.qty_after_transaction
1011
1012 return stock_reco_qty_shift
1013
1014def get_next_stock_reco(args):
1015 """Returns next nearest stock reconciliaton's details."""
1016
1017 return frappe.db.sql("""
1018 select
1019 name, posting_date, posting_time, creation, voucher_no
1020 from
marination8c441262021-07-02 17:46:05 +05301021 `tabStock Ledger Entry`
marination40389772021-07-02 17:13:45 +05301022 where
1023 item_code = %(item_code)s
1024 and warehouse = %(warehouse)s
1025 and voucher_type = 'Stock Reconciliation'
1026 and voucher_no != %(voucher_no)s
1027 and is_cancelled = 0
1028 and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)
1029 or (
1030 timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s)
1031 and creation > %(creation)s
1032 )
1033 )
1034 limit 1
1035 """, args, as_dict=1)
1036
1037def get_datetime_limit_condition(detail):
marination40389772021-07-02 17:13:45 +05301038 return f"""
1039 and
1040 (timestamp(posting_date, posting_time) < timestamp('{detail.posting_date}', '{detail.posting_time}')
1041 or (
1042 timestamp(posting_date, posting_time) = timestamp('{detail.posting_date}', '{detail.posting_time}')
1043 and creation < '{detail.creation}'
1044 )
1045 )"""
1046
Ankush Menate7109c12021-08-26 16:40:45 +05301047def validate_negative_qty_in_future_sle(args, allow_negative_stock=False):
1048 allow_negative_stock = cint(allow_negative_stock) \
Nabin Haita77b8c92020-12-21 14:45:50 +05301049 or cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
1050
Ankush Menat5eba5752021-12-07 23:03:52 +05301051 if allow_negative_stock:
1052 return
1053 if not (args.actual_qty < 0 or args.voucher_type == "Stock Reconciliation"):
1054 return
Deepesh Gargb4be2922021-01-28 13:09:56 +05301055
Ankush Menat5eba5752021-12-07 23:03:52 +05301056 neg_sle = get_future_sle_with_negative_qty(args)
1057 if neg_sle:
1058 message = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
1059 abs(neg_sle[0]["qty_after_transaction"]),
1060 frappe.get_desk_link('Item', args.item_code),
1061 frappe.get_desk_link('Warehouse', args.warehouse),
1062 neg_sle[0]["posting_date"], neg_sle[0]["posting_time"],
1063 frappe.get_desk_link(neg_sle[0]["voucher_type"], neg_sle[0]["voucher_no"]))
1064
1065 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
1066
1067
1068 if not args.batch_no:
1069 return
1070
1071 neg_batch_sle = get_future_sle_with_negative_batch_qty(args)
1072 if neg_batch_sle:
1073 message = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
1074 abs(neg_batch_sle[0]["cumulative_total"]),
1075 frappe.get_desk_link('Batch', args.batch_no),
1076 frappe.get_desk_link('Warehouse', args.warehouse),
1077 neg_batch_sle[0]["posting_date"], neg_batch_sle[0]["posting_time"],
1078 frappe.get_desk_link(neg_batch_sle[0]["voucher_type"], neg_batch_sle[0]["voucher_no"]))
1079 frappe.throw(message, NegativeStockError, title="Insufficient Stock for Batch")
1080
Nabin Haita77b8c92020-12-21 14:45:50 +05301081
1082def get_future_sle_with_negative_qty(args):
1083 return frappe.db.sql("""
1084 select
1085 qty_after_transaction, posting_date, posting_time,
1086 voucher_type, voucher_no
1087 from `tabStock Ledger Entry`
Deepesh Gargb4be2922021-01-28 13:09:56 +05301088 where
Nabin Haita77b8c92020-12-21 14:45:50 +05301089 item_code = %(item_code)s
1090 and warehouse = %(warehouse)s
1091 and voucher_no != %(voucher_no)s
1092 and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s)
1093 and is_cancelled = 0
Nabin Hait186a0452021-02-18 14:14:21 +05301094 and qty_after_transaction < 0
Nabin Hait243d59b2021-02-02 16:55:13 +05301095 order by timestamp(posting_date, posting_time) asc
Nabin Haita77b8c92020-12-21 14:45:50 +05301096 limit 1
Sagar Vorae50324a2021-03-31 12:44:03 +05301097 """, args, as_dict=1)
Ankush Menat6a014d12021-04-12 20:21:27 +05301098
Ankush Menat5eba5752021-12-07 23:03:52 +05301099
1100def get_future_sle_with_negative_batch_qty(args):
1101 return frappe.db.sql("""
1102 with batch_ledger as (
1103 select
1104 posting_date, posting_time, voucher_type, voucher_no,
1105 sum(actual_qty) over (order by posting_date, posting_time, creation) as cumulative_total
1106 from `tabStock Ledger Entry`
1107 where
1108 item_code = %(item_code)s
1109 and warehouse = %(warehouse)s
1110 and batch_no=%(batch_no)s
1111 and is_cancelled = 0
1112 order by posting_date, posting_time, creation
1113 )
1114 select * from batch_ledger
1115 where
1116 cumulative_total < 0.0
1117 and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s)
1118 limit 1
1119 """, args, as_dict=1)