blob: 9c4c67619271900f55848137d8f8bb1af77c0c0d [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
10from frappe.utils import cint, cstr, flt, get_link_to_form, getdate, now
Achilles Rasquinha361366e2018-02-14 17:08:59 +053011
Chillar Anand915b3432021-09-02 16:44:59 +053012import erpnext
13from erpnext.stock.utils import (
Chillar Anand915b3432021-09-02 16:44:59 +053014 get_incoming_outgoing_rate_for_cancel,
Deepesh Garg6f107da2021-10-12 20:15:55 +053015 get_or_make_bin,
Chillar Anand915b3432021-09-02 16:44:59 +053016 get_valuation_method,
17)
18
Nabin Hait97bce3a2021-07-12 13:24:43 +053019
Nabin Hait902e8602013-01-08 18:29:24 +053020# future reposting
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053021class NegativeStockError(frappe.ValidationError): pass
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +053022class SerialNoExistsInFutureTransaction(frappe.ValidationError):
23 pass
Nabin Hait902e8602013-01-08 18:29:24 +053024
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053025_exceptions = frappe.local('stockledger_exceptions')
Pratik Vyas16371b72013-09-18 18:31:03 +053026# _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:
Rushabh Mehta1f847992013-12-12 19:12:19 +053031 from erpnext.stock.utils import update_bin
Nabin Haitdc82d4f2014-04-07 12:02:57 +053032
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
Nabin Hait54c865e2015-03-27 15:38:31 +053067 update_bin(args, allow_negative_stock, via_landed_cost_voucher)
Nabin Haitadeb9762014-10-06 11:53:52 +053068
Rohit Waghchaure4d81d452021-06-15 10:21:44 +053069def get_args_for_future_sle(row):
70 return frappe._dict({
71 'voucher_type': row.get('voucher_type'),
72 'voucher_no': row.get('voucher_no'),
73 'posting_date': row.get('posting_date'),
74 'posting_time': row.get('posting_time')
75 })
76
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +053077def validate_serial_no(sle):
78 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
79 for sn in get_serial_nos(sle.serial_no):
80 args = copy.deepcopy(sle)
81 args.serial_no = sn
82 args.warehouse = ''
83
84 vouchers = []
85 for row in get_stock_ledger_entries(args, '>'):
86 voucher_type = frappe.bold(row.voucher_type)
87 voucher_no = frappe.bold(get_link_to_form(row.voucher_type, row.voucher_no))
88 vouchers.append(f'{voucher_type} {voucher_no}')
89
90 if vouchers:
91 serial_no = frappe.bold(sn)
92 msg = (f'''The serial no {serial_no} has been used in the future transactions so you need to cancel them first.
93 The list of the transactions are as below.''' + '<br><br><ul><li>')
94
95 msg += '</li><li>'.join(vouchers)
96 msg += '</li></ul>'
97
98 title = 'Cannot Submit' if not sle.get('is_cancelled') else 'Cannot Cancel'
99 frappe.throw(_(msg), title=_(title), exc=SerialNoExistsInFutureTransaction)
100
Nabin Hait186a0452021-02-18 14:14:21 +0530101def validate_cancellation(args):
102 if args[0].get("is_cancelled"):
103 repost_entry = frappe.db.get_value("Repost Item Valuation", {
104 'voucher_type': args[0].voucher_type,
105 'voucher_no': args[0].voucher_no,
106 'docstatus': 1
107 }, ['name', 'status'], as_dict=1)
108
109 if repost_entry:
110 if repost_entry.status == 'In Progress':
111 frappe.throw(_("Cannot cancel the transaction. Reposting of item valuation on submission is not completed yet."))
112 if repost_entry.status == 'Queued':
Nabin Haitd46b2362021-02-23 16:38:52 +0530113 doc = frappe.get_doc("Repost Item Valuation", repost_entry.name)
114 doc.cancel()
115 doc.delete()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530116
Nabin Hait9653f602013-08-20 15:37:33 +0530117def set_as_cancel(voucher_type, voucher_no):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530118 frappe.db.sql("""update `tabStock Ledger Entry` set is_cancelled=1,
Nabin Hait9653f602013-08-20 15:37:33 +0530119 modified=%s, modified_by=%s
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530120 where voucher_type=%s and voucher_no=%s and is_cancelled = 0""",
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530121 (now(), frappe.session.user, voucher_type, voucher_no))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530122
Nabin Hait54c865e2015-03-27 15:38:31 +0530123def make_entry(args, allow_negative_stock=False, via_landed_cost_voucher=False):
Saqib Ansaric7fc6092021-10-12 13:30:40 +0530124 args["doctype"] = "Stock Ledger Entry"
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530125 sle = frappe.get_doc(args)
Anand Doshi6dfd4302015-02-10 14:41:27 +0530126 sle.flags.ignore_permissions = 1
Nabin Hait4ccd8d32015-01-23 12:18:01 +0530127 sle.allow_negative_stock=allow_negative_stock
Nabin Hait54c865e2015-03-27 15:38:31 +0530128 sle.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Haitaeba24e2013-08-23 15:17:36 +0530129 sle.submit()
Nabin Haita77b8c92020-12-21 14:45:50 +0530130 return sle
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530131
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530132def 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 +0530133 if not args and voucher_type and voucher_no:
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530134 args = get_items_to_be_repost(voucher_type, voucher_no, doc)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530135
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530136 distinct_item_warehouses = get_distinct_item_warehouse(args, doc)
Nabin Haita77b8c92020-12-21 14:45:50 +0530137
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530138 i = get_current_index(doc) or 0
Nabin Haita77b8c92020-12-21 14:45:50 +0530139 while i < len(args):
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530140 validate_item_warehouse(args[i])
141
Nabin Haita77b8c92020-12-21 14:45:50 +0530142 obj = update_entries_after({
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530143 'item_code': args[i].get('item_code'),
144 'warehouse': args[i].get('warehouse'),
145 'posting_date': args[i].get('posting_date'),
146 'posting_time': args[i].get('posting_time'),
147 'creation': args[i].get('creation'),
148 'distinct_item_warehouses': distinct_item_warehouses
Nabin Haita77b8c92020-12-21 14:45:50 +0530149 }, allow_negative_stock=allow_negative_stock, via_landed_cost_voucher=via_landed_cost_voucher)
150
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530151 distinct_item_warehouses[(args[i].get('item_code'), args[i].get('warehouse'))].reposting_status = True
Deepesh Gargb4be2922021-01-28 13:09:56 +0530152
Nabin Hait97bce3a2021-07-12 13:24:43 +0530153 if obj.new_items_found:
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530154 for item_wh, data in distinct_item_warehouses.items():
Nabin Hait97bce3a2021-07-12 13:24:43 +0530155 if ('args_idx' not in data and not data.reposting_status) or (data.sle_changed and data.reposting_status):
156 data.args_idx = len(args)
157 args.append(data.sle)
158 elif data.sle_changed and not data.reposting_status:
159 args[data.args_idx] = data.sle
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530160
Nabin Hait97bce3a2021-07-12 13:24:43 +0530161 data.sle_changed = False
Nabin Haita77b8c92020-12-21 14:45:50 +0530162 i += 1
163
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530164 if doc and i % 2 == 0:
165 update_args_in_repost_item_valuation(doc, i, args, distinct_item_warehouses)
166
167 if doc and args:
168 update_args_in_repost_item_valuation(doc, i, args, distinct_item_warehouses)
169
170def validate_item_warehouse(args):
171 for field in ['item_code', 'warehouse', 'posting_date', 'posting_time']:
172 if not args.get(field):
173 validation_msg = f'The field {frappe.unscrub(args.get(field))} is required for the reposting'
174 frappe.throw(_(validation_msg))
175
176def update_args_in_repost_item_valuation(doc, index, args, distinct_item_warehouses):
177 frappe.db.set_value(doc.doctype, doc.name, {
178 'items_to_be_repost': json.dumps(args, default=str),
179 'distinct_item_and_warehouse': json.dumps({str(k): v for k,v in distinct_item_warehouses.items()}, default=str),
180 'current_index': index
181 })
182
183 frappe.db.commit()
184
185 frappe.publish_realtime('item_reposting_progress', {
186 'name': doc.name,
187 'items_to_be_repost': json.dumps(args, default=str),
188 'current_index': index
189 })
190
191def get_items_to_be_repost(voucher_type, voucher_no, doc=None):
192 if doc and doc.items_to_be_repost:
193 return json.loads(doc.items_to_be_repost) or []
194
Nabin Haita77b8c92020-12-21 14:45:50 +0530195 return frappe.db.get_all("Stock Ledger Entry",
196 filters={"voucher_type": voucher_type, "voucher_no": voucher_no},
Nabin Hait186a0452021-02-18 14:14:21 +0530197 fields=["item_code", "warehouse", "posting_date", "posting_time", "creation"],
Nabin Haita77b8c92020-12-21 14:45:50 +0530198 order_by="creation asc",
199 group_by="item_code, warehouse"
200 )
Nabin Hait74c281c2013-08-19 16:17:18 +0530201
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530202def get_distinct_item_warehouse(args=None, doc=None):
203 distinct_item_warehouses = {}
204 if doc and doc.distinct_item_and_warehouse:
205 distinct_item_warehouses = json.loads(doc.distinct_item_and_warehouse)
206 distinct_item_warehouses = {frappe.safe_eval(k): frappe._dict(v) for k, v in distinct_item_warehouses.items()}
207 else:
208 for i, d in enumerate(args):
209 distinct_item_warehouses.setdefault((d.item_code, d.warehouse), frappe._dict({
210 "reposting_status": False,
211 "sle": d,
212 "args_idx": i
213 }))
214
215 return distinct_item_warehouses
216
217def get_current_index(doc=None):
218 if doc and doc.current_index:
219 return doc.current_index
220
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530221class update_entries_after(object):
Nabin Hait902e8602013-01-08 18:29:24 +0530222 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530223 update valution rate and qty after transaction
Nabin Hait902e8602013-01-08 18:29:24 +0530224 from the current time-bucket onwards
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530225
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530226 :param args: args as dict
227
228 args = {
229 "item_code": "ABC",
230 "warehouse": "XYZ",
231 "posting_date": "2012-12-12",
232 "posting_time": "12:00"
233 }
Nabin Hait902e8602013-01-08 18:29:24 +0530234 """
Anand Doshi0dc79f42015-04-06 12:59:34 +0530235 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 +0530236 self.exceptions = {}
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530237 self.verbose = verbose
238 self.allow_zero_rate = allow_zero_rate
Anand Doshi0dc79f42015-04-06 12:59:34 +0530239 self.via_landed_cost_voucher = via_landed_cost_voucher
Ankush Menat7bafa112021-10-12 20:39:10 +0530240 self.allow_negative_stock = allow_negative_stock \
241 or cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530242
Nabin Haita77b8c92020-12-21 14:45:50 +0530243 self.args = frappe._dict(args)
244 self.item_code = args.get("item_code")
245 if self.args.sle_id:
246 self.args['name'] = self.args.sle_id
Nabin Haitd46b2362021-02-23 16:38:52 +0530247
Nabin Haita77b8c92020-12-21 14:45:50 +0530248 self.company = frappe.get_cached_value("Warehouse", self.args.warehouse, "company")
249 self.get_precision()
250 self.valuation_method = get_valuation_method(self.item_code)
Nabin Hait97bce3a2021-07-12 13:24:43 +0530251
252 self.new_items_found = False
253 self.distinct_item_warehouses = args.get("distinct_item_warehouses", frappe._dict())
Nabin Haita77b8c92020-12-21 14:45:50 +0530254
255 self.data = frappe._dict()
256 self.initialize_previous_data(self.args)
Nabin Haita77b8c92020-12-21 14:45:50 +0530257 self.build()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530258
Nabin Haita77b8c92020-12-21 14:45:50 +0530259 def get_precision(self):
260 company_base_currency = frappe.get_cached_value('Company', self.company, "default_currency")
261 self.precision = get_field_precision(frappe.get_meta("Stock Ledger Entry").get_field("stock_value"),
262 currency=company_base_currency)
263
264 def initialize_previous_data(self, args):
265 """
266 Get previous sl entries for current item for each related warehouse
267 and assigns into self.data dict
268
269 :Data Structure:
270
271 self.data = {
272 warehouse1: {
273 'previus_sle': {},
274 'qty_after_transaction': 10,
275 'valuation_rate': 100,
276 'stock_value': 1000,
277 'prev_stock_value': 1000,
278 'stock_queue': '[[10, 100]]',
279 'stock_value_difference': 1000
280 }
281 }
282
283 """
Ankush Menatc1d986a2021-08-31 19:43:42 +0530284 self.data.setdefault(args.warehouse, frappe._dict())
285 warehouse_dict = self.data[args.warehouse]
marination8418c4b2021-06-22 21:35:25 +0530286 previous_sle = get_previous_sle_of_current_voucher(args)
Ankush Menatc1d986a2021-08-31 19:43:42 +0530287 warehouse_dict.previous_sle = previous_sle
Nabin Haitbb777562013-08-29 18:19:37 +0530288
Ankush Menatc1d986a2021-08-31 19:43:42 +0530289 for key in ("qty_after_transaction", "valuation_rate", "stock_value"):
290 setattr(warehouse_dict, key, flt(previous_sle.get(key)))
291
292 warehouse_dict.update({
Nabin Haita77b8c92020-12-21 14:45:50 +0530293 "prev_stock_value": previous_sle.stock_value or 0.0,
294 "stock_queue": json.loads(previous_sle.stock_queue or "[]"),
295 "stock_value_difference": 0.0
296 })
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530297
Nabin Haita77b8c92020-12-21 14:45:50 +0530298 def build(self):
Sagar Vorae50324a2021-03-31 12:44:03 +0530299 from erpnext.controllers.stock_controller import future_sle_exists
Nabin Hait186a0452021-02-18 14:14:21 +0530300
Nabin Haita77b8c92020-12-21 14:45:50 +0530301 if self.args.get("sle_id"):
Nabin Hait186a0452021-02-18 14:14:21 +0530302 self.process_sle_against_current_timestamp()
Sagar Vorae50324a2021-03-31 12:44:03 +0530303 if not future_sle_exists(self.args):
Nabin Hait186a0452021-02-18 14:14:21 +0530304 self.update_bin()
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530305 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530306 entries_to_fix = self.get_future_entries_to_fix()
307
308 i = 0
309 while i < len(entries_to_fix):
310 sle = entries_to_fix[i]
311 i += 1
312
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530313 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530314
Nabin Haita77b8c92020-12-21 14:45:50 +0530315 if sle.dependant_sle_voucher_detail_no:
Nabin Hait243d59b2021-02-02 16:55:13 +0530316 entries_to_fix = self.get_dependent_entries_to_fix(entries_to_fix, sle)
Nabin Haitd46b2362021-02-23 16:38:52 +0530317
Nabin Hait186a0452021-02-18 14:14:21 +0530318 self.update_bin()
Nabin Haita77b8c92020-12-21 14:45:50 +0530319
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530320 if self.exceptions:
321 self.raise_exceptions()
322
Nabin Hait186a0452021-02-18 14:14:21 +0530323 def process_sle_against_current_timestamp(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530324 sl_entries = self.get_sle_against_current_voucher()
325 for sle in sl_entries:
326 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530327
Nabin Haita77b8c92020-12-21 14:45:50 +0530328 def get_sle_against_current_voucher(self):
Nabin Haitf2be0802021-02-15 19:27:49 +0530329 self.args['time_format'] = '%H:%i:%s'
330
Nabin Haita77b8c92020-12-21 14:45:50 +0530331 return frappe.db.sql("""
332 select
333 *, timestamp(posting_date, posting_time) as "timestamp"
334 from
335 `tabStock Ledger Entry`
336 where
337 item_code = %(item_code)s
338 and warehouse = %(warehouse)s
rohitwaghchaurefe4540d2021-08-26 12:52:36 +0530339 and is_cancelled = 0
Nabin Hait186a0452021-02-18 14:14:21 +0530340 and timestamp(posting_date, time_format(posting_time, %(time_format)s)) = timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
341
Nabin Haita77b8c92020-12-21 14:45:50 +0530342 order by
343 creation ASC
344 for update
345 """, self.args, as_dict=1)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530346
Nabin Haita77b8c92020-12-21 14:45:50 +0530347 def get_future_entries_to_fix(self):
348 # includes current entry!
349 args = self.data[self.args.warehouse].previous_sle \
350 or frappe._dict({"item_code": self.item_code, "warehouse": self.args.warehouse})
Deepesh Gargb4be2922021-01-28 13:09:56 +0530351
Nabin Haita77b8c92020-12-21 14:45:50 +0530352 return list(self.get_sle_after_datetime(args))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530353
Nabin Haita77b8c92020-12-21 14:45:50 +0530354 def get_dependent_entries_to_fix(self, entries_to_fix, sle):
355 dependant_sle = get_sle_by_voucher_detail_no(sle.dependant_sle_voucher_detail_no,
356 excluded_sle=sle.name)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530357
Nabin Haita77b8c92020-12-21 14:45:50 +0530358 if not dependant_sle:
Nabin Hait243d59b2021-02-02 16:55:13 +0530359 return entries_to_fix
Nabin Haita77b8c92020-12-21 14:45:50 +0530360 elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse == self.args.warehouse:
Nabin Hait243d59b2021-02-02 16:55:13 +0530361 return entries_to_fix
362 elif dependant_sle.item_code != self.item_code:
Nabin Hait97bce3a2021-07-12 13:24:43 +0530363 self.update_distinct_item_warehouses(dependant_sle)
Nabin Hait243d59b2021-02-02 16:55:13 +0530364 return entries_to_fix
365 elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse in self.data:
366 return entries_to_fix
Nabin Hait97bce3a2021-07-12 13:24:43 +0530367 else:
368 return self.append_future_sle_for_dependant(dependant_sle, entries_to_fix)
369
370 def update_distinct_item_warehouses(self, dependant_sle):
371 key = (dependant_sle.item_code, dependant_sle.warehouse)
372 val = frappe._dict({
373 "sle": dependant_sle
374 })
375 if key not in self.distinct_item_warehouses:
376 self.distinct_item_warehouses[key] = val
377 self.new_items_found = True
378 else:
379 existing_sle_posting_date = self.distinct_item_warehouses[key].get("sle", {}).get("posting_date")
380 if getdate(dependant_sle.posting_date) < getdate(existing_sle_posting_date):
381 val.sle_changed = True
382 self.distinct_item_warehouses[key] = val
383 self.new_items_found = True
384
385 def append_future_sle_for_dependant(self, dependant_sle, entries_to_fix):
Nabin Haita77b8c92020-12-21 14:45:50 +0530386 self.initialize_previous_data(dependant_sle)
387
388 args = self.data[dependant_sle.warehouse].previous_sle \
389 or frappe._dict({"item_code": self.item_code, "warehouse": dependant_sle.warehouse})
390 future_sle_for_dependant = list(self.get_sle_after_datetime(args))
391
392 entries_to_fix.extend(future_sle_for_dependant)
Nabin Hait243d59b2021-02-02 16:55:13 +0530393 return sorted(entries_to_fix, key=lambda k: k['timestamp'])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530394
395 def process_sle(self, sle):
Nabin Haita77b8c92020-12-21 14:45:50 +0530396 # previous sle data for this warehouse
397 self.wh_data = self.data[sle.warehouse]
398
Anand Doshi0dc79f42015-04-06 12:59:34 +0530399 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 +0530400 # validate negative stock for serialized items, fifo valuation
Nabin Hait902e8602013-01-08 18:29:24 +0530401 # or when negative stock is not allowed for moving average
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530402 if not self.validate_negative_stock(sle):
Nabin Haita77b8c92020-12-21 14:45:50 +0530403 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530404 return
Nabin Haitb96c0142014-10-07 11:25:04 +0530405
Nabin Haita77b8c92020-12-21 14:45:50 +0530406 # Get dynamic incoming/outgoing rate
rohitwaghchauree6a1ad82021-09-15 20:42:47 +0530407 if not self.args.get("sle_id"):
408 self.get_dynamic_incoming_outgoing_rate(sle)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530409
Anand Doshi1b531862013-01-10 19:29:51 +0530410 if sle.serial_no:
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530411 self.get_serialized_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530412 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530413 if sle.voucher_type == "Stock Reconciliation":
Nabin Haita77b8c92020-12-21 14:45:50 +0530414 self.wh_data.qty_after_transaction = sle.qty_after_transaction
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530415
Nabin Haita77b8c92020-12-21 14:45:50 +0530416 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 +0530417 else:
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530418 if sle.voucher_type=="Stock Reconciliation" and not sle.batch_no:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530419 # assert
Nabin Haita77b8c92020-12-21 14:45:50 +0530420 self.wh_data.valuation_rate = sle.valuation_rate
421 self.wh_data.qty_after_transaction = sle.qty_after_transaction
422 self.wh_data.stock_queue = [[self.wh_data.qty_after_transaction, self.wh_data.valuation_rate]]
423 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 +0530424 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530425 if self.valuation_method == "Moving Average":
426 self.get_moving_average_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530427 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
428 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 +0530429 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530430 self.get_fifo_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530431 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530432 self.wh_data.stock_value = sum(flt(batch[0]) * flt(batch[1]) for batch in self.wh_data.stock_queue)
Nabin Haitb96c0142014-10-07 11:25:04 +0530433
Rushabh Mehta54047782013-12-26 11:07:46 +0530434 # rounding as per precision
Nabin Haita77b8c92020-12-21 14:45:50 +0530435 self.wh_data.stock_value = flt(self.wh_data.stock_value, self.precision)
436 stock_value_difference = self.wh_data.stock_value - self.wh_data.prev_stock_value
437 self.wh_data.prev_stock_value = self.wh_data.stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530438
Nabin Hait902e8602013-01-08 18:29:24 +0530439 # update current sle
Nabin Haita77b8c92020-12-21 14:45:50 +0530440 sle.qty_after_transaction = self.wh_data.qty_after_transaction
441 sle.valuation_rate = self.wh_data.valuation_rate
442 sle.stock_value = self.wh_data.stock_value
443 sle.stock_queue = json.dumps(self.wh_data.stock_queue)
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530444 sle.stock_value_difference = stock_value_difference
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530445 sle.doctype="Stock Ledger Entry"
446 frappe.get_doc(sle).db_update()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530447
rohitwaghchauree6a1ad82021-09-15 20:42:47 +0530448 if not self.args.get("sle_id"):
449 self.update_outgoing_rate_on_transaction(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530450
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530451 def validate_negative_stock(self, sle):
452 """
453 validate negative stock for entries current datetime onwards
454 will not consider cancelled entries
455 """
Nabin Haita77b8c92020-12-21 14:45:50 +0530456 diff = self.wh_data.qty_after_transaction + flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530457
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530458 if diff < 0 and abs(diff) > 0.0001:
459 # negative stock!
460 exc = sle.copy().update({"diff": diff})
Nabin Haita77b8c92020-12-21 14:45:50 +0530461 self.exceptions.setdefault(sle.warehouse, []).append(exc)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530462 return False
Nabin Hait902e8602013-01-08 18:29:24 +0530463 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530464 return True
465
Nabin Haita77b8c92020-12-21 14:45:50 +0530466 def get_dynamic_incoming_outgoing_rate(self, sle):
467 # Get updated incoming/outgoing rate from transaction
468 if sle.recalculate_rate:
469 rate = self.get_incoming_outgoing_rate_from_transaction(sle)
470
471 if flt(sle.actual_qty) >= 0:
472 sle.incoming_rate = rate
473 else:
474 sle.outgoing_rate = rate
475
476 def get_incoming_outgoing_rate_from_transaction(self, sle):
477 rate = 0
478 # Material Transfer, Repack, Manufacturing
479 if sle.voucher_type == "Stock Entry":
Nabin Hait97bce3a2021-07-12 13:24:43 +0530480 self.recalculate_amounts_in_stock_entry(sle.voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530481 rate = frappe.db.get_value("Stock Entry Detail", sle.voucher_detail_no, "valuation_rate")
482 # Sales and Purchase Return
483 elif sle.voucher_type in ("Purchase Receipt", "Purchase Invoice", "Delivery Note", "Sales Invoice"):
484 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_return"):
Chillar Anand915b3432021-09-02 16:44:59 +0530485 from erpnext.controllers.sales_and_purchase_return import (
486 get_rate_for_return, # don't move this import to top
487 )
rohitwaghchaurece6c3b52021-04-13 20:55:52 +0530488 rate = get_rate_for_return(sle.voucher_type, sle.voucher_no, sle.item_code,
489 voucher_detail_no=sle.voucher_detail_no, sle = sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530490 else:
491 if sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530492 rate_field = "valuation_rate"
Nabin Haita77b8c92020-12-21 14:45:50 +0530493 else:
494 rate_field = "incoming_rate"
495
496 # check in item table
497 item_code, incoming_rate = frappe.db.get_value(sle.voucher_type + " Item",
498 sle.voucher_detail_no, ["item_code", rate_field])
499
500 if item_code == sle.item_code:
501 rate = incoming_rate
502 else:
503 if sle.voucher_type in ("Delivery Note", "Sales Invoice"):
504 ref_doctype = "Packed Item"
505 else:
506 ref_doctype = "Purchase Receipt Item Supplied"
Deepesh Gargb4be2922021-01-28 13:09:56 +0530507
Nabin Haita77b8c92020-12-21 14:45:50 +0530508 rate = frappe.db.get_value(ref_doctype, {"parent_detail_docname": sle.voucher_detail_no,
509 "item_code": sle.item_code}, rate_field)
510
511 return rate
512
513 def update_outgoing_rate_on_transaction(self, sle):
514 """
515 Update outgoing rate in Stock Entry, Delivery Note, Sales Invoice and Sales Return
516 In case of Stock Entry, also calculate FG Item rate and total incoming/outgoing amount
517 """
518 if sle.actual_qty and sle.voucher_detail_no:
519 outgoing_rate = abs(flt(sle.stock_value_difference)) / abs(sle.actual_qty)
520
521 if flt(sle.actual_qty) < 0 and sle.voucher_type == "Stock Entry":
522 self.update_rate_on_stock_entry(sle, outgoing_rate)
523 elif sle.voucher_type in ("Delivery Note", "Sales Invoice"):
524 self.update_rate_on_delivery_and_sales_return(sle, outgoing_rate)
525 elif flt(sle.actual_qty) < 0 and sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
526 self.update_rate_on_purchase_receipt(sle, outgoing_rate)
527
528 def update_rate_on_stock_entry(self, sle, outgoing_rate):
529 frappe.db.set_value("Stock Entry Detail", sle.voucher_detail_no, "basic_rate", outgoing_rate)
530
531 # Update outgoing item's rate, recalculate FG Item's rate and total incoming/outgoing amount
Nabin Hait97bce3a2021-07-12 13:24:43 +0530532 if not sle.dependant_sle_voucher_detail_no:
533 self.recalculate_amounts_in_stock_entry(sle.voucher_no)
534
535 def recalculate_amounts_in_stock_entry(self, voucher_no):
536 stock_entry = frappe.get_doc("Stock Entry", voucher_no, for_update=True)
Nabin Haita77b8c92020-12-21 14:45:50 +0530537 stock_entry.calculate_rate_and_amount(reset_outgoing_rate=False, raise_error_if_no_rate=False)
538 stock_entry.db_update()
539 for d in stock_entry.items:
540 d.db_update()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530541
Nabin Haita77b8c92020-12-21 14:45:50 +0530542 def update_rate_on_delivery_and_sales_return(self, sle, outgoing_rate):
543 # Update item's incoming rate on transaction
544 item_code = frappe.db.get_value(sle.voucher_type + " Item", sle.voucher_detail_no, "item_code")
545 if item_code == sle.item_code:
546 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "incoming_rate", outgoing_rate)
547 else:
548 # packed item
549 frappe.db.set_value("Packed Item",
550 {"parent_detail_docname": sle.voucher_detail_no, "item_code": sle.item_code},
551 "incoming_rate", outgoing_rate)
552
553 def update_rate_on_purchase_receipt(self, sle, outgoing_rate):
554 if frappe.db.exists(sle.voucher_type + " Item", sle.voucher_detail_no):
555 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "base_net_rate", outgoing_rate)
556 else:
557 frappe.db.set_value("Purchase Receipt Item Supplied", sle.voucher_detail_no, "rate", outgoing_rate)
558
559 # Recalculate subcontracted item's rate in case of subcontracted purchase receipt/invoice
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530560 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_subcontracted") == 'Yes':
Rohit Waghchauree5fb2392021-06-18 20:37:42 +0530561 doc = frappe.get_doc(sle.voucher_type, sle.voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530562 doc.update_valuation_rate(reset_outgoing_rate=False)
563 for d in (doc.items + doc.supplied_items):
564 d.db_update()
565
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530566 def get_serialized_values(self, sle):
567 incoming_rate = flt(sle.incoming_rate)
568 actual_qty = flt(sle.actual_qty)
Nabin Hait328c4f92020-01-02 19:00:32 +0530569 serial_nos = cstr(sle.serial_no).split("\n")
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530570
571 if incoming_rate < 0:
572 # wrong incoming rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530573 incoming_rate = self.wh_data.valuation_rate
Rushabh Mehta538607e2016-06-12 11:03:00 +0530574
Nabin Hait2620bf42016-02-29 11:30:27 +0530575 stock_value_change = 0
576 if incoming_rate:
577 stock_value_change = actual_qty * incoming_rate
578 elif actual_qty < 0:
579 # In case of delivery/stock issue, get average purchase rate
580 # of serial nos of current entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530581 if not sle.is_cancelled:
582 outgoing_value = self.get_incoming_value_for_serial_nos(sle, serial_nos)
583 stock_value_change = -1 * outgoing_value
584 else:
585 stock_value_change = actual_qty * sle.outgoing_rate
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530586
Nabin Haita77b8c92020-12-21 14:45:50 +0530587 new_stock_qty = self.wh_data.qty_after_transaction + actual_qty
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530588
Nabin Hait2620bf42016-02-29 11:30:27 +0530589 if new_stock_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530590 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + stock_value_change
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530591 if new_stock_value >= 0:
Nabin Hait2620bf42016-02-29 11:30:27 +0530592 # calculate new valuation rate only if stock value is positive
593 # else it remains the same as that of previous entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530594 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530595
Nabin Haita77b8c92020-12-21 14:45:50 +0530596 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530597 allow_zero_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
598 if not allow_zero_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530599 self.wh_data.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530600 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
Ankush Menata0727b22021-11-01 13:17:40 +0530601 currency=erpnext.get_company_currency(sle.company), company=sle.company)
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530602
Nabin Hait328c4f92020-01-02 19:00:32 +0530603 def get_incoming_value_for_serial_nos(self, sle, serial_nos):
604 # get rate from serial nos within same company
605 all_serial_nos = frappe.get_all("Serial No",
606 fields=["purchase_rate", "name", "company"],
607 filters = {'name': ('in', serial_nos)})
608
Ankush Menat98917802021-06-11 18:40:22 +0530609 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 +0530610
611 # Get rate for serial nos which has been transferred to other company
612 invalid_serial_nos = [d.name for d in all_serial_nos if d.company!=sle.company]
613 for serial_no in invalid_serial_nos:
614 incoming_rate = frappe.db.sql("""
615 select incoming_rate
616 from `tabStock Ledger Entry`
617 where
618 company = %s
619 and actual_qty > 0
620 and (serial_no = %s
621 or serial_no like %s
622 or serial_no like %s
623 or serial_no like %s
624 )
625 order by posting_date desc
626 limit 1
627 """, (sle.company, serial_no, serial_no+'\n%', '%\n'+serial_no, '%\n'+serial_no+'\n%'))
628
629 incoming_values += flt(incoming_rate[0][0]) if incoming_rate else 0
630
631 return incoming_values
632
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530633 def get_moving_average_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530634 actual_qty = flt(sle.actual_qty)
Nabin Haita77b8c92020-12-21 14:45:50 +0530635 new_stock_qty = flt(self.wh_data.qty_after_transaction) + actual_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530636 if new_stock_qty >= 0:
637 if actual_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530638 if flt(self.wh_data.qty_after_transaction) <= 0:
639 self.wh_data.valuation_rate = sle.incoming_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530640 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530641 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530642 (actual_qty * sle.incoming_rate)
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530643
Nabin Haita77b8c92020-12-21 14:45:50 +0530644 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530645
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530646 elif sle.outgoing_rate:
647 if new_stock_qty:
Nabin Haita77b8c92020-12-21 14:45:50 +0530648 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530649 (actual_qty * sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530650
Nabin Haita77b8c92020-12-21 14:45:50 +0530651 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530652 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530653 self.wh_data.valuation_rate = sle.outgoing_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530654 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530655 if flt(self.wh_data.qty_after_transaction) >= 0 and sle.outgoing_rate:
656 self.wh_data.valuation_rate = sle.outgoing_rate
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530657
Nabin Haita77b8c92020-12-21 14:45:50 +0530658 if not self.wh_data.valuation_rate and actual_qty > 0:
659 self.wh_data.valuation_rate = sle.incoming_rate
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530660
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530661 # Get valuation rate from previous SLE or Item master, if item does not have the
Javier Wong9b11d9b2017-04-14 18:24:04 +0800662 # allow zero valuration rate flag set
Nabin Haita77b8c92020-12-21 14:45:50 +0530663 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
Javier Wong9b11d9b2017-04-14 18:24:04 +0800664 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
665 if not allow_zero_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530666 self.wh_data.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530667 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
Ankush Menata0727b22021-11-01 13:17:40 +0530668 currency=erpnext.get_company_currency(sle.company), company=sle.company)
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530669
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530670 def get_fifo_values(self, sle):
671 incoming_rate = flt(sle.incoming_rate)
672 actual_qty = flt(sle.actual_qty)
Nabin Haitada485f2015-07-17 15:09:56 +0530673 outgoing_rate = flt(sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530674
675 if actual_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530676 if not self.wh_data.stock_queue:
677 self.wh_data.stock_queue.append([0, 0])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530678
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530679 # last row has the same rate, just updated the qty
Nabin Haita77b8c92020-12-21 14:45:50 +0530680 if self.wh_data.stock_queue[-1][1]==incoming_rate:
681 self.wh_data.stock_queue[-1][0] += actual_qty
Nabin Hait4d742162014-10-09 19:25:03 +0530682 else:
Frappe PR Botd4d5e272021-09-15 17:07:58 +0530683 # Item has a positive balance qty, add new entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530684 if self.wh_data.stock_queue[-1][0] > 0:
685 self.wh_data.stock_queue.append([actual_qty, incoming_rate])
Frappe PR Botd4d5e272021-09-15 17:07:58 +0530686 else: # negative balance qty
Nabin Haita77b8c92020-12-21 14:45:50 +0530687 qty = self.wh_data.stock_queue[-1][0] + actual_qty
Frappe PR Botd4d5e272021-09-15 17:07:58 +0530688 if qty > 0: # new balance qty is positive
689 self.wh_data.stock_queue[-1] = [qty, incoming_rate]
690 else: # new balance qty is still negative, maintain same rate
691 self.wh_data.stock_queue[-1][0] = qty
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530692 else:
693 qty_to_pop = abs(actual_qty)
694 while qty_to_pop:
Nabin Haita77b8c92020-12-21 14:45:50 +0530695 if not self.wh_data.stock_queue:
Nabin Haita0b967f2017-01-18 18:35:58 +0530696 # Get valuation rate from last sle if exists or from valuation rate field in item master
Javier Wong9b11d9b2017-04-14 18:24:04 +0800697 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
698 if not allow_zero_valuation_rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530699 _rate = get_valuation_rate(sle.item_code, sle.warehouse,
700 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
Ankush Menata0727b22021-11-01 13:17:40 +0530701 currency=erpnext.get_company_currency(sle.company), company=sle.company)
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530702 else:
703 _rate = 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530704
Nabin Haita77b8c92020-12-21 14:45:50 +0530705 self.wh_data.stock_queue.append([0, _rate])
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530706
Nabin Haitada485f2015-07-17 15:09:56 +0530707 index = None
708 if outgoing_rate > 0:
709 # Find the entry where rate matched with outgoing rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530710 for i, v in enumerate(self.wh_data.stock_queue):
Nabin Haitada485f2015-07-17 15:09:56 +0530711 if v[1] == outgoing_rate:
712 index = i
713 break
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530714
Nabin Haitada485f2015-07-17 15:09:56 +0530715 # If no entry found with outgoing rate, collapse stack
Ankush Menat4dcac4a2021-05-21 13:12:30 +0530716 if index is None: # nosemgrep
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530717 new_stock_value = sum(d[0]*d[1] for d in self.wh_data.stock_queue) - qty_to_pop*outgoing_rate
718 new_stock_qty = sum(d[0] for d in self.wh_data.stock_queue) - qty_to_pop
Nabin Haita77b8c92020-12-21 14:45:50 +0530719 self.wh_data.stock_queue = [[new_stock_qty, new_stock_value/new_stock_qty if new_stock_qty > 0 else outgoing_rate]]
Nabin Haitada485f2015-07-17 15:09:56 +0530720 break
721 else:
722 index = 0
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530723
Nabin Haitada485f2015-07-17 15:09:56 +0530724 # select first batch or the batch with same rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530725 batch = self.wh_data.stock_queue[index]
Nabin Hait8142cd22015-08-05 18:57:26 +0530726 if qty_to_pop >= batch[0]:
727 # consume current batch
Ankush Menat6a014d12021-04-12 20:21:27 +0530728 qty_to_pop = _round_off_if_near_zero(qty_to_pop - batch[0])
Nabin Haita77b8c92020-12-21 14:45:50 +0530729 self.wh_data.stock_queue.pop(index)
730 if not self.wh_data.stock_queue and qty_to_pop:
Nabin Hait8142cd22015-08-05 18:57:26 +0530731 # stock finished, qty still remains to be withdrawn
732 # negative stock, keep in as a negative batch
Nabin Haita77b8c92020-12-21 14:45:50 +0530733 self.wh_data.stock_queue.append([-qty_to_pop, outgoing_rate or batch[1]])
Nabin Hait8142cd22015-08-05 18:57:26 +0530734 break
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530735
Nabin Hait8142cd22015-08-05 18:57:26 +0530736 else:
737 # qty found in current batch
738 # consume it and exit
739 batch[0] = batch[0] - qty_to_pop
740 qty_to_pop = 0
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530741
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530742 stock_value = _round_off_if_near_zero(sum(flt(batch[0]) * flt(batch[1]) for batch in self.wh_data.stock_queue))
743 stock_qty = _round_off_if_near_zero(sum(flt(batch[0]) for batch in self.wh_data.stock_queue))
Nabin Hait902e8602013-01-08 18:29:24 +0530744
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530745 if stock_qty:
Nabin Haita77b8c92020-12-21 14:45:50 +0530746 self.wh_data.valuation_rate = stock_value / flt(stock_qty)
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530747
Nabin Haita77b8c92020-12-21 14:45:50 +0530748 if not self.wh_data.stock_queue:
749 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 +0530750
Javier Wong9b11d9b2017-04-14 18:24:04 +0800751 def check_if_allow_zero_valuation_rate(self, voucher_type, voucher_detail_no):
deepeshgarg007f9c0ef32019-07-30 18:49:19 +0530752 ref_item_dt = ""
753
754 if voucher_type == "Stock Entry":
755 ref_item_dt = voucher_type + " Detail"
756 elif voucher_type in ["Purchase Invoice", "Sales Invoice", "Delivery Note", "Purchase Receipt"]:
757 ref_item_dt = voucher_type + " Item"
758
759 if ref_item_dt:
760 return frappe.db.get_value(ref_item_dt, voucher_detail_no, "allow_zero_valuation_rate")
761 else:
762 return 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530763
Nabin Haita77b8c92020-12-21 14:45:50 +0530764 def get_sle_before_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530765 """get previous stock ledger entry before current time-bucket"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530766 sle = get_stock_ledger_entries(args, "<", "desc", "limit 1", for_update=False)
767 sle = sle[0] if sle else frappe._dict()
768 return sle
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530769
Nabin Haita77b8c92020-12-21 14:45:50 +0530770 def get_sle_after_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530771 """get Stock Ledger Entries after a particular datetime, for reposting"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530772 return get_stock_ledger_entries(args, ">", "asc", for_update=True, check_serial_no=False)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530773
774 def raise_exceptions(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530775 msg_list = []
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530776 for warehouse, exceptions in self.exceptions.items():
Nabin Haita77b8c92020-12-21 14:45:50 +0530777 deficiency = min(e["diff"] for e in exceptions)
Rushabh Mehta538607e2016-06-12 11:03:00 +0530778
Nabin Haita77b8c92020-12-21 14:45:50 +0530779 if ((exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]) in
780 frappe.local.flags.currently_saving):
Nabin Hait3edefb12016-07-20 16:13:18 +0530781
Nabin Haita77b8c92020-12-21 14:45:50 +0530782 msg = _("{0} units of {1} needed in {2} to complete this transaction.").format(
Nabin Hait243d59b2021-02-02 16:55:13 +0530783 abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]),
Nabin Haita77b8c92020-12-21 14:45:50 +0530784 frappe.get_desk_link('Warehouse', warehouse))
785 else:
786 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 +0530787 abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]),
Nabin Haita77b8c92020-12-21 14:45:50 +0530788 frappe.get_desk_link('Warehouse', warehouse),
789 exceptions[0]["posting_date"], exceptions[0]["posting_time"],
790 frappe.get_desk_link(exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530791
Nabin Haita77b8c92020-12-21 14:45:50 +0530792 if msg:
793 msg_list.append(msg)
794
795 if msg_list:
796 message = "\n\n".join(msg_list)
797 if self.verbose:
798 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
799 else:
800 raise NegativeStockError(message)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530801
Nabin Haita77b8c92020-12-21 14:45:50 +0530802 def update_bin(self):
803 # update bin for each warehouse
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530804 for warehouse, data in self.data.items():
Deepesh Garg6f107da2021-10-12 20:15:55 +0530805 bin_record = get_or_make_bin(self.item_code, warehouse)
806
807 frappe.db.set_value('Bin', bin_record, {
Nabin Haita77b8c92020-12-21 14:45:50 +0530808 "valuation_rate": data.valuation_rate,
809 "actual_qty": data.qty_after_transaction,
810 "stock_value": data.stock_value
811 })
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530812
marination8418c4b2021-06-22 21:35:25 +0530813
814def get_previous_sle_of_current_voucher(args, exclude_current_voucher=False):
815 """get stock ledger entries filtered by specific posting datetime conditions"""
816
817 args['time_format'] = '%H:%i:%s'
818 if not args.get("posting_date"):
819 args["posting_date"] = "1900-01-01"
820 if not args.get("posting_time"):
821 args["posting_time"] = "00:00"
822
823 voucher_condition = ""
824 if exclude_current_voucher:
825 voucher_no = args.get("voucher_no")
826 voucher_condition = f"and voucher_no != '{voucher_no}'"
827
828 sle = frappe.db.sql("""
829 select *, timestamp(posting_date, posting_time) as "timestamp"
830 from `tabStock Ledger Entry`
831 where item_code = %(item_code)s
832 and warehouse = %(warehouse)s
833 and is_cancelled = 0
834 {voucher_condition}
835 and timestamp(posting_date, time_format(posting_time, %(time_format)s)) < timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
836 order by timestamp(posting_date, posting_time) desc, creation desc
837 limit 1
838 for update""".format(voucher_condition=voucher_condition), args, as_dict=1)
839
840 return sle[0] if sle else frappe._dict()
841
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530842def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530843 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530844 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530845 to get actual qty before transaction, this function
846 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530847
Anand Doshi1b531862013-01-10 19:29:51 +0530848 args = {
849 "item_code": "ABC",
850 "warehouse": "XYZ",
851 "posting_date": "2012-12-12",
852 "posting_time": "12:00",
853 "sle": "name of reference Stock Ledger Entry"
854 }
855 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530856 args["name"] = args.get("sle", None) or ""
857 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530858 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530859
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530860def get_stock_ledger_entries(previous_sle, operator=None,
861 order="desc", limit=None, for_update=False, debug=False, check_serial_no=True):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530862 """get stock ledger entries filtered by specific posting datetime conditions"""
Nabin Haitb9ce1042018-02-01 14:58:50 +0530863 conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
864 if previous_sle.get("warehouse"):
865 conditions += " and warehouse = %(warehouse)s"
866 elif previous_sle.get("warehouse_condition"):
867 conditions += " and " + previous_sle.get("warehouse_condition")
868
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530869 if check_serial_no and previous_sle.get("serial_no"):
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530870 # conditions += " and serial_no like {}".format(frappe.db.escape('%{0}%'.format(previous_sle.get("serial_no"))))
871 serial_no = previous_sle.get("serial_no")
872 conditions += (""" and
873 (
874 serial_no = {0}
875 or serial_no like {1}
876 or serial_no like {2}
877 or serial_no like {3}
878 )
879 """).format(frappe.db.escape(serial_no), frappe.db.escape('{}\n%'.format(serial_no)),
880 frappe.db.escape('%\n{}'.format(serial_no)), frappe.db.escape('%\n{}\n%'.format(serial_no)))
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530881
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530882 if not previous_sle.get("posting_date"):
883 previous_sle["posting_date"] = "1900-01-01"
884 if not previous_sle.get("posting_time"):
885 previous_sle["posting_time"] = "00:00"
886
887 if operator in (">", "<=") and previous_sle.get("name"):
888 conditions += " and name!=%(name)s"
889
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530890 return frappe.db.sql("""
891 select *, timestamp(posting_date, posting_time) as "timestamp"
892 from `tabStock Ledger Entry`
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530893 where item_code = %%(item_code)s
Nabin Haita77b8c92020-12-21 14:45:50 +0530894 and is_cancelled = 0
Nabin Haitb9ce1042018-02-01 14:58:50 +0530895 %(conditions)s
Aditya Hase0c164242019-01-07 22:07:13 +0530896 order by timestamp(posting_date, posting_time) %(order)s, creation %(order)s
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530897 %(limit)s %(for_update)s""" % {
898 "conditions": conditions,
899 "limit": limit or "",
900 "for_update": for_update and "for update" or "",
901 "order": order
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530902 }, previous_sle, as_dict=1, debug=debug)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530903
Nabin Haita77b8c92020-12-21 14:45:50 +0530904def get_sle_by_voucher_detail_no(voucher_detail_no, excluded_sle=None):
905 return frappe.db.get_value('Stock Ledger Entry',
906 {'voucher_detail_no': voucher_detail_no, 'name': ['!=', excluded_sle]},
907 ['item_code', 'warehouse', 'posting_date', 'posting_time', 'timestamp(posting_date, posting_time) as timestamp'],
908 as_dict=1)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530909
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530910def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no,
Nabin Hait7ba092e2018-02-01 10:51:27 +0530911 allow_zero_rate=False, currency=None, company=None, raise_error_if_no_rate=True):
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530912
Ankush Menatf7ffe042021-11-01 13:21:14 +0530913 if not company:
914 company = frappe.get_cached_value("Warehouse", warehouse, "company")
915
916 # Get valuation rate from last sle for the same item and warehouse
Nabin Haitfb6e4342014-10-15 11:34:40 +0530917 last_valuation_rate = frappe.db.sql("""select valuation_rate
Deepesh Garg6f107da2021-10-12 20:15:55 +0530918 from `tabStock Ledger Entry` force index (item_warehouse)
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530919 where
920 item_code = %s
921 AND warehouse = %s
922 AND valuation_rate >= 0
923 AND NOT (voucher_no = %s AND voucher_type = %s)
924 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 +0530925
926 if not last_valuation_rate:
Nabin Haita0b967f2017-01-18 18:35:58 +0530927 # Get valuation rate from last sle for the item against any warehouse
Nabin Haitfb6e4342014-10-15 11:34:40 +0530928 last_valuation_rate = frappe.db.sql("""select valuation_rate
Deepesh Garg6f107da2021-10-12 20:15:55 +0530929 from `tabStock Ledger Entry` force index (item_code)
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530930 where
931 item_code = %s
932 AND valuation_rate > 0
933 AND NOT(voucher_no = %s AND voucher_type = %s)
934 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 +0530935
Nabin Haita645f362018-03-01 10:31:24 +0530936 if last_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530937 return flt(last_valuation_rate[0][0])
Nabin Haita645f362018-03-01 10:31:24 +0530938
939 # If negative stock allowed, and item delivered without any incoming entry,
940 # system does not found any SLE, then take valuation rate from Item
941 valuation_rate = frappe.db.get_value("Item", item_code, "valuation_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530942
943 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530944 # try Item Standard rate
945 valuation_rate = frappe.db.get_value("Item", item_code, "standard_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530946
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530947 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530948 # try in price list
949 valuation_rate = frappe.db.get_value('Item Price',
950 dict(item_code=item_code, buying=1, currency=currency),
951 'price_list_rate')
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530952
Nabin Hait7ba092e2018-02-01 10:51:27 +0530953 if not allow_zero_rate and not valuation_rate and raise_error_if_no_rate \
Rohit Waghchauree9ff1912017-06-19 12:54:59 +0530954 and cint(erpnext.is_perpetual_inventory_enabled(company)):
Neil Trini Lasrado193c8912017-03-28 17:39:34 +0530955 frappe.local.message_log = []
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530956 form_link = get_link_to_form("Item", item_code)
Marica97715f22020-05-11 20:45:37 +0530957
958 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 +0530959 message += "<br><br>" + _("Here are the options to proceed:")
Marica97715f22020-05-11 20:45:37 +0530960 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 +0530961 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 +0530962 sub_solutions = "<ul><li>" + _("Create an incoming stock transaction for the Item.") + "</li>"
963 sub_solutions += "<li>" + _("Mention Valuation Rate in the Item master.") + "</li></ul>"
964 msg = message + solutions + sub_solutions + "</li>"
965
966 frappe.throw(msg=msg, title=_("Valuation Rate Missing"))
Nabin Haitfb6e4342014-10-15 11:34:40 +0530967
968 return valuation_rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530969
Ankush Menate7109c12021-08-26 16:40:45 +0530970def update_qty_in_future_sle(args, allow_negative_stock=False):
marination8418c4b2021-06-22 21:35:25 +0530971 """Recalculate Qty after Transaction in future SLEs based on current SLE."""
marination40389772021-07-02 17:13:45 +0530972 datetime_limit_condition = ""
marination8418c4b2021-06-22 21:35:25 +0530973 qty_shift = args.actual_qty
974
975 # find difference/shift in qty caused by stock reconciliation
976 if args.voucher_type == "Stock Reconciliation":
marination40389772021-07-02 17:13:45 +0530977 qty_shift = get_stock_reco_qty_shift(args)
978
979 # find the next nearest stock reco so that we only recalculate SLEs till that point
980 next_stock_reco_detail = get_next_stock_reco(args)
981 if next_stock_reco_detail:
982 detail = next_stock_reco_detail[0]
983 # add condition to update SLEs before this date & time
984 datetime_limit_condition = get_datetime_limit_condition(detail)
marination8418c4b2021-06-22 21:35:25 +0530985
Nabin Hait186a0452021-02-18 14:14:21 +0530986 frappe.db.sql("""
987 update `tabStock Ledger Entry`
marination8418c4b2021-06-22 21:35:25 +0530988 set qty_after_transaction = qty_after_transaction + {qty_shift}
Nabin Hait186a0452021-02-18 14:14:21 +0530989 where
990 item_code = %(item_code)s
991 and warehouse = %(warehouse)s
992 and voucher_no != %(voucher_no)s
993 and is_cancelled = 0
994 and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)
995 or (
996 timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s)
997 and creation > %(creation)s
998 )
999 )
marination40389772021-07-02 17:13:45 +05301000 {datetime_limit_condition}
1001 """.format(qty_shift=qty_shift, datetime_limit_condition=datetime_limit_condition), args)
Nabin Hait186a0452021-02-18 14:14:21 +05301002
1003 validate_negative_qty_in_future_sle(args, allow_negative_stock)
1004
marination40389772021-07-02 17:13:45 +05301005def get_stock_reco_qty_shift(args):
1006 stock_reco_qty_shift = 0
1007 if args.get("is_cancelled"):
1008 if args.get("previous_qty_after_transaction"):
1009 # get qty (balance) that was set at submission
1010 last_balance = args.get("previous_qty_after_transaction")
1011 stock_reco_qty_shift = flt(args.qty_after_transaction) - flt(last_balance)
1012 else:
1013 stock_reco_qty_shift = flt(args.actual_qty)
1014 else:
1015 # reco is being submitted
1016 last_balance = get_previous_sle_of_current_voucher(args,
1017 exclude_current_voucher=True).get("qty_after_transaction")
1018
1019 if last_balance is not None:
1020 stock_reco_qty_shift = flt(args.qty_after_transaction) - flt(last_balance)
1021 else:
1022 stock_reco_qty_shift = args.qty_after_transaction
1023
1024 return stock_reco_qty_shift
1025
1026def get_next_stock_reco(args):
1027 """Returns next nearest stock reconciliaton's details."""
1028
1029 return frappe.db.sql("""
1030 select
1031 name, posting_date, posting_time, creation, voucher_no
1032 from
marination8c441262021-07-02 17:46:05 +05301033 `tabStock Ledger Entry`
marination40389772021-07-02 17:13:45 +05301034 where
1035 item_code = %(item_code)s
1036 and warehouse = %(warehouse)s
1037 and voucher_type = 'Stock Reconciliation'
1038 and voucher_no != %(voucher_no)s
1039 and is_cancelled = 0
1040 and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)
1041 or (
1042 timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s)
1043 and creation > %(creation)s
1044 )
1045 )
1046 limit 1
1047 """, args, as_dict=1)
1048
1049def get_datetime_limit_condition(detail):
marination40389772021-07-02 17:13:45 +05301050 return f"""
1051 and
1052 (timestamp(posting_date, posting_time) < timestamp('{detail.posting_date}', '{detail.posting_time}')
1053 or (
1054 timestamp(posting_date, posting_time) = timestamp('{detail.posting_date}', '{detail.posting_time}')
1055 and creation < '{detail.creation}'
1056 )
1057 )"""
1058
Ankush Menate7109c12021-08-26 16:40:45 +05301059def validate_negative_qty_in_future_sle(args, allow_negative_stock=False):
1060 allow_negative_stock = cint(allow_negative_stock) \
Nabin Haita77b8c92020-12-21 14:45:50 +05301061 or cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
1062
marination8418c4b2021-06-22 21:35:25 +05301063 if (args.actual_qty < 0 or args.voucher_type == "Stock Reconciliation") and not allow_negative_stock:
Nabin Haita77b8c92020-12-21 14:45:50 +05301064 sle = get_future_sle_with_negative_qty(args)
1065 if sle:
1066 message = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
1067 abs(sle[0]["qty_after_transaction"]),
1068 frappe.get_desk_link('Item', args.item_code),
1069 frappe.get_desk_link('Warehouse', args.warehouse),
1070 sle[0]["posting_date"], sle[0]["posting_time"],
1071 frappe.get_desk_link(sle[0]["voucher_type"], sle[0]["voucher_no"]))
Deepesh Gargb4be2922021-01-28 13:09:56 +05301072
Nabin Haita77b8c92020-12-21 14:45:50 +05301073 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
1074
1075def get_future_sle_with_negative_qty(args):
1076 return frappe.db.sql("""
1077 select
1078 qty_after_transaction, posting_date, posting_time,
1079 voucher_type, voucher_no
1080 from `tabStock Ledger Entry`
Deepesh Gargb4be2922021-01-28 13:09:56 +05301081 where
Nabin Haita77b8c92020-12-21 14:45:50 +05301082 item_code = %(item_code)s
1083 and warehouse = %(warehouse)s
1084 and voucher_no != %(voucher_no)s
1085 and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s)
1086 and is_cancelled = 0
Nabin Hait186a0452021-02-18 14:14:21 +05301087 and qty_after_transaction < 0
Nabin Hait243d59b2021-02-02 16:55:13 +05301088 order by timestamp(posting_date, posting_time) asc
Nabin Haita77b8c92020-12-21 14:45:50 +05301089 limit 1
Sagar Vorae50324a2021-03-31 12:44:03 +05301090 """, args, as_dict=1)
Ankush Menat6a014d12021-04-12 20:21:27 +05301091
1092def _round_off_if_near_zero(number: float, precision: int = 6) -> float:
1093 """ Rounds off the number to zero only if number is close to zero for decimal
1094 specified in precision. Precision defaults to 6.
1095 """
1096 if flt(number) < (1.0 / (10**precision)):
1097 return 0
1098
1099 return flt(number)