blob: 677266ee0cd7344b34cf90b5d30d49db5e56665f [file] [log] [blame]
Anand Doshi885e0742015-03-03 14:55:30 +05301# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
Rushabh Mehtae67d1fb2013-08-05 14:59:54 +05302# License: GNU General Public License v3. See license.txt
Nabin Hait902e8602013-01-08 18:29:24 +05303
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +05304import copy
Nabin Hait26d46552013-01-09 15:23:05 +05305import json
Ankush Menateb8b4242022-02-12 13:08:28 +05306from typing import Optional
Chillar Anand915b3432021-09-02 16:44:59 +05307
8import frappe
9from frappe import _
10from frappe.model.meta import get_field_precision
Ankush Menat102fff22022-02-19 15:51:04 +053011from frappe.query_builder.functions import Sum
Ankush Menatcef84c22021-12-03 12:18:59 +053012from frappe.utils import cint, cstr, flt, get_link_to_form, getdate, now, nowdate
Ankush Menat102fff22022-02-19 15:51:04 +053013from pypika import CustomFunction
Achilles Rasquinha361366e2018-02-14 17:08:59 +053014
Chillar Anand915b3432021-09-02 16:44:59 +053015import erpnext
Ankush Menatcef84c22021-12-03 12:18:59 +053016from erpnext.stock.doctype.bin.bin import update_qty as update_bin_qty
Chillar Anand915b3432021-09-02 16:44:59 +053017from erpnext.stock.utils import (
Chillar Anand915b3432021-09-02 16:44:59 +053018 get_incoming_outgoing_rate_for_cancel,
Deepesh Garg6f107da2021-10-12 20:15:55 +053019 get_or_make_bin,
Chillar Anand915b3432021-09-02 16:44:59 +053020 get_valuation_method,
21)
Ankush Menatb534fee2022-02-19 20:58:36 +053022from erpnext.stock.valuation import FIFOValuation, LIFOValuation, round_off_if_near_zero
Chillar Anand915b3432021-09-02 16:44:59 +053023
Nabin Hait97bce3a2021-07-12 13:24:43 +053024
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053025class NegativeStockError(frappe.ValidationError): pass
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +053026class SerialNoExistsInFutureTransaction(frappe.ValidationError):
27 pass
Nabin Hait902e8602013-01-08 18:29:24 +053028
Anand Doshi5b004ff2013-09-25 19:55:41 +053029
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053030def make_sl_entries(sl_entries, allow_negative_stock=False, via_landed_cost_voucher=False):
Rohit Waghchaure4d81d452021-06-15 10:21:44 +053031 from erpnext.controllers.stock_controller import future_sle_exists
Nabin Haitca775742013-09-26 16:16:44 +053032 if sl_entries:
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053033 cancel = sl_entries[0].get("is_cancelled")
Nabin Haitca775742013-09-26 16:16:44 +053034 if cancel:
Nabin Hait186a0452021-02-18 14:14:21 +053035 validate_cancellation(sl_entries)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053036 set_as_cancel(sl_entries[0].get('voucher_type'), sl_entries[0].get('voucher_no'))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053037
Rohit Waghchaure4d81d452021-06-15 10:21:44 +053038 args = get_args_for_future_sle(sl_entries[0])
39 future_sle_exists(args, sl_entries)
40
Nabin Haitca775742013-09-26 16:16:44 +053041 for sle in sl_entries:
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +053042 if sle.serial_no:
43 validate_serial_no(sle)
44
Nabin Haita77b8c92020-12-21 14:45:50 +053045 if cancel:
46 sle['actual_qty'] = -flt(sle.get('actual_qty'))
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053047
Nabin Haita77b8c92020-12-21 14:45:50 +053048 if sle['actual_qty'] < 0 and not sle.get('outgoing_rate'):
49 sle['outgoing_rate'] = get_incoming_outgoing_rate_for_cancel(sle.item_code,
50 sle.voucher_type, sle.voucher_no, sle.voucher_detail_no)
51 sle['incoming_rate'] = 0.0
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053052
Nabin Haita77b8c92020-12-21 14:45:50 +053053 if sle['actual_qty'] > 0 and not sle.get('incoming_rate'):
54 sle['incoming_rate'] = get_incoming_outgoing_rate_for_cancel(sle.item_code,
55 sle.voucher_type, sle.voucher_no, sle.voucher_detail_no)
56 sle['outgoing_rate'] = 0.0
Nabin Haitdc82d4f2014-04-07 12:02:57 +053057
Nabin Hait5288bde2014-11-03 15:08:21 +053058 if sle.get("actual_qty") or sle.get("voucher_type")=="Stock Reconciliation":
Nabin Haita77b8c92020-12-21 14:45:50 +053059 sle_doc = make_entry(sle, allow_negative_stock, via_landed_cost_voucher)
Deepesh Gargb4be2922021-01-28 13:09:56 +053060
Nabin Haita77b8c92020-12-21 14:45:50 +053061 args = sle_doc.as_dict()
marination40389772021-07-02 17:13:45 +053062
63 if sle.get("voucher_type") == "Stock Reconciliation":
64 # preserve previous_qty_after_transaction for qty reposting
65 args.previous_qty_after_transaction = sle.get("previous_qty_after_transaction")
66
Ankush Menatcef84c22021-12-03 12:18:59 +053067 is_stock_item = frappe.get_cached_value('Item', args.get("item_code"), 'is_stock_item')
68 if is_stock_item:
69 bin_name = get_or_make_bin(args.get("item_code"), args.get("warehouse"))
Ankush Menatcef84c22021-12-03 12:18:59 +053070 repost_current_voucher(args, allow_negative_stock, via_landed_cost_voucher)
Ankush Menatff9a6e82021-12-20 15:07:41 +053071 update_bin_qty(bin_name, args)
Ankush Menatcef84c22021-12-03 12:18:59 +053072 else:
73 frappe.msgprint(_("Item {0} ignored since it is not a stock item").format(args.get("item_code")))
74
75def repost_current_voucher(args, allow_negative_stock=False, via_landed_cost_voucher=False):
76 if args.get("actual_qty") or args.get("voucher_type") == "Stock Reconciliation":
77 if not args.get("posting_date"):
78 args["posting_date"] = nowdate()
79
80 if args.get("is_cancelled") and via_landed_cost_voucher:
81 return
82
83 # Reposts only current voucher SL Entries
84 # Updates valuation rate, stock value, stock queue for current transaction
85 update_entries_after({
86 "item_code": args.get('item_code'),
87 "warehouse": args.get('warehouse'),
88 "posting_date": args.get("posting_date"),
89 "posting_time": args.get("posting_time"),
90 "voucher_type": args.get("voucher_type"),
91 "voucher_no": args.get("voucher_no"),
92 "sle_id": args.get('name'),
93 "creation": args.get('creation')
94 }, allow_negative_stock=allow_negative_stock, via_landed_cost_voucher=via_landed_cost_voucher)
95
96 # update qty in future sle and Validate negative qty
97 update_qty_in_future_sle(args, allow_negative_stock)
98
Nabin Haitadeb9762014-10-06 11:53:52 +053099
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530100def get_args_for_future_sle(row):
101 return frappe._dict({
102 'voucher_type': row.get('voucher_type'),
103 'voucher_no': row.get('voucher_no'),
104 'posting_date': row.get('posting_date'),
105 'posting_time': row.get('posting_time')
106 })
107
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530108def validate_serial_no(sle):
109 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
Ankush Menat66bf21f2022-01-16 20:45:59 +0530110
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530111 for sn in get_serial_nos(sle.serial_no):
112 args = copy.deepcopy(sle)
113 args.serial_no = sn
114 args.warehouse = ''
115
116 vouchers = []
117 for row in get_stock_ledger_entries(args, '>'):
118 voucher_type = frappe.bold(row.voucher_type)
119 voucher_no = frappe.bold(get_link_to_form(row.voucher_type, row.voucher_no))
120 vouchers.append(f'{voucher_type} {voucher_no}')
121
122 if vouchers:
123 serial_no = frappe.bold(sn)
124 msg = (f'''The serial no {serial_no} has been used in the future transactions so you need to cancel them first.
125 The list of the transactions are as below.''' + '<br><br><ul><li>')
126
127 msg += '</li><li>'.join(vouchers)
128 msg += '</li></ul>'
129
130 title = 'Cannot Submit' if not sle.get('is_cancelled') else 'Cannot Cancel'
131 frappe.throw(_(msg), title=_(title), exc=SerialNoExistsInFutureTransaction)
132
Nabin Hait186a0452021-02-18 14:14:21 +0530133def validate_cancellation(args):
134 if args[0].get("is_cancelled"):
135 repost_entry = frappe.db.get_value("Repost Item Valuation", {
136 'voucher_type': args[0].voucher_type,
137 'voucher_no': args[0].voucher_no,
138 'docstatus': 1
139 }, ['name', 'status'], as_dict=1)
140
141 if repost_entry:
142 if repost_entry.status == 'In Progress':
143 frappe.throw(_("Cannot cancel the transaction. Reposting of item valuation on submission is not completed yet."))
144 if repost_entry.status == 'Queued':
Nabin Haitd46b2362021-02-23 16:38:52 +0530145 doc = frappe.get_doc("Repost Item Valuation", repost_entry.name)
Ankush Menataa024fc2021-11-18 12:51:26 +0530146 doc.flags.ignore_permissions = True
Nabin Haitd46b2362021-02-23 16:38:52 +0530147 doc.cancel()
148 doc.delete()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530149
Nabin Hait9653f602013-08-20 15:37:33 +0530150def set_as_cancel(voucher_type, voucher_no):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530151 frappe.db.sql("""update `tabStock Ledger Entry` set is_cancelled=1,
Nabin Hait9653f602013-08-20 15:37:33 +0530152 modified=%s, modified_by=%s
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530153 where voucher_type=%s and voucher_no=%s and is_cancelled = 0""",
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530154 (now(), frappe.session.user, voucher_type, voucher_no))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530155
Nabin Hait54c865e2015-03-27 15:38:31 +0530156def make_entry(args, allow_negative_stock=False, via_landed_cost_voucher=False):
Saqib Ansaric7fc6092021-10-12 13:30:40 +0530157 args["doctype"] = "Stock Ledger Entry"
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530158 sle = frappe.get_doc(args)
Anand Doshi6dfd4302015-02-10 14:41:27 +0530159 sle.flags.ignore_permissions = 1
Nabin Hait4ccd8d32015-01-23 12:18:01 +0530160 sle.allow_negative_stock=allow_negative_stock
Nabin Hait54c865e2015-03-27 15:38:31 +0530161 sle.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Haitaeba24e2013-08-23 15:17:36 +0530162 sle.submit()
Nabin Haita77b8c92020-12-21 14:45:50 +0530163 return sle
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530164
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530165def repost_future_sle(args=None, voucher_type=None, voucher_no=None, allow_negative_stock=None, via_landed_cost_voucher=False, doc=None):
Nabin Haita77b8c92020-12-21 14:45:50 +0530166 if not args and voucher_type and voucher_no:
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530167 args = get_items_to_be_repost(voucher_type, voucher_no, doc)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530168
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530169 distinct_item_warehouses = get_distinct_item_warehouse(args, doc)
Nabin Haita77b8c92020-12-21 14:45:50 +0530170
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530171 i = get_current_index(doc) or 0
Nabin Haita77b8c92020-12-21 14:45:50 +0530172 while i < len(args):
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530173 validate_item_warehouse(args[i])
174
Nabin Haita77b8c92020-12-21 14:45:50 +0530175 obj = update_entries_after({
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530176 'item_code': args[i].get('item_code'),
177 'warehouse': args[i].get('warehouse'),
178 'posting_date': args[i].get('posting_date'),
179 'posting_time': args[i].get('posting_time'),
180 'creation': args[i].get('creation'),
181 'distinct_item_warehouses': distinct_item_warehouses
Nabin Haita77b8c92020-12-21 14:45:50 +0530182 }, allow_negative_stock=allow_negative_stock, via_landed_cost_voucher=via_landed_cost_voucher)
183
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530184 distinct_item_warehouses[(args[i].get('item_code'), args[i].get('warehouse'))].reposting_status = True
Deepesh Gargb4be2922021-01-28 13:09:56 +0530185
Nabin Hait97bce3a2021-07-12 13:24:43 +0530186 if obj.new_items_found:
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530187 for item_wh, data in distinct_item_warehouses.items():
Nabin Hait97bce3a2021-07-12 13:24:43 +0530188 if ('args_idx' not in data and not data.reposting_status) or (data.sle_changed and data.reposting_status):
189 data.args_idx = len(args)
190 args.append(data.sle)
191 elif data.sle_changed and not data.reposting_status:
192 args[data.args_idx] = data.sle
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530193
Nabin Hait97bce3a2021-07-12 13:24:43 +0530194 data.sle_changed = False
Nabin Haita77b8c92020-12-21 14:45:50 +0530195 i += 1
196
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530197 if doc and i % 2 == 0:
198 update_args_in_repost_item_valuation(doc, i, args, distinct_item_warehouses)
199
200 if doc and args:
201 update_args_in_repost_item_valuation(doc, i, args, distinct_item_warehouses)
202
203def validate_item_warehouse(args):
204 for field in ['item_code', 'warehouse', 'posting_date', 'posting_time']:
205 if not args.get(field):
206 validation_msg = f'The field {frappe.unscrub(args.get(field))} is required for the reposting'
207 frappe.throw(_(validation_msg))
208
209def update_args_in_repost_item_valuation(doc, index, args, distinct_item_warehouses):
210 frappe.db.set_value(doc.doctype, doc.name, {
211 'items_to_be_repost': json.dumps(args, default=str),
212 'distinct_item_and_warehouse': json.dumps({str(k): v for k,v in distinct_item_warehouses.items()}, default=str),
213 'current_index': index
214 })
215
216 frappe.db.commit()
217
218 frappe.publish_realtime('item_reposting_progress', {
219 'name': doc.name,
220 'items_to_be_repost': json.dumps(args, default=str),
221 'current_index': index
222 })
223
224def get_items_to_be_repost(voucher_type, voucher_no, doc=None):
225 if doc and doc.items_to_be_repost:
226 return json.loads(doc.items_to_be_repost) or []
227
Nabin Haita77b8c92020-12-21 14:45:50 +0530228 return frappe.db.get_all("Stock Ledger Entry",
229 filters={"voucher_type": voucher_type, "voucher_no": voucher_no},
Nabin Hait186a0452021-02-18 14:14:21 +0530230 fields=["item_code", "warehouse", "posting_date", "posting_time", "creation"],
Nabin Haita77b8c92020-12-21 14:45:50 +0530231 order_by="creation asc",
232 group_by="item_code, warehouse"
233 )
Nabin Hait74c281c2013-08-19 16:17:18 +0530234
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530235def get_distinct_item_warehouse(args=None, doc=None):
236 distinct_item_warehouses = {}
237 if doc and doc.distinct_item_and_warehouse:
238 distinct_item_warehouses = json.loads(doc.distinct_item_and_warehouse)
239 distinct_item_warehouses = {frappe.safe_eval(k): frappe._dict(v) for k, v in distinct_item_warehouses.items()}
240 else:
241 for i, d in enumerate(args):
242 distinct_item_warehouses.setdefault((d.item_code, d.warehouse), frappe._dict({
243 "reposting_status": False,
244 "sle": d,
245 "args_idx": i
246 }))
247
248 return distinct_item_warehouses
249
250def get_current_index(doc=None):
251 if doc and doc.current_index:
252 return doc.current_index
253
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530254class update_entries_after(object):
Nabin Hait902e8602013-01-08 18:29:24 +0530255 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530256 update valution rate and qty after transaction
Nabin Hait902e8602013-01-08 18:29:24 +0530257 from the current time-bucket onwards
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530258
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530259 :param args: args as dict
260
261 args = {
262 "item_code": "ABC",
263 "warehouse": "XYZ",
264 "posting_date": "2012-12-12",
265 "posting_time": "12:00"
266 }
Nabin Hait902e8602013-01-08 18:29:24 +0530267 """
Anand Doshi0dc79f42015-04-06 12:59:34 +0530268 def __init__(self, args, allow_zero_rate=False, allow_negative_stock=None, via_landed_cost_voucher=False, verbose=1):
Nabin Haita77b8c92020-12-21 14:45:50 +0530269 self.exceptions = {}
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530270 self.verbose = verbose
271 self.allow_zero_rate = allow_zero_rate
Anand Doshi0dc79f42015-04-06 12:59:34 +0530272 self.via_landed_cost_voucher = via_landed_cost_voucher
Ankush Menateb8b4242022-02-12 13:08:28 +0530273 self.item_code = args.get("item_code")
274 self.allow_negative_stock = allow_negative_stock or is_negative_stock_allowed(item_code=self.item_code)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530275
Nabin Haita77b8c92020-12-21 14:45:50 +0530276 self.args = frappe._dict(args)
Nabin Haita77b8c92020-12-21 14:45:50 +0530277 if self.args.sle_id:
278 self.args['name'] = self.args.sle_id
Nabin Haitd46b2362021-02-23 16:38:52 +0530279
Nabin Haita77b8c92020-12-21 14:45:50 +0530280 self.company = frappe.get_cached_value("Warehouse", self.args.warehouse, "company")
281 self.get_precision()
282 self.valuation_method = get_valuation_method(self.item_code)
Nabin Hait97bce3a2021-07-12 13:24:43 +0530283
284 self.new_items_found = False
285 self.distinct_item_warehouses = args.get("distinct_item_warehouses", frappe._dict())
Nabin Haita77b8c92020-12-21 14:45:50 +0530286
287 self.data = frappe._dict()
288 self.initialize_previous_data(self.args)
Nabin Haita77b8c92020-12-21 14:45:50 +0530289 self.build()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530290
Nabin Haita77b8c92020-12-21 14:45:50 +0530291 def get_precision(self):
292 company_base_currency = frappe.get_cached_value('Company', self.company, "default_currency")
293 self.precision = get_field_precision(frappe.get_meta("Stock Ledger Entry").get_field("stock_value"),
294 currency=company_base_currency)
295
296 def initialize_previous_data(self, args):
297 """
298 Get previous sl entries for current item for each related warehouse
299 and assigns into self.data dict
300
301 :Data Structure:
302
303 self.data = {
304 warehouse1: {
305 'previus_sle': {},
306 'qty_after_transaction': 10,
307 'valuation_rate': 100,
308 'stock_value': 1000,
309 'prev_stock_value': 1000,
310 'stock_queue': '[[10, 100]]',
311 'stock_value_difference': 1000
312 }
313 }
314
315 """
Ankush Menatc1d986a2021-08-31 19:43:42 +0530316 self.data.setdefault(args.warehouse, frappe._dict())
317 warehouse_dict = self.data[args.warehouse]
marination8418c4b2021-06-22 21:35:25 +0530318 previous_sle = get_previous_sle_of_current_voucher(args)
Ankush Menatc1d986a2021-08-31 19:43:42 +0530319 warehouse_dict.previous_sle = previous_sle
Nabin Haitbb777562013-08-29 18:19:37 +0530320
Ankush Menatc1d986a2021-08-31 19:43:42 +0530321 for key in ("qty_after_transaction", "valuation_rate", "stock_value"):
322 setattr(warehouse_dict, key, flt(previous_sle.get(key)))
323
324 warehouse_dict.update({
Nabin Haita77b8c92020-12-21 14:45:50 +0530325 "prev_stock_value": previous_sle.stock_value or 0.0,
326 "stock_queue": json.loads(previous_sle.stock_queue or "[]"),
327 "stock_value_difference": 0.0
328 })
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530329
Nabin Haita77b8c92020-12-21 14:45:50 +0530330 def build(self):
Sagar Vorae50324a2021-03-31 12:44:03 +0530331 from erpnext.controllers.stock_controller import future_sle_exists
Nabin Hait186a0452021-02-18 14:14:21 +0530332
Nabin Haita77b8c92020-12-21 14:45:50 +0530333 if self.args.get("sle_id"):
Nabin Hait186a0452021-02-18 14:14:21 +0530334 self.process_sle_against_current_timestamp()
Sagar Vorae50324a2021-03-31 12:44:03 +0530335 if not future_sle_exists(self.args):
Nabin Hait186a0452021-02-18 14:14:21 +0530336 self.update_bin()
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530337 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530338 entries_to_fix = self.get_future_entries_to_fix()
339
340 i = 0
341 while i < len(entries_to_fix):
342 sle = entries_to_fix[i]
343 i += 1
344
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530345 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530346
Nabin Haita77b8c92020-12-21 14:45:50 +0530347 if sle.dependant_sle_voucher_detail_no:
Nabin Hait243d59b2021-02-02 16:55:13 +0530348 entries_to_fix = self.get_dependent_entries_to_fix(entries_to_fix, sle)
Nabin Haitd46b2362021-02-23 16:38:52 +0530349
Nabin Hait186a0452021-02-18 14:14:21 +0530350 self.update_bin()
Nabin Haita77b8c92020-12-21 14:45:50 +0530351
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530352 if self.exceptions:
353 self.raise_exceptions()
354
Nabin Hait186a0452021-02-18 14:14:21 +0530355 def process_sle_against_current_timestamp(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530356 sl_entries = self.get_sle_against_current_voucher()
357 for sle in sl_entries:
358 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530359
Nabin Haita77b8c92020-12-21 14:45:50 +0530360 def get_sle_against_current_voucher(self):
Nabin Haitf2be0802021-02-15 19:27:49 +0530361 self.args['time_format'] = '%H:%i:%s'
362
Nabin Haita77b8c92020-12-21 14:45:50 +0530363 return frappe.db.sql("""
364 select
365 *, timestamp(posting_date, posting_time) as "timestamp"
366 from
367 `tabStock Ledger Entry`
368 where
369 item_code = %(item_code)s
370 and warehouse = %(warehouse)s
rohitwaghchaurefe4540d2021-08-26 12:52:36 +0530371 and is_cancelled = 0
Nabin Hait186a0452021-02-18 14:14:21 +0530372 and timestamp(posting_date, time_format(posting_time, %(time_format)s)) = timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
373
Nabin Haita77b8c92020-12-21 14:45:50 +0530374 order by
375 creation ASC
376 for update
377 """, self.args, as_dict=1)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530378
Nabin Haita77b8c92020-12-21 14:45:50 +0530379 def get_future_entries_to_fix(self):
380 # includes current entry!
381 args = self.data[self.args.warehouse].previous_sle \
382 or frappe._dict({"item_code": self.item_code, "warehouse": self.args.warehouse})
Deepesh Gargb4be2922021-01-28 13:09:56 +0530383
Nabin Haita77b8c92020-12-21 14:45:50 +0530384 return list(self.get_sle_after_datetime(args))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530385
Nabin Haita77b8c92020-12-21 14:45:50 +0530386 def get_dependent_entries_to_fix(self, entries_to_fix, sle):
387 dependant_sle = get_sle_by_voucher_detail_no(sle.dependant_sle_voucher_detail_no,
388 excluded_sle=sle.name)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530389
Nabin Haita77b8c92020-12-21 14:45:50 +0530390 if not dependant_sle:
Nabin Hait243d59b2021-02-02 16:55:13 +0530391 return entries_to_fix
Nabin Haita77b8c92020-12-21 14:45:50 +0530392 elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse == self.args.warehouse:
Nabin Hait243d59b2021-02-02 16:55:13 +0530393 return entries_to_fix
394 elif dependant_sle.item_code != self.item_code:
Nabin Hait97bce3a2021-07-12 13:24:43 +0530395 self.update_distinct_item_warehouses(dependant_sle)
Nabin Hait243d59b2021-02-02 16:55:13 +0530396 return entries_to_fix
397 elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse in self.data:
398 return entries_to_fix
Nabin Hait97bce3a2021-07-12 13:24:43 +0530399 else:
400 return self.append_future_sle_for_dependant(dependant_sle, entries_to_fix)
401
402 def update_distinct_item_warehouses(self, dependant_sle):
403 key = (dependant_sle.item_code, dependant_sle.warehouse)
404 val = frappe._dict({
405 "sle": dependant_sle
406 })
407 if key not in self.distinct_item_warehouses:
408 self.distinct_item_warehouses[key] = val
409 self.new_items_found = True
410 else:
411 existing_sle_posting_date = self.distinct_item_warehouses[key].get("sle", {}).get("posting_date")
412 if getdate(dependant_sle.posting_date) < getdate(existing_sle_posting_date):
413 val.sle_changed = True
414 self.distinct_item_warehouses[key] = val
415 self.new_items_found = True
416
417 def append_future_sle_for_dependant(self, dependant_sle, entries_to_fix):
Nabin Haita77b8c92020-12-21 14:45:50 +0530418 self.initialize_previous_data(dependant_sle)
419
420 args = self.data[dependant_sle.warehouse].previous_sle \
421 or frappe._dict({"item_code": self.item_code, "warehouse": dependant_sle.warehouse})
422 future_sle_for_dependant = list(self.get_sle_after_datetime(args))
423
424 entries_to_fix.extend(future_sle_for_dependant)
Nabin Hait243d59b2021-02-02 16:55:13 +0530425 return sorted(entries_to_fix, key=lambda k: k['timestamp'])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530426
427 def process_sle(self, sle):
Ankush Menat66bf21f2022-01-16 20:45:59 +0530428 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
429
Nabin Haita77b8c92020-12-21 14:45:50 +0530430 # previous sle data for this warehouse
431 self.wh_data = self.data[sle.warehouse]
432
Anand Doshi0dc79f42015-04-06 12:59:34 +0530433 if (sle.serial_no and not self.via_landed_cost_voucher) or not cint(self.allow_negative_stock):
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530434 # validate negative stock for serialized items, fifo valuation
Nabin Hait902e8602013-01-08 18:29:24 +0530435 # or when negative stock is not allowed for moving average
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530436 if not self.validate_negative_stock(sle):
Nabin Haita77b8c92020-12-21 14:45:50 +0530437 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530438 return
Nabin Haitb96c0142014-10-07 11:25:04 +0530439
Nabin Haita77b8c92020-12-21 14:45:50 +0530440 # Get dynamic incoming/outgoing rate
rohitwaghchauree6a1ad82021-09-15 20:42:47 +0530441 if not self.args.get("sle_id"):
442 self.get_dynamic_incoming_outgoing_rate(sle)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530443
Ankush Menat66bf21f2022-01-16 20:45:59 +0530444 if get_serial_nos(sle.serial_no):
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530445 self.get_serialized_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530446 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530447 if sle.voucher_type == "Stock Reconciliation":
Nabin Haita77b8c92020-12-21 14:45:50 +0530448 self.wh_data.qty_after_transaction = sle.qty_after_transaction
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530449
Nabin Haita77b8c92020-12-21 14:45:50 +0530450 self.wh_data.stock_value = flt(self.wh_data.qty_after_transaction) * flt(self.wh_data.valuation_rate)
Ankush Menatce0514c2022-02-15 11:41:41 +0530451 elif sle.batch_no and frappe.db.get_value("Batch", sle.batch_no, "use_batchwise_valuation", cache=True):
452 self.update_batched_values(sle)
Nabin Haitb96c0142014-10-07 11:25:04 +0530453 else:
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530454 if sle.voucher_type=="Stock Reconciliation" and not sle.batch_no:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530455 # assert
Nabin Haita77b8c92020-12-21 14:45:50 +0530456 self.wh_data.valuation_rate = sle.valuation_rate
457 self.wh_data.qty_after_transaction = sle.qty_after_transaction
Nabin Haita77b8c92020-12-21 14:45:50 +0530458 self.wh_data.stock_value = flt(self.wh_data.qty_after_transaction) * flt(self.wh_data.valuation_rate)
Ankush Menatb0cf6192022-01-16 13:02:23 +0530459 if self.valuation_method != "Moving Average":
460 self.wh_data.stock_queue = [[self.wh_data.qty_after_transaction, self.wh_data.valuation_rate]]
Nabin Haitb96c0142014-10-07 11:25:04 +0530461 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530462 if self.valuation_method == "Moving Average":
463 self.get_moving_average_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530464 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
465 self.wh_data.stock_value = flt(self.wh_data.qty_after_transaction) * flt(self.wh_data.valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530466 else:
Ankush Menatf089d392022-02-02 12:51:21 +0530467 self.update_queue_values(sle)
Nabin Haitb96c0142014-10-07 11:25:04 +0530468
Rushabh Mehta54047782013-12-26 11:07:46 +0530469 # rounding as per precision
Nabin Haita77b8c92020-12-21 14:45:50 +0530470 self.wh_data.stock_value = flt(self.wh_data.stock_value, self.precision)
471 stock_value_difference = self.wh_data.stock_value - self.wh_data.prev_stock_value
472 self.wh_data.prev_stock_value = self.wh_data.stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530473
Nabin Hait902e8602013-01-08 18:29:24 +0530474 # update current sle
Nabin Haita77b8c92020-12-21 14:45:50 +0530475 sle.qty_after_transaction = self.wh_data.qty_after_transaction
476 sle.valuation_rate = self.wh_data.valuation_rate
477 sle.stock_value = self.wh_data.stock_value
478 sle.stock_queue = json.dumps(self.wh_data.stock_queue)
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530479 sle.stock_value_difference = stock_value_difference
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530480 sle.doctype="Stock Ledger Entry"
481 frappe.get_doc(sle).db_update()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530482
rohitwaghchauree6a1ad82021-09-15 20:42:47 +0530483 if not self.args.get("sle_id"):
484 self.update_outgoing_rate_on_transaction(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530485
Ankush Menatce0514c2022-02-15 11:41:41 +0530486
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530487 def validate_negative_stock(self, sle):
488 """
489 validate negative stock for entries current datetime onwards
490 will not consider cancelled entries
491 """
Nabin Haita77b8c92020-12-21 14:45:50 +0530492 diff = self.wh_data.qty_after_transaction + flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530493
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530494 if diff < 0 and abs(diff) > 0.0001:
495 # negative stock!
496 exc = sle.copy().update({"diff": diff})
Nabin Haita77b8c92020-12-21 14:45:50 +0530497 self.exceptions.setdefault(sle.warehouse, []).append(exc)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530498 return False
Nabin Hait902e8602013-01-08 18:29:24 +0530499 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530500 return True
501
Nabin Haita77b8c92020-12-21 14:45:50 +0530502 def get_dynamic_incoming_outgoing_rate(self, sle):
503 # Get updated incoming/outgoing rate from transaction
504 if sle.recalculate_rate:
505 rate = self.get_incoming_outgoing_rate_from_transaction(sle)
506
507 if flt(sle.actual_qty) >= 0:
508 sle.incoming_rate = rate
509 else:
510 sle.outgoing_rate = rate
511
512 def get_incoming_outgoing_rate_from_transaction(self, sle):
513 rate = 0
514 # Material Transfer, Repack, Manufacturing
515 if sle.voucher_type == "Stock Entry":
Nabin Hait97bce3a2021-07-12 13:24:43 +0530516 self.recalculate_amounts_in_stock_entry(sle.voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530517 rate = frappe.db.get_value("Stock Entry Detail", sle.voucher_detail_no, "valuation_rate")
518 # Sales and Purchase Return
519 elif sle.voucher_type in ("Purchase Receipt", "Purchase Invoice", "Delivery Note", "Sales Invoice"):
520 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_return"):
Chillar Anand915b3432021-09-02 16:44:59 +0530521 from erpnext.controllers.sales_and_purchase_return import (
522 get_rate_for_return, # don't move this import to top
523 )
rohitwaghchaurece6c3b52021-04-13 20:55:52 +0530524 rate = get_rate_for_return(sle.voucher_type, sle.voucher_no, sle.item_code,
525 voucher_detail_no=sle.voucher_detail_no, sle = sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530526 else:
527 if sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530528 rate_field = "valuation_rate"
Nabin Haita77b8c92020-12-21 14:45:50 +0530529 else:
530 rate_field = "incoming_rate"
531
532 # check in item table
533 item_code, incoming_rate = frappe.db.get_value(sle.voucher_type + " Item",
534 sle.voucher_detail_no, ["item_code", rate_field])
535
536 if item_code == sle.item_code:
537 rate = incoming_rate
538 else:
539 if sle.voucher_type in ("Delivery Note", "Sales Invoice"):
540 ref_doctype = "Packed Item"
541 else:
542 ref_doctype = "Purchase Receipt Item Supplied"
Deepesh Gargb4be2922021-01-28 13:09:56 +0530543
Nabin Haita77b8c92020-12-21 14:45:50 +0530544 rate = frappe.db.get_value(ref_doctype, {"parent_detail_docname": sle.voucher_detail_no,
545 "item_code": sle.item_code}, rate_field)
546
547 return rate
548
549 def update_outgoing_rate_on_transaction(self, sle):
550 """
551 Update outgoing rate in Stock Entry, Delivery Note, Sales Invoice and Sales Return
552 In case of Stock Entry, also calculate FG Item rate and total incoming/outgoing amount
553 """
554 if sle.actual_qty and sle.voucher_detail_no:
555 outgoing_rate = abs(flt(sle.stock_value_difference)) / abs(sle.actual_qty)
556
557 if flt(sle.actual_qty) < 0 and sle.voucher_type == "Stock Entry":
558 self.update_rate_on_stock_entry(sle, outgoing_rate)
559 elif sle.voucher_type in ("Delivery Note", "Sales Invoice"):
560 self.update_rate_on_delivery_and_sales_return(sle, outgoing_rate)
561 elif flt(sle.actual_qty) < 0 and sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
562 self.update_rate_on_purchase_receipt(sle, outgoing_rate)
563
564 def update_rate_on_stock_entry(self, sle, outgoing_rate):
565 frappe.db.set_value("Stock Entry Detail", sle.voucher_detail_no, "basic_rate", outgoing_rate)
566
567 # Update outgoing item's rate, recalculate FG Item's rate and total incoming/outgoing amount
Nabin Hait97bce3a2021-07-12 13:24:43 +0530568 if not sle.dependant_sle_voucher_detail_no:
569 self.recalculate_amounts_in_stock_entry(sle.voucher_no)
570
571 def recalculate_amounts_in_stock_entry(self, voucher_no):
572 stock_entry = frappe.get_doc("Stock Entry", voucher_no, for_update=True)
Nabin Haita77b8c92020-12-21 14:45:50 +0530573 stock_entry.calculate_rate_and_amount(reset_outgoing_rate=False, raise_error_if_no_rate=False)
574 stock_entry.db_update()
575 for d in stock_entry.items:
576 d.db_update()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530577
Nabin Haita77b8c92020-12-21 14:45:50 +0530578 def update_rate_on_delivery_and_sales_return(self, sle, outgoing_rate):
579 # Update item's incoming rate on transaction
580 item_code = frappe.db.get_value(sle.voucher_type + " Item", sle.voucher_detail_no, "item_code")
581 if item_code == sle.item_code:
582 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "incoming_rate", outgoing_rate)
583 else:
584 # packed item
585 frappe.db.set_value("Packed Item",
586 {"parent_detail_docname": sle.voucher_detail_no, "item_code": sle.item_code},
587 "incoming_rate", outgoing_rate)
588
589 def update_rate_on_purchase_receipt(self, sle, outgoing_rate):
590 if frappe.db.exists(sle.voucher_type + " Item", sle.voucher_detail_no):
591 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "base_net_rate", outgoing_rate)
592 else:
593 frappe.db.set_value("Purchase Receipt Item Supplied", sle.voucher_detail_no, "rate", outgoing_rate)
594
595 # Recalculate subcontracted item's rate in case of subcontracted purchase receipt/invoice
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530596 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_subcontracted") == 'Yes':
Rohit Waghchauree5fb2392021-06-18 20:37:42 +0530597 doc = frappe.get_doc(sle.voucher_type, sle.voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530598 doc.update_valuation_rate(reset_outgoing_rate=False)
599 for d in (doc.items + doc.supplied_items):
600 d.db_update()
601
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530602 def get_serialized_values(self, sle):
603 incoming_rate = flt(sle.incoming_rate)
604 actual_qty = flt(sle.actual_qty)
Nabin Hait328c4f92020-01-02 19:00:32 +0530605 serial_nos = cstr(sle.serial_no).split("\n")
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530606
607 if incoming_rate < 0:
608 # wrong incoming rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530609 incoming_rate = self.wh_data.valuation_rate
Rushabh Mehta538607e2016-06-12 11:03:00 +0530610
Nabin Hait2620bf42016-02-29 11:30:27 +0530611 stock_value_change = 0
Ankush Menatb9642a12021-12-21 16:49:41 +0530612 if actual_qty > 0:
Nabin Hait2620bf42016-02-29 11:30:27 +0530613 stock_value_change = actual_qty * incoming_rate
Ankush Menatb9642a12021-12-21 16:49:41 +0530614 else:
Nabin Hait2620bf42016-02-29 11:30:27 +0530615 # In case of delivery/stock issue, get average purchase rate
616 # of serial nos of current entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530617 if not sle.is_cancelled:
618 outgoing_value = self.get_incoming_value_for_serial_nos(sle, serial_nos)
619 stock_value_change = -1 * outgoing_value
620 else:
621 stock_value_change = actual_qty * sle.outgoing_rate
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530622
Nabin Haita77b8c92020-12-21 14:45:50 +0530623 new_stock_qty = self.wh_data.qty_after_transaction + actual_qty
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530624
Nabin Hait2620bf42016-02-29 11:30:27 +0530625 if new_stock_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530626 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + stock_value_change
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530627 if new_stock_value >= 0:
Nabin Hait2620bf42016-02-29 11:30:27 +0530628 # calculate new valuation rate only if stock value is positive
629 # else it remains the same as that of previous entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530630 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530631
Nabin Haita77b8c92020-12-21 14:45:50 +0530632 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530633 allow_zero_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
634 if not allow_zero_rate:
Ankush Menatd7ca83e2022-02-19 19:35:33 +0530635 self.wh_data.valuation_rate = self.get_fallback_rate(sle)
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530636
Nabin Hait328c4f92020-01-02 19:00:32 +0530637 def get_incoming_value_for_serial_nos(self, sle, serial_nos):
638 # get rate from serial nos within same company
639 all_serial_nos = frappe.get_all("Serial No",
640 fields=["purchase_rate", "name", "company"],
641 filters = {'name': ('in', serial_nos)})
642
Ankush Menat98917802021-06-11 18:40:22 +0530643 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 +0530644
645 # Get rate for serial nos which has been transferred to other company
646 invalid_serial_nos = [d.name for d in all_serial_nos if d.company!=sle.company]
647 for serial_no in invalid_serial_nos:
648 incoming_rate = frappe.db.sql("""
649 select incoming_rate
650 from `tabStock Ledger Entry`
651 where
652 company = %s
653 and actual_qty > 0
Ankush Menat82ea9582022-01-16 20:19:04 +0530654 and is_cancelled = 0
Nabin Hait328c4f92020-01-02 19:00:32 +0530655 and (serial_no = %s
656 or serial_no like %s
657 or serial_no like %s
658 or serial_no like %s
659 )
660 order by posting_date desc
661 limit 1
662 """, (sle.company, serial_no, serial_no+'\n%', '%\n'+serial_no, '%\n'+serial_no+'\n%'))
663
664 incoming_values += flt(incoming_rate[0][0]) if incoming_rate else 0
665
666 return incoming_values
667
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530668 def get_moving_average_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530669 actual_qty = flt(sle.actual_qty)
Nabin Haita77b8c92020-12-21 14:45:50 +0530670 new_stock_qty = flt(self.wh_data.qty_after_transaction) + actual_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530671 if new_stock_qty >= 0:
672 if actual_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530673 if flt(self.wh_data.qty_after_transaction) <= 0:
674 self.wh_data.valuation_rate = sle.incoming_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530675 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530676 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530677 (actual_qty * sle.incoming_rate)
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530678
Nabin Haita77b8c92020-12-21 14:45:50 +0530679 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530680
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530681 elif sle.outgoing_rate:
682 if new_stock_qty:
Nabin Haita77b8c92020-12-21 14:45:50 +0530683 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530684 (actual_qty * sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530685
Nabin Haita77b8c92020-12-21 14:45:50 +0530686 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530687 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530688 self.wh_data.valuation_rate = sle.outgoing_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530689 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530690 if flt(self.wh_data.qty_after_transaction) >= 0 and sle.outgoing_rate:
691 self.wh_data.valuation_rate = sle.outgoing_rate
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530692
Nabin Haita77b8c92020-12-21 14:45:50 +0530693 if not self.wh_data.valuation_rate and actual_qty > 0:
694 self.wh_data.valuation_rate = sle.incoming_rate
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530695
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530696 # Get valuation rate from previous SLE or Item master, if item does not have the
Javier Wong9b11d9b2017-04-14 18:24:04 +0800697 # allow zero valuration rate flag set
Nabin Haita77b8c92020-12-21 14:45:50 +0530698 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
Javier Wong9b11d9b2017-04-14 18:24:04 +0800699 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
700 if not allow_zero_valuation_rate:
Ankush Menatd7ca83e2022-02-19 19:35:33 +0530701 self.wh_data.valuation_rate = self.get_fallback_rate(sle)
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530702
Ankush Menatf089d392022-02-02 12:51:21 +0530703 def update_queue_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530704 incoming_rate = flt(sle.incoming_rate)
705 actual_qty = flt(sle.actual_qty)
Nabin Haitada485f2015-07-17 15:09:56 +0530706 outgoing_rate = flt(sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530707
Ankush Menatb534fee2022-02-19 20:58:36 +0530708 self.wh_data.qty_after_transaction = round_off_if_near_zero(self.wh_data.qty_after_transaction + actual_qty)
709
Ankush Menat97e18a12022-01-15 17:42:25 +0530710 if self.valuation_method == "LIFO":
711 stock_queue = LIFOValuation(self.wh_data.stock_queue)
712 else:
713 stock_queue = FIFOValuation(self.wh_data.stock_queue)
714
Ankush Menatb534fee2022-02-19 20:58:36 +0530715 _prev_qty, prev_stock_value = stock_queue.get_total_stock_and_value()
716
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530717 if actual_qty > 0:
Ankush Menat97e18a12022-01-15 17:42:25 +0530718 stock_queue.add_stock(qty=actual_qty, rate=incoming_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530719 else:
Ankush Menat4b29fb62021-12-18 18:40:22 +0530720 def rate_generator() -> float:
721 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
722 if not allow_zero_valuation_rate:
Ankush Menatd7ca83e2022-02-19 19:35:33 +0530723 return self.get_fallback_rate(sle)
Nabin Haitada485f2015-07-17 15:09:56 +0530724 else:
Ankush Menat4b29fb62021-12-18 18:40:22 +0530725 return 0.0
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530726
Ankush Menat97e18a12022-01-15 17:42:25 +0530727 stock_queue.remove_stock(qty=abs(actual_qty), outgoing_rate=outgoing_rate, rate_generator=rate_generator)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530728
Ankush Menatb534fee2022-02-19 20:58:36 +0530729 _qty, stock_value = stock_queue.get_total_stock_and_value()
730
731 stock_value_difference = stock_value - prev_stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530732
Ankush Menat97e18a12022-01-15 17:42:25 +0530733 self.wh_data.stock_queue = stock_queue.state
Ankush Menatb534fee2022-02-19 20:58:36 +0530734 self.wh_data.stock_value = round_off_if_near_zero(self.wh_data.stock_value + stock_value_difference)
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530735
Nabin Haita77b8c92020-12-21 14:45:50 +0530736 if not self.wh_data.stock_queue:
737 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 +0530738
Ankush Menatb534fee2022-02-19 20:58:36 +0530739 if self.wh_data.qty_after_transaction:
740 self.wh_data.valuation_rate = self.wh_data.stock_value / self.wh_data.qty_after_transaction
741
Ankush Menatce0514c2022-02-15 11:41:41 +0530742 def update_batched_values(self, sle):
743 incoming_rate = flt(sle.incoming_rate)
744 actual_qty = flt(sle.actual_qty)
Ankush Menat4b29fb62021-12-18 18:40:22 +0530745
Ankush Menatce0514c2022-02-15 11:41:41 +0530746 self.wh_data.qty_after_transaction += actual_qty
747
748 if actual_qty > 0:
749 stock_value_difference = incoming_rate * actual_qty
Ankush Menatce0514c2022-02-15 11:41:41 +0530750 else:
Ankush Menatab926522022-02-19 15:37:03 +0530751 outgoing_rate = get_batch_incoming_rate(item_code=sle.item_code, warehouse=sle.warehouse, batch_no=sle.batch_no, posting_date=sle.posting_date, posting_time=sle.posting_time, creation=sle.creation)
Ankush Menataba7a7c2022-02-19 19:36:28 +0530752 if outgoing_rate is None:
753 # This can *only* happen if qty available for the batch is zero.
754 # in such case fall back various other rates.
755 # future entries will correct the overall accounting as each
756 # batch individually uses moving average rates.
757 outgoing_rate = self.get_fallback_rate(sle)
Ankush Menatce0514c2022-02-15 11:41:41 +0530758 stock_value_difference = outgoing_rate * actual_qty
Ankush Menatce0514c2022-02-15 11:41:41 +0530759
Ankush Menataba7a7c2022-02-19 19:36:28 +0530760 self.wh_data.stock_value += stock_value_difference
Ankush Menatce0514c2022-02-15 11:41:41 +0530761 if self.wh_data.qty_after_transaction:
762 self.wh_data.valuation_rate = self.wh_data.stock_value / self.wh_data.qty_after_transaction
Ankush Menat4b29fb62021-12-18 18:40:22 +0530763
Javier Wong9b11d9b2017-04-14 18:24:04 +0800764 def check_if_allow_zero_valuation_rate(self, voucher_type, voucher_detail_no):
deepeshgarg007f9c0ef32019-07-30 18:49:19 +0530765 ref_item_dt = ""
766
767 if voucher_type == "Stock Entry":
768 ref_item_dt = voucher_type + " Detail"
769 elif voucher_type in ["Purchase Invoice", "Sales Invoice", "Delivery Note", "Purchase Receipt"]:
770 ref_item_dt = voucher_type + " Item"
771
772 if ref_item_dt:
773 return frappe.db.get_value(ref_item_dt, voucher_detail_no, "allow_zero_valuation_rate")
774 else:
775 return 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530776
Ankush Menatd7ca83e2022-02-19 19:35:33 +0530777 def get_fallback_rate(self, sle) -> float:
778 """When exact incoming rate isn't available use any of other "average" rates as fallback.
779 This should only get used for negative stock."""
780 return get_valuation_rate(sle.item_code, sle.warehouse,
781 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
782 currency=erpnext.get_company_currency(sle.company), company=sle.company, batch_no=sle.batch_no)
783
Nabin Haita77b8c92020-12-21 14:45:50 +0530784 def get_sle_before_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530785 """get previous stock ledger entry before current time-bucket"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530786 sle = get_stock_ledger_entries(args, "<", "desc", "limit 1", for_update=False)
787 sle = sle[0] if sle else frappe._dict()
788 return sle
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530789
Nabin Haita77b8c92020-12-21 14:45:50 +0530790 def get_sle_after_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530791 """get Stock Ledger Entries after a particular datetime, for reposting"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530792 return get_stock_ledger_entries(args, ">", "asc", for_update=True, check_serial_no=False)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530793
794 def raise_exceptions(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530795 msg_list = []
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530796 for warehouse, exceptions in self.exceptions.items():
Nabin Haita77b8c92020-12-21 14:45:50 +0530797 deficiency = min(e["diff"] for e in exceptions)
Rushabh Mehta538607e2016-06-12 11:03:00 +0530798
Nabin Haita77b8c92020-12-21 14:45:50 +0530799 if ((exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]) in
800 frappe.local.flags.currently_saving):
Nabin Hait3edefb12016-07-20 16:13:18 +0530801
Nabin Haita77b8c92020-12-21 14:45:50 +0530802 msg = _("{0} units of {1} needed in {2} to complete this transaction.").format(
Nabin Hait243d59b2021-02-02 16:55:13 +0530803 abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]),
Nabin Haita77b8c92020-12-21 14:45:50 +0530804 frappe.get_desk_link('Warehouse', warehouse))
805 else:
806 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 +0530807 abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]),
Nabin Haita77b8c92020-12-21 14:45:50 +0530808 frappe.get_desk_link('Warehouse', warehouse),
809 exceptions[0]["posting_date"], exceptions[0]["posting_time"],
810 frappe.get_desk_link(exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530811
Nabin Haita77b8c92020-12-21 14:45:50 +0530812 if msg:
813 msg_list.append(msg)
814
815 if msg_list:
816 message = "\n\n".join(msg_list)
817 if self.verbose:
818 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
819 else:
820 raise NegativeStockError(message)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530821
Nabin Haita77b8c92020-12-21 14:45:50 +0530822 def update_bin(self):
823 # update bin for each warehouse
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530824 for warehouse, data in self.data.items():
Ankush Menat97060c42021-12-03 11:50:38 +0530825 bin_name = get_or_make_bin(self.item_code, warehouse)
Deepesh Garg6f107da2021-10-12 20:15:55 +0530826
Ankush Menat97060c42021-12-03 11:50:38 +0530827 frappe.db.set_value('Bin', bin_name, {
Nabin Haita77b8c92020-12-21 14:45:50 +0530828 "valuation_rate": data.valuation_rate,
829 "actual_qty": data.qty_after_transaction,
830 "stock_value": data.stock_value
831 })
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530832
marination8418c4b2021-06-22 21:35:25 +0530833
834def get_previous_sle_of_current_voucher(args, exclude_current_voucher=False):
835 """get stock ledger entries filtered by specific posting datetime conditions"""
836
837 args['time_format'] = '%H:%i:%s'
838 if not args.get("posting_date"):
839 args["posting_date"] = "1900-01-01"
840 if not args.get("posting_time"):
841 args["posting_time"] = "00:00"
842
843 voucher_condition = ""
844 if exclude_current_voucher:
845 voucher_no = args.get("voucher_no")
846 voucher_condition = f"and voucher_no != '{voucher_no}'"
847
848 sle = frappe.db.sql("""
849 select *, timestamp(posting_date, posting_time) as "timestamp"
850 from `tabStock Ledger Entry`
851 where item_code = %(item_code)s
852 and warehouse = %(warehouse)s
853 and is_cancelled = 0
854 {voucher_condition}
855 and timestamp(posting_date, time_format(posting_time, %(time_format)s)) < timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
856 order by timestamp(posting_date, posting_time) desc, creation desc
857 limit 1
858 for update""".format(voucher_condition=voucher_condition), args, as_dict=1)
859
860 return sle[0] if sle else frappe._dict()
861
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530862def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530863 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530864 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530865 to get actual qty before transaction, this function
866 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530867
Anand Doshi1b531862013-01-10 19:29:51 +0530868 args = {
869 "item_code": "ABC",
870 "warehouse": "XYZ",
871 "posting_date": "2012-12-12",
872 "posting_time": "12:00",
873 "sle": "name of reference Stock Ledger Entry"
874 }
875 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530876 args["name"] = args.get("sle", None) or ""
877 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530878 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530879
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530880def get_stock_ledger_entries(previous_sle, operator=None,
881 order="desc", limit=None, for_update=False, debug=False, check_serial_no=True):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530882 """get stock ledger entries filtered by specific posting datetime conditions"""
Nabin Haitb9ce1042018-02-01 14:58:50 +0530883 conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
884 if previous_sle.get("warehouse"):
885 conditions += " and warehouse = %(warehouse)s"
886 elif previous_sle.get("warehouse_condition"):
887 conditions += " and " + previous_sle.get("warehouse_condition")
888
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530889 if check_serial_no and previous_sle.get("serial_no"):
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530890 # conditions += " and serial_no like {}".format(frappe.db.escape('%{0}%'.format(previous_sle.get("serial_no"))))
891 serial_no = previous_sle.get("serial_no")
892 conditions += (""" and
893 (
894 serial_no = {0}
895 or serial_no like {1}
896 or serial_no like {2}
897 or serial_no like {3}
898 )
899 """).format(frappe.db.escape(serial_no), frappe.db.escape('{}\n%'.format(serial_no)),
900 frappe.db.escape('%\n{}'.format(serial_no)), frappe.db.escape('%\n{}\n%'.format(serial_no)))
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530901
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530902 if not previous_sle.get("posting_date"):
903 previous_sle["posting_date"] = "1900-01-01"
904 if not previous_sle.get("posting_time"):
905 previous_sle["posting_time"] = "00:00"
906
907 if operator in (">", "<=") and previous_sle.get("name"):
908 conditions += " and name!=%(name)s"
909
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530910 return frappe.db.sql("""
911 select *, timestamp(posting_date, posting_time) as "timestamp"
912 from `tabStock Ledger Entry`
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530913 where item_code = %%(item_code)s
Nabin Haita77b8c92020-12-21 14:45:50 +0530914 and is_cancelled = 0
Nabin Haitb9ce1042018-02-01 14:58:50 +0530915 %(conditions)s
Aditya Hase0c164242019-01-07 22:07:13 +0530916 order by timestamp(posting_date, posting_time) %(order)s, creation %(order)s
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530917 %(limit)s %(for_update)s""" % {
918 "conditions": conditions,
919 "limit": limit or "",
920 "for_update": for_update and "for update" or "",
921 "order": order
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530922 }, previous_sle, as_dict=1, debug=debug)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530923
Nabin Haita77b8c92020-12-21 14:45:50 +0530924def get_sle_by_voucher_detail_no(voucher_detail_no, excluded_sle=None):
925 return frappe.db.get_value('Stock Ledger Entry',
926 {'voucher_detail_no': voucher_detail_no, 'name': ['!=', excluded_sle]},
927 ['item_code', 'warehouse', 'posting_date', 'posting_time', 'timestamp(posting_date, posting_time) as timestamp'],
928 as_dict=1)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530929
Ankush Menatab926522022-02-19 15:37:03 +0530930def get_batch_incoming_rate(item_code, warehouse, batch_no, posting_date, posting_time, creation=None):
Ankush Menatce0514c2022-02-15 11:41:41 +0530931
Ankush Menat102fff22022-02-19 15:51:04 +0530932 Timestamp = CustomFunction('timestamp', ['date', 'time'])
933
934 sle = frappe.qb.DocType("Stock Ledger Entry")
935
936 timestamp_condition = (Timestamp(sle.posting_date, sle.posting_time) < Timestamp(posting_date, posting_time))
937 if creation:
938 timestamp_condition |= (
939 (Timestamp(sle.posting_date, sle.posting_time) == Timestamp(posting_date, posting_time))
940 & (sle.creation < creation)
Ankush Menatce0514c2022-02-15 11:41:41 +0530941 )
Ankush Menat102fff22022-02-19 15:51:04 +0530942
943 batch_details = (
944 frappe.qb
945 .from_(sle)
946 .select(
947 Sum(sle.stock_value_difference).as_("batch_value"),
948 Sum(sle.actual_qty).as_("batch_qty")
949 )
950 .where(
951 (sle.item_code == item_code)
952 & (sle.warehouse == warehouse)
953 & (sle.batch_no == batch_no)
954 & (sle.is_cancelled == 0)
955 )
956 .where(timestamp_condition)
957 ).run(as_dict=True)
Ankush Menatce0514c2022-02-15 11:41:41 +0530958
959 if batch_details and batch_details[0].batch_qty:
960 return batch_details[0].batch_value / batch_details[0].batch_qty
961
962
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530963def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no,
Ankush Menat342d09a2022-02-19 14:28:51 +0530964 allow_zero_rate=False, currency=None, company=None, raise_error_if_no_rate=True, batch_no=None):
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530965
Ankush Menatf7ffe042021-11-01 13:21:14 +0530966 if not company:
967 company = frappe.get_cached_value("Warehouse", warehouse, "company")
968
Ankush Menat342d09a2022-02-19 14:28:51 +0530969 last_valuation_rate = None
970
971 # Get moving average rate of a specific batch number
972 if warehouse and batch_no and frappe.db.get_value("Batch", batch_no, "use_batchwise_valuation"):
973 last_valuation_rate = frappe.db.sql("""
974 select sum(stock_value_difference) / sum(actual_qty)
975 from `tabStock Ledger Entry`
976 where
977 item_code = %s
978 AND warehouse = %s
979 AND batch_no = %s
980 AND is_cancelled = 0
981 AND NOT (voucher_no = %s AND voucher_type = %s)
982 """,
983 (item_code, warehouse, batch_no, voucher_no, voucher_type))
984
Ankush Menatf7ffe042021-11-01 13:21:14 +0530985 # Get valuation rate from last sle for the same item and warehouse
Ankush Menat342d09a2022-02-19 14:28:51 +0530986 if not last_valuation_rate or last_valuation_rate[0][0] is None:
987 last_valuation_rate = frappe.db.sql("""select valuation_rate
988 from `tabStock Ledger Entry` force index (item_warehouse)
989 where
990 item_code = %s
991 AND warehouse = %s
992 AND valuation_rate >= 0
993 AND is_cancelled = 0
994 AND NOT (voucher_no = %s AND voucher_type = %s)
995 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 +0530996
997 if not last_valuation_rate:
Nabin Haita0b967f2017-01-18 18:35:58 +0530998 # Get valuation rate from last sle for the item against any warehouse
Nabin Haitfb6e4342014-10-15 11:34:40 +0530999 last_valuation_rate = frappe.db.sql("""select valuation_rate
Deepesh Garg6f107da2021-10-12 20:15:55 +05301000 from `tabStock Ledger Entry` force index (item_code)
Mangesh-Khairnar0df51342019-08-19 10:04:52 +05301001 where
1002 item_code = %s
1003 AND valuation_rate > 0
Ankush Menat82ea9582022-01-16 20:19:04 +05301004 AND is_cancelled = 0
Mangesh-Khairnar0df51342019-08-19 10:04:52 +05301005 AND NOT(voucher_no = %s AND voucher_type = %s)
1006 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 +05301007
Nabin Haita645f362018-03-01 10:31:24 +05301008 if last_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +05301009 return flt(last_valuation_rate[0][0])
Nabin Haita645f362018-03-01 10:31:24 +05301010
1011 # If negative stock allowed, and item delivered without any incoming entry,
1012 # system does not found any SLE, then take valuation rate from Item
1013 valuation_rate = frappe.db.get_value("Item", item_code, "valuation_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +05301014
1015 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +05301016 # try Item Standard rate
1017 valuation_rate = frappe.db.get_value("Item", item_code, "standard_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +05301018
Rushabh Mehtaaedaac62017-05-04 09:35:19 +05301019 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +05301020 # try in price list
1021 valuation_rate = frappe.db.get_value('Item Price',
1022 dict(item_code=item_code, buying=1, currency=currency),
1023 'price_list_rate')
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +05301024
Nabin Hait7ba092e2018-02-01 10:51:27 +05301025 if not allow_zero_rate and not valuation_rate and raise_error_if_no_rate \
Rohit Waghchauree9ff1912017-06-19 12:54:59 +05301026 and cint(erpnext.is_perpetual_inventory_enabled(company)):
Neil Trini Lasrado193c8912017-03-28 17:39:34 +05301027 frappe.local.message_log = []
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +05301028 form_link = get_link_to_form("Item", item_code)
Marica97715f22020-05-11 20:45:37 +05301029
1030 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 +05301031 message += "<br><br>" + _("Here are the options to proceed:")
Marica97715f22020-05-11 20:45:37 +05301032 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 +05301033 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 +05301034 sub_solutions = "<ul><li>" + _("Create an incoming stock transaction for the Item.") + "</li>"
1035 sub_solutions += "<li>" + _("Mention Valuation Rate in the Item master.") + "</li></ul>"
1036 msg = message + solutions + sub_solutions + "</li>"
1037
1038 frappe.throw(msg=msg, title=_("Valuation Rate Missing"))
Nabin Haitfb6e4342014-10-15 11:34:40 +05301039
1040 return valuation_rate
Nabin Haita77b8c92020-12-21 14:45:50 +05301041
Ankush Menate7109c12021-08-26 16:40:45 +05301042def update_qty_in_future_sle(args, allow_negative_stock=False):
marination8418c4b2021-06-22 21:35:25 +05301043 """Recalculate Qty after Transaction in future SLEs based on current SLE."""
marination40389772021-07-02 17:13:45 +05301044 datetime_limit_condition = ""
marination8418c4b2021-06-22 21:35:25 +05301045 qty_shift = args.actual_qty
1046
1047 # find difference/shift in qty caused by stock reconciliation
1048 if args.voucher_type == "Stock Reconciliation":
marination40389772021-07-02 17:13:45 +05301049 qty_shift = get_stock_reco_qty_shift(args)
1050
1051 # find the next nearest stock reco so that we only recalculate SLEs till that point
1052 next_stock_reco_detail = get_next_stock_reco(args)
1053 if next_stock_reco_detail:
1054 detail = next_stock_reco_detail[0]
1055 # add condition to update SLEs before this date & time
1056 datetime_limit_condition = get_datetime_limit_condition(detail)
marination8418c4b2021-06-22 21:35:25 +05301057
Nabin Hait186a0452021-02-18 14:14:21 +05301058 frappe.db.sql("""
1059 update `tabStock Ledger Entry`
marination8418c4b2021-06-22 21:35:25 +05301060 set qty_after_transaction = qty_after_transaction + {qty_shift}
Nabin Hait186a0452021-02-18 14:14:21 +05301061 where
1062 item_code = %(item_code)s
1063 and warehouse = %(warehouse)s
1064 and voucher_no != %(voucher_no)s
1065 and is_cancelled = 0
1066 and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)
1067 or (
1068 timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s)
1069 and creation > %(creation)s
1070 )
1071 )
marination40389772021-07-02 17:13:45 +05301072 {datetime_limit_condition}
1073 """.format(qty_shift=qty_shift, datetime_limit_condition=datetime_limit_condition), args)
Nabin Hait186a0452021-02-18 14:14:21 +05301074
1075 validate_negative_qty_in_future_sle(args, allow_negative_stock)
1076
marination40389772021-07-02 17:13:45 +05301077def get_stock_reco_qty_shift(args):
1078 stock_reco_qty_shift = 0
1079 if args.get("is_cancelled"):
1080 if args.get("previous_qty_after_transaction"):
1081 # get qty (balance) that was set at submission
1082 last_balance = args.get("previous_qty_after_transaction")
1083 stock_reco_qty_shift = flt(args.qty_after_transaction) - flt(last_balance)
1084 else:
1085 stock_reco_qty_shift = flt(args.actual_qty)
1086 else:
1087 # reco is being submitted
1088 last_balance = get_previous_sle_of_current_voucher(args,
1089 exclude_current_voucher=True).get("qty_after_transaction")
1090
1091 if last_balance is not None:
1092 stock_reco_qty_shift = flt(args.qty_after_transaction) - flt(last_balance)
1093 else:
1094 stock_reco_qty_shift = args.qty_after_transaction
1095
1096 return stock_reco_qty_shift
1097
1098def get_next_stock_reco(args):
1099 """Returns next nearest stock reconciliaton's details."""
1100
1101 return frappe.db.sql("""
1102 select
1103 name, posting_date, posting_time, creation, voucher_no
1104 from
marination8c441262021-07-02 17:46:05 +05301105 `tabStock Ledger Entry`
marination40389772021-07-02 17:13:45 +05301106 where
1107 item_code = %(item_code)s
1108 and warehouse = %(warehouse)s
1109 and voucher_type = 'Stock Reconciliation'
1110 and voucher_no != %(voucher_no)s
1111 and is_cancelled = 0
1112 and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)
1113 or (
1114 timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s)
1115 and creation > %(creation)s
1116 )
1117 )
1118 limit 1
1119 """, args, as_dict=1)
1120
1121def get_datetime_limit_condition(detail):
marination40389772021-07-02 17:13:45 +05301122 return f"""
1123 and
1124 (timestamp(posting_date, posting_time) < timestamp('{detail.posting_date}', '{detail.posting_time}')
1125 or (
1126 timestamp(posting_date, posting_time) = timestamp('{detail.posting_date}', '{detail.posting_time}')
1127 and creation < '{detail.creation}'
1128 )
1129 )"""
1130
Ankush Menate7109c12021-08-26 16:40:45 +05301131def validate_negative_qty_in_future_sle(args, allow_negative_stock=False):
Ankush Menateb8b4242022-02-12 13:08:28 +05301132 if allow_negative_stock or is_negative_stock_allowed(item_code=args.item_code):
Ankush Menat5eba5752021-12-07 23:03:52 +05301133 return
1134 if not (args.actual_qty < 0 or args.voucher_type == "Stock Reconciliation"):
1135 return
Deepesh Gargb4be2922021-01-28 13:09:56 +05301136
Ankush Menat5eba5752021-12-07 23:03:52 +05301137 neg_sle = get_future_sle_with_negative_qty(args)
1138 if neg_sle:
1139 message = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
1140 abs(neg_sle[0]["qty_after_transaction"]),
1141 frappe.get_desk_link('Item', args.item_code),
1142 frappe.get_desk_link('Warehouse', args.warehouse),
1143 neg_sle[0]["posting_date"], neg_sle[0]["posting_time"],
1144 frappe.get_desk_link(neg_sle[0]["voucher_type"], neg_sle[0]["voucher_no"]))
1145
1146 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
1147
1148
1149 if not args.batch_no:
1150 return
1151
1152 neg_batch_sle = get_future_sle_with_negative_batch_qty(args)
1153 if neg_batch_sle:
1154 message = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
1155 abs(neg_batch_sle[0]["cumulative_total"]),
1156 frappe.get_desk_link('Batch', args.batch_no),
1157 frappe.get_desk_link('Warehouse', args.warehouse),
1158 neg_batch_sle[0]["posting_date"], neg_batch_sle[0]["posting_time"],
1159 frappe.get_desk_link(neg_batch_sle[0]["voucher_type"], neg_batch_sle[0]["voucher_no"]))
1160 frappe.throw(message, NegativeStockError, title="Insufficient Stock for Batch")
1161
Nabin Haita77b8c92020-12-21 14:45:50 +05301162
1163def get_future_sle_with_negative_qty(args):
1164 return frappe.db.sql("""
1165 select
1166 qty_after_transaction, posting_date, posting_time,
1167 voucher_type, voucher_no
1168 from `tabStock Ledger Entry`
Deepesh Gargb4be2922021-01-28 13:09:56 +05301169 where
Nabin Haita77b8c92020-12-21 14:45:50 +05301170 item_code = %(item_code)s
1171 and warehouse = %(warehouse)s
1172 and voucher_no != %(voucher_no)s
1173 and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s)
1174 and is_cancelled = 0
Nabin Hait186a0452021-02-18 14:14:21 +05301175 and qty_after_transaction < 0
Nabin Hait243d59b2021-02-02 16:55:13 +05301176 order by timestamp(posting_date, posting_time) asc
Nabin Haita77b8c92020-12-21 14:45:50 +05301177 limit 1
Sagar Vorae50324a2021-03-31 12:44:03 +05301178 """, args, as_dict=1)
Ankush Menat6a014d12021-04-12 20:21:27 +05301179
Ankush Menat5eba5752021-12-07 23:03:52 +05301180
1181def get_future_sle_with_negative_batch_qty(args):
1182 return frappe.db.sql("""
1183 with batch_ledger as (
1184 select
1185 posting_date, posting_time, voucher_type, voucher_no,
1186 sum(actual_qty) over (order by posting_date, posting_time, creation) as cumulative_total
1187 from `tabStock Ledger Entry`
1188 where
1189 item_code = %(item_code)s
1190 and warehouse = %(warehouse)s
1191 and batch_no=%(batch_no)s
1192 and is_cancelled = 0
1193 order by posting_date, posting_time, creation
1194 )
1195 select * from batch_ledger
1196 where
1197 cumulative_total < 0.0
1198 and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s)
1199 limit 1
1200 """, args, as_dict=1)
Ankush Menateb8b4242022-02-12 13:08:28 +05301201
1202
1203def is_negative_stock_allowed(*, item_code: Optional[str] = None) -> bool:
1204 if cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock", cache=True)):
1205 return True
1206 if item_code and cint(frappe.db.get_value("Item", item_code, "allow_negative_stock", cache=True)):
1207 return True
1208 return False