blob: 542124204b5eee43adf0a771a10ca04edc973387 [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
Anand Doshi56a31652013-11-29 19:15:26 +05303from __future__ import unicode_literals
Nabin Hait902e8602013-01-08 18:29:24 +05304
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +05305import copy
Nabin Hait26d46552013-01-09 15:23:05 +05306import json
Chillar Anand915b3432021-09-02 16:44:59 +05307
8import frappe
9from frappe import _
10from frappe.model.meta import get_field_precision
11from frappe.utils import cint, cstr, flt, get_link_to_form, getdate, now
Achilles Rasquinha361366e2018-02-14 17:08:59 +053012from six import iteritems
13
Chillar Anand915b3432021-09-02 16:44:59 +053014import erpnext
15from erpnext.stock.utils import (
16 get_bin,
17 get_incoming_outgoing_rate_for_cancel,
18 get_valuation_method,
19)
20
Nabin Hait97bce3a2021-07-12 13:24:43 +053021
Nabin Hait902e8602013-01-08 18:29:24 +053022# future reposting
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053023class NegativeStockError(frappe.ValidationError): pass
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +053024class SerialNoExistsInFutureTransaction(frappe.ValidationError):
25 pass
Nabin Hait902e8602013-01-08 18:29:24 +053026
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053027_exceptions = frappe.local('stockledger_exceptions')
Pratik Vyas16371b72013-09-18 18:31:03 +053028# _exceptions = []
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:
Rushabh Mehta1f847992013-12-12 19:12:19 +053033 from erpnext.stock.utils import update_bin
Nabin Haitdc82d4f2014-04-07 12:02:57 +053034
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053035 cancel = sl_entries[0].get("is_cancelled")
Nabin Haitca775742013-09-26 16:16:44 +053036 if cancel:
Nabin Hait186a0452021-02-18 14:14:21 +053037 validate_cancellation(sl_entries)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053038 set_as_cancel(sl_entries[0].get('voucher_type'), sl_entries[0].get('voucher_no'))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053039
Rohit Waghchaure4d81d452021-06-15 10:21:44 +053040 args = get_args_for_future_sle(sl_entries[0])
41 future_sle_exists(args, sl_entries)
42
Nabin Haitca775742013-09-26 16:16:44 +053043 for sle in sl_entries:
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +053044 if sle.serial_no:
45 validate_serial_no(sle)
46
Nabin Haita77b8c92020-12-21 14:45:50 +053047 if cancel:
48 sle['actual_qty'] = -flt(sle.get('actual_qty'))
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053049
Nabin Haita77b8c92020-12-21 14:45:50 +053050 if sle['actual_qty'] < 0 and not sle.get('outgoing_rate'):
51 sle['outgoing_rate'] = get_incoming_outgoing_rate_for_cancel(sle.item_code,
52 sle.voucher_type, sle.voucher_no, sle.voucher_detail_no)
53 sle['incoming_rate'] = 0.0
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053054
Nabin Haita77b8c92020-12-21 14:45:50 +053055 if sle['actual_qty'] > 0 and not sle.get('incoming_rate'):
56 sle['incoming_rate'] = get_incoming_outgoing_rate_for_cancel(sle.item_code,
57 sle.voucher_type, sle.voucher_no, sle.voucher_detail_no)
58 sle['outgoing_rate'] = 0.0
Nabin Haitdc82d4f2014-04-07 12:02:57 +053059
Nabin Hait5288bde2014-11-03 15:08:21 +053060 if sle.get("actual_qty") or sle.get("voucher_type")=="Stock Reconciliation":
Nabin Haita77b8c92020-12-21 14:45:50 +053061 sle_doc = make_entry(sle, allow_negative_stock, via_landed_cost_voucher)
Deepesh Gargb4be2922021-01-28 13:09:56 +053062
Nabin Haita77b8c92020-12-21 14:45:50 +053063 args = sle_doc.as_dict()
marination40389772021-07-02 17:13:45 +053064
65 if sle.get("voucher_type") == "Stock Reconciliation":
66 # preserve previous_qty_after_transaction for qty reposting
67 args.previous_qty_after_transaction = sle.get("previous_qty_after_transaction")
68
Nabin Hait54c865e2015-03-27 15:38:31 +053069 update_bin(args, allow_negative_stock, via_landed_cost_voucher)
Nabin Haitadeb9762014-10-06 11:53:52 +053070
Rohit Waghchaure4d81d452021-06-15 10:21:44 +053071def get_args_for_future_sle(row):
72 return frappe._dict({
73 'voucher_type': row.get('voucher_type'),
74 'voucher_no': row.get('voucher_no'),
75 'posting_date': row.get('posting_date'),
76 'posting_time': row.get('posting_time')
77 })
78
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +053079def validate_serial_no(sle):
80 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
81 for sn in get_serial_nos(sle.serial_no):
82 args = copy.deepcopy(sle)
83 args.serial_no = sn
84 args.warehouse = ''
85
86 vouchers = []
87 for row in get_stock_ledger_entries(args, '>'):
88 voucher_type = frappe.bold(row.voucher_type)
89 voucher_no = frappe.bold(get_link_to_form(row.voucher_type, row.voucher_no))
90 vouchers.append(f'{voucher_type} {voucher_no}')
91
92 if vouchers:
93 serial_no = frappe.bold(sn)
94 msg = (f'''The serial no {serial_no} has been used in the future transactions so you need to cancel them first.
95 The list of the transactions are as below.''' + '<br><br><ul><li>')
96
97 msg += '</li><li>'.join(vouchers)
98 msg += '</li></ul>'
99
100 title = 'Cannot Submit' if not sle.get('is_cancelled') else 'Cannot Cancel'
101 frappe.throw(_(msg), title=_(title), exc=SerialNoExistsInFutureTransaction)
102
Nabin Hait186a0452021-02-18 14:14:21 +0530103def validate_cancellation(args):
104 if args[0].get("is_cancelled"):
105 repost_entry = frappe.db.get_value("Repost Item Valuation", {
106 'voucher_type': args[0].voucher_type,
107 'voucher_no': args[0].voucher_no,
108 'docstatus': 1
109 }, ['name', 'status'], as_dict=1)
110
111 if repost_entry:
112 if repost_entry.status == 'In Progress':
113 frappe.throw(_("Cannot cancel the transaction. Reposting of item valuation on submission is not completed yet."))
114 if repost_entry.status == 'Queued':
Nabin Haitd46b2362021-02-23 16:38:52 +0530115 doc = frappe.get_doc("Repost Item Valuation", repost_entry.name)
116 doc.cancel()
117 doc.delete()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530118
Nabin Hait9653f602013-08-20 15:37:33 +0530119def set_as_cancel(voucher_type, voucher_no):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530120 frappe.db.sql("""update `tabStock Ledger Entry` set is_cancelled=1,
Nabin Hait9653f602013-08-20 15:37:33 +0530121 modified=%s, modified_by=%s
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530122 where voucher_type=%s and voucher_no=%s and is_cancelled = 0""",
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530123 (now(), frappe.session.user, voucher_type, voucher_no))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530124
Nabin Hait54c865e2015-03-27 15:38:31 +0530125def make_entry(args, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Hait74c281c2013-08-19 16:17:18 +0530126 args.update({"doctype": "Stock Ledger Entry"})
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530127 sle = frappe.get_doc(args)
Anand Doshi6dfd4302015-02-10 14:41:27 +0530128 sle.flags.ignore_permissions = 1
Nabin Hait4ccd8d32015-01-23 12:18:01 +0530129 sle.allow_negative_stock=allow_negative_stock
Nabin Hait54c865e2015-03-27 15:38:31 +0530130 sle.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Hait74c281c2013-08-19 16:17:18 +0530131 sle.insert()
Nabin Haitaeba24e2013-08-23 15:17:36 +0530132 sle.submit()
Nabin Haita77b8c92020-12-21 14:45:50 +0530133 return sle
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530134
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530135def 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 +0530136 if not args and voucher_type and voucher_no:
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530137 args = get_items_to_be_repost(voucher_type, voucher_no, doc)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530138
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530139 distinct_item_warehouses = get_distinct_item_warehouse(args, doc)
Nabin Haita77b8c92020-12-21 14:45:50 +0530140
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530141 i = get_current_index(doc) or 0
Nabin Haita77b8c92020-12-21 14:45:50 +0530142 while i < len(args):
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530143 validate_item_warehouse(args[i])
144
Nabin Haita77b8c92020-12-21 14:45:50 +0530145 obj = update_entries_after({
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530146 'item_code': args[i].get('item_code'),
147 'warehouse': args[i].get('warehouse'),
148 'posting_date': args[i].get('posting_date'),
149 'posting_time': args[i].get('posting_time'),
150 'creation': args[i].get('creation'),
151 'distinct_item_warehouses': distinct_item_warehouses
Nabin Haita77b8c92020-12-21 14:45:50 +0530152 }, allow_negative_stock=allow_negative_stock, via_landed_cost_voucher=via_landed_cost_voucher)
153
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530154 distinct_item_warehouses[(args[i].get('item_code'), args[i].get('warehouse'))].reposting_status = True
Deepesh Gargb4be2922021-01-28 13:09:56 +0530155
Nabin Hait97bce3a2021-07-12 13:24:43 +0530156 if obj.new_items_found:
157 for item_wh, data in iteritems(distinct_item_warehouses):
158 if ('args_idx' not in data and not data.reposting_status) or (data.sle_changed and data.reposting_status):
159 data.args_idx = len(args)
160 args.append(data.sle)
161 elif data.sle_changed and not data.reposting_status:
162 args[data.args_idx] = data.sle
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530163
Nabin Hait97bce3a2021-07-12 13:24:43 +0530164 data.sle_changed = False
Nabin Haita77b8c92020-12-21 14:45:50 +0530165 i += 1
166
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530167 if doc and i % 2 == 0:
168 update_args_in_repost_item_valuation(doc, i, args, distinct_item_warehouses)
169
170 if doc and args:
171 update_args_in_repost_item_valuation(doc, i, args, distinct_item_warehouses)
172
173def validate_item_warehouse(args):
174 for field in ['item_code', 'warehouse', 'posting_date', 'posting_time']:
175 if not args.get(field):
176 validation_msg = f'The field {frappe.unscrub(args.get(field))} is required for the reposting'
177 frappe.throw(_(validation_msg))
178
179def update_args_in_repost_item_valuation(doc, index, args, distinct_item_warehouses):
180 frappe.db.set_value(doc.doctype, doc.name, {
181 'items_to_be_repost': json.dumps(args, default=str),
182 'distinct_item_and_warehouse': json.dumps({str(k): v for k,v in distinct_item_warehouses.items()}, default=str),
183 'current_index': index
184 })
185
186 frappe.db.commit()
187
188 frappe.publish_realtime('item_reposting_progress', {
189 'name': doc.name,
190 'items_to_be_repost': json.dumps(args, default=str),
191 'current_index': index
192 })
193
194def get_items_to_be_repost(voucher_type, voucher_no, doc=None):
195 if doc and doc.items_to_be_repost:
196 return json.loads(doc.items_to_be_repost) or []
197
Nabin Haita77b8c92020-12-21 14:45:50 +0530198 return frappe.db.get_all("Stock Ledger Entry",
199 filters={"voucher_type": voucher_type, "voucher_no": voucher_no},
Nabin Hait186a0452021-02-18 14:14:21 +0530200 fields=["item_code", "warehouse", "posting_date", "posting_time", "creation"],
Nabin Haita77b8c92020-12-21 14:45:50 +0530201 order_by="creation asc",
202 group_by="item_code, warehouse"
203 )
Nabin Hait74c281c2013-08-19 16:17:18 +0530204
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530205def get_distinct_item_warehouse(args=None, doc=None):
206 distinct_item_warehouses = {}
207 if doc and doc.distinct_item_and_warehouse:
208 distinct_item_warehouses = json.loads(doc.distinct_item_and_warehouse)
209 distinct_item_warehouses = {frappe.safe_eval(k): frappe._dict(v) for k, v in distinct_item_warehouses.items()}
210 else:
211 for i, d in enumerate(args):
212 distinct_item_warehouses.setdefault((d.item_code, d.warehouse), frappe._dict({
213 "reposting_status": False,
214 "sle": d,
215 "args_idx": i
216 }))
217
218 return distinct_item_warehouses
219
220def get_current_index(doc=None):
221 if doc and doc.current_index:
222 return doc.current_index
223
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530224class update_entries_after(object):
Nabin Hait902e8602013-01-08 18:29:24 +0530225 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530226 update valution rate and qty after transaction
Nabin Hait902e8602013-01-08 18:29:24 +0530227 from the current time-bucket onwards
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530228
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530229 :param args: args as dict
230
231 args = {
232 "item_code": "ABC",
233 "warehouse": "XYZ",
234 "posting_date": "2012-12-12",
235 "posting_time": "12:00"
236 }
Nabin Hait902e8602013-01-08 18:29:24 +0530237 """
Anand Doshi0dc79f42015-04-06 12:59:34 +0530238 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 +0530239 self.exceptions = {}
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530240 self.verbose = verbose
241 self.allow_zero_rate = allow_zero_rate
Anand Doshi0dc79f42015-04-06 12:59:34 +0530242 self.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Haita77b8c92020-12-21 14:45:50 +0530243 self.allow_negative_stock = allow_negative_stock \
244 or cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530245
Nabin Haita77b8c92020-12-21 14:45:50 +0530246 self.args = frappe._dict(args)
247 self.item_code = args.get("item_code")
248 if self.args.sle_id:
249 self.args['name'] = self.args.sle_id
Nabin Haitd46b2362021-02-23 16:38:52 +0530250
Nabin Haita77b8c92020-12-21 14:45:50 +0530251 self.company = frappe.get_cached_value("Warehouse", self.args.warehouse, "company")
252 self.get_precision()
253 self.valuation_method = get_valuation_method(self.item_code)
Nabin Hait97bce3a2021-07-12 13:24:43 +0530254
255 self.new_items_found = False
256 self.distinct_item_warehouses = args.get("distinct_item_warehouses", frappe._dict())
Nabin Haita77b8c92020-12-21 14:45:50 +0530257
258 self.data = frappe._dict()
259 self.initialize_previous_data(self.args)
Nabin Haita77b8c92020-12-21 14:45:50 +0530260 self.build()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530261
Nabin Haita77b8c92020-12-21 14:45:50 +0530262 def get_precision(self):
263 company_base_currency = frappe.get_cached_value('Company', self.company, "default_currency")
264 self.precision = get_field_precision(frappe.get_meta("Stock Ledger Entry").get_field("stock_value"),
265 currency=company_base_currency)
266
267 def initialize_previous_data(self, args):
268 """
269 Get previous sl entries for current item for each related warehouse
270 and assigns into self.data dict
271
272 :Data Structure:
273
274 self.data = {
275 warehouse1: {
276 'previus_sle': {},
277 'qty_after_transaction': 10,
278 'valuation_rate': 100,
279 'stock_value': 1000,
280 'prev_stock_value': 1000,
281 'stock_queue': '[[10, 100]]',
282 'stock_value_difference': 1000
283 }
284 }
285
286 """
Ankush Menatc1d986a2021-08-31 19:43:42 +0530287 self.data.setdefault(args.warehouse, frappe._dict())
288 warehouse_dict = self.data[args.warehouse]
marination8418c4b2021-06-22 21:35:25 +0530289 previous_sle = get_previous_sle_of_current_voucher(args)
Ankush Menatc1d986a2021-08-31 19:43:42 +0530290 warehouse_dict.previous_sle = previous_sle
Nabin Haitbb777562013-08-29 18:19:37 +0530291
Ankush Menatc1d986a2021-08-31 19:43:42 +0530292 for key in ("qty_after_transaction", "valuation_rate", "stock_value"):
293 setattr(warehouse_dict, key, flt(previous_sle.get(key)))
294
295 warehouse_dict.update({
Nabin Haita77b8c92020-12-21 14:45:50 +0530296 "prev_stock_value": previous_sle.stock_value or 0.0,
297 "stock_queue": json.loads(previous_sle.stock_queue or "[]"),
298 "stock_value_difference": 0.0
299 })
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530300
Nabin Haita77b8c92020-12-21 14:45:50 +0530301 def build(self):
Sagar Vorae50324a2021-03-31 12:44:03 +0530302 from erpnext.controllers.stock_controller import future_sle_exists
Nabin Hait186a0452021-02-18 14:14:21 +0530303
Nabin Haita77b8c92020-12-21 14:45:50 +0530304 if self.args.get("sle_id"):
Nabin Hait186a0452021-02-18 14:14:21 +0530305 self.process_sle_against_current_timestamp()
Sagar Vorae50324a2021-03-31 12:44:03 +0530306 if not future_sle_exists(self.args):
Nabin Hait186a0452021-02-18 14:14:21 +0530307 self.update_bin()
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530308 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530309 entries_to_fix = self.get_future_entries_to_fix()
310
311 i = 0
312 while i < len(entries_to_fix):
313 sle = entries_to_fix[i]
314 i += 1
315
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530316 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530317
Nabin Haita77b8c92020-12-21 14:45:50 +0530318 if sle.dependant_sle_voucher_detail_no:
Nabin Hait243d59b2021-02-02 16:55:13 +0530319 entries_to_fix = self.get_dependent_entries_to_fix(entries_to_fix, sle)
Nabin Haitd46b2362021-02-23 16:38:52 +0530320
Nabin Hait186a0452021-02-18 14:14:21 +0530321 self.update_bin()
Nabin Haita77b8c92020-12-21 14:45:50 +0530322
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530323 if self.exceptions:
324 self.raise_exceptions()
325
Nabin Hait186a0452021-02-18 14:14:21 +0530326 def process_sle_against_current_timestamp(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530327 sl_entries = self.get_sle_against_current_voucher()
328 for sle in sl_entries:
329 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530330
Nabin Haita77b8c92020-12-21 14:45:50 +0530331 def get_sle_against_current_voucher(self):
Nabin Haitf2be0802021-02-15 19:27:49 +0530332 self.args['time_format'] = '%H:%i:%s'
333
Nabin Haita77b8c92020-12-21 14:45:50 +0530334 return frappe.db.sql("""
335 select
336 *, timestamp(posting_date, posting_time) as "timestamp"
337 from
338 `tabStock Ledger Entry`
339 where
340 item_code = %(item_code)s
341 and warehouse = %(warehouse)s
rohitwaghchaurefe4540d2021-08-26 12:52:36 +0530342 and is_cancelled = 0
Nabin Hait186a0452021-02-18 14:14:21 +0530343 and timestamp(posting_date, time_format(posting_time, %(time_format)s)) = timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
344
Nabin Haita77b8c92020-12-21 14:45:50 +0530345 order by
346 creation ASC
347 for update
348 """, self.args, as_dict=1)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530349
Nabin Haita77b8c92020-12-21 14:45:50 +0530350 def get_future_entries_to_fix(self):
351 # includes current entry!
352 args = self.data[self.args.warehouse].previous_sle \
353 or frappe._dict({"item_code": self.item_code, "warehouse": self.args.warehouse})
Deepesh Gargb4be2922021-01-28 13:09:56 +0530354
Nabin Haita77b8c92020-12-21 14:45:50 +0530355 return list(self.get_sle_after_datetime(args))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530356
Nabin Haita77b8c92020-12-21 14:45:50 +0530357 def get_dependent_entries_to_fix(self, entries_to_fix, sle):
358 dependant_sle = get_sle_by_voucher_detail_no(sle.dependant_sle_voucher_detail_no,
359 excluded_sle=sle.name)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530360
Nabin Haita77b8c92020-12-21 14:45:50 +0530361 if not dependant_sle:
Nabin Hait243d59b2021-02-02 16:55:13 +0530362 return entries_to_fix
Nabin Haita77b8c92020-12-21 14:45:50 +0530363 elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse == self.args.warehouse:
Nabin Hait243d59b2021-02-02 16:55:13 +0530364 return entries_to_fix
365 elif dependant_sle.item_code != self.item_code:
Nabin Hait97bce3a2021-07-12 13:24:43 +0530366 self.update_distinct_item_warehouses(dependant_sle)
Nabin Hait243d59b2021-02-02 16:55:13 +0530367 return entries_to_fix
368 elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse in self.data:
369 return entries_to_fix
Nabin Hait97bce3a2021-07-12 13:24:43 +0530370 else:
371 return self.append_future_sle_for_dependant(dependant_sle, entries_to_fix)
372
373 def update_distinct_item_warehouses(self, dependant_sle):
374 key = (dependant_sle.item_code, dependant_sle.warehouse)
375 val = frappe._dict({
376 "sle": dependant_sle
377 })
378 if key not in self.distinct_item_warehouses:
379 self.distinct_item_warehouses[key] = val
380 self.new_items_found = True
381 else:
382 existing_sle_posting_date = self.distinct_item_warehouses[key].get("sle", {}).get("posting_date")
383 if getdate(dependant_sle.posting_date) < getdate(existing_sle_posting_date):
384 val.sle_changed = True
385 self.distinct_item_warehouses[key] = val
386 self.new_items_found = True
387
388 def append_future_sle_for_dependant(self, dependant_sle, entries_to_fix):
Nabin Haita77b8c92020-12-21 14:45:50 +0530389 self.initialize_previous_data(dependant_sle)
390
391 args = self.data[dependant_sle.warehouse].previous_sle \
392 or frappe._dict({"item_code": self.item_code, "warehouse": dependant_sle.warehouse})
393 future_sle_for_dependant = list(self.get_sle_after_datetime(args))
394
395 entries_to_fix.extend(future_sle_for_dependant)
Nabin Hait243d59b2021-02-02 16:55:13 +0530396 return sorted(entries_to_fix, key=lambda k: k['timestamp'])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530397
398 def process_sle(self, sle):
Nabin Haita77b8c92020-12-21 14:45:50 +0530399 # previous sle data for this warehouse
400 self.wh_data = self.data[sle.warehouse]
401
Anand Doshi0dc79f42015-04-06 12:59:34 +0530402 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 +0530403 # validate negative stock for serialized items, fifo valuation
Nabin Hait902e8602013-01-08 18:29:24 +0530404 # or when negative stock is not allowed for moving average
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530405 if not self.validate_negative_stock(sle):
Nabin Haita77b8c92020-12-21 14:45:50 +0530406 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530407 return
Nabin Haitb96c0142014-10-07 11:25:04 +0530408
Nabin Haita77b8c92020-12-21 14:45:50 +0530409 # Get dynamic incoming/outgoing rate
410 self.get_dynamic_incoming_outgoing_rate(sle)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530411
Anand Doshi1b531862013-01-10 19:29:51 +0530412 if sle.serial_no:
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530413 self.get_serialized_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530414 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530415 if sle.voucher_type == "Stock Reconciliation":
Nabin Haita77b8c92020-12-21 14:45:50 +0530416 self.wh_data.qty_after_transaction = sle.qty_after_transaction
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530417
Nabin Haita77b8c92020-12-21 14:45:50 +0530418 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 +0530419 else:
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530420 if sle.voucher_type=="Stock Reconciliation" and not sle.batch_no:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530421 # assert
Nabin Haita77b8c92020-12-21 14:45:50 +0530422 self.wh_data.valuation_rate = sle.valuation_rate
423 self.wh_data.qty_after_transaction = sle.qty_after_transaction
424 self.wh_data.stock_queue = [[self.wh_data.qty_after_transaction, self.wh_data.valuation_rate]]
425 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 +0530426 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530427 if self.valuation_method == "Moving Average":
428 self.get_moving_average_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530429 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
430 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 +0530431 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530432 self.get_fifo_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530433 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
434 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 +0530435
Rushabh Mehta54047782013-12-26 11:07:46 +0530436 # rounding as per precision
Nabin Haita77b8c92020-12-21 14:45:50 +0530437 self.wh_data.stock_value = flt(self.wh_data.stock_value, self.precision)
438 stock_value_difference = self.wh_data.stock_value - self.wh_data.prev_stock_value
439 self.wh_data.prev_stock_value = self.wh_data.stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530440
Nabin Hait902e8602013-01-08 18:29:24 +0530441 # update current sle
Nabin Haita77b8c92020-12-21 14:45:50 +0530442 sle.qty_after_transaction = self.wh_data.qty_after_transaction
443 sle.valuation_rate = self.wh_data.valuation_rate
444 sle.stock_value = self.wh_data.stock_value
445 sle.stock_queue = json.dumps(self.wh_data.stock_queue)
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530446 sle.stock_value_difference = stock_value_difference
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530447 sle.doctype="Stock Ledger Entry"
448 frappe.get_doc(sle).db_update()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530449
Nabin Haita77b8c92020-12-21 14:45:50 +0530450 self.update_outgoing_rate_on_transaction(sle)
451
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530452 def validate_negative_stock(self, sle):
453 """
454 validate negative stock for entries current datetime onwards
455 will not consider cancelled entries
456 """
Nabin Haita77b8c92020-12-21 14:45:50 +0530457 diff = self.wh_data.qty_after_transaction + flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530458
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530459 if diff < 0 and abs(diff) > 0.0001:
460 # negative stock!
461 exc = sle.copy().update({"diff": diff})
Nabin Haita77b8c92020-12-21 14:45:50 +0530462 self.exceptions.setdefault(sle.warehouse, []).append(exc)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530463 return False
Nabin Hait902e8602013-01-08 18:29:24 +0530464 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530465 return True
466
Nabin Haita77b8c92020-12-21 14:45:50 +0530467 def get_dynamic_incoming_outgoing_rate(self, sle):
468 # Get updated incoming/outgoing rate from transaction
469 if sle.recalculate_rate:
470 rate = self.get_incoming_outgoing_rate_from_transaction(sle)
471
472 if flt(sle.actual_qty) >= 0:
473 sle.incoming_rate = rate
474 else:
475 sle.outgoing_rate = rate
476
477 def get_incoming_outgoing_rate_from_transaction(self, sle):
478 rate = 0
479 # Material Transfer, Repack, Manufacturing
480 if sle.voucher_type == "Stock Entry":
Nabin Hait97bce3a2021-07-12 13:24:43 +0530481 self.recalculate_amounts_in_stock_entry(sle.voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530482 rate = frappe.db.get_value("Stock Entry Detail", sle.voucher_detail_no, "valuation_rate")
483 # Sales and Purchase Return
484 elif sle.voucher_type in ("Purchase Receipt", "Purchase Invoice", "Delivery Note", "Sales Invoice"):
485 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_return"):
Chillar Anand915b3432021-09-02 16:44:59 +0530486 from erpnext.controllers.sales_and_purchase_return import (
487 get_rate_for_return, # don't move this import to top
488 )
rohitwaghchaurece6c3b52021-04-13 20:55:52 +0530489 rate = get_rate_for_return(sle.voucher_type, sle.voucher_no, sle.item_code,
490 voucher_detail_no=sle.voucher_detail_no, sle = sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530491 else:
492 if sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530493 rate_field = "valuation_rate"
Nabin Haita77b8c92020-12-21 14:45:50 +0530494 else:
495 rate_field = "incoming_rate"
496
497 # check in item table
498 item_code, incoming_rate = frappe.db.get_value(sle.voucher_type + " Item",
499 sle.voucher_detail_no, ["item_code", rate_field])
500
501 if item_code == sle.item_code:
502 rate = incoming_rate
503 else:
504 if sle.voucher_type in ("Delivery Note", "Sales Invoice"):
505 ref_doctype = "Packed Item"
506 else:
507 ref_doctype = "Purchase Receipt Item Supplied"
Deepesh Gargb4be2922021-01-28 13:09:56 +0530508
Nabin Haita77b8c92020-12-21 14:45:50 +0530509 rate = frappe.db.get_value(ref_doctype, {"parent_detail_docname": sle.voucher_detail_no,
510 "item_code": sle.item_code}, rate_field)
511
512 return rate
513
514 def update_outgoing_rate_on_transaction(self, sle):
515 """
516 Update outgoing rate in Stock Entry, Delivery Note, Sales Invoice and Sales Return
517 In case of Stock Entry, also calculate FG Item rate and total incoming/outgoing amount
518 """
519 if sle.actual_qty and sle.voucher_detail_no:
520 outgoing_rate = abs(flt(sle.stock_value_difference)) / abs(sle.actual_qty)
521
522 if flt(sle.actual_qty) < 0 and sle.voucher_type == "Stock Entry":
523 self.update_rate_on_stock_entry(sle, outgoing_rate)
524 elif sle.voucher_type in ("Delivery Note", "Sales Invoice"):
525 self.update_rate_on_delivery_and_sales_return(sle, outgoing_rate)
526 elif flt(sle.actual_qty) < 0 and sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
527 self.update_rate_on_purchase_receipt(sle, outgoing_rate)
528
529 def update_rate_on_stock_entry(self, sle, outgoing_rate):
530 frappe.db.set_value("Stock Entry Detail", sle.voucher_detail_no, "basic_rate", outgoing_rate)
531
532 # Update outgoing item's rate, recalculate FG Item's rate and total incoming/outgoing amount
Nabin Hait97bce3a2021-07-12 13:24:43 +0530533 if not sle.dependant_sle_voucher_detail_no:
534 self.recalculate_amounts_in_stock_entry(sle.voucher_no)
535
536 def recalculate_amounts_in_stock_entry(self, voucher_no):
537 stock_entry = frappe.get_doc("Stock Entry", voucher_no, for_update=True)
Nabin Haita77b8c92020-12-21 14:45:50 +0530538 stock_entry.calculate_rate_and_amount(reset_outgoing_rate=False, raise_error_if_no_rate=False)
539 stock_entry.db_update()
540 for d in stock_entry.items:
541 d.db_update()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530542
Nabin Haita77b8c92020-12-21 14:45:50 +0530543 def update_rate_on_delivery_and_sales_return(self, sle, outgoing_rate):
544 # Update item's incoming rate on transaction
545 item_code = frappe.db.get_value(sle.voucher_type + " Item", sle.voucher_detail_no, "item_code")
546 if item_code == sle.item_code:
547 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "incoming_rate", outgoing_rate)
548 else:
549 # packed item
550 frappe.db.set_value("Packed Item",
551 {"parent_detail_docname": sle.voucher_detail_no, "item_code": sle.item_code},
552 "incoming_rate", outgoing_rate)
553
554 def update_rate_on_purchase_receipt(self, sle, outgoing_rate):
555 if frappe.db.exists(sle.voucher_type + " Item", sle.voucher_detail_no):
556 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "base_net_rate", outgoing_rate)
557 else:
558 frappe.db.set_value("Purchase Receipt Item Supplied", sle.voucher_detail_no, "rate", outgoing_rate)
559
560 # Recalculate subcontracted item's rate in case of subcontracted purchase receipt/invoice
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530561 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_subcontracted") == 'Yes':
Rohit Waghchauree5fb2392021-06-18 20:37:42 +0530562 doc = frappe.get_doc(sle.voucher_type, sle.voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530563 doc.update_valuation_rate(reset_outgoing_rate=False)
564 for d in (doc.items + doc.supplied_items):
565 d.db_update()
566
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530567 def get_serialized_values(self, sle):
568 incoming_rate = flt(sle.incoming_rate)
569 actual_qty = flt(sle.actual_qty)
Nabin Hait328c4f92020-01-02 19:00:32 +0530570 serial_nos = cstr(sle.serial_no).split("\n")
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530571
572 if incoming_rate < 0:
573 # wrong incoming rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530574 incoming_rate = self.wh_data.valuation_rate
Rushabh Mehta538607e2016-06-12 11:03:00 +0530575
Nabin Hait2620bf42016-02-29 11:30:27 +0530576 stock_value_change = 0
577 if incoming_rate:
578 stock_value_change = actual_qty * incoming_rate
579 elif actual_qty < 0:
580 # In case of delivery/stock issue, get average purchase rate
581 # of serial nos of current entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530582 if not sle.is_cancelled:
583 outgoing_value = self.get_incoming_value_for_serial_nos(sle, serial_nos)
584 stock_value_change = -1 * outgoing_value
585 else:
586 stock_value_change = actual_qty * sle.outgoing_rate
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530587
Nabin Haita77b8c92020-12-21 14:45:50 +0530588 new_stock_qty = self.wh_data.qty_after_transaction + actual_qty
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530589
Nabin Hait2620bf42016-02-29 11:30:27 +0530590 if new_stock_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530591 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + stock_value_change
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530592 if new_stock_value >= 0:
Nabin Hait2620bf42016-02-29 11:30:27 +0530593 # calculate new valuation rate only if stock value is positive
594 # else it remains the same as that of previous entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530595 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530596
Nabin Haita77b8c92020-12-21 14:45:50 +0530597 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530598 allow_zero_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
599 if not allow_zero_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530600 self.wh_data.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530601 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
602 currency=erpnext.get_company_currency(sle.company))
603
Nabin Hait328c4f92020-01-02 19:00:32 +0530604 def get_incoming_value_for_serial_nos(self, sle, serial_nos):
605 # get rate from serial nos within same company
606 all_serial_nos = frappe.get_all("Serial No",
607 fields=["purchase_rate", "name", "company"],
608 filters = {'name': ('in', serial_nos)})
609
Ankush Menat98917802021-06-11 18:40:22 +0530610 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 +0530611
612 # Get rate for serial nos which has been transferred to other company
613 invalid_serial_nos = [d.name for d in all_serial_nos if d.company!=sle.company]
614 for serial_no in invalid_serial_nos:
615 incoming_rate = frappe.db.sql("""
616 select incoming_rate
617 from `tabStock Ledger Entry`
618 where
619 company = %s
620 and actual_qty > 0
621 and (serial_no = %s
622 or serial_no like %s
623 or serial_no like %s
624 or serial_no like %s
625 )
626 order by posting_date desc
627 limit 1
628 """, (sle.company, serial_no, serial_no+'\n%', '%\n'+serial_no, '%\n'+serial_no+'\n%'))
629
630 incoming_values += flt(incoming_rate[0][0]) if incoming_rate else 0
631
632 return incoming_values
633
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530634 def get_moving_average_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530635 actual_qty = flt(sle.actual_qty)
Nabin Haita77b8c92020-12-21 14:45:50 +0530636 new_stock_qty = flt(self.wh_data.qty_after_transaction) + actual_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530637 if new_stock_qty >= 0:
638 if actual_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530639 if flt(self.wh_data.qty_after_transaction) <= 0:
640 self.wh_data.valuation_rate = sle.incoming_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530641 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530642 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530643 (actual_qty * sle.incoming_rate)
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530644
Nabin Haita77b8c92020-12-21 14:45:50 +0530645 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530646
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530647 elif sle.outgoing_rate:
648 if new_stock_qty:
Nabin Haita77b8c92020-12-21 14:45:50 +0530649 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530650 (actual_qty * sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530651
Nabin Haita77b8c92020-12-21 14:45:50 +0530652 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530653 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530654 self.wh_data.valuation_rate = sle.outgoing_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530655 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530656 if flt(self.wh_data.qty_after_transaction) >= 0 and sle.outgoing_rate:
657 self.wh_data.valuation_rate = sle.outgoing_rate
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530658
Nabin Haita77b8c92020-12-21 14:45:50 +0530659 if not self.wh_data.valuation_rate and actual_qty > 0:
660 self.wh_data.valuation_rate = sle.incoming_rate
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530661
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530662 # Get valuation rate from previous SLE or Item master, if item does not have the
Javier Wong9b11d9b2017-04-14 18:24:04 +0800663 # allow zero valuration rate flag set
Nabin Haita77b8c92020-12-21 14:45:50 +0530664 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
Javier Wong9b11d9b2017-04-14 18:24:04 +0800665 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
666 if not allow_zero_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530667 self.wh_data.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530668 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
669 currency=erpnext.get_company_currency(sle.company))
670
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530671 def get_fifo_values(self, sle):
672 incoming_rate = flt(sle.incoming_rate)
673 actual_qty = flt(sle.actual_qty)
Nabin Haitada485f2015-07-17 15:09:56 +0530674 outgoing_rate = flt(sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530675
676 if actual_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530677 if not self.wh_data.stock_queue:
678 self.wh_data.stock_queue.append([0, 0])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530679
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530680 # last row has the same rate, just updated the qty
Nabin Haita77b8c92020-12-21 14:45:50 +0530681 if self.wh_data.stock_queue[-1][1]==incoming_rate:
682 self.wh_data.stock_queue[-1][0] += actual_qty
Nabin Hait4d742162014-10-09 19:25:03 +0530683 else:
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])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530686 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530687 qty = self.wh_data.stock_queue[-1][0] + actual_qty
688 self.wh_data.stock_queue[-1] = [qty, incoming_rate]
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530689 else:
690 qty_to_pop = abs(actual_qty)
691 while qty_to_pop:
Nabin Haita77b8c92020-12-21 14:45:50 +0530692 if not self.wh_data.stock_queue:
Nabin Haita0b967f2017-01-18 18:35:58 +0530693 # Get valuation rate from last sle if exists or from valuation rate field in item master
Javier Wong9b11d9b2017-04-14 18:24:04 +0800694 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
695 if not allow_zero_valuation_rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530696 _rate = get_valuation_rate(sle.item_code, sle.warehouse,
697 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
698 currency=erpnext.get_company_currency(sle.company))
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530699 else:
700 _rate = 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530701
Nabin Haita77b8c92020-12-21 14:45:50 +0530702 self.wh_data.stock_queue.append([0, _rate])
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530703
Nabin Haitada485f2015-07-17 15:09:56 +0530704 index = None
705 if outgoing_rate > 0:
706 # Find the entry where rate matched with outgoing rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530707 for i, v in enumerate(self.wh_data.stock_queue):
Nabin Haitada485f2015-07-17 15:09:56 +0530708 if v[1] == outgoing_rate:
709 index = i
710 break
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530711
Nabin Haitada485f2015-07-17 15:09:56 +0530712 # If no entry found with outgoing rate, collapse stack
Ankush Menat4dcac4a2021-05-21 13:12:30 +0530713 if index is None: # nosemgrep
Nabin Haita77b8c92020-12-21 14:45:50 +0530714 new_stock_value = sum((d[0]*d[1] for d in self.wh_data.stock_queue)) - qty_to_pop*outgoing_rate
715 new_stock_qty = sum((d[0] for d in self.wh_data.stock_queue)) - qty_to_pop
716 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 +0530717 break
718 else:
719 index = 0
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530720
Nabin Haitada485f2015-07-17 15:09:56 +0530721 # select first batch or the batch with same rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530722 batch = self.wh_data.stock_queue[index]
Nabin Hait8142cd22015-08-05 18:57:26 +0530723 if qty_to_pop >= batch[0]:
724 # consume current batch
Ankush Menat6a014d12021-04-12 20:21:27 +0530725 qty_to_pop = _round_off_if_near_zero(qty_to_pop - batch[0])
Nabin Haita77b8c92020-12-21 14:45:50 +0530726 self.wh_data.stock_queue.pop(index)
727 if not self.wh_data.stock_queue and qty_to_pop:
Nabin Hait8142cd22015-08-05 18:57:26 +0530728 # stock finished, qty still remains to be withdrawn
729 # negative stock, keep in as a negative batch
Nabin Haita77b8c92020-12-21 14:45:50 +0530730 self.wh_data.stock_queue.append([-qty_to_pop, outgoing_rate or batch[1]])
Nabin Hait8142cd22015-08-05 18:57:26 +0530731 break
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530732
Nabin Hait8142cd22015-08-05 18:57:26 +0530733 else:
734 # qty found in current batch
735 # consume it and exit
736 batch[0] = batch[0] - qty_to_pop
737 qty_to_pop = 0
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530738
Ankush Menat6a014d12021-04-12 20:21:27 +0530739 stock_value = _round_off_if_near_zero(sum((flt(batch[0]) * flt(batch[1]) for batch in self.wh_data.stock_queue)))
740 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 +0530741
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530742 if stock_qty:
Nabin Haita77b8c92020-12-21 14:45:50 +0530743 self.wh_data.valuation_rate = stock_value / flt(stock_qty)
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530744
Nabin Haita77b8c92020-12-21 14:45:50 +0530745 if not self.wh_data.stock_queue:
746 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 +0530747
Javier Wong9b11d9b2017-04-14 18:24:04 +0800748 def check_if_allow_zero_valuation_rate(self, voucher_type, voucher_detail_no):
deepeshgarg007f9c0ef32019-07-30 18:49:19 +0530749 ref_item_dt = ""
750
751 if voucher_type == "Stock Entry":
752 ref_item_dt = voucher_type + " Detail"
753 elif voucher_type in ["Purchase Invoice", "Sales Invoice", "Delivery Note", "Purchase Receipt"]:
754 ref_item_dt = voucher_type + " Item"
755
756 if ref_item_dt:
757 return frappe.db.get_value(ref_item_dt, voucher_detail_no, "allow_zero_valuation_rate")
758 else:
759 return 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530760
Nabin Haita77b8c92020-12-21 14:45:50 +0530761 def get_sle_before_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530762 """get previous stock ledger entry before current time-bucket"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530763 sle = get_stock_ledger_entries(args, "<", "desc", "limit 1", for_update=False)
764 sle = sle[0] if sle else frappe._dict()
765 return sle
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530766
Nabin Haita77b8c92020-12-21 14:45:50 +0530767 def get_sle_after_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530768 """get Stock Ledger Entries after a particular datetime, for reposting"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530769 return get_stock_ledger_entries(args, ">", "asc", for_update=True, check_serial_no=False)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530770
771 def raise_exceptions(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530772 msg_list = []
773 for warehouse, exceptions in iteritems(self.exceptions):
774 deficiency = min(e["diff"] for e in exceptions)
Rushabh Mehta538607e2016-06-12 11:03:00 +0530775
Nabin Haita77b8c92020-12-21 14:45:50 +0530776 if ((exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]) in
777 frappe.local.flags.currently_saving):
Nabin Hait3edefb12016-07-20 16:13:18 +0530778
Nabin Haita77b8c92020-12-21 14:45:50 +0530779 msg = _("{0} units of {1} needed in {2} to complete this transaction.").format(
Nabin Hait243d59b2021-02-02 16:55:13 +0530780 abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]),
Nabin Haita77b8c92020-12-21 14:45:50 +0530781 frappe.get_desk_link('Warehouse', warehouse))
782 else:
783 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 +0530784 abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]),
Nabin Haita77b8c92020-12-21 14:45:50 +0530785 frappe.get_desk_link('Warehouse', warehouse),
786 exceptions[0]["posting_date"], exceptions[0]["posting_time"],
787 frappe.get_desk_link(exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530788
Nabin Haita77b8c92020-12-21 14:45:50 +0530789 if msg:
790 msg_list.append(msg)
791
792 if msg_list:
793 message = "\n\n".join(msg_list)
794 if self.verbose:
795 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
796 else:
797 raise NegativeStockError(message)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530798
Nabin Haita77b8c92020-12-21 14:45:50 +0530799 def update_bin(self):
800 # update bin for each warehouse
801 for warehouse, data in iteritems(self.data):
802 bin_doc = get_bin(self.item_code, warehouse)
Nabin Haita77b8c92020-12-21 14:45:50 +0530803 bin_doc.update({
804 "valuation_rate": data.valuation_rate,
805 "actual_qty": data.qty_after_transaction,
806 "stock_value": data.stock_value
807 })
808 bin_doc.flags.via_stock_ledger_entry = True
809 bin_doc.save(ignore_permissions=True)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530810
marination8418c4b2021-06-22 21:35:25 +0530811
812def get_previous_sle_of_current_voucher(args, exclude_current_voucher=False):
813 """get stock ledger entries filtered by specific posting datetime conditions"""
814
815 args['time_format'] = '%H:%i:%s'
816 if not args.get("posting_date"):
817 args["posting_date"] = "1900-01-01"
818 if not args.get("posting_time"):
819 args["posting_time"] = "00:00"
820
821 voucher_condition = ""
822 if exclude_current_voucher:
823 voucher_no = args.get("voucher_no")
824 voucher_condition = f"and voucher_no != '{voucher_no}'"
825
826 sle = frappe.db.sql("""
827 select *, timestamp(posting_date, posting_time) as "timestamp"
828 from `tabStock Ledger Entry`
829 where item_code = %(item_code)s
830 and warehouse = %(warehouse)s
831 and is_cancelled = 0
832 {voucher_condition}
833 and timestamp(posting_date, time_format(posting_time, %(time_format)s)) < timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
834 order by timestamp(posting_date, posting_time) desc, creation desc
835 limit 1
836 for update""".format(voucher_condition=voucher_condition), args, as_dict=1)
837
838 return sle[0] if sle else frappe._dict()
839
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530840def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530841 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530842 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530843 to get actual qty before transaction, this function
844 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530845
Anand Doshi1b531862013-01-10 19:29:51 +0530846 args = {
847 "item_code": "ABC",
848 "warehouse": "XYZ",
849 "posting_date": "2012-12-12",
850 "posting_time": "12:00",
851 "sle": "name of reference Stock Ledger Entry"
852 }
853 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530854 args["name"] = args.get("sle", None) or ""
855 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530856 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530857
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530858def get_stock_ledger_entries(previous_sle, operator=None,
859 order="desc", limit=None, for_update=False, debug=False, check_serial_no=True):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530860 """get stock ledger entries filtered by specific posting datetime conditions"""
Nabin Haitb9ce1042018-02-01 14:58:50 +0530861 conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
862 if previous_sle.get("warehouse"):
863 conditions += " and warehouse = %(warehouse)s"
864 elif previous_sle.get("warehouse_condition"):
865 conditions += " and " + previous_sle.get("warehouse_condition")
866
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530867 if check_serial_no and previous_sle.get("serial_no"):
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530868 # conditions += " and serial_no like {}".format(frappe.db.escape('%{0}%'.format(previous_sle.get("serial_no"))))
869 serial_no = previous_sle.get("serial_no")
870 conditions += (""" and
871 (
872 serial_no = {0}
873 or serial_no like {1}
874 or serial_no like {2}
875 or serial_no like {3}
876 )
877 """).format(frappe.db.escape(serial_no), frappe.db.escape('{}\n%'.format(serial_no)),
878 frappe.db.escape('%\n{}'.format(serial_no)), frappe.db.escape('%\n{}\n%'.format(serial_no)))
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530879
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530880 if not previous_sle.get("posting_date"):
881 previous_sle["posting_date"] = "1900-01-01"
882 if not previous_sle.get("posting_time"):
883 previous_sle["posting_time"] = "00:00"
884
885 if operator in (">", "<=") and previous_sle.get("name"):
886 conditions += " and name!=%(name)s"
887
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530888 return frappe.db.sql("""
889 select *, timestamp(posting_date, posting_time) as "timestamp"
890 from `tabStock Ledger Entry`
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530891 where item_code = %%(item_code)s
Nabin Haita77b8c92020-12-21 14:45:50 +0530892 and is_cancelled = 0
Nabin Haitb9ce1042018-02-01 14:58:50 +0530893 %(conditions)s
Aditya Hase0c164242019-01-07 22:07:13 +0530894 order by timestamp(posting_date, posting_time) %(order)s, creation %(order)s
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530895 %(limit)s %(for_update)s""" % {
896 "conditions": conditions,
897 "limit": limit or "",
898 "for_update": for_update and "for update" or "",
899 "order": order
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530900 }, previous_sle, as_dict=1, debug=debug)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530901
Nabin Haita77b8c92020-12-21 14:45:50 +0530902def get_sle_by_voucher_detail_no(voucher_detail_no, excluded_sle=None):
903 return frappe.db.get_value('Stock Ledger Entry',
904 {'voucher_detail_no': voucher_detail_no, 'name': ['!=', excluded_sle]},
905 ['item_code', 'warehouse', 'posting_date', 'posting_time', 'timestamp(posting_date, posting_time) as timestamp'],
906 as_dict=1)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530907
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530908def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no,
Nabin Hait7ba092e2018-02-01 10:51:27 +0530909 allow_zero_rate=False, currency=None, company=None, raise_error_if_no_rate=True):
Nabin Haita0b967f2017-01-18 18:35:58 +0530910 # Get valuation rate from last sle for the same item and warehouse
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530911 if not company:
912 company = erpnext.get_default_company()
913
Nabin Haitfb6e4342014-10-15 11:34:40 +0530914 last_valuation_rate = frappe.db.sql("""select valuation_rate
915 from `tabStock Ledger Entry`
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530916 where
917 item_code = %s
918 AND warehouse = %s
919 AND valuation_rate >= 0
920 AND NOT (voucher_no = %s AND voucher_type = %s)
921 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 +0530922
923 if not last_valuation_rate:
Nabin Haita0b967f2017-01-18 18:35:58 +0530924 # Get valuation rate from last sle for the item against any warehouse
Nabin Haitfb6e4342014-10-15 11:34:40 +0530925 last_valuation_rate = frappe.db.sql("""select valuation_rate
926 from `tabStock Ledger Entry`
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530927 where
928 item_code = %s
929 AND valuation_rate > 0
930 AND NOT(voucher_no = %s AND voucher_type = %s)
931 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 +0530932
Nabin Haita645f362018-03-01 10:31:24 +0530933 if last_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530934 return flt(last_valuation_rate[0][0])
Nabin Haita645f362018-03-01 10:31:24 +0530935
936 # If negative stock allowed, and item delivered without any incoming entry,
937 # system does not found any SLE, then take valuation rate from Item
938 valuation_rate = frappe.db.get_value("Item", item_code, "valuation_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530939
940 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530941 # try Item Standard rate
942 valuation_rate = frappe.db.get_value("Item", item_code, "standard_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530943
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530944 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530945 # try in price list
946 valuation_rate = frappe.db.get_value('Item Price',
947 dict(item_code=item_code, buying=1, currency=currency),
948 'price_list_rate')
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530949
Nabin Hait7ba092e2018-02-01 10:51:27 +0530950 if not allow_zero_rate and not valuation_rate and raise_error_if_no_rate \
Rohit Waghchauree9ff1912017-06-19 12:54:59 +0530951 and cint(erpnext.is_perpetual_inventory_enabled(company)):
Neil Trini Lasrado193c8912017-03-28 17:39:34 +0530952 frappe.local.message_log = []
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530953 form_link = get_link_to_form("Item", item_code)
Marica97715f22020-05-11 20:45:37 +0530954
955 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 +0530956 message += "<br><br>" + _("Here are the options to proceed:")
Marica97715f22020-05-11 20:45:37 +0530957 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 +0530958 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 +0530959 sub_solutions = "<ul><li>" + _("Create an incoming stock transaction for the Item.") + "</li>"
960 sub_solutions += "<li>" + _("Mention Valuation Rate in the Item master.") + "</li></ul>"
961 msg = message + solutions + sub_solutions + "</li>"
962
963 frappe.throw(msg=msg, title=_("Valuation Rate Missing"))
Nabin Haitfb6e4342014-10-15 11:34:40 +0530964
965 return valuation_rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530966
Ankush Menate7109c12021-08-26 16:40:45 +0530967def update_qty_in_future_sle(args, allow_negative_stock=False):
marination8418c4b2021-06-22 21:35:25 +0530968 """Recalculate Qty after Transaction in future SLEs based on current SLE."""
marination40389772021-07-02 17:13:45 +0530969 datetime_limit_condition = ""
marination8418c4b2021-06-22 21:35:25 +0530970 qty_shift = args.actual_qty
971
972 # find difference/shift in qty caused by stock reconciliation
973 if args.voucher_type == "Stock Reconciliation":
marination40389772021-07-02 17:13:45 +0530974 qty_shift = get_stock_reco_qty_shift(args)
975
976 # find the next nearest stock reco so that we only recalculate SLEs till that point
977 next_stock_reco_detail = get_next_stock_reco(args)
978 if next_stock_reco_detail:
979 detail = next_stock_reco_detail[0]
980 # add condition to update SLEs before this date & time
981 datetime_limit_condition = get_datetime_limit_condition(detail)
marination8418c4b2021-06-22 21:35:25 +0530982
Nabin Hait186a0452021-02-18 14:14:21 +0530983 frappe.db.sql("""
984 update `tabStock Ledger Entry`
marination8418c4b2021-06-22 21:35:25 +0530985 set qty_after_transaction = qty_after_transaction + {qty_shift}
Nabin Hait186a0452021-02-18 14:14:21 +0530986 where
987 item_code = %(item_code)s
988 and warehouse = %(warehouse)s
989 and voucher_no != %(voucher_no)s
990 and is_cancelled = 0
991 and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)
992 or (
993 timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s)
994 and creation > %(creation)s
995 )
996 )
marination40389772021-07-02 17:13:45 +0530997 {datetime_limit_condition}
998 """.format(qty_shift=qty_shift, datetime_limit_condition=datetime_limit_condition), args)
Nabin Hait186a0452021-02-18 14:14:21 +0530999
1000 validate_negative_qty_in_future_sle(args, allow_negative_stock)
1001
marination40389772021-07-02 17:13:45 +05301002def get_stock_reco_qty_shift(args):
1003 stock_reco_qty_shift = 0
1004 if args.get("is_cancelled"):
1005 if args.get("previous_qty_after_transaction"):
1006 # get qty (balance) that was set at submission
1007 last_balance = args.get("previous_qty_after_transaction")
1008 stock_reco_qty_shift = flt(args.qty_after_transaction) - flt(last_balance)
1009 else:
1010 stock_reco_qty_shift = flt(args.actual_qty)
1011 else:
1012 # reco is being submitted
1013 last_balance = get_previous_sle_of_current_voucher(args,
1014 exclude_current_voucher=True).get("qty_after_transaction")
1015
1016 if last_balance is not None:
1017 stock_reco_qty_shift = flt(args.qty_after_transaction) - flt(last_balance)
1018 else:
1019 stock_reco_qty_shift = args.qty_after_transaction
1020
1021 return stock_reco_qty_shift
1022
1023def get_next_stock_reco(args):
1024 """Returns next nearest stock reconciliaton's details."""
1025
1026 return frappe.db.sql("""
1027 select
1028 name, posting_date, posting_time, creation, voucher_no
1029 from
marination8c441262021-07-02 17:46:05 +05301030 `tabStock Ledger Entry`
marination40389772021-07-02 17:13:45 +05301031 where
1032 item_code = %(item_code)s
1033 and warehouse = %(warehouse)s
1034 and voucher_type = 'Stock Reconciliation'
1035 and voucher_no != %(voucher_no)s
1036 and is_cancelled = 0
1037 and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)
1038 or (
1039 timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s)
1040 and creation > %(creation)s
1041 )
1042 )
1043 limit 1
1044 """, args, as_dict=1)
1045
1046def get_datetime_limit_condition(detail):
marination40389772021-07-02 17:13:45 +05301047 return f"""
1048 and
1049 (timestamp(posting_date, posting_time) < timestamp('{detail.posting_date}', '{detail.posting_time}')
1050 or (
1051 timestamp(posting_date, posting_time) = timestamp('{detail.posting_date}', '{detail.posting_time}')
1052 and creation < '{detail.creation}'
1053 )
1054 )"""
1055
Ankush Menate7109c12021-08-26 16:40:45 +05301056def validate_negative_qty_in_future_sle(args, allow_negative_stock=False):
1057 allow_negative_stock = cint(allow_negative_stock) \
Nabin Haita77b8c92020-12-21 14:45:50 +05301058 or cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
1059
marination8418c4b2021-06-22 21:35:25 +05301060 if (args.actual_qty < 0 or args.voucher_type == "Stock Reconciliation") and not allow_negative_stock:
Nabin Haita77b8c92020-12-21 14:45:50 +05301061 sle = get_future_sle_with_negative_qty(args)
1062 if sle:
1063 message = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
1064 abs(sle[0]["qty_after_transaction"]),
1065 frappe.get_desk_link('Item', args.item_code),
1066 frappe.get_desk_link('Warehouse', args.warehouse),
1067 sle[0]["posting_date"], sle[0]["posting_time"],
1068 frappe.get_desk_link(sle[0]["voucher_type"], sle[0]["voucher_no"]))
Deepesh Gargb4be2922021-01-28 13:09:56 +05301069
Nabin Haita77b8c92020-12-21 14:45:50 +05301070 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
1071
1072def get_future_sle_with_negative_qty(args):
1073 return frappe.db.sql("""
1074 select
1075 qty_after_transaction, posting_date, posting_time,
1076 voucher_type, voucher_no
1077 from `tabStock Ledger Entry`
Deepesh Gargb4be2922021-01-28 13:09:56 +05301078 where
Nabin Haita77b8c92020-12-21 14:45:50 +05301079 item_code = %(item_code)s
1080 and warehouse = %(warehouse)s
1081 and voucher_no != %(voucher_no)s
1082 and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s)
1083 and is_cancelled = 0
Nabin Hait186a0452021-02-18 14:14:21 +05301084 and qty_after_transaction < 0
Nabin Hait243d59b2021-02-02 16:55:13 +05301085 order by timestamp(posting_date, posting_time) asc
Nabin Haita77b8c92020-12-21 14:45:50 +05301086 limit 1
Sagar Vorae50324a2021-03-31 12:44:03 +05301087 """, args, as_dict=1)
Ankush Menat6a014d12021-04-12 20:21:27 +05301088
1089def _round_off_if_near_zero(number: float, precision: int = 6) -> float:
1090 """ Rounds off the number to zero only if number is close to zero for decimal
1091 specified in precision. Precision defaults to 6.
1092 """
1093 if flt(number) < (1.0 / (10**precision)):
1094 return 0
1095
1096 return flt(number)