blob: 48fd7d3d26195dad4eda02a0164a74b29d4ee8da [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 frappe
6import erpnext
7import copy
Rushabh Mehta9f0d6252014-04-14 19:20:45 +05308from frappe import _
Nabin Hait97bce3a2021-07-12 13:24:43 +05309from frappe.utils import cint, flt, cstr, now, get_link_to_form, getdate
Nabin Haita77b8c92020-12-21 14:45:50 +053010from frappe.model.meta import get_field_precision
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053011from erpnext.stock.utils import get_valuation_method, get_incoming_outgoing_rate_for_cancel
Nabin Haita77b8c92020-12-21 14:45:50 +053012from erpnext.stock.utils import get_bin
Nabin Hait26d46552013-01-09 15:23:05 +053013import json
Achilles Rasquinha361366e2018-02-14 17:08:59 +053014from six import iteritems
15
Nabin Hait97bce3a2021-07-12 13:24:43 +053016
Nabin Hait902e8602013-01-08 18:29:24 +053017# future reposting
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053018class NegativeStockError(frappe.ValidationError): pass
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +053019class SerialNoExistsInFutureTransaction(frappe.ValidationError):
20 pass
Nabin Hait902e8602013-01-08 18:29:24 +053021
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053022_exceptions = frappe.local('stockledger_exceptions')
Pratik Vyas16371b72013-09-18 18:31:03 +053023# _exceptions = []
Anand Doshi5b004ff2013-09-25 19:55:41 +053024
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053025def make_sl_entries(sl_entries, allow_negative_stock=False, via_landed_cost_voucher=False):
Rohit Waghchaure4d81d452021-06-15 10:21:44 +053026 from erpnext.controllers.stock_controller import future_sle_exists
Nabin Haitca775742013-09-26 16:16:44 +053027 if sl_entries:
Rushabh Mehta1f847992013-12-12 19:12:19 +053028 from erpnext.stock.utils import update_bin
Nabin Haitdc82d4f2014-04-07 12:02:57 +053029
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053030 cancel = sl_entries[0].get("is_cancelled")
Nabin Haitca775742013-09-26 16:16:44 +053031 if cancel:
Nabin Hait186a0452021-02-18 14:14:21 +053032 validate_cancellation(sl_entries)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053033 set_as_cancel(sl_entries[0].get('voucher_type'), sl_entries[0].get('voucher_no'))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053034
Rohit Waghchaure4d81d452021-06-15 10:21:44 +053035 args = get_args_for_future_sle(sl_entries[0])
36 future_sle_exists(args, sl_entries)
37
Nabin Haitca775742013-09-26 16:16:44 +053038 for sle in sl_entries:
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +053039 if sle.serial_no:
40 validate_serial_no(sle)
41
Nabin Haita77b8c92020-12-21 14:45:50 +053042 if cancel:
43 sle['actual_qty'] = -flt(sle.get('actual_qty'))
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053044
Nabin Haita77b8c92020-12-21 14:45:50 +053045 if sle['actual_qty'] < 0 and not sle.get('outgoing_rate'):
46 sle['outgoing_rate'] = get_incoming_outgoing_rate_for_cancel(sle.item_code,
47 sle.voucher_type, sle.voucher_no, sle.voucher_detail_no)
48 sle['incoming_rate'] = 0.0
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('incoming_rate'):
51 sle['incoming_rate'] = get_incoming_outgoing_rate_for_cancel(sle.item_code,
52 sle.voucher_type, sle.voucher_no, sle.voucher_detail_no)
53 sle['outgoing_rate'] = 0.0
Nabin Haitdc82d4f2014-04-07 12:02:57 +053054
Nabin Hait5288bde2014-11-03 15:08:21 +053055 if sle.get("actual_qty") or sle.get("voucher_type")=="Stock Reconciliation":
Nabin Haita77b8c92020-12-21 14:45:50 +053056 sle_doc = make_entry(sle, allow_negative_stock, via_landed_cost_voucher)
Deepesh Gargb4be2922021-01-28 13:09:56 +053057
Nabin Haita77b8c92020-12-21 14:45:50 +053058 args = sle_doc.as_dict()
marination40389772021-07-02 17:13:45 +053059
60 if sle.get("voucher_type") == "Stock Reconciliation":
61 # preserve previous_qty_after_transaction for qty reposting
62 args.previous_qty_after_transaction = sle.get("previous_qty_after_transaction")
63
Nabin Hait54c865e2015-03-27 15:38:31 +053064 update_bin(args, allow_negative_stock, via_landed_cost_voucher)
Nabin Haitadeb9762014-10-06 11:53:52 +053065
Rohit Waghchaure4d81d452021-06-15 10:21:44 +053066def get_args_for_future_sle(row):
67 return frappe._dict({
68 'voucher_type': row.get('voucher_type'),
69 'voucher_no': row.get('voucher_no'),
70 'posting_date': row.get('posting_date'),
71 'posting_time': row.get('posting_time')
72 })
73
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +053074def validate_serial_no(sle):
75 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
76 for sn in get_serial_nos(sle.serial_no):
77 args = copy.deepcopy(sle)
78 args.serial_no = sn
79 args.warehouse = ''
80
81 vouchers = []
82 for row in get_stock_ledger_entries(args, '>'):
83 voucher_type = frappe.bold(row.voucher_type)
84 voucher_no = frappe.bold(get_link_to_form(row.voucher_type, row.voucher_no))
85 vouchers.append(f'{voucher_type} {voucher_no}')
86
87 if vouchers:
88 serial_no = frappe.bold(sn)
89 msg = (f'''The serial no {serial_no} has been used in the future transactions so you need to cancel them first.
90 The list of the transactions are as below.''' + '<br><br><ul><li>')
91
92 msg += '</li><li>'.join(vouchers)
93 msg += '</li></ul>'
94
95 title = 'Cannot Submit' if not sle.get('is_cancelled') else 'Cannot Cancel'
96 frappe.throw(_(msg), title=_(title), exc=SerialNoExistsInFutureTransaction)
97
Nabin Hait186a0452021-02-18 14:14:21 +053098def validate_cancellation(args):
99 if args[0].get("is_cancelled"):
100 repost_entry = frappe.db.get_value("Repost Item Valuation", {
101 'voucher_type': args[0].voucher_type,
102 'voucher_no': args[0].voucher_no,
103 'docstatus': 1
104 }, ['name', 'status'], as_dict=1)
105
106 if repost_entry:
107 if repost_entry.status == 'In Progress':
108 frappe.throw(_("Cannot cancel the transaction. Reposting of item valuation on submission is not completed yet."))
109 if repost_entry.status == 'Queued':
Nabin Haitd46b2362021-02-23 16:38:52 +0530110 doc = frappe.get_doc("Repost Item Valuation", repost_entry.name)
111 doc.cancel()
112 doc.delete()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530113
Nabin Hait9653f602013-08-20 15:37:33 +0530114def set_as_cancel(voucher_type, voucher_no):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530115 frappe.db.sql("""update `tabStock Ledger Entry` set is_cancelled=1,
Nabin Hait9653f602013-08-20 15:37:33 +0530116 modified=%s, modified_by=%s
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530117 where voucher_type=%s and voucher_no=%s and is_cancelled = 0""",
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530118 (now(), frappe.session.user, voucher_type, voucher_no))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530119
Nabin Hait54c865e2015-03-27 15:38:31 +0530120def make_entry(args, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Hait74c281c2013-08-19 16:17:18 +0530121 args.update({"doctype": "Stock Ledger Entry"})
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530122 sle = frappe.get_doc(args)
Anand Doshi6dfd4302015-02-10 14:41:27 +0530123 sle.flags.ignore_permissions = 1
Nabin Hait4ccd8d32015-01-23 12:18:01 +0530124 sle.allow_negative_stock=allow_negative_stock
Nabin Hait54c865e2015-03-27 15:38:31 +0530125 sle.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Hait74c281c2013-08-19 16:17:18 +0530126 sle.insert()
Nabin Haitaeba24e2013-08-23 15:17:36 +0530127 sle.submit()
Nabin Haita77b8c92020-12-21 14:45:50 +0530128 return sle
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530129
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530130def 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 +0530131 if not args and voucher_type and voucher_no:
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530132 args = get_items_to_be_repost(voucher_type, voucher_no, doc)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530133
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530134 distinct_item_warehouses = get_distinct_item_warehouse(args, doc)
Nabin Haita77b8c92020-12-21 14:45:50 +0530135
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530136 i = get_current_index(doc) or 0
Nabin Haita77b8c92020-12-21 14:45:50 +0530137 while i < len(args):
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530138 validate_item_warehouse(args[i])
139
Nabin Haita77b8c92020-12-21 14:45:50 +0530140 obj = update_entries_after({
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530141 'item_code': args[i].get('item_code'),
142 'warehouse': args[i].get('warehouse'),
143 'posting_date': args[i].get('posting_date'),
144 'posting_time': args[i].get('posting_time'),
145 'creation': args[i].get('creation'),
146 'distinct_item_warehouses': distinct_item_warehouses
Nabin Haita77b8c92020-12-21 14:45:50 +0530147 }, allow_negative_stock=allow_negative_stock, via_landed_cost_voucher=via_landed_cost_voucher)
148
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530149 distinct_item_warehouses[(args[i].get('item_code'), args[i].get('warehouse'))].reposting_status = True
Deepesh Gargb4be2922021-01-28 13:09:56 +0530150
Nabin Hait97bce3a2021-07-12 13:24:43 +0530151 if obj.new_items_found:
152 for item_wh, data in iteritems(distinct_item_warehouses):
153 if ('args_idx' not in data and not data.reposting_status) or (data.sle_changed and data.reposting_status):
154 data.args_idx = len(args)
155 args.append(data.sle)
156 elif data.sle_changed and not data.reposting_status:
157 args[data.args_idx] = data.sle
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530158
Nabin Hait97bce3a2021-07-12 13:24:43 +0530159 data.sle_changed = False
Nabin Haita77b8c92020-12-21 14:45:50 +0530160 i += 1
161
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530162 if doc and i % 2 == 0:
163 update_args_in_repost_item_valuation(doc, i, args, distinct_item_warehouses)
164
165 if doc and args:
166 update_args_in_repost_item_valuation(doc, i, args, distinct_item_warehouses)
167
168def validate_item_warehouse(args):
169 for field in ['item_code', 'warehouse', 'posting_date', 'posting_time']:
170 if not args.get(field):
171 validation_msg = f'The field {frappe.unscrub(args.get(field))} is required for the reposting'
172 frappe.throw(_(validation_msg))
173
174def update_args_in_repost_item_valuation(doc, index, args, distinct_item_warehouses):
175 frappe.db.set_value(doc.doctype, doc.name, {
176 'items_to_be_repost': json.dumps(args, default=str),
177 'distinct_item_and_warehouse': json.dumps({str(k): v for k,v in distinct_item_warehouses.items()}, default=str),
178 'current_index': index
179 })
180
181 frappe.db.commit()
182
183 frappe.publish_realtime('item_reposting_progress', {
184 'name': doc.name,
185 'items_to_be_repost': json.dumps(args, default=str),
186 'current_index': index
187 })
188
189def get_items_to_be_repost(voucher_type, voucher_no, doc=None):
190 if doc and doc.items_to_be_repost:
191 return json.loads(doc.items_to_be_repost) or []
192
Nabin Haita77b8c92020-12-21 14:45:50 +0530193 return frappe.db.get_all("Stock Ledger Entry",
194 filters={"voucher_type": voucher_type, "voucher_no": voucher_no},
Nabin Hait186a0452021-02-18 14:14:21 +0530195 fields=["item_code", "warehouse", "posting_date", "posting_time", "creation"],
Nabin Haita77b8c92020-12-21 14:45:50 +0530196 order_by="creation asc",
197 group_by="item_code, warehouse"
198 )
Nabin Hait74c281c2013-08-19 16:17:18 +0530199
rohitwaghchaure31fe5f52021-08-02 11:01:30 +0530200def get_distinct_item_warehouse(args=None, doc=None):
201 distinct_item_warehouses = {}
202 if doc and doc.distinct_item_and_warehouse:
203 distinct_item_warehouses = json.loads(doc.distinct_item_and_warehouse)
204 distinct_item_warehouses = {frappe.safe_eval(k): frappe._dict(v) for k, v in distinct_item_warehouses.items()}
205 else:
206 for i, d in enumerate(args):
207 distinct_item_warehouses.setdefault((d.item_code, d.warehouse), frappe._dict({
208 "reposting_status": False,
209 "sle": d,
210 "args_idx": i
211 }))
212
213 return distinct_item_warehouses
214
215def get_current_index(doc=None):
216 if doc and doc.current_index:
217 return doc.current_index
218
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530219class update_entries_after(object):
Nabin Hait902e8602013-01-08 18:29:24 +0530220 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530221 update valution rate and qty after transaction
Nabin Hait902e8602013-01-08 18:29:24 +0530222 from the current time-bucket onwards
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530223
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530224 :param args: args as dict
225
226 args = {
227 "item_code": "ABC",
228 "warehouse": "XYZ",
229 "posting_date": "2012-12-12",
230 "posting_time": "12:00"
231 }
Nabin Hait902e8602013-01-08 18:29:24 +0530232 """
Anand Doshi0dc79f42015-04-06 12:59:34 +0530233 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 +0530234 self.exceptions = {}
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530235 self.verbose = verbose
236 self.allow_zero_rate = allow_zero_rate
Anand Doshi0dc79f42015-04-06 12:59:34 +0530237 self.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Haita77b8c92020-12-21 14:45:50 +0530238 self.allow_negative_stock = allow_negative_stock \
239 or cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530240
Nabin Haita77b8c92020-12-21 14:45:50 +0530241 self.args = frappe._dict(args)
242 self.item_code = args.get("item_code")
243 if self.args.sle_id:
244 self.args['name'] = self.args.sle_id
Nabin Haitd46b2362021-02-23 16:38:52 +0530245
Nabin Haita77b8c92020-12-21 14:45:50 +0530246 self.company = frappe.get_cached_value("Warehouse", self.args.warehouse, "company")
247 self.get_precision()
248 self.valuation_method = get_valuation_method(self.item_code)
Nabin Hait97bce3a2021-07-12 13:24:43 +0530249
250 self.new_items_found = False
251 self.distinct_item_warehouses = args.get("distinct_item_warehouses", frappe._dict())
Nabin Haita77b8c92020-12-21 14:45:50 +0530252
253 self.data = frappe._dict()
254 self.initialize_previous_data(self.args)
Nabin Haita77b8c92020-12-21 14:45:50 +0530255 self.build()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530256
Nabin Haita77b8c92020-12-21 14:45:50 +0530257 def get_precision(self):
258 company_base_currency = frappe.get_cached_value('Company', self.company, "default_currency")
259 self.precision = get_field_precision(frappe.get_meta("Stock Ledger Entry").get_field("stock_value"),
260 currency=company_base_currency)
261
262 def initialize_previous_data(self, args):
263 """
264 Get previous sl entries for current item for each related warehouse
265 and assigns into self.data dict
266
267 :Data Structure:
268
269 self.data = {
270 warehouse1: {
271 'previus_sle': {},
272 'qty_after_transaction': 10,
273 'valuation_rate': 100,
274 'stock_value': 1000,
275 'prev_stock_value': 1000,
276 'stock_queue': '[[10, 100]]',
277 'stock_value_difference': 1000
278 }
279 }
280
281 """
marination8418c4b2021-06-22 21:35:25 +0530282 previous_sle = get_previous_sle_of_current_voucher(args)
Nabin Haitbb777562013-08-29 18:19:37 +0530283
Ankush91527152021-08-11 11:17:50 +0530284 self.data[args.warehouse] = frappe._dict({
285 "previous_sle": previous_sle,
286 "qty_after_transaction": flt(previous_sle.qty_after_transaction),
287 "valuation_rate": flt(previous_sle.valuation_rate),
288 "stock_value": flt(previous_sle.stock_value),
Nabin Haita77b8c92020-12-21 14:45:50 +0530289 "prev_stock_value": previous_sle.stock_value or 0.0,
290 "stock_queue": json.loads(previous_sle.stock_queue or "[]"),
291 "stock_value_difference": 0.0
292 })
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530293
Nabin Haita77b8c92020-12-21 14:45:50 +0530294 def build(self):
Sagar Vorae50324a2021-03-31 12:44:03 +0530295 from erpnext.controllers.stock_controller import future_sle_exists
Nabin Hait186a0452021-02-18 14:14:21 +0530296
Nabin Haita77b8c92020-12-21 14:45:50 +0530297 if self.args.get("sle_id"):
Nabin Hait186a0452021-02-18 14:14:21 +0530298 self.process_sle_against_current_timestamp()
Sagar Vorae50324a2021-03-31 12:44:03 +0530299 if not future_sle_exists(self.args):
Nabin Hait186a0452021-02-18 14:14:21 +0530300 self.update_bin()
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530301 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530302 entries_to_fix = self.get_future_entries_to_fix()
303
304 i = 0
305 while i < len(entries_to_fix):
306 sle = entries_to_fix[i]
307 i += 1
308
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530309 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530310
Nabin Haita77b8c92020-12-21 14:45:50 +0530311 if sle.dependant_sle_voucher_detail_no:
Nabin Hait243d59b2021-02-02 16:55:13 +0530312 entries_to_fix = self.get_dependent_entries_to_fix(entries_to_fix, sle)
Nabin Haitd46b2362021-02-23 16:38:52 +0530313
Nabin Hait186a0452021-02-18 14:14:21 +0530314 self.update_bin()
Nabin Haita77b8c92020-12-21 14:45:50 +0530315
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530316 if self.exceptions:
317 self.raise_exceptions()
318
Nabin Hait186a0452021-02-18 14:14:21 +0530319 def process_sle_against_current_timestamp(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530320 sl_entries = self.get_sle_against_current_voucher()
321 for sle in sl_entries:
322 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530323
Nabin Haita77b8c92020-12-21 14:45:50 +0530324 def get_sle_against_current_voucher(self):
Nabin Haitf2be0802021-02-15 19:27:49 +0530325 self.args['time_format'] = '%H:%i:%s'
326
Nabin Haita77b8c92020-12-21 14:45:50 +0530327 return frappe.db.sql("""
328 select
329 *, timestamp(posting_date, posting_time) as "timestamp"
330 from
331 `tabStock Ledger Entry`
332 where
333 item_code = %(item_code)s
334 and warehouse = %(warehouse)s
rohitwaghchaurefe4540d2021-08-26 12:52:36 +0530335 and is_cancelled = 0
Nabin Hait186a0452021-02-18 14:14:21 +0530336 and timestamp(posting_date, time_format(posting_time, %(time_format)s)) = timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
337
Nabin Haita77b8c92020-12-21 14:45:50 +0530338 order by
339 creation ASC
340 for update
341 """, self.args, as_dict=1)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530342
Nabin Haita77b8c92020-12-21 14:45:50 +0530343 def get_future_entries_to_fix(self):
344 # includes current entry!
345 args = self.data[self.args.warehouse].previous_sle \
346 or frappe._dict({"item_code": self.item_code, "warehouse": self.args.warehouse})
Deepesh Gargb4be2922021-01-28 13:09:56 +0530347
Nabin Haita77b8c92020-12-21 14:45:50 +0530348 return list(self.get_sle_after_datetime(args))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530349
Nabin Haita77b8c92020-12-21 14:45:50 +0530350 def get_dependent_entries_to_fix(self, entries_to_fix, sle):
351 dependant_sle = get_sle_by_voucher_detail_no(sle.dependant_sle_voucher_detail_no,
352 excluded_sle=sle.name)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530353
Nabin Haita77b8c92020-12-21 14:45:50 +0530354 if not dependant_sle:
Nabin Hait243d59b2021-02-02 16:55:13 +0530355 return entries_to_fix
Nabin Haita77b8c92020-12-21 14:45:50 +0530356 elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse == self.args.warehouse:
Nabin Hait243d59b2021-02-02 16:55:13 +0530357 return entries_to_fix
358 elif dependant_sle.item_code != self.item_code:
Nabin Hait97bce3a2021-07-12 13:24:43 +0530359 self.update_distinct_item_warehouses(dependant_sle)
Nabin Hait243d59b2021-02-02 16:55:13 +0530360 return entries_to_fix
361 elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse in self.data:
362 return entries_to_fix
Nabin Hait97bce3a2021-07-12 13:24:43 +0530363 else:
364 return self.append_future_sle_for_dependant(dependant_sle, entries_to_fix)
365
366 def update_distinct_item_warehouses(self, dependant_sle):
367 key = (dependant_sle.item_code, dependant_sle.warehouse)
368 val = frappe._dict({
369 "sle": dependant_sle
370 })
371 if key not in self.distinct_item_warehouses:
372 self.distinct_item_warehouses[key] = val
373 self.new_items_found = True
374 else:
375 existing_sle_posting_date = self.distinct_item_warehouses[key].get("sle", {}).get("posting_date")
376 if getdate(dependant_sle.posting_date) < getdate(existing_sle_posting_date):
377 val.sle_changed = True
378 self.distinct_item_warehouses[key] = val
379 self.new_items_found = True
380
381 def append_future_sle_for_dependant(self, dependant_sle, entries_to_fix):
Nabin Haita77b8c92020-12-21 14:45:50 +0530382 self.initialize_previous_data(dependant_sle)
383
384 args = self.data[dependant_sle.warehouse].previous_sle \
385 or frappe._dict({"item_code": self.item_code, "warehouse": dependant_sle.warehouse})
386 future_sle_for_dependant = list(self.get_sle_after_datetime(args))
387
388 entries_to_fix.extend(future_sle_for_dependant)
Nabin Hait243d59b2021-02-02 16:55:13 +0530389 return sorted(entries_to_fix, key=lambda k: k['timestamp'])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530390
391 def process_sle(self, sle):
Nabin Haita77b8c92020-12-21 14:45:50 +0530392 # previous sle data for this warehouse
393 self.wh_data = self.data[sle.warehouse]
394
Anand Doshi0dc79f42015-04-06 12:59:34 +0530395 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 +0530396 # validate negative stock for serialized items, fifo valuation
Nabin Hait902e8602013-01-08 18:29:24 +0530397 # or when negative stock is not allowed for moving average
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530398 if not self.validate_negative_stock(sle):
Nabin Haita77b8c92020-12-21 14:45:50 +0530399 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530400 return
Nabin Haitb96c0142014-10-07 11:25:04 +0530401
Nabin Haita77b8c92020-12-21 14:45:50 +0530402 # Get dynamic incoming/outgoing rate
403 self.get_dynamic_incoming_outgoing_rate(sle)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530404
Anand Doshi1b531862013-01-10 19:29:51 +0530405 if sle.serial_no:
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530406 self.get_serialized_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530407 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530408 if sle.voucher_type == "Stock Reconciliation":
Nabin Haita77b8c92020-12-21 14:45:50 +0530409 self.wh_data.qty_after_transaction = sle.qty_after_transaction
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530410
Nabin Haita77b8c92020-12-21 14:45:50 +0530411 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 +0530412 else:
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530413 if sle.voucher_type=="Stock Reconciliation" and not sle.batch_no:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530414 # assert
Nabin Haita77b8c92020-12-21 14:45:50 +0530415 self.wh_data.valuation_rate = sle.valuation_rate
416 self.wh_data.qty_after_transaction = sle.qty_after_transaction
417 self.wh_data.stock_queue = [[self.wh_data.qty_after_transaction, self.wh_data.valuation_rate]]
418 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:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530420 if self.valuation_method == "Moving Average":
421 self.get_moving_average_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530422 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
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 self.get_fifo_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530426 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
427 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 +0530428
Rushabh Mehta54047782013-12-26 11:07:46 +0530429 # rounding as per precision
Nabin Haita77b8c92020-12-21 14:45:50 +0530430 self.wh_data.stock_value = flt(self.wh_data.stock_value, self.precision)
431 stock_value_difference = self.wh_data.stock_value - self.wh_data.prev_stock_value
432 self.wh_data.prev_stock_value = self.wh_data.stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530433
Nabin Hait902e8602013-01-08 18:29:24 +0530434 # update current sle
Nabin Haita77b8c92020-12-21 14:45:50 +0530435 sle.qty_after_transaction = self.wh_data.qty_after_transaction
436 sle.valuation_rate = self.wh_data.valuation_rate
437 sle.stock_value = self.wh_data.stock_value
438 sle.stock_queue = json.dumps(self.wh_data.stock_queue)
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530439 sle.stock_value_difference = stock_value_difference
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530440 sle.doctype="Stock Ledger Entry"
441 frappe.get_doc(sle).db_update()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530442
Nabin Haita77b8c92020-12-21 14:45:50 +0530443 self.update_outgoing_rate_on_transaction(sle)
444
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530445 def validate_negative_stock(self, sle):
446 """
447 validate negative stock for entries current datetime onwards
448 will not consider cancelled entries
449 """
Nabin Haita77b8c92020-12-21 14:45:50 +0530450 diff = self.wh_data.qty_after_transaction + flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530451
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530452 if diff < 0 and abs(diff) > 0.0001:
453 # negative stock!
454 exc = sle.copy().update({"diff": diff})
Nabin Haita77b8c92020-12-21 14:45:50 +0530455 self.exceptions.setdefault(sle.warehouse, []).append(exc)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530456 return False
Nabin Hait902e8602013-01-08 18:29:24 +0530457 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530458 return True
459
Nabin Haita77b8c92020-12-21 14:45:50 +0530460 def get_dynamic_incoming_outgoing_rate(self, sle):
461 # Get updated incoming/outgoing rate from transaction
462 if sle.recalculate_rate:
463 rate = self.get_incoming_outgoing_rate_from_transaction(sle)
464
465 if flt(sle.actual_qty) >= 0:
466 sle.incoming_rate = rate
467 else:
468 sle.outgoing_rate = rate
469
470 def get_incoming_outgoing_rate_from_transaction(self, sle):
471 rate = 0
472 # Material Transfer, Repack, Manufacturing
473 if sle.voucher_type == "Stock Entry":
Nabin Hait97bce3a2021-07-12 13:24:43 +0530474 self.recalculate_amounts_in_stock_entry(sle.voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530475 rate = frappe.db.get_value("Stock Entry Detail", sle.voucher_detail_no, "valuation_rate")
476 # Sales and Purchase Return
477 elif sle.voucher_type in ("Purchase Receipt", "Purchase Invoice", "Delivery Note", "Sales Invoice"):
478 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_return"):
479 from erpnext.controllers.sales_and_purchase_return import get_rate_for_return # don't move this import to top
rohitwaghchaurece6c3b52021-04-13 20:55:52 +0530480 rate = get_rate_for_return(sle.voucher_type, sle.voucher_no, sle.item_code,
481 voucher_detail_no=sle.voucher_detail_no, sle = sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530482 else:
483 if sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530484 rate_field = "valuation_rate"
Nabin Haita77b8c92020-12-21 14:45:50 +0530485 else:
486 rate_field = "incoming_rate"
487
488 # check in item table
489 item_code, incoming_rate = frappe.db.get_value(sle.voucher_type + " Item",
490 sle.voucher_detail_no, ["item_code", rate_field])
491
492 if item_code == sle.item_code:
493 rate = incoming_rate
494 else:
495 if sle.voucher_type in ("Delivery Note", "Sales Invoice"):
496 ref_doctype = "Packed Item"
497 else:
498 ref_doctype = "Purchase Receipt Item Supplied"
Deepesh Gargb4be2922021-01-28 13:09:56 +0530499
Nabin Haita77b8c92020-12-21 14:45:50 +0530500 rate = frappe.db.get_value(ref_doctype, {"parent_detail_docname": sle.voucher_detail_no,
501 "item_code": sle.item_code}, rate_field)
502
503 return rate
504
505 def update_outgoing_rate_on_transaction(self, sle):
506 """
507 Update outgoing rate in Stock Entry, Delivery Note, Sales Invoice and Sales Return
508 In case of Stock Entry, also calculate FG Item rate and total incoming/outgoing amount
509 """
510 if sle.actual_qty and sle.voucher_detail_no:
511 outgoing_rate = abs(flt(sle.stock_value_difference)) / abs(sle.actual_qty)
512
513 if flt(sle.actual_qty) < 0 and sle.voucher_type == "Stock Entry":
514 self.update_rate_on_stock_entry(sle, outgoing_rate)
515 elif sle.voucher_type in ("Delivery Note", "Sales Invoice"):
516 self.update_rate_on_delivery_and_sales_return(sle, outgoing_rate)
517 elif flt(sle.actual_qty) < 0 and sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
518 self.update_rate_on_purchase_receipt(sle, outgoing_rate)
519
520 def update_rate_on_stock_entry(self, sle, outgoing_rate):
521 frappe.db.set_value("Stock Entry Detail", sle.voucher_detail_no, "basic_rate", outgoing_rate)
522
523 # Update outgoing item's rate, recalculate FG Item's rate and total incoming/outgoing amount
Nabin Hait97bce3a2021-07-12 13:24:43 +0530524 if not sle.dependant_sle_voucher_detail_no:
525 self.recalculate_amounts_in_stock_entry(sle.voucher_no)
526
527 def recalculate_amounts_in_stock_entry(self, voucher_no):
528 stock_entry = frappe.get_doc("Stock Entry", voucher_no, for_update=True)
Nabin Haita77b8c92020-12-21 14:45:50 +0530529 stock_entry.calculate_rate_and_amount(reset_outgoing_rate=False, raise_error_if_no_rate=False)
530 stock_entry.db_update()
531 for d in stock_entry.items:
532 d.db_update()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530533
Nabin Haita77b8c92020-12-21 14:45:50 +0530534 def update_rate_on_delivery_and_sales_return(self, sle, outgoing_rate):
535 # Update item's incoming rate on transaction
536 item_code = frappe.db.get_value(sle.voucher_type + " Item", sle.voucher_detail_no, "item_code")
537 if item_code == sle.item_code:
538 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "incoming_rate", outgoing_rate)
539 else:
540 # packed item
541 frappe.db.set_value("Packed Item",
542 {"parent_detail_docname": sle.voucher_detail_no, "item_code": sle.item_code},
543 "incoming_rate", outgoing_rate)
544
545 def update_rate_on_purchase_receipt(self, sle, outgoing_rate):
546 if frappe.db.exists(sle.voucher_type + " Item", sle.voucher_detail_no):
547 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "base_net_rate", outgoing_rate)
548 else:
549 frappe.db.set_value("Purchase Receipt Item Supplied", sle.voucher_detail_no, "rate", outgoing_rate)
550
551 # Recalculate subcontracted item's rate in case of subcontracted purchase receipt/invoice
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530552 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_subcontracted") == 'Yes':
Rohit Waghchauree5fb2392021-06-18 20:37:42 +0530553 doc = frappe.get_doc(sle.voucher_type, sle.voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530554 doc.update_valuation_rate(reset_outgoing_rate=False)
555 for d in (doc.items + doc.supplied_items):
556 d.db_update()
557
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530558 def get_serialized_values(self, sle):
559 incoming_rate = flt(sle.incoming_rate)
560 actual_qty = flt(sle.actual_qty)
Nabin Hait328c4f92020-01-02 19:00:32 +0530561 serial_nos = cstr(sle.serial_no).split("\n")
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530562
563 if incoming_rate < 0:
564 # wrong incoming rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530565 incoming_rate = self.wh_data.valuation_rate
Rushabh Mehta538607e2016-06-12 11:03:00 +0530566
Nabin Hait2620bf42016-02-29 11:30:27 +0530567 stock_value_change = 0
568 if incoming_rate:
569 stock_value_change = actual_qty * incoming_rate
570 elif actual_qty < 0:
571 # In case of delivery/stock issue, get average purchase rate
572 # of serial nos of current entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530573 if not sle.is_cancelled:
574 outgoing_value = self.get_incoming_value_for_serial_nos(sle, serial_nos)
575 stock_value_change = -1 * outgoing_value
576 else:
577 stock_value_change = actual_qty * sle.outgoing_rate
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530578
Nabin Haita77b8c92020-12-21 14:45:50 +0530579 new_stock_qty = self.wh_data.qty_after_transaction + actual_qty
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530580
Nabin Hait2620bf42016-02-29 11:30:27 +0530581 if new_stock_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530582 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + stock_value_change
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530583 if new_stock_value >= 0:
Nabin Hait2620bf42016-02-29 11:30:27 +0530584 # calculate new valuation rate only if stock value is positive
585 # else it remains the same as that of previous entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530586 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530587
Nabin Haita77b8c92020-12-21 14:45:50 +0530588 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530589 allow_zero_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
590 if not allow_zero_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530591 self.wh_data.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530592 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
593 currency=erpnext.get_company_currency(sle.company))
594
Nabin Hait328c4f92020-01-02 19:00:32 +0530595 def get_incoming_value_for_serial_nos(self, sle, serial_nos):
596 # get rate from serial nos within same company
597 all_serial_nos = frappe.get_all("Serial No",
598 fields=["purchase_rate", "name", "company"],
599 filters = {'name': ('in', serial_nos)})
600
Ankush Menat98917802021-06-11 18:40:22 +0530601 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 +0530602
603 # Get rate for serial nos which has been transferred to other company
604 invalid_serial_nos = [d.name for d in all_serial_nos if d.company!=sle.company]
605 for serial_no in invalid_serial_nos:
606 incoming_rate = frappe.db.sql("""
607 select incoming_rate
608 from `tabStock Ledger Entry`
609 where
610 company = %s
611 and actual_qty > 0
612 and (serial_no = %s
613 or serial_no like %s
614 or serial_no like %s
615 or serial_no like %s
616 )
617 order by posting_date desc
618 limit 1
619 """, (sle.company, serial_no, serial_no+'\n%', '%\n'+serial_no, '%\n'+serial_no+'\n%'))
620
621 incoming_values += flt(incoming_rate[0][0]) if incoming_rate else 0
622
623 return incoming_values
624
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530625 def get_moving_average_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530626 actual_qty = flt(sle.actual_qty)
Nabin Haita77b8c92020-12-21 14:45:50 +0530627 new_stock_qty = flt(self.wh_data.qty_after_transaction) + actual_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530628 if new_stock_qty >= 0:
629 if actual_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530630 if flt(self.wh_data.qty_after_transaction) <= 0:
631 self.wh_data.valuation_rate = sle.incoming_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530632 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530633 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530634 (actual_qty * sle.incoming_rate)
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530635
Nabin Haita77b8c92020-12-21 14:45:50 +0530636 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530637
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530638 elif sle.outgoing_rate:
639 if new_stock_qty:
Nabin Haita77b8c92020-12-21 14:45:50 +0530640 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530641 (actual_qty * sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530642
Nabin Haita77b8c92020-12-21 14:45:50 +0530643 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530644 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530645 self.wh_data.valuation_rate = sle.outgoing_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530646 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530647 if flt(self.wh_data.qty_after_transaction) >= 0 and sle.outgoing_rate:
648 self.wh_data.valuation_rate = sle.outgoing_rate
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530649
Nabin Haita77b8c92020-12-21 14:45:50 +0530650 if not self.wh_data.valuation_rate and actual_qty > 0:
651 self.wh_data.valuation_rate = sle.incoming_rate
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530652
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530653 # Get valuation rate from previous SLE or Item master, if item does not have the
Javier Wong9b11d9b2017-04-14 18:24:04 +0800654 # allow zero valuration rate flag set
Nabin Haita77b8c92020-12-21 14:45:50 +0530655 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
Javier Wong9b11d9b2017-04-14 18:24:04 +0800656 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
657 if not allow_zero_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530658 self.wh_data.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530659 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
660 currency=erpnext.get_company_currency(sle.company))
661
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530662 def get_fifo_values(self, sle):
663 incoming_rate = flt(sle.incoming_rate)
664 actual_qty = flt(sle.actual_qty)
Nabin Haitada485f2015-07-17 15:09:56 +0530665 outgoing_rate = flt(sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530666
667 if actual_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530668 if not self.wh_data.stock_queue:
669 self.wh_data.stock_queue.append([0, 0])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530670
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530671 # last row has the same rate, just updated the qty
Nabin Haita77b8c92020-12-21 14:45:50 +0530672 if self.wh_data.stock_queue[-1][1]==incoming_rate:
673 self.wh_data.stock_queue[-1][0] += actual_qty
Nabin Hait4d742162014-10-09 19:25:03 +0530674 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530675 if self.wh_data.stock_queue[-1][0] > 0:
676 self.wh_data.stock_queue.append([actual_qty, incoming_rate])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530677 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530678 qty = self.wh_data.stock_queue[-1][0] + actual_qty
679 self.wh_data.stock_queue[-1] = [qty, incoming_rate]
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530680 else:
681 qty_to_pop = abs(actual_qty)
682 while qty_to_pop:
Nabin Haita77b8c92020-12-21 14:45:50 +0530683 if not self.wh_data.stock_queue:
Nabin Haita0b967f2017-01-18 18:35:58 +0530684 # Get valuation rate from last sle if exists or from valuation rate field in item master
Javier Wong9b11d9b2017-04-14 18:24:04 +0800685 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
686 if not allow_zero_valuation_rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530687 _rate = get_valuation_rate(sle.item_code, sle.warehouse,
688 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
689 currency=erpnext.get_company_currency(sle.company))
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530690 else:
691 _rate = 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530692
Nabin Haita77b8c92020-12-21 14:45:50 +0530693 self.wh_data.stock_queue.append([0, _rate])
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530694
Nabin Haitada485f2015-07-17 15:09:56 +0530695 index = None
696 if outgoing_rate > 0:
697 # Find the entry where rate matched with outgoing rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530698 for i, v in enumerate(self.wh_data.stock_queue):
Nabin Haitada485f2015-07-17 15:09:56 +0530699 if v[1] == outgoing_rate:
700 index = i
701 break
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530702
Nabin Haitada485f2015-07-17 15:09:56 +0530703 # If no entry found with outgoing rate, collapse stack
Ankush Menat4dcac4a2021-05-21 13:12:30 +0530704 if index is None: # nosemgrep
Nabin Haita77b8c92020-12-21 14:45:50 +0530705 new_stock_value = sum((d[0]*d[1] for d in self.wh_data.stock_queue)) - qty_to_pop*outgoing_rate
706 new_stock_qty = sum((d[0] for d in self.wh_data.stock_queue)) - qty_to_pop
707 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 +0530708 break
709 else:
710 index = 0
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530711
Nabin Haitada485f2015-07-17 15:09:56 +0530712 # select first batch or the batch with same rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530713 batch = self.wh_data.stock_queue[index]
Nabin Hait8142cd22015-08-05 18:57:26 +0530714 if qty_to_pop >= batch[0]:
715 # consume current batch
Ankush Menat6a014d12021-04-12 20:21:27 +0530716 qty_to_pop = _round_off_if_near_zero(qty_to_pop - batch[0])
Nabin Haita77b8c92020-12-21 14:45:50 +0530717 self.wh_data.stock_queue.pop(index)
718 if not self.wh_data.stock_queue and qty_to_pop:
Nabin Hait8142cd22015-08-05 18:57:26 +0530719 # stock finished, qty still remains to be withdrawn
720 # negative stock, keep in as a negative batch
Nabin Haita77b8c92020-12-21 14:45:50 +0530721 self.wh_data.stock_queue.append([-qty_to_pop, outgoing_rate or batch[1]])
Nabin Hait8142cd22015-08-05 18:57:26 +0530722 break
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530723
Nabin Hait8142cd22015-08-05 18:57:26 +0530724 else:
725 # qty found in current batch
726 # consume it and exit
727 batch[0] = batch[0] - qty_to_pop
728 qty_to_pop = 0
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530729
Ankush Menat6a014d12021-04-12 20:21:27 +0530730 stock_value = _round_off_if_near_zero(sum((flt(batch[0]) * flt(batch[1]) for batch in self.wh_data.stock_queue)))
731 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 +0530732
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530733 if stock_qty:
Nabin Haita77b8c92020-12-21 14:45:50 +0530734 self.wh_data.valuation_rate = stock_value / flt(stock_qty)
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530735
Nabin Haita77b8c92020-12-21 14:45:50 +0530736 if not self.wh_data.stock_queue:
737 self.wh_data.stock_queue.append([0, sle.incoming_rate or sle.outgoing_rate or self.wh_data.valuation_rate])
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530738
Javier Wong9b11d9b2017-04-14 18:24:04 +0800739 def check_if_allow_zero_valuation_rate(self, voucher_type, voucher_detail_no):
deepeshgarg007f9c0ef32019-07-30 18:49:19 +0530740 ref_item_dt = ""
741
742 if voucher_type == "Stock Entry":
743 ref_item_dt = voucher_type + " Detail"
744 elif voucher_type in ["Purchase Invoice", "Sales Invoice", "Delivery Note", "Purchase Receipt"]:
745 ref_item_dt = voucher_type + " Item"
746
747 if ref_item_dt:
748 return frappe.db.get_value(ref_item_dt, voucher_detail_no, "allow_zero_valuation_rate")
749 else:
750 return 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530751
Nabin Haita77b8c92020-12-21 14:45:50 +0530752 def get_sle_before_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530753 """get previous stock ledger entry before current time-bucket"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530754 sle = get_stock_ledger_entries(args, "<", "desc", "limit 1", for_update=False)
755 sle = sle[0] if sle else frappe._dict()
756 return sle
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530757
Nabin Haita77b8c92020-12-21 14:45:50 +0530758 def get_sle_after_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530759 """get Stock Ledger Entries after a particular datetime, for reposting"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530760 return get_stock_ledger_entries(args, ">", "asc", for_update=True, check_serial_no=False)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530761
762 def raise_exceptions(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530763 msg_list = []
764 for warehouse, exceptions in iteritems(self.exceptions):
765 deficiency = min(e["diff"] for e in exceptions)
Rushabh Mehta538607e2016-06-12 11:03:00 +0530766
Nabin Haita77b8c92020-12-21 14:45:50 +0530767 if ((exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]) in
768 frappe.local.flags.currently_saving):
Nabin Hait3edefb12016-07-20 16:13:18 +0530769
Nabin Haita77b8c92020-12-21 14:45:50 +0530770 msg = _("{0} units of {1} needed in {2} to complete this transaction.").format(
Nabin Hait243d59b2021-02-02 16:55:13 +0530771 abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]),
Nabin Haita77b8c92020-12-21 14:45:50 +0530772 frappe.get_desk_link('Warehouse', warehouse))
773 else:
774 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 +0530775 abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]),
Nabin Haita77b8c92020-12-21 14:45:50 +0530776 frappe.get_desk_link('Warehouse', warehouse),
777 exceptions[0]["posting_date"], exceptions[0]["posting_time"],
778 frappe.get_desk_link(exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530779
Nabin Haita77b8c92020-12-21 14:45:50 +0530780 if msg:
781 msg_list.append(msg)
782
783 if msg_list:
784 message = "\n\n".join(msg_list)
785 if self.verbose:
786 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
787 else:
788 raise NegativeStockError(message)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530789
Nabin Haita77b8c92020-12-21 14:45:50 +0530790 def update_bin(self):
791 # update bin for each warehouse
792 for warehouse, data in iteritems(self.data):
793 bin_doc = get_bin(self.item_code, warehouse)
Nabin Haita77b8c92020-12-21 14:45:50 +0530794 bin_doc.update({
795 "valuation_rate": data.valuation_rate,
796 "actual_qty": data.qty_after_transaction,
797 "stock_value": data.stock_value
798 })
799 bin_doc.flags.via_stock_ledger_entry = True
800 bin_doc.save(ignore_permissions=True)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530801
marination8418c4b2021-06-22 21:35:25 +0530802
803def get_previous_sle_of_current_voucher(args, exclude_current_voucher=False):
804 """get stock ledger entries filtered by specific posting datetime conditions"""
805
806 args['time_format'] = '%H:%i:%s'
807 if not args.get("posting_date"):
808 args["posting_date"] = "1900-01-01"
809 if not args.get("posting_time"):
810 args["posting_time"] = "00:00"
811
812 voucher_condition = ""
813 if exclude_current_voucher:
814 voucher_no = args.get("voucher_no")
815 voucher_condition = f"and voucher_no != '{voucher_no}'"
816
817 sle = frappe.db.sql("""
818 select *, timestamp(posting_date, posting_time) as "timestamp"
819 from `tabStock Ledger Entry`
820 where item_code = %(item_code)s
821 and warehouse = %(warehouse)s
822 and is_cancelled = 0
823 {voucher_condition}
824 and timestamp(posting_date, time_format(posting_time, %(time_format)s)) < timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
825 order by timestamp(posting_date, posting_time) desc, creation desc
826 limit 1
827 for update""".format(voucher_condition=voucher_condition), args, as_dict=1)
828
829 return sle[0] if sle else frappe._dict()
830
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530831def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530832 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530833 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530834 to get actual qty before transaction, this function
835 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530836
Anand Doshi1b531862013-01-10 19:29:51 +0530837 args = {
838 "item_code": "ABC",
839 "warehouse": "XYZ",
840 "posting_date": "2012-12-12",
841 "posting_time": "12:00",
842 "sle": "name of reference Stock Ledger Entry"
843 }
844 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530845 args["name"] = args.get("sle", None) or ""
846 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530847 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530848
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530849def get_stock_ledger_entries(previous_sle, operator=None,
850 order="desc", limit=None, for_update=False, debug=False, check_serial_no=True):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530851 """get stock ledger entries filtered by specific posting datetime conditions"""
Nabin Haitb9ce1042018-02-01 14:58:50 +0530852 conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
853 if previous_sle.get("warehouse"):
854 conditions += " and warehouse = %(warehouse)s"
855 elif previous_sle.get("warehouse_condition"):
856 conditions += " and " + previous_sle.get("warehouse_condition")
857
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530858 if check_serial_no and previous_sle.get("serial_no"):
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530859 # conditions += " and serial_no like {}".format(frappe.db.escape('%{0}%'.format(previous_sle.get("serial_no"))))
860 serial_no = previous_sle.get("serial_no")
861 conditions += (""" and
862 (
863 serial_no = {0}
864 or serial_no like {1}
865 or serial_no like {2}
866 or serial_no like {3}
867 )
868 """).format(frappe.db.escape(serial_no), frappe.db.escape('{}\n%'.format(serial_no)),
869 frappe.db.escape('%\n{}'.format(serial_no)), frappe.db.escape('%\n{}\n%'.format(serial_no)))
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530870
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530871 if not previous_sle.get("posting_date"):
872 previous_sle["posting_date"] = "1900-01-01"
873 if not previous_sle.get("posting_time"):
874 previous_sle["posting_time"] = "00:00"
875
876 if operator in (">", "<=") and previous_sle.get("name"):
877 conditions += " and name!=%(name)s"
878
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530879 return frappe.db.sql("""
880 select *, timestamp(posting_date, posting_time) as "timestamp"
881 from `tabStock Ledger Entry`
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530882 where item_code = %%(item_code)s
Nabin Haita77b8c92020-12-21 14:45:50 +0530883 and is_cancelled = 0
Nabin Haitb9ce1042018-02-01 14:58:50 +0530884 %(conditions)s
Aditya Hase0c164242019-01-07 22:07:13 +0530885 order by timestamp(posting_date, posting_time) %(order)s, creation %(order)s
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530886 %(limit)s %(for_update)s""" % {
887 "conditions": conditions,
888 "limit": limit or "",
889 "for_update": for_update and "for update" or "",
890 "order": order
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530891 }, previous_sle, as_dict=1, debug=debug)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530892
Nabin Haita77b8c92020-12-21 14:45:50 +0530893def get_sle_by_voucher_detail_no(voucher_detail_no, excluded_sle=None):
894 return frappe.db.get_value('Stock Ledger Entry',
895 {'voucher_detail_no': voucher_detail_no, 'name': ['!=', excluded_sle]},
896 ['item_code', 'warehouse', 'posting_date', 'posting_time', 'timestamp(posting_date, posting_time) as timestamp'],
897 as_dict=1)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530898
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530899def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no,
Nabin Hait7ba092e2018-02-01 10:51:27 +0530900 allow_zero_rate=False, currency=None, company=None, raise_error_if_no_rate=True):
Nabin Haita0b967f2017-01-18 18:35:58 +0530901 # Get valuation rate from last sle for the same item and warehouse
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530902 if not company:
903 company = erpnext.get_default_company()
904
Nabin Haitfb6e4342014-10-15 11:34:40 +0530905 last_valuation_rate = frappe.db.sql("""select valuation_rate
906 from `tabStock Ledger Entry`
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530907 where
908 item_code = %s
909 AND warehouse = %s
910 AND valuation_rate >= 0
911 AND NOT (voucher_no = %s AND voucher_type = %s)
912 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 +0530913
914 if not last_valuation_rate:
Nabin Haita0b967f2017-01-18 18:35:58 +0530915 # Get valuation rate from last sle for the item against any warehouse
Nabin Haitfb6e4342014-10-15 11:34:40 +0530916 last_valuation_rate = frappe.db.sql("""select valuation_rate
917 from `tabStock Ledger Entry`
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530918 where
919 item_code = %s
920 AND valuation_rate > 0
921 AND NOT(voucher_no = %s AND voucher_type = %s)
922 order by posting_date desc, posting_time desc, name desc limit 1""", (item_code, voucher_no, voucher_type))
Nabin Haitfb6e4342014-10-15 11:34:40 +0530923
Nabin Haita645f362018-03-01 10:31:24 +0530924 if last_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530925 return flt(last_valuation_rate[0][0])
Nabin Haita645f362018-03-01 10:31:24 +0530926
927 # If negative stock allowed, and item delivered without any incoming entry,
928 # system does not found any SLE, then take valuation rate from Item
929 valuation_rate = frappe.db.get_value("Item", item_code, "valuation_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530930
931 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530932 # try Item Standard rate
933 valuation_rate = frappe.db.get_value("Item", item_code, "standard_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530934
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530935 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530936 # try in price list
937 valuation_rate = frappe.db.get_value('Item Price',
938 dict(item_code=item_code, buying=1, currency=currency),
939 'price_list_rate')
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530940
Nabin Hait7ba092e2018-02-01 10:51:27 +0530941 if not allow_zero_rate and not valuation_rate and raise_error_if_no_rate \
Rohit Waghchauree9ff1912017-06-19 12:54:59 +0530942 and cint(erpnext.is_perpetual_inventory_enabled(company)):
Neil Trini Lasrado193c8912017-03-28 17:39:34 +0530943 frappe.local.message_log = []
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530944 form_link = get_link_to_form("Item", item_code)
Marica97715f22020-05-11 20:45:37 +0530945
946 message = _("Valuation Rate for the Item {0}, is required to do accounting entries for {1} {2}.").format(form_link, voucher_type, voucher_no)
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530947 message += "<br><br>" + _("Here are the options to proceed:")
Marica97715f22020-05-11 20:45:37 +0530948 solutions = "<li>" + _("If the item is transacting as a Zero Valuation Rate item in this entry, please enable 'Allow Zero Valuation Rate' in the {0} Item table.").format(voucher_type) + "</li>"
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530949 solutions += "<li>" + _("If not, you can Cancel / Submit this entry") + " {0} ".format(frappe.bold("after")) + _("performing either one below:") + "</li>"
Marica97715f22020-05-11 20:45:37 +0530950 sub_solutions = "<ul><li>" + _("Create an incoming stock transaction for the Item.") + "</li>"
951 sub_solutions += "<li>" + _("Mention Valuation Rate in the Item master.") + "</li></ul>"
952 msg = message + solutions + sub_solutions + "</li>"
953
954 frappe.throw(msg=msg, title=_("Valuation Rate Missing"))
Nabin Haitfb6e4342014-10-15 11:34:40 +0530955
956 return valuation_rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530957
Ankush Menate7109c12021-08-26 16:40:45 +0530958def update_qty_in_future_sle(args, allow_negative_stock=False):
marination8418c4b2021-06-22 21:35:25 +0530959 """Recalculate Qty after Transaction in future SLEs based on current SLE."""
marination40389772021-07-02 17:13:45 +0530960 datetime_limit_condition = ""
marination8418c4b2021-06-22 21:35:25 +0530961 qty_shift = args.actual_qty
962
963 # find difference/shift in qty caused by stock reconciliation
964 if args.voucher_type == "Stock Reconciliation":
marination40389772021-07-02 17:13:45 +0530965 qty_shift = get_stock_reco_qty_shift(args)
966
967 # find the next nearest stock reco so that we only recalculate SLEs till that point
968 next_stock_reco_detail = get_next_stock_reco(args)
969 if next_stock_reco_detail:
970 detail = next_stock_reco_detail[0]
971 # add condition to update SLEs before this date & time
972 datetime_limit_condition = get_datetime_limit_condition(detail)
marination8418c4b2021-06-22 21:35:25 +0530973
Nabin Hait186a0452021-02-18 14:14:21 +0530974 frappe.db.sql("""
975 update `tabStock Ledger Entry`
marination8418c4b2021-06-22 21:35:25 +0530976 set qty_after_transaction = qty_after_transaction + {qty_shift}
Nabin Hait186a0452021-02-18 14:14:21 +0530977 where
978 item_code = %(item_code)s
979 and warehouse = %(warehouse)s
980 and voucher_no != %(voucher_no)s
981 and is_cancelled = 0
982 and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)
983 or (
984 timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s)
985 and creation > %(creation)s
986 )
987 )
marination40389772021-07-02 17:13:45 +0530988 {datetime_limit_condition}
989 """.format(qty_shift=qty_shift, datetime_limit_condition=datetime_limit_condition), args)
Nabin Hait186a0452021-02-18 14:14:21 +0530990
991 validate_negative_qty_in_future_sle(args, allow_negative_stock)
992
marination40389772021-07-02 17:13:45 +0530993def get_stock_reco_qty_shift(args):
994 stock_reco_qty_shift = 0
995 if args.get("is_cancelled"):
996 if args.get("previous_qty_after_transaction"):
997 # get qty (balance) that was set at submission
998 last_balance = args.get("previous_qty_after_transaction")
999 stock_reco_qty_shift = flt(args.qty_after_transaction) - flt(last_balance)
1000 else:
1001 stock_reco_qty_shift = flt(args.actual_qty)
1002 else:
1003 # reco is being submitted
1004 last_balance = get_previous_sle_of_current_voucher(args,
1005 exclude_current_voucher=True).get("qty_after_transaction")
1006
1007 if last_balance is not None:
1008 stock_reco_qty_shift = flt(args.qty_after_transaction) - flt(last_balance)
1009 else:
1010 stock_reco_qty_shift = args.qty_after_transaction
1011
1012 return stock_reco_qty_shift
1013
1014def get_next_stock_reco(args):
1015 """Returns next nearest stock reconciliaton's details."""
1016
1017 return frappe.db.sql("""
1018 select
1019 name, posting_date, posting_time, creation, voucher_no
1020 from
marination8c441262021-07-02 17:46:05 +05301021 `tabStock Ledger Entry`
marination40389772021-07-02 17:13:45 +05301022 where
1023 item_code = %(item_code)s
1024 and warehouse = %(warehouse)s
1025 and voucher_type = 'Stock Reconciliation'
1026 and voucher_no != %(voucher_no)s
1027 and is_cancelled = 0
1028 and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)
1029 or (
1030 timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s)
1031 and creation > %(creation)s
1032 )
1033 )
1034 limit 1
1035 """, args, as_dict=1)
1036
1037def get_datetime_limit_condition(detail):
marination40389772021-07-02 17:13:45 +05301038 return f"""
1039 and
1040 (timestamp(posting_date, posting_time) < timestamp('{detail.posting_date}', '{detail.posting_time}')
1041 or (
1042 timestamp(posting_date, posting_time) = timestamp('{detail.posting_date}', '{detail.posting_time}')
1043 and creation < '{detail.creation}'
1044 )
1045 )"""
1046
Ankush Menate7109c12021-08-26 16:40:45 +05301047def validate_negative_qty_in_future_sle(args, allow_negative_stock=False):
1048 allow_negative_stock = cint(allow_negative_stock) \
Nabin Haita77b8c92020-12-21 14:45:50 +05301049 or cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
1050
marination8418c4b2021-06-22 21:35:25 +05301051 if (args.actual_qty < 0 or args.voucher_type == "Stock Reconciliation") and not allow_negative_stock:
Nabin Haita77b8c92020-12-21 14:45:50 +05301052 sle = get_future_sle_with_negative_qty(args)
1053 if sle:
1054 message = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
1055 abs(sle[0]["qty_after_transaction"]),
1056 frappe.get_desk_link('Item', args.item_code),
1057 frappe.get_desk_link('Warehouse', args.warehouse),
1058 sle[0]["posting_date"], sle[0]["posting_time"],
1059 frappe.get_desk_link(sle[0]["voucher_type"], sle[0]["voucher_no"]))
Deepesh Gargb4be2922021-01-28 13:09:56 +05301060
Nabin Haita77b8c92020-12-21 14:45:50 +05301061 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
1062
1063def get_future_sle_with_negative_qty(args):
1064 return frappe.db.sql("""
1065 select
1066 qty_after_transaction, posting_date, posting_time,
1067 voucher_type, voucher_no
1068 from `tabStock Ledger Entry`
Deepesh Gargb4be2922021-01-28 13:09:56 +05301069 where
Nabin Haita77b8c92020-12-21 14:45:50 +05301070 item_code = %(item_code)s
1071 and warehouse = %(warehouse)s
1072 and voucher_no != %(voucher_no)s
1073 and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s)
1074 and is_cancelled = 0
Nabin Hait186a0452021-02-18 14:14:21 +05301075 and qty_after_transaction < 0
Nabin Hait243d59b2021-02-02 16:55:13 +05301076 order by timestamp(posting_date, posting_time) asc
Nabin Haita77b8c92020-12-21 14:45:50 +05301077 limit 1
Sagar Vorae50324a2021-03-31 12:44:03 +05301078 """, args, as_dict=1)
Ankush Menat6a014d12021-04-12 20:21:27 +05301079
1080def _round_off_if_near_zero(number: float, precision: int = 6) -> float:
1081 """ Rounds off the number to zero only if number is close to zero for decimal
1082 specified in precision. Precision defaults to 6.
1083 """
1084 if flt(number) < (1.0 / (10**precision)):
1085 return 0
1086
1087 return flt(number)