blob: b2825fc26f5a9433f04037e6d5c47818e3cdb9b1 [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):
Nabin Haitca775742013-09-26 16:16:44 +053025 if sl_entries:
Rushabh Mehta1f847992013-12-12 19:12:19 +053026 from erpnext.stock.utils import update_bin
Nabin Haitdc82d4f2014-04-07 12:02:57 +053027
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053028 cancel = sl_entries[0].get("is_cancelled")
Nabin Haitca775742013-09-26 16:16:44 +053029 if cancel:
Nabin Hait186a0452021-02-18 14:14:21 +053030 validate_cancellation(sl_entries)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053031 set_as_cancel(sl_entries[0].get('voucher_type'), sl_entries[0].get('voucher_no'))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053032
Nabin Haitca775742013-09-26 16:16:44 +053033 for sle in sl_entries:
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +053034 if sle.serial_no:
35 validate_serial_no(sle)
36
Nabin Haita77b8c92020-12-21 14:45:50 +053037 if cancel:
38 sle['actual_qty'] = -flt(sle.get('actual_qty'))
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053039
Nabin Haita77b8c92020-12-21 14:45:50 +053040 if sle['actual_qty'] < 0 and not sle.get('outgoing_rate'):
41 sle['outgoing_rate'] = get_incoming_outgoing_rate_for_cancel(sle.item_code,
42 sle.voucher_type, sle.voucher_no, sle.voucher_detail_no)
43 sle['incoming_rate'] = 0.0
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('incoming_rate'):
46 sle['incoming_rate'] = get_incoming_outgoing_rate_for_cancel(sle.item_code,
47 sle.voucher_type, sle.voucher_no, sle.voucher_detail_no)
48 sle['outgoing_rate'] = 0.0
Nabin Haitdc82d4f2014-04-07 12:02:57 +053049
Nabin Hait5288bde2014-11-03 15:08:21 +053050 if sle.get("actual_qty") or sle.get("voucher_type")=="Stock Reconciliation":
Nabin Haita77b8c92020-12-21 14:45:50 +053051 sle_doc = make_entry(sle, allow_negative_stock, via_landed_cost_voucher)
Deepesh Gargb4be2922021-01-28 13:09:56 +053052
Nabin Haita77b8c92020-12-21 14:45:50 +053053 args = sle_doc.as_dict()
Nabin Hait54c865e2015-03-27 15:38:31 +053054 update_bin(args, allow_negative_stock, via_landed_cost_voucher)
Nabin Haitadeb9762014-10-06 11:53:52 +053055
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +053056def validate_serial_no(sle):
57 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
58 for sn in get_serial_nos(sle.serial_no):
59 args = copy.deepcopy(sle)
60 args.serial_no = sn
61 args.warehouse = ''
62
63 vouchers = []
64 for row in get_stock_ledger_entries(args, '>'):
65 voucher_type = frappe.bold(row.voucher_type)
66 voucher_no = frappe.bold(get_link_to_form(row.voucher_type, row.voucher_no))
67 vouchers.append(f'{voucher_type} {voucher_no}')
68
69 if vouchers:
70 serial_no = frappe.bold(sn)
71 msg = (f'''The serial no {serial_no} has been used in the future transactions so you need to cancel them first.
72 The list of the transactions are as below.''' + '<br><br><ul><li>')
73
74 msg += '</li><li>'.join(vouchers)
75 msg += '</li></ul>'
76
77 title = 'Cannot Submit' if not sle.get('is_cancelled') else 'Cannot Cancel'
78 frappe.throw(_(msg), title=_(title), exc=SerialNoExistsInFutureTransaction)
79
Nabin Hait186a0452021-02-18 14:14:21 +053080def validate_cancellation(args):
81 if args[0].get("is_cancelled"):
82 repost_entry = frappe.db.get_value("Repost Item Valuation", {
83 'voucher_type': args[0].voucher_type,
84 'voucher_no': args[0].voucher_no,
85 'docstatus': 1
86 }, ['name', 'status'], as_dict=1)
87
88 if repost_entry:
89 if repost_entry.status == 'In Progress':
90 frappe.throw(_("Cannot cancel the transaction. Reposting of item valuation on submission is not completed yet."))
91 if repost_entry.status == 'Queued':
Nabin Haitd46b2362021-02-23 16:38:52 +053092 doc = frappe.get_doc("Repost Item Valuation", repost_entry.name)
93 doc.cancel()
94 doc.delete()
Nabin Haitdc82d4f2014-04-07 12:02:57 +053095
Nabin Hait9653f602013-08-20 15:37:33 +053096def set_as_cancel(voucher_type, voucher_no):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053097 frappe.db.sql("""update `tabStock Ledger Entry` set is_cancelled=1,
Nabin Hait9653f602013-08-20 15:37:33 +053098 modified=%s, modified_by=%s
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053099 where voucher_type=%s and voucher_no=%s and is_cancelled = 0""",
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530100 (now(), frappe.session.user, voucher_type, voucher_no))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530101
Nabin Hait54c865e2015-03-27 15:38:31 +0530102def make_entry(args, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Hait74c281c2013-08-19 16:17:18 +0530103 args.update({"doctype": "Stock Ledger Entry"})
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530104 sle = frappe.get_doc(args)
Anand Doshi6dfd4302015-02-10 14:41:27 +0530105 sle.flags.ignore_permissions = 1
Nabin Hait4ccd8d32015-01-23 12:18:01 +0530106 sle.allow_negative_stock=allow_negative_stock
Nabin Hait54c865e2015-03-27 15:38:31 +0530107 sle.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Hait74c281c2013-08-19 16:17:18 +0530108 sle.insert()
Nabin Haitaeba24e2013-08-23 15:17:36 +0530109 sle.submit()
Nabin Haita77b8c92020-12-21 14:45:50 +0530110 return sle
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530111
Nabin Hait243d59b2021-02-02 16:55:13 +0530112def 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 +0530113 if not args and voucher_type and voucher_no:
114 args = get_args_for_voucher(voucher_type, voucher_no)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530115
Nabin Haita77b8c92020-12-21 14:45:50 +0530116 distinct_item_warehouses = [(d.item_code, d.warehouse) for d in args]
117
118 i = 0
119 while i < len(args):
120 obj = update_entries_after({
121 "item_code": args[i].item_code,
122 "warehouse": args[i].warehouse,
123 "posting_date": args[i].posting_date,
Nabin Hait186a0452021-02-18 14:14:21 +0530124 "posting_time": args[i].posting_time,
125 "creation": args[i].get("creation")
Nabin Haita77b8c92020-12-21 14:45:50 +0530126 }, allow_negative_stock=allow_negative_stock, via_landed_cost_voucher=via_landed_cost_voucher)
127
128 for item_wh, new_sle in iteritems(obj.new_items):
129 if item_wh not in distinct_item_warehouses:
130 args.append(new_sle)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530131
Nabin Haita77b8c92020-12-21 14:45:50 +0530132 i += 1
133
134def get_args_for_voucher(voucher_type, voucher_no):
135 return frappe.db.get_all("Stock Ledger Entry",
136 filters={"voucher_type": voucher_type, "voucher_no": voucher_no},
Nabin Hait186a0452021-02-18 14:14:21 +0530137 fields=["item_code", "warehouse", "posting_date", "posting_time", "creation"],
Nabin Haita77b8c92020-12-21 14:45:50 +0530138 order_by="creation asc",
139 group_by="item_code, warehouse"
140 )
Nabin Hait74c281c2013-08-19 16:17:18 +0530141
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530142class update_entries_after(object):
Nabin Hait902e8602013-01-08 18:29:24 +0530143 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530144 update valution rate and qty after transaction
Nabin Hait902e8602013-01-08 18:29:24 +0530145 from the current time-bucket onwards
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530146
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530147 :param args: args as dict
148
149 args = {
150 "item_code": "ABC",
151 "warehouse": "XYZ",
152 "posting_date": "2012-12-12",
153 "posting_time": "12:00"
154 }
Nabin Hait902e8602013-01-08 18:29:24 +0530155 """
Anand Doshi0dc79f42015-04-06 12:59:34 +0530156 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 +0530157 self.exceptions = {}
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530158 self.verbose = verbose
159 self.allow_zero_rate = allow_zero_rate
Anand Doshi0dc79f42015-04-06 12:59:34 +0530160 self.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Haita77b8c92020-12-21 14:45:50 +0530161 self.allow_negative_stock = allow_negative_stock \
162 or cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530163
Nabin Haita77b8c92020-12-21 14:45:50 +0530164 self.args = frappe._dict(args)
165 self.item_code = args.get("item_code")
166 if self.args.sle_id:
167 self.args['name'] = self.args.sle_id
Nabin Haitd46b2362021-02-23 16:38:52 +0530168
Nabin Haita77b8c92020-12-21 14:45:50 +0530169 self.company = frappe.get_cached_value("Warehouse", self.args.warehouse, "company")
170 self.get_precision()
171 self.valuation_method = get_valuation_method(self.item_code)
172 self.new_items = {}
173
174 self.data = frappe._dict()
175 self.initialize_previous_data(self.args)
176
177 self.build()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530178
Nabin Haita77b8c92020-12-21 14:45:50 +0530179 def get_precision(self):
180 company_base_currency = frappe.get_cached_value('Company', self.company, "default_currency")
181 self.precision = get_field_precision(frappe.get_meta("Stock Ledger Entry").get_field("stock_value"),
182 currency=company_base_currency)
183
184 def initialize_previous_data(self, args):
185 """
186 Get previous sl entries for current item for each related warehouse
187 and assigns into self.data dict
188
189 :Data Structure:
190
191 self.data = {
192 warehouse1: {
193 'previus_sle': {},
194 'qty_after_transaction': 10,
195 'valuation_rate': 100,
196 'stock_value': 1000,
197 'prev_stock_value': 1000,
198 'stock_queue': '[[10, 100]]',
199 'stock_value_difference': 1000
200 }
201 }
202
203 """
204 self.data.setdefault(args.warehouse, frappe._dict())
205 warehouse_dict = self.data[args.warehouse]
Nabin Hait186a0452021-02-18 14:14:21 +0530206 previous_sle = self.get_previous_sle_of_current_voucher(args)
Nabin Haita77b8c92020-12-21 14:45:50 +0530207 warehouse_dict.previous_sle = previous_sle
Nabin Haitbb777562013-08-29 18:19:37 +0530208
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530209 for key in ("qty_after_transaction", "valuation_rate", "stock_value"):
Nabin Haita77b8c92020-12-21 14:45:50 +0530210 setattr(warehouse_dict, key, flt(previous_sle.get(key)))
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530211
Nabin Haita77b8c92020-12-21 14:45:50 +0530212 warehouse_dict.update({
213 "prev_stock_value": previous_sle.stock_value or 0.0,
214 "stock_queue": json.loads(previous_sle.stock_queue or "[]"),
215 "stock_value_difference": 0.0
216 })
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530217
Nabin Hait186a0452021-02-18 14:14:21 +0530218 def get_previous_sle_of_current_voucher(self, args):
219 """get stock ledger entries filtered by specific posting datetime conditions"""
220
221 args['time_format'] = '%H:%i:%s'
222 if not args.get("posting_date"):
223 args["posting_date"] = "1900-01-01"
224 if not args.get("posting_time"):
225 args["posting_time"] = "00:00"
226
227 sle = frappe.db.sql("""
228 select *, timestamp(posting_date, posting_time) as "timestamp"
229 from `tabStock Ledger Entry`
230 where item_code = %(item_code)s
231 and warehouse = %(warehouse)s
232 and is_cancelled = 0
233 and timestamp(posting_date, time_format(posting_time, %(time_format)s)) < timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
234 order by timestamp(posting_date, posting_time) desc, creation desc
Ankush Menat9979cf52021-05-21 12:12:42 +0530235 limit 1
236 for update""", args, as_dict=1)
Nabin Haitd46b2362021-02-23 16:38:52 +0530237
Nabin Hait186a0452021-02-18 14:14:21 +0530238 return sle[0] if sle else frappe._dict()
239
240
Nabin Haita77b8c92020-12-21 14:45:50 +0530241 def build(self):
Sagar Vorae50324a2021-03-31 12:44:03 +0530242 from erpnext.controllers.stock_controller import future_sle_exists
Nabin Hait186a0452021-02-18 14:14:21 +0530243
Nabin Haita77b8c92020-12-21 14:45:50 +0530244 if self.args.get("sle_id"):
Nabin Hait186a0452021-02-18 14:14:21 +0530245 self.process_sle_against_current_timestamp()
Sagar Vorae50324a2021-03-31 12:44:03 +0530246 if not future_sle_exists(self.args):
Nabin Hait186a0452021-02-18 14:14:21 +0530247 self.update_bin()
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530248 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530249 entries_to_fix = self.get_future_entries_to_fix()
250
251 i = 0
252 while i < len(entries_to_fix):
253 sle = entries_to_fix[i]
254 i += 1
255
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530256 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530257
Nabin Haita77b8c92020-12-21 14:45:50 +0530258 if sle.dependant_sle_voucher_detail_no:
Nabin Hait243d59b2021-02-02 16:55:13 +0530259 entries_to_fix = self.get_dependent_entries_to_fix(entries_to_fix, sle)
Nabin Haitd46b2362021-02-23 16:38:52 +0530260
Nabin Hait186a0452021-02-18 14:14:21 +0530261 self.update_bin()
Nabin Haita77b8c92020-12-21 14:45:50 +0530262
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530263 if self.exceptions:
264 self.raise_exceptions()
265
Nabin Hait186a0452021-02-18 14:14:21 +0530266 def process_sle_against_current_timestamp(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530267 sl_entries = self.get_sle_against_current_voucher()
268 for sle in sl_entries:
269 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530270
Nabin Haita77b8c92020-12-21 14:45:50 +0530271 def get_sle_against_current_voucher(self):
Nabin Haitf2be0802021-02-15 19:27:49 +0530272 self.args['time_format'] = '%H:%i:%s'
273
Nabin Haita77b8c92020-12-21 14:45:50 +0530274 return frappe.db.sql("""
275 select
276 *, timestamp(posting_date, posting_time) as "timestamp"
277 from
278 `tabStock Ledger Entry`
279 where
280 item_code = %(item_code)s
281 and warehouse = %(warehouse)s
Nabin Hait186a0452021-02-18 14:14:21 +0530282 and timestamp(posting_date, time_format(posting_time, %(time_format)s)) = timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
283
Nabin Haita77b8c92020-12-21 14:45:50 +0530284 order by
285 creation ASC
286 for update
287 """, self.args, as_dict=1)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530288
Nabin Haita77b8c92020-12-21 14:45:50 +0530289 def get_future_entries_to_fix(self):
290 # includes current entry!
291 args = self.data[self.args.warehouse].previous_sle \
292 or frappe._dict({"item_code": self.item_code, "warehouse": self.args.warehouse})
Deepesh Gargb4be2922021-01-28 13:09:56 +0530293
Nabin Haita77b8c92020-12-21 14:45:50 +0530294 return list(self.get_sle_after_datetime(args))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530295
Nabin Haita77b8c92020-12-21 14:45:50 +0530296 def get_dependent_entries_to_fix(self, entries_to_fix, sle):
297 dependant_sle = get_sle_by_voucher_detail_no(sle.dependant_sle_voucher_detail_no,
298 excluded_sle=sle.name)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530299
Nabin Haita77b8c92020-12-21 14:45:50 +0530300 if not dependant_sle:
Nabin Hait243d59b2021-02-02 16:55:13 +0530301 return entries_to_fix
Nabin Haita77b8c92020-12-21 14:45:50 +0530302 elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse == self.args.warehouse:
Nabin Hait243d59b2021-02-02 16:55:13 +0530303 return entries_to_fix
304 elif dependant_sle.item_code != self.item_code:
305 if (dependant_sle.item_code, dependant_sle.warehouse) not in self.new_items:
306 self.new_items[(dependant_sle.item_code, dependant_sle.warehouse)] = dependant_sle
307 return entries_to_fix
308 elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse in self.data:
309 return entries_to_fix
Nabin Haita77b8c92020-12-21 14:45:50 +0530310 self.initialize_previous_data(dependant_sle)
311
312 args = self.data[dependant_sle.warehouse].previous_sle \
313 or frappe._dict({"item_code": self.item_code, "warehouse": dependant_sle.warehouse})
314 future_sle_for_dependant = list(self.get_sle_after_datetime(args))
315
316 entries_to_fix.extend(future_sle_for_dependant)
Nabin Hait243d59b2021-02-02 16:55:13 +0530317 return sorted(entries_to_fix, key=lambda k: k['timestamp'])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530318
319 def process_sle(self, sle):
Nabin Haita77b8c92020-12-21 14:45:50 +0530320 # previous sle data for this warehouse
321 self.wh_data = self.data[sle.warehouse]
322
Anand Doshi0dc79f42015-04-06 12:59:34 +0530323 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 +0530324 # validate negative stock for serialized items, fifo valuation
Nabin Hait902e8602013-01-08 18:29:24 +0530325 # or when negative stock is not allowed for moving average
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530326 if not self.validate_negative_stock(sle):
Nabin Haita77b8c92020-12-21 14:45:50 +0530327 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530328 return
Nabin Haitb96c0142014-10-07 11:25:04 +0530329
Nabin Haita77b8c92020-12-21 14:45:50 +0530330 # Get dynamic incoming/outgoing rate
331 self.get_dynamic_incoming_outgoing_rate(sle)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530332
Anand Doshi1b531862013-01-10 19:29:51 +0530333 if sle.serial_no:
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530334 self.get_serialized_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530335 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530336 if sle.voucher_type == "Stock Reconciliation":
Nabin Haita77b8c92020-12-21 14:45:50 +0530337 self.wh_data.qty_after_transaction = sle.qty_after_transaction
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530338
Nabin Haita77b8c92020-12-21 14:45:50 +0530339 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 +0530340 else:
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530341 if sle.voucher_type=="Stock Reconciliation" and not sle.batch_no:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530342 # assert
Nabin Haita77b8c92020-12-21 14:45:50 +0530343 self.wh_data.valuation_rate = sle.valuation_rate
344 self.wh_data.qty_after_transaction = sle.qty_after_transaction
345 self.wh_data.stock_queue = [[self.wh_data.qty_after_transaction, self.wh_data.valuation_rate]]
346 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 +0530347 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530348 if self.valuation_method == "Moving Average":
349 self.get_moving_average_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530350 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
351 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:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530353 self.get_fifo_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530354 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
355 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 +0530356
Rushabh Mehta54047782013-12-26 11:07:46 +0530357 # rounding as per precision
Nabin Haita77b8c92020-12-21 14:45:50 +0530358 self.wh_data.stock_value = flt(self.wh_data.stock_value, self.precision)
359 stock_value_difference = self.wh_data.stock_value - self.wh_data.prev_stock_value
360 self.wh_data.prev_stock_value = self.wh_data.stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530361
Nabin Hait902e8602013-01-08 18:29:24 +0530362 # update current sle
Nabin Haita77b8c92020-12-21 14:45:50 +0530363 sle.qty_after_transaction = self.wh_data.qty_after_transaction
364 sle.valuation_rate = self.wh_data.valuation_rate
365 sle.stock_value = self.wh_data.stock_value
366 sle.stock_queue = json.dumps(self.wh_data.stock_queue)
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530367 sle.stock_value_difference = stock_value_difference
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530368 sle.doctype="Stock Ledger Entry"
369 frappe.get_doc(sle).db_update()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530370
Nabin Haita77b8c92020-12-21 14:45:50 +0530371 self.update_outgoing_rate_on_transaction(sle)
372
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530373 def validate_negative_stock(self, sle):
374 """
375 validate negative stock for entries current datetime onwards
376 will not consider cancelled entries
377 """
Nabin Haita77b8c92020-12-21 14:45:50 +0530378 diff = self.wh_data.qty_after_transaction + flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530379
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530380 if diff < 0 and abs(diff) > 0.0001:
381 # negative stock!
382 exc = sle.copy().update({"diff": diff})
Nabin Haita77b8c92020-12-21 14:45:50 +0530383 self.exceptions.setdefault(sle.warehouse, []).append(exc)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530384 return False
Nabin Hait902e8602013-01-08 18:29:24 +0530385 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530386 return True
387
Nabin Haita77b8c92020-12-21 14:45:50 +0530388 def get_dynamic_incoming_outgoing_rate(self, sle):
389 # Get updated incoming/outgoing rate from transaction
390 if sle.recalculate_rate:
391 rate = self.get_incoming_outgoing_rate_from_transaction(sle)
392
393 if flt(sle.actual_qty) >= 0:
394 sle.incoming_rate = rate
395 else:
396 sle.outgoing_rate = rate
397
398 def get_incoming_outgoing_rate_from_transaction(self, sle):
399 rate = 0
400 # Material Transfer, Repack, Manufacturing
401 if sle.voucher_type == "Stock Entry":
402 rate = frappe.db.get_value("Stock Entry Detail", sle.voucher_detail_no, "valuation_rate")
403 # Sales and Purchase Return
404 elif sle.voucher_type in ("Purchase Receipt", "Purchase Invoice", "Delivery Note", "Sales Invoice"):
405 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_return"):
406 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 +0530407 rate = get_rate_for_return(sle.voucher_type, sle.voucher_no, sle.item_code,
408 voucher_detail_no=sle.voucher_detail_no, sle = sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530409 else:
410 if sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530411 rate_field = "valuation_rate"
Nabin Haita77b8c92020-12-21 14:45:50 +0530412 else:
413 rate_field = "incoming_rate"
414
415 # check in item table
416 item_code, incoming_rate = frappe.db.get_value(sle.voucher_type + " Item",
417 sle.voucher_detail_no, ["item_code", rate_field])
418
419 if item_code == sle.item_code:
420 rate = incoming_rate
421 else:
422 if sle.voucher_type in ("Delivery Note", "Sales Invoice"):
423 ref_doctype = "Packed Item"
424 else:
425 ref_doctype = "Purchase Receipt Item Supplied"
Deepesh Gargb4be2922021-01-28 13:09:56 +0530426
Nabin Haita77b8c92020-12-21 14:45:50 +0530427 rate = frappe.db.get_value(ref_doctype, {"parent_detail_docname": sle.voucher_detail_no,
428 "item_code": sle.item_code}, rate_field)
429
430 return rate
431
432 def update_outgoing_rate_on_transaction(self, sle):
433 """
434 Update outgoing rate in Stock Entry, Delivery Note, Sales Invoice and Sales Return
435 In case of Stock Entry, also calculate FG Item rate and total incoming/outgoing amount
436 """
437 if sle.actual_qty and sle.voucher_detail_no:
438 outgoing_rate = abs(flt(sle.stock_value_difference)) / abs(sle.actual_qty)
439
440 if flt(sle.actual_qty) < 0 and sle.voucher_type == "Stock Entry":
441 self.update_rate_on_stock_entry(sle, outgoing_rate)
442 elif sle.voucher_type in ("Delivery Note", "Sales Invoice"):
443 self.update_rate_on_delivery_and_sales_return(sle, outgoing_rate)
444 elif flt(sle.actual_qty) < 0 and sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
445 self.update_rate_on_purchase_receipt(sle, outgoing_rate)
446
447 def update_rate_on_stock_entry(self, sle, outgoing_rate):
448 frappe.db.set_value("Stock Entry Detail", sle.voucher_detail_no, "basic_rate", outgoing_rate)
449
450 # Update outgoing item's rate, recalculate FG Item's rate and total incoming/outgoing amount
rohitwaghchaure00ea3362021-05-01 13:53:39 +0530451 stock_entry = frappe.get_doc("Stock Entry", sle.voucher_no, for_update=True)
Nabin Haita77b8c92020-12-21 14:45:50 +0530452 stock_entry.calculate_rate_and_amount(reset_outgoing_rate=False, raise_error_if_no_rate=False)
453 stock_entry.db_update()
454 for d in stock_entry.items:
455 d.db_update()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530456
Nabin Haita77b8c92020-12-21 14:45:50 +0530457 def update_rate_on_delivery_and_sales_return(self, sle, outgoing_rate):
458 # Update item's incoming rate on transaction
459 item_code = frappe.db.get_value(sle.voucher_type + " Item", sle.voucher_detail_no, "item_code")
460 if item_code == sle.item_code:
461 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "incoming_rate", outgoing_rate)
462 else:
463 # packed item
464 frappe.db.set_value("Packed Item",
465 {"parent_detail_docname": sle.voucher_detail_no, "item_code": sle.item_code},
466 "incoming_rate", outgoing_rate)
467
468 def update_rate_on_purchase_receipt(self, sle, outgoing_rate):
469 if frappe.db.exists(sle.voucher_type + " Item", sle.voucher_detail_no):
470 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "base_net_rate", outgoing_rate)
471 else:
472 frappe.db.set_value("Purchase Receipt Item Supplied", sle.voucher_detail_no, "rate", outgoing_rate)
473
474 # Recalculate subcontracted item's rate in case of subcontracted purchase receipt/invoice
475 if frappe.db.get_value(sle.voucher_type, sle.voucher_no, "is_subcontracted"):
Nabin Haitd46b2362021-02-23 16:38:52 +0530476 doc = frappe.get_doc(sle.voucher_type, sle.voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530477 doc.update_valuation_rate(reset_outgoing_rate=False)
478 for d in (doc.items + doc.supplied_items):
479 d.db_update()
480
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530481 def get_serialized_values(self, sle):
482 incoming_rate = flt(sle.incoming_rate)
483 actual_qty = flt(sle.actual_qty)
Nabin Hait328c4f92020-01-02 19:00:32 +0530484 serial_nos = cstr(sle.serial_no).split("\n")
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530485
486 if incoming_rate < 0:
487 # wrong incoming rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530488 incoming_rate = self.wh_data.valuation_rate
Rushabh Mehta538607e2016-06-12 11:03:00 +0530489
Nabin Hait2620bf42016-02-29 11:30:27 +0530490 stock_value_change = 0
491 if incoming_rate:
492 stock_value_change = actual_qty * incoming_rate
493 elif actual_qty < 0:
494 # In case of delivery/stock issue, get average purchase rate
495 # of serial nos of current entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530496 if not sle.is_cancelled:
497 outgoing_value = self.get_incoming_value_for_serial_nos(sle, serial_nos)
498 stock_value_change = -1 * outgoing_value
499 else:
500 stock_value_change = actual_qty * sle.outgoing_rate
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530501
Nabin Haita77b8c92020-12-21 14:45:50 +0530502 new_stock_qty = self.wh_data.qty_after_transaction + actual_qty
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530503
Nabin Hait2620bf42016-02-29 11:30:27 +0530504 if new_stock_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530505 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + stock_value_change
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530506 if new_stock_value >= 0:
Nabin Hait2620bf42016-02-29 11:30:27 +0530507 # calculate new valuation rate only if stock value is positive
508 # else it remains the same as that of previous entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530509 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530510
Nabin Haita77b8c92020-12-21 14:45:50 +0530511 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530512 allow_zero_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
513 if not allow_zero_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530514 self.wh_data.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530515 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
516 currency=erpnext.get_company_currency(sle.company))
517
Nabin Hait328c4f92020-01-02 19:00:32 +0530518 def get_incoming_value_for_serial_nos(self, sle, serial_nos):
519 # get rate from serial nos within same company
520 all_serial_nos = frappe.get_all("Serial No",
521 fields=["purchase_rate", "name", "company"],
522 filters = {'name': ('in', serial_nos)})
523
524 incoming_values = sum([flt(d.purchase_rate) for d in all_serial_nos if d.company==sle.company])
525
526 # Get rate for serial nos which has been transferred to other company
527 invalid_serial_nos = [d.name for d in all_serial_nos if d.company!=sle.company]
528 for serial_no in invalid_serial_nos:
529 incoming_rate = frappe.db.sql("""
530 select incoming_rate
531 from `tabStock Ledger Entry`
532 where
533 company = %s
534 and actual_qty > 0
535 and (serial_no = %s
536 or serial_no like %s
537 or serial_no like %s
538 or serial_no like %s
539 )
540 order by posting_date desc
541 limit 1
542 """, (sle.company, serial_no, serial_no+'\n%', '%\n'+serial_no, '%\n'+serial_no+'\n%'))
543
544 incoming_values += flt(incoming_rate[0][0]) if incoming_rate else 0
545
546 return incoming_values
547
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530548 def get_moving_average_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530549 actual_qty = flt(sle.actual_qty)
Nabin Haita77b8c92020-12-21 14:45:50 +0530550 new_stock_qty = flt(self.wh_data.qty_after_transaction) + actual_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530551 if new_stock_qty >= 0:
552 if actual_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530553 if flt(self.wh_data.qty_after_transaction) <= 0:
554 self.wh_data.valuation_rate = sle.incoming_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530555 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530556 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530557 (actual_qty * sle.incoming_rate)
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530558
Nabin Haita77b8c92020-12-21 14:45:50 +0530559 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530560
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530561 elif sle.outgoing_rate:
562 if new_stock_qty:
Nabin Haita77b8c92020-12-21 14:45:50 +0530563 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530564 (actual_qty * sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530565
Nabin Haita77b8c92020-12-21 14:45:50 +0530566 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530567 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530568 self.wh_data.valuation_rate = sle.outgoing_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530569 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530570 if flt(self.wh_data.qty_after_transaction) >= 0 and sle.outgoing_rate:
571 self.wh_data.valuation_rate = sle.outgoing_rate
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530572
Nabin Haita77b8c92020-12-21 14:45:50 +0530573 if not self.wh_data.valuation_rate and actual_qty > 0:
574 self.wh_data.valuation_rate = sle.incoming_rate
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530575
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530576 # Get valuation rate from previous SLE or Item master, if item does not have the
Javier Wong9b11d9b2017-04-14 18:24:04 +0800577 # allow zero valuration rate flag set
Nabin Haita77b8c92020-12-21 14:45:50 +0530578 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
Javier Wong9b11d9b2017-04-14 18:24:04 +0800579 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
580 if not allow_zero_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530581 self.wh_data.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530582 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
583 currency=erpnext.get_company_currency(sle.company))
584
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530585 def get_fifo_values(self, sle):
586 incoming_rate = flt(sle.incoming_rate)
587 actual_qty = flt(sle.actual_qty)
Nabin Haitada485f2015-07-17 15:09:56 +0530588 outgoing_rate = flt(sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530589
590 if actual_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530591 if not self.wh_data.stock_queue:
592 self.wh_data.stock_queue.append([0, 0])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530593
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530594 # last row has the same rate, just updated the qty
Nabin Haita77b8c92020-12-21 14:45:50 +0530595 if self.wh_data.stock_queue[-1][1]==incoming_rate:
596 self.wh_data.stock_queue[-1][0] += actual_qty
Nabin Hait4d742162014-10-09 19:25:03 +0530597 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530598 if self.wh_data.stock_queue[-1][0] > 0:
599 self.wh_data.stock_queue.append([actual_qty, incoming_rate])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530600 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530601 qty = self.wh_data.stock_queue[-1][0] + actual_qty
602 self.wh_data.stock_queue[-1] = [qty, incoming_rate]
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530603 else:
604 qty_to_pop = abs(actual_qty)
605 while qty_to_pop:
Nabin Haita77b8c92020-12-21 14:45:50 +0530606 if not self.wh_data.stock_queue:
Nabin Haita0b967f2017-01-18 18:35:58 +0530607 # Get valuation rate from last sle if exists or from valuation rate field in item master
Javier Wong9b11d9b2017-04-14 18:24:04 +0800608 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
609 if not allow_zero_valuation_rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530610 _rate = get_valuation_rate(sle.item_code, sle.warehouse,
611 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
612 currency=erpnext.get_company_currency(sle.company))
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530613 else:
614 _rate = 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530615
Nabin Haita77b8c92020-12-21 14:45:50 +0530616 self.wh_data.stock_queue.append([0, _rate])
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530617
Nabin Haitada485f2015-07-17 15:09:56 +0530618 index = None
619 if outgoing_rate > 0:
620 # Find the entry where rate matched with outgoing rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530621 for i, v in enumerate(self.wh_data.stock_queue):
Nabin Haitada485f2015-07-17 15:09:56 +0530622 if v[1] == outgoing_rate:
623 index = i
624 break
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530625
Nabin Haitada485f2015-07-17 15:09:56 +0530626 # If no entry found with outgoing rate, collapse stack
Ankush Menat4dcac4a2021-05-21 13:12:30 +0530627 if index is None: # nosemgrep
Nabin Haita77b8c92020-12-21 14:45:50 +0530628 new_stock_value = sum((d[0]*d[1] for d in self.wh_data.stock_queue)) - qty_to_pop*outgoing_rate
629 new_stock_qty = sum((d[0] for d in self.wh_data.stock_queue)) - qty_to_pop
630 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 +0530631 break
632 else:
633 index = 0
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530634
Nabin Haitada485f2015-07-17 15:09:56 +0530635 # select first batch or the batch with same rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530636 batch = self.wh_data.stock_queue[index]
Nabin Hait8142cd22015-08-05 18:57:26 +0530637 if qty_to_pop >= batch[0]:
638 # consume current batch
Ankush Menat6a014d12021-04-12 20:21:27 +0530639 qty_to_pop = _round_off_if_near_zero(qty_to_pop - batch[0])
Nabin Haita77b8c92020-12-21 14:45:50 +0530640 self.wh_data.stock_queue.pop(index)
641 if not self.wh_data.stock_queue and qty_to_pop:
Nabin Hait8142cd22015-08-05 18:57:26 +0530642 # stock finished, qty still remains to be withdrawn
643 # negative stock, keep in as a negative batch
Nabin Haita77b8c92020-12-21 14:45:50 +0530644 self.wh_data.stock_queue.append([-qty_to_pop, outgoing_rate or batch[1]])
Nabin Hait8142cd22015-08-05 18:57:26 +0530645 break
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530646
Nabin Hait8142cd22015-08-05 18:57:26 +0530647 else:
648 # qty found in current batch
649 # consume it and exit
650 batch[0] = batch[0] - qty_to_pop
651 qty_to_pop = 0
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530652
Ankush Menat6a014d12021-04-12 20:21:27 +0530653 stock_value = _round_off_if_near_zero(sum((flt(batch[0]) * flt(batch[1]) for batch in self.wh_data.stock_queue)))
654 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 +0530655
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530656 if stock_qty:
Nabin Haita77b8c92020-12-21 14:45:50 +0530657 self.wh_data.valuation_rate = stock_value / flt(stock_qty)
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530658
Nabin Haita77b8c92020-12-21 14:45:50 +0530659 if not self.wh_data.stock_queue:
660 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 +0530661
Javier Wong9b11d9b2017-04-14 18:24:04 +0800662 def check_if_allow_zero_valuation_rate(self, voucher_type, voucher_detail_no):
deepeshgarg007f9c0ef32019-07-30 18:49:19 +0530663 ref_item_dt = ""
664
665 if voucher_type == "Stock Entry":
666 ref_item_dt = voucher_type + " Detail"
667 elif voucher_type in ["Purchase Invoice", "Sales Invoice", "Delivery Note", "Purchase Receipt"]:
668 ref_item_dt = voucher_type + " Item"
669
670 if ref_item_dt:
671 return frappe.db.get_value(ref_item_dt, voucher_detail_no, "allow_zero_valuation_rate")
672 else:
673 return 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530674
Nabin Haita77b8c92020-12-21 14:45:50 +0530675 def get_sle_before_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530676 """get previous stock ledger entry before current time-bucket"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530677 sle = get_stock_ledger_entries(args, "<", "desc", "limit 1", for_update=False)
678 sle = sle[0] if sle else frappe._dict()
679 return sle
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530680
Nabin Haita77b8c92020-12-21 14:45:50 +0530681 def get_sle_after_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530682 """get Stock Ledger Entries after a particular datetime, for reposting"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530683 return get_stock_ledger_entries(args, ">", "asc", for_update=True, check_serial_no=False)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530684
685 def raise_exceptions(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530686 msg_list = []
687 for warehouse, exceptions in iteritems(self.exceptions):
688 deficiency = min(e["diff"] for e in exceptions)
Rushabh Mehta538607e2016-06-12 11:03:00 +0530689
Nabin Haita77b8c92020-12-21 14:45:50 +0530690 if ((exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]) in
691 frappe.local.flags.currently_saving):
Nabin Hait3edefb12016-07-20 16:13:18 +0530692
Nabin Haita77b8c92020-12-21 14:45:50 +0530693 msg = _("{0} units of {1} needed in {2} to complete this transaction.").format(
Nabin Hait243d59b2021-02-02 16:55:13 +0530694 abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]),
Nabin Haita77b8c92020-12-21 14:45:50 +0530695 frappe.get_desk_link('Warehouse', warehouse))
696 else:
697 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 +0530698 abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]),
Nabin Haita77b8c92020-12-21 14:45:50 +0530699 frappe.get_desk_link('Warehouse', warehouse),
700 exceptions[0]["posting_date"], exceptions[0]["posting_time"],
701 frappe.get_desk_link(exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530702
Nabin Haita77b8c92020-12-21 14:45:50 +0530703 if msg:
704 msg_list.append(msg)
705
706 if msg_list:
707 message = "\n\n".join(msg_list)
708 if self.verbose:
709 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
710 else:
711 raise NegativeStockError(message)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530712
Nabin Haita77b8c92020-12-21 14:45:50 +0530713 def update_bin(self):
714 # update bin for each warehouse
715 for warehouse, data in iteritems(self.data):
716 bin_doc = get_bin(self.item_code, warehouse)
Nabin Haita77b8c92020-12-21 14:45:50 +0530717 bin_doc.update({
718 "valuation_rate": data.valuation_rate,
719 "actual_qty": data.qty_after_transaction,
720 "stock_value": data.stock_value
721 })
722 bin_doc.flags.via_stock_ledger_entry = True
723 bin_doc.save(ignore_permissions=True)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530724
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530725def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530726 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530727 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530728 to get actual qty before transaction, this function
729 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530730
Anand Doshi1b531862013-01-10 19:29:51 +0530731 args = {
732 "item_code": "ABC",
733 "warehouse": "XYZ",
734 "posting_date": "2012-12-12",
735 "posting_time": "12:00",
736 "sle": "name of reference Stock Ledger Entry"
737 }
738 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530739 args["name"] = args.get("sle", None) or ""
740 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530741 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530742
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530743def get_stock_ledger_entries(previous_sle, operator=None,
744 order="desc", limit=None, for_update=False, debug=False, check_serial_no=True):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530745 """get stock ledger entries filtered by specific posting datetime conditions"""
Nabin Haitb9ce1042018-02-01 14:58:50 +0530746 conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
747 if previous_sle.get("warehouse"):
748 conditions += " and warehouse = %(warehouse)s"
749 elif previous_sle.get("warehouse_condition"):
750 conditions += " and " + previous_sle.get("warehouse_condition")
751
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530752 if check_serial_no and previous_sle.get("serial_no"):
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530753 # conditions += " and serial_no like {}".format(frappe.db.escape('%{0}%'.format(previous_sle.get("serial_no"))))
754 serial_no = previous_sle.get("serial_no")
755 conditions += (""" and
756 (
757 serial_no = {0}
758 or serial_no like {1}
759 or serial_no like {2}
760 or serial_no like {3}
761 )
762 """).format(frappe.db.escape(serial_no), frappe.db.escape('{}\n%'.format(serial_no)),
763 frappe.db.escape('%\n{}'.format(serial_no)), frappe.db.escape('%\n{}\n%'.format(serial_no)))
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530764
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530765 if not previous_sle.get("posting_date"):
766 previous_sle["posting_date"] = "1900-01-01"
767 if not previous_sle.get("posting_time"):
768 previous_sle["posting_time"] = "00:00"
769
770 if operator in (">", "<=") and previous_sle.get("name"):
771 conditions += " and name!=%(name)s"
772
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530773 return frappe.db.sql("""
774 select *, timestamp(posting_date, posting_time) as "timestamp"
775 from `tabStock Ledger Entry`
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530776 where item_code = %%(item_code)s
Nabin Haita77b8c92020-12-21 14:45:50 +0530777 and is_cancelled = 0
Nabin Haitb9ce1042018-02-01 14:58:50 +0530778 %(conditions)s
Aditya Hase0c164242019-01-07 22:07:13 +0530779 order by timestamp(posting_date, posting_time) %(order)s, creation %(order)s
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530780 %(limit)s %(for_update)s""" % {
781 "conditions": conditions,
782 "limit": limit or "",
783 "for_update": for_update and "for update" or "",
784 "order": order
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530785 }, previous_sle, as_dict=1, debug=debug)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530786
Nabin Haita77b8c92020-12-21 14:45:50 +0530787def get_sle_by_voucher_detail_no(voucher_detail_no, excluded_sle=None):
788 return frappe.db.get_value('Stock Ledger Entry',
789 {'voucher_detail_no': voucher_detail_no, 'name': ['!=', excluded_sle]},
790 ['item_code', 'warehouse', 'posting_date', 'posting_time', 'timestamp(posting_date, posting_time) as timestamp'],
791 as_dict=1)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530792
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530793def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no,
Nabin Hait7ba092e2018-02-01 10:51:27 +0530794 allow_zero_rate=False, currency=None, company=None, raise_error_if_no_rate=True):
Nabin Haita0b967f2017-01-18 18:35:58 +0530795 # Get valuation rate from last sle for the same item and warehouse
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530796 if not company:
797 company = erpnext.get_default_company()
798
Nabin Haitfb6e4342014-10-15 11:34:40 +0530799 last_valuation_rate = frappe.db.sql("""select valuation_rate
800 from `tabStock Ledger Entry`
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530801 where
802 item_code = %s
803 AND warehouse = %s
804 AND valuation_rate >= 0
805 AND NOT (voucher_no = %s AND voucher_type = %s)
806 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 +0530807
808 if not last_valuation_rate:
Nabin Haita0b967f2017-01-18 18:35:58 +0530809 # Get valuation rate from last sle for the item against any warehouse
Nabin Haitfb6e4342014-10-15 11:34:40 +0530810 last_valuation_rate = frappe.db.sql("""select valuation_rate
811 from `tabStock Ledger Entry`
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530812 where
813 item_code = %s
814 AND valuation_rate > 0
815 AND NOT(voucher_no = %s AND voucher_type = %s)
816 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 +0530817
Nabin Haita645f362018-03-01 10:31:24 +0530818 if last_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530819 return flt(last_valuation_rate[0][0])
Nabin Haita645f362018-03-01 10:31:24 +0530820
821 # If negative stock allowed, and item delivered without any incoming entry,
822 # system does not found any SLE, then take valuation rate from Item
823 valuation_rate = frappe.db.get_value("Item", item_code, "valuation_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530824
825 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530826 # try Item Standard rate
827 valuation_rate = frappe.db.get_value("Item", item_code, "standard_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530828
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530829 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530830 # try in price list
831 valuation_rate = frappe.db.get_value('Item Price',
832 dict(item_code=item_code, buying=1, currency=currency),
833 'price_list_rate')
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530834
Nabin Hait7ba092e2018-02-01 10:51:27 +0530835 if not allow_zero_rate and not valuation_rate and raise_error_if_no_rate \
Rohit Waghchauree9ff1912017-06-19 12:54:59 +0530836 and cint(erpnext.is_perpetual_inventory_enabled(company)):
Neil Trini Lasrado193c8912017-03-28 17:39:34 +0530837 frappe.local.message_log = []
Rohit Waghchaurebb3e5d02021-04-24 17:28:33 +0530838 form_link = get_link_to_form("Item", item_code)
Marica97715f22020-05-11 20:45:37 +0530839
840 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 +0530841 message += "<br><br>" + _("Here are the options to proceed:")
Marica97715f22020-05-11 20:45:37 +0530842 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 +0530843 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 +0530844 sub_solutions = "<ul><li>" + _("Create an incoming stock transaction for the Item.") + "</li>"
845 sub_solutions += "<li>" + _("Mention Valuation Rate in the Item master.") + "</li></ul>"
846 msg = message + solutions + sub_solutions + "</li>"
847
848 frappe.throw(msg=msg, title=_("Valuation Rate Missing"))
Nabin Haitfb6e4342014-10-15 11:34:40 +0530849
850 return valuation_rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530851
Nabin Hait186a0452021-02-18 14:14:21 +0530852def update_qty_in_future_sle(args, allow_negative_stock=None):
853 frappe.db.sql("""
854 update `tabStock Ledger Entry`
855 set qty_after_transaction = qty_after_transaction + {qty}
856 where
857 item_code = %(item_code)s
858 and warehouse = %(warehouse)s
859 and voucher_no != %(voucher_no)s
860 and is_cancelled = 0
861 and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)
862 or (
863 timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s)
864 and creation > %(creation)s
865 )
866 )
867 """.format(qty=args.actual_qty), args)
868
869 validate_negative_qty_in_future_sle(args, allow_negative_stock)
870
Nabin Haita77b8c92020-12-21 14:45:50 +0530871def validate_negative_qty_in_future_sle(args, allow_negative_stock=None):
872 allow_negative_stock = allow_negative_stock \
873 or cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
874
875 if args.actual_qty < 0 and not allow_negative_stock:
876 sle = get_future_sle_with_negative_qty(args)
877 if sle:
878 message = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
879 abs(sle[0]["qty_after_transaction"]),
880 frappe.get_desk_link('Item', args.item_code),
881 frappe.get_desk_link('Warehouse', args.warehouse),
882 sle[0]["posting_date"], sle[0]["posting_time"],
883 frappe.get_desk_link(sle[0]["voucher_type"], sle[0]["voucher_no"]))
Deepesh Gargb4be2922021-01-28 13:09:56 +0530884
Nabin Haita77b8c92020-12-21 14:45:50 +0530885 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
886
887def get_future_sle_with_negative_qty(args):
888 return frappe.db.sql("""
889 select
890 qty_after_transaction, posting_date, posting_time,
891 voucher_type, voucher_no
892 from `tabStock Ledger Entry`
Deepesh Gargb4be2922021-01-28 13:09:56 +0530893 where
Nabin Haita77b8c92020-12-21 14:45:50 +0530894 item_code = %(item_code)s
895 and warehouse = %(warehouse)s
896 and voucher_no != %(voucher_no)s
897 and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s)
898 and is_cancelled = 0
Nabin Hait186a0452021-02-18 14:14:21 +0530899 and qty_after_transaction < 0
Nabin Hait243d59b2021-02-02 16:55:13 +0530900 order by timestamp(posting_date, posting_time) asc
Nabin Haita77b8c92020-12-21 14:45:50 +0530901 limit 1
Sagar Vorae50324a2021-03-31 12:44:03 +0530902 """, args, as_dict=1)
Ankush Menat6a014d12021-04-12 20:21:27 +0530903
904def _round_off_if_near_zero(number: float, precision: int = 6) -> float:
905 """ Rounds off the number to zero only if number is close to zero for decimal
906 specified in precision. Precision defaults to 6.
907 """
908 if flt(number) < (1.0 / (10**precision)):
909 return 0
910
911 return flt(number)