blob: 9fe89c3fa59883245d87038026a3c1be14c5dbe5 [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 _
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +05309from frappe.utils import cint, flt, cstr, now, get_link_to_form
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 Hait902e8602013-01-08 18:29:24 +053016# future reposting
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053017class NegativeStockError(frappe.ValidationError): pass
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +053018class SerialNoExistsInFutureTransaction(frappe.ValidationError):
19 pass
Nabin Hait902e8602013-01-08 18:29:24 +053020
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053021_exceptions = frappe.local('stockledger_exceptions')
Pratik Vyas16371b72013-09-18 18:31:03 +053022# _exceptions = []
Anand Doshi5b004ff2013-09-25 19:55:41 +053023
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053024def make_sl_entries(sl_entries, allow_negative_stock=False, via_landed_cost_voucher=False):
Rohit Waghchaure8520edc2021-06-15 10:21:44 +053025 from erpnext.controllers.stock_controller import future_sle_exists
Nabin Haitca775742013-09-26 16:16:44 +053026 if sl_entries:
Rushabh Mehta1f847992013-12-12 19:12:19 +053027 from erpnext.stock.utils import update_bin
Nabin Haitdc82d4f2014-04-07 12:02:57 +053028
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053029 cancel = sl_entries[0].get("is_cancelled")
Nabin Haitca775742013-09-26 16:16:44 +053030 if cancel:
Nabin Hait186a0452021-02-18 14:14:21 +053031 validate_cancellation(sl_entries)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053032 set_as_cancel(sl_entries[0].get('voucher_type'), sl_entries[0].get('voucher_no'))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053033
Rohit Waghchaure8520edc2021-06-15 10:21:44 +053034 args = get_args_for_future_sle(sl_entries[0])
35 future_sle_exists(args, sl_entries)
36
Nabin Haitca775742013-09-26 16:16:44 +053037 for sle in sl_entries:
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +053038 if sle.serial_no:
39 validate_serial_no(sle)
40
Nabin Haita77b8c92020-12-21 14:45:50 +053041 if cancel:
42 sle['actual_qty'] = -flt(sle.get('actual_qty'))
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053043
Nabin Haita77b8c92020-12-21 14:45:50 +053044 if sle['actual_qty'] < 0 and not sle.get('outgoing_rate'):
45 sle['outgoing_rate'] = get_incoming_outgoing_rate_for_cancel(sle.item_code,
46 sle.voucher_type, sle.voucher_no, sle.voucher_detail_no)
47 sle['incoming_rate'] = 0.0
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053048
Nabin Haita77b8c92020-12-21 14:45:50 +053049 if sle['actual_qty'] > 0 and not sle.get('incoming_rate'):
50 sle['incoming_rate'] = get_incoming_outgoing_rate_for_cancel(sle.item_code,
51 sle.voucher_type, sle.voucher_no, sle.voucher_detail_no)
52 sle['outgoing_rate'] = 0.0
Nabin Haitdc82d4f2014-04-07 12:02:57 +053053
Nabin Hait5288bde2014-11-03 15:08:21 +053054 if sle.get("actual_qty") or sle.get("voucher_type")=="Stock Reconciliation":
Nabin Haita77b8c92020-12-21 14:45:50 +053055 sle_doc = make_entry(sle, allow_negative_stock, via_landed_cost_voucher)
Deepesh Gargb4be2922021-01-28 13:09:56 +053056
Nabin Haita77b8c92020-12-21 14:45:50 +053057 args = sle_doc.as_dict()
Nabin Hait54c865e2015-03-27 15:38:31 +053058 update_bin(args, allow_negative_stock, via_landed_cost_voucher)
Nabin Haitadeb9762014-10-06 11:53:52 +053059
Rohit Waghchaure8520edc2021-06-15 10:21:44 +053060def get_args_for_future_sle(row):
61 return frappe._dict({
62 'voucher_type': row.get('voucher_type'),
63 'voucher_no': row.get('voucher_no'),
64 'posting_date': row.get('posting_date'),
65 'posting_time': row.get('posting_time')
66 })
67
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +053068def validate_serial_no(sle):
69 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
70 for sn in get_serial_nos(sle.serial_no):
71 args = copy.deepcopy(sle)
72 args.serial_no = sn
73 args.warehouse = ''
74
75 vouchers = []
76 for row in get_stock_ledger_entries(args, '>'):
77 voucher_type = frappe.bold(row.voucher_type)
78 voucher_no = frappe.bold(get_link_to_form(row.voucher_type, row.voucher_no))
79 vouchers.append(f'{voucher_type} {voucher_no}')
80
81 if vouchers:
82 serial_no = frappe.bold(sn)
83 msg = (f'''The serial no {serial_no} has been used in the future transactions so you need to cancel them first.
84 The list of the transactions are as below.''' + '<br><br><ul><li>')
85
86 msg += '</li><li>'.join(vouchers)
87 msg += '</li></ul>'
88
89 title = 'Cannot Submit' if not sle.get('is_cancelled') else 'Cannot Cancel'
90 frappe.throw(_(msg), title=_(title), exc=SerialNoExistsInFutureTransaction)
91
Nabin Hait186a0452021-02-18 14:14:21 +053092def validate_cancellation(args):
93 if args[0].get("is_cancelled"):
94 repost_entry = frappe.db.get_value("Repost Item Valuation", {
95 'voucher_type': args[0].voucher_type,
96 'voucher_no': args[0].voucher_no,
97 'docstatus': 1
98 }, ['name', 'status'], as_dict=1)
99
100 if repost_entry:
101 if repost_entry.status == 'In Progress':
102 frappe.throw(_("Cannot cancel the transaction. Reposting of item valuation on submission is not completed yet."))
103 if repost_entry.status == 'Queued':
Nabin Haitd46b2362021-02-23 16:38:52 +0530104 doc = frappe.get_doc("Repost Item Valuation", repost_entry.name)
105 doc.cancel()
106 doc.delete()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530107
Nabin Hait9653f602013-08-20 15:37:33 +0530108def set_as_cancel(voucher_type, voucher_no):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530109 frappe.db.sql("""update `tabStock Ledger Entry` set is_cancelled=1,
Nabin Hait9653f602013-08-20 15:37:33 +0530110 modified=%s, modified_by=%s
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530111 where voucher_type=%s and voucher_no=%s and is_cancelled = 0""",
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530112 (now(), frappe.session.user, voucher_type, voucher_no))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530113
Nabin Hait54c865e2015-03-27 15:38:31 +0530114def make_entry(args, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Hait74c281c2013-08-19 16:17:18 +0530115 args.update({"doctype": "Stock Ledger Entry"})
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530116 sle = frappe.get_doc(args)
Anand Doshi6dfd4302015-02-10 14:41:27 +0530117 sle.flags.ignore_permissions = 1
Nabin Hait4ccd8d32015-01-23 12:18:01 +0530118 sle.allow_negative_stock=allow_negative_stock
Nabin Hait54c865e2015-03-27 15:38:31 +0530119 sle.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Hait74c281c2013-08-19 16:17:18 +0530120 sle.insert()
Nabin Haitaeba24e2013-08-23 15:17:36 +0530121 sle.submit()
Nabin Haita77b8c92020-12-21 14:45:50 +0530122 return sle
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530123
Nabin Hait243d59b2021-02-02 16:55:13 +0530124def repost_future_sle(args=None, voucher_type=None, voucher_no=None, allow_negative_stock=None, via_landed_cost_voucher=False):
Nabin Haita77b8c92020-12-21 14:45:50 +0530125 if not args and voucher_type and voucher_no:
126 args = get_args_for_voucher(voucher_type, voucher_no)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530127
Nabin Haita77b8c92020-12-21 14:45:50 +0530128 distinct_item_warehouses = [(d.item_code, d.warehouse) for d in args]
129
130 i = 0
131 while i < len(args):
132 obj = update_entries_after({
133 "item_code": args[i].item_code,
134 "warehouse": args[i].warehouse,
135 "posting_date": args[i].posting_date,
Nabin Hait186a0452021-02-18 14:14:21 +0530136 "posting_time": args[i].posting_time,
137 "creation": args[i].get("creation")
Nabin Haita77b8c92020-12-21 14:45:50 +0530138 }, allow_negative_stock=allow_negative_stock, via_landed_cost_voucher=via_landed_cost_voucher)
139
140 for item_wh, new_sle in iteritems(obj.new_items):
141 if item_wh not in distinct_item_warehouses:
142 args.append(new_sle)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530143
Nabin Haita77b8c92020-12-21 14:45:50 +0530144 i += 1
145
146def get_args_for_voucher(voucher_type, voucher_no):
147 return frappe.db.get_all("Stock Ledger Entry",
148 filters={"voucher_type": voucher_type, "voucher_no": voucher_no},
Nabin Hait186a0452021-02-18 14:14:21 +0530149 fields=["item_code", "warehouse", "posting_date", "posting_time", "creation"],
Nabin Haita77b8c92020-12-21 14:45:50 +0530150 order_by="creation asc",
151 group_by="item_code, warehouse"
152 )
Nabin Hait74c281c2013-08-19 16:17:18 +0530153
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530154class update_entries_after(object):
Nabin Hait902e8602013-01-08 18:29:24 +0530155 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530156 update valution rate and qty after transaction
Nabin Hait902e8602013-01-08 18:29:24 +0530157 from the current time-bucket onwards
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530158
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530159 :param args: args as dict
160
161 args = {
162 "item_code": "ABC",
163 "warehouse": "XYZ",
164 "posting_date": "2012-12-12",
165 "posting_time": "12:00"
166 }
Nabin Hait902e8602013-01-08 18:29:24 +0530167 """
Anand Doshi0dc79f42015-04-06 12:59:34 +0530168 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 +0530169 self.exceptions = {}
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530170 self.verbose = verbose
171 self.allow_zero_rate = allow_zero_rate
Anand Doshi0dc79f42015-04-06 12:59:34 +0530172 self.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Haita77b8c92020-12-21 14:45:50 +0530173 self.allow_negative_stock = allow_negative_stock \
174 or cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530175
Nabin Haita77b8c92020-12-21 14:45:50 +0530176 self.args = frappe._dict(args)
177 self.item_code = args.get("item_code")
178 if self.args.sle_id:
179 self.args['name'] = self.args.sle_id
Nabin Haitd46b2362021-02-23 16:38:52 +0530180
Nabin Haita77b8c92020-12-21 14:45:50 +0530181 self.company = frappe.get_cached_value("Warehouse", self.args.warehouse, "company")
182 self.get_precision()
183 self.valuation_method = get_valuation_method(self.item_code)
184 self.new_items = {}
185
186 self.data = frappe._dict()
187 self.initialize_previous_data(self.args)
188
189 self.build()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530190
Nabin Haita77b8c92020-12-21 14:45:50 +0530191 def get_precision(self):
192 company_base_currency = frappe.get_cached_value('Company', self.company, "default_currency")
193 self.precision = get_field_precision(frappe.get_meta("Stock Ledger Entry").get_field("stock_value"),
194 currency=company_base_currency)
195
196 def initialize_previous_data(self, args):
197 """
198 Get previous sl entries for current item for each related warehouse
199 and assigns into self.data dict
200
201 :Data Structure:
202
203 self.data = {
204 warehouse1: {
205 'previus_sle': {},
206 'qty_after_transaction': 10,
207 'valuation_rate': 100,
208 'stock_value': 1000,
209 'prev_stock_value': 1000,
210 'stock_queue': '[[10, 100]]',
211 'stock_value_difference': 1000
212 }
213 }
214
215 """
216 self.data.setdefault(args.warehouse, frappe._dict())
217 warehouse_dict = self.data[args.warehouse]
Nabin Hait186a0452021-02-18 14:14:21 +0530218 previous_sle = self.get_previous_sle_of_current_voucher(args)
Nabin Haita77b8c92020-12-21 14:45:50 +0530219 warehouse_dict.previous_sle = previous_sle
Nabin Haitbb777562013-08-29 18:19:37 +0530220
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530221 for key in ("qty_after_transaction", "valuation_rate", "stock_value"):
Nabin Haita77b8c92020-12-21 14:45:50 +0530222 setattr(warehouse_dict, key, flt(previous_sle.get(key)))
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530223
Nabin Haita77b8c92020-12-21 14:45:50 +0530224 warehouse_dict.update({
225 "prev_stock_value": previous_sle.stock_value or 0.0,
226 "stock_queue": json.loads(previous_sle.stock_queue or "[]"),
227 "stock_value_difference": 0.0
228 })
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530229
Nabin Hait186a0452021-02-18 14:14:21 +0530230 def get_previous_sle_of_current_voucher(self, args):
231 """get stock ledger entries filtered by specific posting datetime conditions"""
232
233 args['time_format'] = '%H:%i:%s'
234 if not args.get("posting_date"):
235 args["posting_date"] = "1900-01-01"
236 if not args.get("posting_time"):
237 args["posting_time"] = "00:00"
238
239 sle = frappe.db.sql("""
240 select *, timestamp(posting_date, posting_time) as "timestamp"
241 from `tabStock Ledger Entry`
242 where item_code = %(item_code)s
243 and warehouse = %(warehouse)s
244 and is_cancelled = 0
245 and timestamp(posting_date, time_format(posting_time, %(time_format)s)) < timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
246 order by timestamp(posting_date, posting_time) desc, creation desc
Ankush Menat9979cf52021-05-21 12:12:42 +0530247 limit 1
248 for update""", args, as_dict=1)
Nabin Haitd46b2362021-02-23 16:38:52 +0530249
Nabin Hait186a0452021-02-18 14:14:21 +0530250 return sle[0] if sle else frappe._dict()
251
252
Nabin Haita77b8c92020-12-21 14:45:50 +0530253 def build(self):
Sagar Vorae50324a2021-03-31 12:44:03 +0530254 from erpnext.controllers.stock_controller import future_sle_exists
Nabin Hait186a0452021-02-18 14:14:21 +0530255
Nabin Haita77b8c92020-12-21 14:45:50 +0530256 if self.args.get("sle_id"):
Nabin Hait186a0452021-02-18 14:14:21 +0530257 self.process_sle_against_current_timestamp()
Sagar Vorae50324a2021-03-31 12:44:03 +0530258 if not future_sle_exists(self.args):
Nabin Hait186a0452021-02-18 14:14:21 +0530259 self.update_bin()
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530260 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530261 entries_to_fix = self.get_future_entries_to_fix()
262
263 i = 0
264 while i < len(entries_to_fix):
265 sle = entries_to_fix[i]
266 i += 1
267
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530268 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530269
Nabin Haita77b8c92020-12-21 14:45:50 +0530270 if sle.dependant_sle_voucher_detail_no:
Nabin Hait243d59b2021-02-02 16:55:13 +0530271 entries_to_fix = self.get_dependent_entries_to_fix(entries_to_fix, sle)
Nabin Haitd46b2362021-02-23 16:38:52 +0530272
Nabin Hait186a0452021-02-18 14:14:21 +0530273 self.update_bin()
Nabin Haita77b8c92020-12-21 14:45:50 +0530274
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530275 if self.exceptions:
276 self.raise_exceptions()
277
Nabin Hait186a0452021-02-18 14:14:21 +0530278 def process_sle_against_current_timestamp(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530279 sl_entries = self.get_sle_against_current_voucher()
280 for sle in sl_entries:
281 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530282
Nabin Haita77b8c92020-12-21 14:45:50 +0530283 def get_sle_against_current_voucher(self):
Nabin Haitf2be0802021-02-15 19:27:49 +0530284 self.args['time_format'] = '%H:%i:%s'
285
Nabin Haita77b8c92020-12-21 14:45:50 +0530286 return frappe.db.sql("""
287 select
288 *, timestamp(posting_date, posting_time) as "timestamp"
289 from
290 `tabStock Ledger Entry`
291 where
292 item_code = %(item_code)s
293 and warehouse = %(warehouse)s
Nabin Hait186a0452021-02-18 14:14:21 +0530294 and timestamp(posting_date, time_format(posting_time, %(time_format)s)) = timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
295
Nabin Haita77b8c92020-12-21 14:45:50 +0530296 order by
297 creation ASC
298 for update
299 """, self.args, as_dict=1)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530300
Nabin Haita77b8c92020-12-21 14:45:50 +0530301 def get_future_entries_to_fix(self):
302 # includes current entry!
303 args = self.data[self.args.warehouse].previous_sle \
304 or frappe._dict({"item_code": self.item_code, "warehouse": self.args.warehouse})
Deepesh Gargb4be2922021-01-28 13:09:56 +0530305
Nabin Haita77b8c92020-12-21 14:45:50 +0530306 return list(self.get_sle_after_datetime(args))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530307
Nabin Haita77b8c92020-12-21 14:45:50 +0530308 def get_dependent_entries_to_fix(self, entries_to_fix, sle):
309 dependant_sle = get_sle_by_voucher_detail_no(sle.dependant_sle_voucher_detail_no,
310 excluded_sle=sle.name)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530311
Nabin Haita77b8c92020-12-21 14:45:50 +0530312 if not dependant_sle:
Nabin Hait243d59b2021-02-02 16:55:13 +0530313 return entries_to_fix
Nabin Haita77b8c92020-12-21 14:45:50 +0530314 elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse == self.args.warehouse:
Nabin Hait243d59b2021-02-02 16:55:13 +0530315 return entries_to_fix
316 elif dependant_sle.item_code != self.item_code:
317 if (dependant_sle.item_code, dependant_sle.warehouse) not in self.new_items:
318 self.new_items[(dependant_sle.item_code, dependant_sle.warehouse)] = dependant_sle
319 return entries_to_fix
320 elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse in self.data:
321 return entries_to_fix
Nabin Haita77b8c92020-12-21 14:45:50 +0530322 self.initialize_previous_data(dependant_sle)
323
324 args = self.data[dependant_sle.warehouse].previous_sle \
325 or frappe._dict({"item_code": self.item_code, "warehouse": dependant_sle.warehouse})
326 future_sle_for_dependant = list(self.get_sle_after_datetime(args))
327
328 entries_to_fix.extend(future_sle_for_dependant)
Nabin Hait243d59b2021-02-02 16:55:13 +0530329 return sorted(entries_to_fix, key=lambda k: k['timestamp'])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530330
331 def process_sle(self, sle):
Nabin Haita77b8c92020-12-21 14:45:50 +0530332 # previous sle data for this warehouse
333 self.wh_data = self.data[sle.warehouse]
334
Anand Doshi0dc79f42015-04-06 12:59:34 +0530335 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 +0530336 # validate negative stock for serialized items, fifo valuation
Nabin Hait902e8602013-01-08 18:29:24 +0530337 # or when negative stock is not allowed for moving average
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530338 if not self.validate_negative_stock(sle):
Nabin Haita77b8c92020-12-21 14:45:50 +0530339 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530340 return
Nabin Haitb96c0142014-10-07 11:25:04 +0530341
Nabin Haita77b8c92020-12-21 14:45:50 +0530342 # Get dynamic incoming/outgoing rate
343 self.get_dynamic_incoming_outgoing_rate(sle)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530344
Anand Doshi1b531862013-01-10 19:29:51 +0530345 if sle.serial_no:
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530346 self.get_serialized_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530347 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530348 if sle.voucher_type == "Stock Reconciliation":
Nabin Haita77b8c92020-12-21 14:45:50 +0530349 self.wh_data.qty_after_transaction = sle.qty_after_transaction
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530350
Nabin Haita77b8c92020-12-21 14:45:50 +0530351 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 +0530352 else:
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530353 if sle.voucher_type=="Stock Reconciliation" and not sle.batch_no:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530354 # assert
Nabin Haita77b8c92020-12-21 14:45:50 +0530355 self.wh_data.valuation_rate = sle.valuation_rate
356 self.wh_data.qty_after_transaction = sle.qty_after_transaction
357 self.wh_data.stock_queue = [[self.wh_data.qty_after_transaction, self.wh_data.valuation_rate]]
358 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 +0530359 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530360 if self.valuation_method == "Moving Average":
361 self.get_moving_average_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530362 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
363 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 +0530364 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530365 self.get_fifo_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530366 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
367 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 +0530368
Rushabh Mehta54047782013-12-26 11:07:46 +0530369 # rounding as per precision
Nabin Haita77b8c92020-12-21 14:45:50 +0530370 self.wh_data.stock_value = flt(self.wh_data.stock_value, self.precision)
371 stock_value_difference = self.wh_data.stock_value - self.wh_data.prev_stock_value
372 self.wh_data.prev_stock_value = self.wh_data.stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530373
Nabin Hait902e8602013-01-08 18:29:24 +0530374 # update current sle
Nabin Haita77b8c92020-12-21 14:45:50 +0530375 sle.qty_after_transaction = self.wh_data.qty_after_transaction
376 sle.valuation_rate = self.wh_data.valuation_rate
377 sle.stock_value = self.wh_data.stock_value
378 sle.stock_queue = json.dumps(self.wh_data.stock_queue)
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530379 sle.stock_value_difference = stock_value_difference
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530380 sle.doctype="Stock Ledger Entry"
381 frappe.get_doc(sle).db_update()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530382
Nabin Haita77b8c92020-12-21 14:45:50 +0530383 self.update_outgoing_rate_on_transaction(sle)
384
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530385 def validate_negative_stock(self, sle):
386 """
387 validate negative stock for entries current datetime onwards
388 will not consider cancelled entries
389 """
Nabin Haita77b8c92020-12-21 14:45:50 +0530390 diff = self.wh_data.qty_after_transaction + flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530391
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530392 if diff < 0 and abs(diff) > 0.0001:
393 # negative stock!
394 exc = sle.copy().update({"diff": diff})
Nabin Haita77b8c92020-12-21 14:45:50 +0530395 self.exceptions.setdefault(sle.warehouse, []).append(exc)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530396 return False
Nabin Hait902e8602013-01-08 18:29:24 +0530397 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530398 return True
399
Nabin Haita77b8c92020-12-21 14:45:50 +0530400 def get_dynamic_incoming_outgoing_rate(self, sle):
401 # Get updated incoming/outgoing rate from transaction
402 if sle.recalculate_rate:
403 rate = self.get_incoming_outgoing_rate_from_transaction(sle)
404
405 if flt(sle.actual_qty) >= 0:
406 sle.incoming_rate = rate
407 else:
408 sle.outgoing_rate = rate
409
410 def get_incoming_outgoing_rate_from_transaction(self, sle):
411 rate = 0
412 # Material Transfer, Repack, Manufacturing
413 if sle.voucher_type == "Stock Entry":
414 rate = frappe.db.get_value("Stock Entry Detail", sle.voucher_detail_no, "valuation_rate")
415 # Sales and Purchase Return
416 elif sle.voucher_type in ("Purchase Receipt", "Purchase Invoice", "Delivery Note", "Sales Invoice"):
417 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_return"):
418 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 +0530419 rate = get_rate_for_return(sle.voucher_type, sle.voucher_no, sle.item_code,
420 voucher_detail_no=sle.voucher_detail_no, sle = sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530421 else:
422 if sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530423 rate_field = "valuation_rate"
Nabin Haita77b8c92020-12-21 14:45:50 +0530424 else:
425 rate_field = "incoming_rate"
426
427 # check in item table
428 item_code, incoming_rate = frappe.db.get_value(sle.voucher_type + " Item",
429 sle.voucher_detail_no, ["item_code", rate_field])
430
431 if item_code == sle.item_code:
432 rate = incoming_rate
433 else:
434 if sle.voucher_type in ("Delivery Note", "Sales Invoice"):
435 ref_doctype = "Packed Item"
436 else:
437 ref_doctype = "Purchase Receipt Item Supplied"
Deepesh Gargb4be2922021-01-28 13:09:56 +0530438
Nabin Haita77b8c92020-12-21 14:45:50 +0530439 rate = frappe.db.get_value(ref_doctype, {"parent_detail_docname": sle.voucher_detail_no,
440 "item_code": sle.item_code}, rate_field)
441
442 return rate
443
444 def update_outgoing_rate_on_transaction(self, sle):
445 """
446 Update outgoing rate in Stock Entry, Delivery Note, Sales Invoice and Sales Return
447 In case of Stock Entry, also calculate FG Item rate and total incoming/outgoing amount
448 """
449 if sle.actual_qty and sle.voucher_detail_no:
450 outgoing_rate = abs(flt(sle.stock_value_difference)) / abs(sle.actual_qty)
451
452 if flt(sle.actual_qty) < 0 and sle.voucher_type == "Stock Entry":
453 self.update_rate_on_stock_entry(sle, outgoing_rate)
454 elif sle.voucher_type in ("Delivery Note", "Sales Invoice"):
455 self.update_rate_on_delivery_and_sales_return(sle, outgoing_rate)
456 elif flt(sle.actual_qty) < 0 and sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
457 self.update_rate_on_purchase_receipt(sle, outgoing_rate)
458
459 def update_rate_on_stock_entry(self, sle, outgoing_rate):
460 frappe.db.set_value("Stock Entry Detail", sle.voucher_detail_no, "basic_rate", outgoing_rate)
461
462 # Update outgoing item's rate, recalculate FG Item's rate and total incoming/outgoing amount
rohitwaghchaure00ea3362021-05-01 13:53:39 +0530463 stock_entry = frappe.get_doc("Stock Entry", sle.voucher_no, for_update=True)
Nabin Haita77b8c92020-12-21 14:45:50 +0530464 stock_entry.calculate_rate_and_amount(reset_outgoing_rate=False, raise_error_if_no_rate=False)
465 stock_entry.db_update()
466 for d in stock_entry.items:
467 d.db_update()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530468
Nabin Haita77b8c92020-12-21 14:45:50 +0530469 def update_rate_on_delivery_and_sales_return(self, sle, outgoing_rate):
470 # Update item's incoming rate on transaction
471 item_code = frappe.db.get_value(sle.voucher_type + " Item", sle.voucher_detail_no, "item_code")
472 if item_code == sle.item_code:
473 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "incoming_rate", outgoing_rate)
474 else:
475 # packed item
476 frappe.db.set_value("Packed Item",
477 {"parent_detail_docname": sle.voucher_detail_no, "item_code": sle.item_code},
478 "incoming_rate", outgoing_rate)
479
480 def update_rate_on_purchase_receipt(self, sle, outgoing_rate):
481 if frappe.db.exists(sle.voucher_type + " Item", sle.voucher_detail_no):
482 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "base_net_rate", outgoing_rate)
483 else:
484 frappe.db.set_value("Purchase Receipt Item Supplied", sle.voucher_detail_no, "rate", outgoing_rate)
485
486 # Recalculate subcontracted item's rate in case of subcontracted purchase receipt/invoice
Rohit Waghchaure8520edc2021-06-15 10:21:44 +0530487 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_subcontracted") == 'Yes':
Rohit Waghchauref5db4072021-06-18 20:37:42 +0530488 doc = frappe.get_doc(sle.voucher_type, sle.voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530489 doc.update_valuation_rate(reset_outgoing_rate=False)
490 for d in (doc.items + doc.supplied_items):
491 d.db_update()
492
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530493 def get_serialized_values(self, sle):
494 incoming_rate = flt(sle.incoming_rate)
495 actual_qty = flt(sle.actual_qty)
Nabin Hait328c4f92020-01-02 19:00:32 +0530496 serial_nos = cstr(sle.serial_no).split("\n")
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530497
498 if incoming_rate < 0:
499 # wrong incoming rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530500 incoming_rate = self.wh_data.valuation_rate
Rushabh Mehta538607e2016-06-12 11:03:00 +0530501
Nabin Hait2620bf42016-02-29 11:30:27 +0530502 stock_value_change = 0
503 if incoming_rate:
504 stock_value_change = actual_qty * incoming_rate
505 elif actual_qty < 0:
506 # In case of delivery/stock issue, get average purchase rate
507 # of serial nos of current entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530508 if not sle.is_cancelled:
509 outgoing_value = self.get_incoming_value_for_serial_nos(sle, serial_nos)
510 stock_value_change = -1 * outgoing_value
511 else:
512 stock_value_change = actual_qty * sle.outgoing_rate
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530513
Nabin Haita77b8c92020-12-21 14:45:50 +0530514 new_stock_qty = self.wh_data.qty_after_transaction + actual_qty
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530515
Nabin Hait2620bf42016-02-29 11:30:27 +0530516 if new_stock_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530517 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + stock_value_change
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530518 if new_stock_value >= 0:
Nabin Hait2620bf42016-02-29 11:30:27 +0530519 # calculate new valuation rate only if stock value is positive
520 # else it remains the same as that of previous entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530521 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530522
Nabin Haita77b8c92020-12-21 14:45:50 +0530523 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530524 allow_zero_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
525 if not allow_zero_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530526 self.wh_data.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530527 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
528 currency=erpnext.get_company_currency(sle.company))
529
Nabin Hait328c4f92020-01-02 19:00:32 +0530530 def get_incoming_value_for_serial_nos(self, sle, serial_nos):
531 # get rate from serial nos within same company
532 all_serial_nos = frappe.get_all("Serial No",
533 fields=["purchase_rate", "name", "company"],
534 filters = {'name': ('in', serial_nos)})
535
Ankush Menata9c84f72021-06-11 16:00:48 +0530536 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 +0530537
538 # Get rate for serial nos which has been transferred to other company
539 invalid_serial_nos = [d.name for d in all_serial_nos if d.company!=sle.company]
540 for serial_no in invalid_serial_nos:
541 incoming_rate = frappe.db.sql("""
542 select incoming_rate
543 from `tabStock Ledger Entry`
544 where
545 company = %s
546 and actual_qty > 0
547 and (serial_no = %s
548 or serial_no like %s
549 or serial_no like %s
550 or serial_no like %s
551 )
552 order by posting_date desc
553 limit 1
554 """, (sle.company, serial_no, serial_no+'\n%', '%\n'+serial_no, '%\n'+serial_no+'\n%'))
555
556 incoming_values += flt(incoming_rate[0][0]) if incoming_rate else 0
557
558 return incoming_values
559
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530560 def get_moving_average_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530561 actual_qty = flt(sle.actual_qty)
Nabin Haita77b8c92020-12-21 14:45:50 +0530562 new_stock_qty = flt(self.wh_data.qty_after_transaction) + actual_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530563 if new_stock_qty >= 0:
564 if actual_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530565 if flt(self.wh_data.qty_after_transaction) <= 0:
566 self.wh_data.valuation_rate = sle.incoming_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530567 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530568 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530569 (actual_qty * sle.incoming_rate)
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530570
Nabin Haita77b8c92020-12-21 14:45:50 +0530571 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530572
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530573 elif sle.outgoing_rate:
574 if new_stock_qty:
Nabin Haita77b8c92020-12-21 14:45:50 +0530575 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530576 (actual_qty * sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530577
Nabin Haita77b8c92020-12-21 14:45:50 +0530578 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530579 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530580 self.wh_data.valuation_rate = sle.outgoing_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530581 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530582 if flt(self.wh_data.qty_after_transaction) >= 0 and sle.outgoing_rate:
583 self.wh_data.valuation_rate = sle.outgoing_rate
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530584
Nabin Haita77b8c92020-12-21 14:45:50 +0530585 if not self.wh_data.valuation_rate and actual_qty > 0:
586 self.wh_data.valuation_rate = sle.incoming_rate
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530587
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530588 # Get valuation rate from previous SLE or Item master, if item does not have the
Javier Wong9b11d9b2017-04-14 18:24:04 +0800589 # allow zero valuration rate flag set
Nabin Haita77b8c92020-12-21 14:45:50 +0530590 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
Javier Wong9b11d9b2017-04-14 18:24:04 +0800591 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
592 if not allow_zero_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530593 self.wh_data.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530594 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
595 currency=erpnext.get_company_currency(sle.company))
596
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530597 def get_fifo_values(self, sle):
598 incoming_rate = flt(sle.incoming_rate)
599 actual_qty = flt(sle.actual_qty)
Nabin Haitada485f2015-07-17 15:09:56 +0530600 outgoing_rate = flt(sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530601
602 if actual_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530603 if not self.wh_data.stock_queue:
604 self.wh_data.stock_queue.append([0, 0])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530605
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530606 # last row has the same rate, just updated the qty
Nabin Haita77b8c92020-12-21 14:45:50 +0530607 if self.wh_data.stock_queue[-1][1]==incoming_rate:
608 self.wh_data.stock_queue[-1][0] += actual_qty
Nabin Hait4d742162014-10-09 19:25:03 +0530609 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530610 if self.wh_data.stock_queue[-1][0] > 0:
611 self.wh_data.stock_queue.append([actual_qty, incoming_rate])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530612 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530613 qty = self.wh_data.stock_queue[-1][0] + actual_qty
614 self.wh_data.stock_queue[-1] = [qty, incoming_rate]
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530615 else:
616 qty_to_pop = abs(actual_qty)
617 while qty_to_pop:
Nabin Haita77b8c92020-12-21 14:45:50 +0530618 if not self.wh_data.stock_queue:
Nabin Haita0b967f2017-01-18 18:35:58 +0530619 # Get valuation rate from last sle if exists or from valuation rate field in item master
Javier Wong9b11d9b2017-04-14 18:24:04 +0800620 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
621 if not allow_zero_valuation_rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530622 _rate = get_valuation_rate(sle.item_code, sle.warehouse,
623 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
624 currency=erpnext.get_company_currency(sle.company))
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530625 else:
626 _rate = 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530627
Nabin Haita77b8c92020-12-21 14:45:50 +0530628 self.wh_data.stock_queue.append([0, _rate])
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530629
Nabin Haitada485f2015-07-17 15:09:56 +0530630 index = None
631 if outgoing_rate > 0:
632 # Find the entry where rate matched with outgoing rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530633 for i, v in enumerate(self.wh_data.stock_queue):
Nabin Haitada485f2015-07-17 15:09:56 +0530634 if v[1] == outgoing_rate:
635 index = i
636 break
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530637
Nabin Haitada485f2015-07-17 15:09:56 +0530638 # If no entry found with outgoing rate, collapse stack
Ankush Menat4dcac4a2021-05-21 13:12:30 +0530639 if index is None: # nosemgrep
Nabin Haita77b8c92020-12-21 14:45:50 +0530640 new_stock_value = sum((d[0]*d[1] for d in self.wh_data.stock_queue)) - qty_to_pop*outgoing_rate
641 new_stock_qty = sum((d[0] for d in self.wh_data.stock_queue)) - qty_to_pop
642 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 +0530643 break
644 else:
645 index = 0
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530646
Nabin Haitada485f2015-07-17 15:09:56 +0530647 # select first batch or the batch with same rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530648 batch = self.wh_data.stock_queue[index]
Nabin Hait8142cd22015-08-05 18:57:26 +0530649 if qty_to_pop >= batch[0]:
650 # consume current batch
Ankush Menat6a014d12021-04-12 20:21:27 +0530651 qty_to_pop = _round_off_if_near_zero(qty_to_pop - batch[0])
Nabin Haita77b8c92020-12-21 14:45:50 +0530652 self.wh_data.stock_queue.pop(index)
653 if not self.wh_data.stock_queue and qty_to_pop:
Nabin Hait8142cd22015-08-05 18:57:26 +0530654 # stock finished, qty still remains to be withdrawn
655 # negative stock, keep in as a negative batch
Nabin Haita77b8c92020-12-21 14:45:50 +0530656 self.wh_data.stock_queue.append([-qty_to_pop, outgoing_rate or batch[1]])
Nabin Hait8142cd22015-08-05 18:57:26 +0530657 break
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530658
Nabin Hait8142cd22015-08-05 18:57:26 +0530659 else:
660 # qty found in current batch
661 # consume it and exit
662 batch[0] = batch[0] - qty_to_pop
663 qty_to_pop = 0
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530664
Ankush Menat6a014d12021-04-12 20:21:27 +0530665 stock_value = _round_off_if_near_zero(sum((flt(batch[0]) * flt(batch[1]) for batch in self.wh_data.stock_queue)))
666 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 +0530667
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530668 if stock_qty:
Nabin Haita77b8c92020-12-21 14:45:50 +0530669 self.wh_data.valuation_rate = stock_value / flt(stock_qty)
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530670
Nabin Haita77b8c92020-12-21 14:45:50 +0530671 if not self.wh_data.stock_queue:
672 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 +0530673
Javier Wong9b11d9b2017-04-14 18:24:04 +0800674 def check_if_allow_zero_valuation_rate(self, voucher_type, voucher_detail_no):
deepeshgarg007f9c0ef32019-07-30 18:49:19 +0530675 ref_item_dt = ""
676
677 if voucher_type == "Stock Entry":
678 ref_item_dt = voucher_type + " Detail"
679 elif voucher_type in ["Purchase Invoice", "Sales Invoice", "Delivery Note", "Purchase Receipt"]:
680 ref_item_dt = voucher_type + " Item"
681
682 if ref_item_dt:
683 return frappe.db.get_value(ref_item_dt, voucher_detail_no, "allow_zero_valuation_rate")
684 else:
685 return 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530686
Nabin Haita77b8c92020-12-21 14:45:50 +0530687 def get_sle_before_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530688 """get previous stock ledger entry before current time-bucket"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530689 sle = get_stock_ledger_entries(args, "<", "desc", "limit 1", for_update=False)
690 sle = sle[0] if sle else frappe._dict()
691 return sle
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530692
Nabin Haita77b8c92020-12-21 14:45:50 +0530693 def get_sle_after_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530694 """get Stock Ledger Entries after a particular datetime, for reposting"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530695 return get_stock_ledger_entries(args, ">", "asc", for_update=True, check_serial_no=False)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530696
697 def raise_exceptions(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530698 msg_list = []
699 for warehouse, exceptions in iteritems(self.exceptions):
700 deficiency = min(e["diff"] for e in exceptions)
Rushabh Mehta538607e2016-06-12 11:03:00 +0530701
Nabin Haita77b8c92020-12-21 14:45:50 +0530702 if ((exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]) in
703 frappe.local.flags.currently_saving):
Nabin Hait3edefb12016-07-20 16:13:18 +0530704
Nabin Haita77b8c92020-12-21 14:45:50 +0530705 msg = _("{0} units of {1} needed in {2} to complete this transaction.").format(
Nabin Hait243d59b2021-02-02 16:55:13 +0530706 abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]),
Nabin Haita77b8c92020-12-21 14:45:50 +0530707 frappe.get_desk_link('Warehouse', warehouse))
708 else:
709 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 +0530710 abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]),
Nabin Haita77b8c92020-12-21 14:45:50 +0530711 frappe.get_desk_link('Warehouse', warehouse),
712 exceptions[0]["posting_date"], exceptions[0]["posting_time"],
713 frappe.get_desk_link(exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530714
Nabin Haita77b8c92020-12-21 14:45:50 +0530715 if msg:
716 msg_list.append(msg)
717
718 if msg_list:
719 message = "\n\n".join(msg_list)
720 if self.verbose:
721 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
722 else:
723 raise NegativeStockError(message)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530724
Nabin Haita77b8c92020-12-21 14:45:50 +0530725 def update_bin(self):
726 # update bin for each warehouse
727 for warehouse, data in iteritems(self.data):
728 bin_doc = get_bin(self.item_code, warehouse)
Nabin Haita77b8c92020-12-21 14:45:50 +0530729 bin_doc.update({
730 "valuation_rate": data.valuation_rate,
731 "actual_qty": data.qty_after_transaction,
732 "stock_value": data.stock_value
733 })
734 bin_doc.flags.via_stock_ledger_entry = True
735 bin_doc.save(ignore_permissions=True)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530736
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530737def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530738 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530739 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530740 to get actual qty before transaction, this function
741 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530742
Anand Doshi1b531862013-01-10 19:29:51 +0530743 args = {
744 "item_code": "ABC",
745 "warehouse": "XYZ",
746 "posting_date": "2012-12-12",
747 "posting_time": "12:00",
748 "sle": "name of reference Stock Ledger Entry"
749 }
750 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530751 args["name"] = args.get("sle", None) or ""
752 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530753 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530754
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530755def get_stock_ledger_entries(previous_sle, operator=None,
756 order="desc", limit=None, for_update=False, debug=False, check_serial_no=True):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530757 """get stock ledger entries filtered by specific posting datetime conditions"""
Nabin Haitb9ce1042018-02-01 14:58:50 +0530758 conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
759 if previous_sle.get("warehouse"):
760 conditions += " and warehouse = %(warehouse)s"
761 elif previous_sle.get("warehouse_condition"):
762 conditions += " and " + previous_sle.get("warehouse_condition")
763
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530764 if check_serial_no and previous_sle.get("serial_no"):
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530765 # conditions += " and serial_no like {}".format(frappe.db.escape('%{0}%'.format(previous_sle.get("serial_no"))))
766 serial_no = previous_sle.get("serial_no")
767 conditions += (""" and
768 (
769 serial_no = {0}
770 or serial_no like {1}
771 or serial_no like {2}
772 or serial_no like {3}
773 )
774 """).format(frappe.db.escape(serial_no), frappe.db.escape('{}\n%'.format(serial_no)),
775 frappe.db.escape('%\n{}'.format(serial_no)), frappe.db.escape('%\n{}\n%'.format(serial_no)))
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530776
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530777 if not previous_sle.get("posting_date"):
778 previous_sle["posting_date"] = "1900-01-01"
779 if not previous_sle.get("posting_time"):
780 previous_sle["posting_time"] = "00:00"
781
782 if operator in (">", "<=") and previous_sle.get("name"):
783 conditions += " and name!=%(name)s"
784
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530785 return frappe.db.sql("""
786 select *, timestamp(posting_date, posting_time) as "timestamp"
787 from `tabStock Ledger Entry`
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530788 where item_code = %%(item_code)s
Nabin Haita77b8c92020-12-21 14:45:50 +0530789 and is_cancelled = 0
Nabin Haitb9ce1042018-02-01 14:58:50 +0530790 %(conditions)s
Aditya Hase0c164242019-01-07 22:07:13 +0530791 order by timestamp(posting_date, posting_time) %(order)s, creation %(order)s
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530792 %(limit)s %(for_update)s""" % {
793 "conditions": conditions,
794 "limit": limit or "",
795 "for_update": for_update and "for update" or "",
796 "order": order
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530797 }, previous_sle, as_dict=1, debug=debug)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530798
Nabin Haita77b8c92020-12-21 14:45:50 +0530799def get_sle_by_voucher_detail_no(voucher_detail_no, excluded_sle=None):
800 return frappe.db.get_value('Stock Ledger Entry',
801 {'voucher_detail_no': voucher_detail_no, 'name': ['!=', excluded_sle]},
802 ['item_code', 'warehouse', 'posting_date', 'posting_time', 'timestamp(posting_date, posting_time) as timestamp'],
803 as_dict=1)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530804
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530805def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no,
Nabin Hait7ba092e2018-02-01 10:51:27 +0530806 allow_zero_rate=False, currency=None, company=None, raise_error_if_no_rate=True):
Nabin Haita0b967f2017-01-18 18:35:58 +0530807 # Get valuation rate from last sle for the same item and warehouse
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530808 if not company:
809 company = erpnext.get_default_company()
810
Nabin Haitfb6e4342014-10-15 11:34:40 +0530811 last_valuation_rate = frappe.db.sql("""select valuation_rate
812 from `tabStock Ledger Entry`
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530813 where
814 item_code = %s
815 AND warehouse = %s
816 AND valuation_rate >= 0
817 AND NOT (voucher_no = %s AND voucher_type = %s)
818 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 +0530819
820 if not last_valuation_rate:
Nabin Haita0b967f2017-01-18 18:35:58 +0530821 # Get valuation rate from last sle for the item against any warehouse
Nabin Haitfb6e4342014-10-15 11:34:40 +0530822 last_valuation_rate = frappe.db.sql("""select valuation_rate
823 from `tabStock Ledger Entry`
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530824 where
825 item_code = %s
826 AND valuation_rate > 0
827 AND NOT(voucher_no = %s AND voucher_type = %s)
828 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 +0530829
Nabin Haita645f362018-03-01 10:31:24 +0530830 if last_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530831 return flt(last_valuation_rate[0][0])
Nabin Haita645f362018-03-01 10:31:24 +0530832
833 # If negative stock allowed, and item delivered without any incoming entry,
834 # system does not found any SLE, then take valuation rate from Item
835 valuation_rate = frappe.db.get_value("Item", item_code, "valuation_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530836
837 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530838 # try Item Standard rate
839 valuation_rate = frappe.db.get_value("Item", item_code, "standard_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530840
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530841 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530842 # try in price list
843 valuation_rate = frappe.db.get_value('Item Price',
844 dict(item_code=item_code, buying=1, currency=currency),
845 'price_list_rate')
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530846
Nabin Hait7ba092e2018-02-01 10:51:27 +0530847 if not allow_zero_rate and not valuation_rate and raise_error_if_no_rate \
Rohit Waghchauree9ff1912017-06-19 12:54:59 +0530848 and cint(erpnext.is_perpetual_inventory_enabled(company)):
Neil Trini Lasrado193c8912017-03-28 17:39:34 +0530849 frappe.local.message_log = []
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530850 form_link = get_link_to_form("Item", item_code)
Marica97715f22020-05-11 20:45:37 +0530851
852 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 +0530853 message += "<br><br>" + _("Here are the options to proceed:")
Marica97715f22020-05-11 20:45:37 +0530854 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 +0530855 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 +0530856 sub_solutions = "<ul><li>" + _("Create an incoming stock transaction for the Item.") + "</li>"
857 sub_solutions += "<li>" + _("Mention Valuation Rate in the Item master.") + "</li></ul>"
858 msg = message + solutions + sub_solutions + "</li>"
859
860 frappe.throw(msg=msg, title=_("Valuation Rate Missing"))
Nabin Haitfb6e4342014-10-15 11:34:40 +0530861
862 return valuation_rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530863
Nabin Hait186a0452021-02-18 14:14:21 +0530864def update_qty_in_future_sle(args, allow_negative_stock=None):
865 frappe.db.sql("""
866 update `tabStock Ledger Entry`
867 set qty_after_transaction = qty_after_transaction + {qty}
868 where
869 item_code = %(item_code)s
870 and warehouse = %(warehouse)s
871 and voucher_no != %(voucher_no)s
872 and is_cancelled = 0
873 and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)
874 or (
875 timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s)
876 and creation > %(creation)s
877 )
878 )
879 """.format(qty=args.actual_qty), args)
880
881 validate_negative_qty_in_future_sle(args, allow_negative_stock)
882
Nabin Haita77b8c92020-12-21 14:45:50 +0530883def validate_negative_qty_in_future_sle(args, allow_negative_stock=None):
884 allow_negative_stock = allow_negative_stock \
885 or cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
886
887 if args.actual_qty < 0 and not allow_negative_stock:
888 sle = get_future_sle_with_negative_qty(args)
889 if sle:
890 message = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
891 abs(sle[0]["qty_after_transaction"]),
892 frappe.get_desk_link('Item', args.item_code),
893 frappe.get_desk_link('Warehouse', args.warehouse),
894 sle[0]["posting_date"], sle[0]["posting_time"],
895 frappe.get_desk_link(sle[0]["voucher_type"], sle[0]["voucher_no"]))
Deepesh Gargb4be2922021-01-28 13:09:56 +0530896
Nabin Haita77b8c92020-12-21 14:45:50 +0530897 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
898
899def get_future_sle_with_negative_qty(args):
900 return frappe.db.sql("""
901 select
902 qty_after_transaction, posting_date, posting_time,
903 voucher_type, voucher_no
904 from `tabStock Ledger Entry`
Deepesh Gargb4be2922021-01-28 13:09:56 +0530905 where
Nabin Haita77b8c92020-12-21 14:45:50 +0530906 item_code = %(item_code)s
907 and warehouse = %(warehouse)s
908 and voucher_no != %(voucher_no)s
909 and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s)
910 and is_cancelled = 0
Nabin Hait186a0452021-02-18 14:14:21 +0530911 and qty_after_transaction < 0
Nabin Hait243d59b2021-02-02 16:55:13 +0530912 order by timestamp(posting_date, posting_time) asc
Nabin Haita77b8c92020-12-21 14:45:50 +0530913 limit 1
Sagar Vorae50324a2021-03-31 12:44:03 +0530914 """, args, as_dict=1)
Ankush Menat6a014d12021-04-12 20:21:27 +0530915
916def _round_off_if_near_zero(number: float, precision: int = 6) -> float:
917 """ Rounds off the number to zero only if number is close to zero for decimal
918 specified in precision. Precision defaults to 6.
919 """
920 if flt(number) < (1.0 / (10**precision)):
921 return 0
922
923 return flt(number)