blob: b100f4532734af054cb42f1a45e6567a50299b17 [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
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +05305import frappe, erpnext
Rushabh Mehta9f0d6252014-04-14 19:20:45 +05306from frappe import _
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05307from frappe.utils import cint, flt, cstr, now
Rushabh Mehta1f847992013-12-12 19:12:19 +05308from erpnext.stock.utils import get_valuation_method
Nabin Hait26d46552013-01-09 15:23:05 +05309import json
Nabin Hait902e8602013-01-08 18:29:24 +053010
Achilles Rasquinha361366e2018-02-14 17:08:59 +053011from six import iteritems
12
Nabin Hait902e8602013-01-08 18:29:24 +053013# future reposting
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053014class NegativeStockError(frappe.ValidationError): pass
Nabin Hait902e8602013-01-08 18:29:24 +053015
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053016_exceptions = frappe.local('stockledger_exceptions')
Pratik Vyas16371b72013-09-18 18:31:03 +053017# _exceptions = []
Anand Doshi5b004ff2013-09-25 19:55:41 +053018
Nabin Hait54c865e2015-03-27 15:38:31 +053019def make_sl_entries(sl_entries, is_amended=None, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Haitca775742013-09-26 16:16:44 +053020 if sl_entries:
Rushabh Mehta1f847992013-12-12 19:12:19 +053021 from erpnext.stock.utils import update_bin
Nabin Haitdc82d4f2014-04-07 12:02:57 +053022
Nabin Haitca775742013-09-26 16:16:44 +053023 cancel = True if sl_entries[0].get("is_cancelled") == "Yes" else False
24 if cancel:
25 set_as_cancel(sl_entries[0].get('voucher_no'), sl_entries[0].get('voucher_type'))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053026
Nabin Haitca775742013-09-26 16:16:44 +053027 for sle in sl_entries:
28 sle_id = None
29 if sle.get('is_cancelled') == 'Yes':
30 sle['actual_qty'] = -flt(sle['actual_qty'])
Nabin Haitdc82d4f2014-04-07 12:02:57 +053031
Nabin Hait5288bde2014-11-03 15:08:21 +053032 if sle.get("actual_qty") or sle.get("voucher_type")=="Stock Reconciliation":
Nabin Hait54c865e2015-03-27 15:38:31 +053033 sle_id = make_entry(sle, allow_negative_stock, via_landed_cost_voucher)
Nabin Haitdc82d4f2014-04-07 12:02:57 +053034
Nabin Haitca775742013-09-26 16:16:44 +053035 args = sle.copy()
36 args.update({
37 "sle_id": sle_id,
38 "is_amended": is_amended
39 })
Nabin Hait54c865e2015-03-27 15:38:31 +053040 update_bin(args, allow_negative_stock, via_landed_cost_voucher)
Nabin Haitadeb9762014-10-06 11:53:52 +053041
Nabin Haitca775742013-09-26 16:16:44 +053042 if cancel:
Nabin Haitadeb9762014-10-06 11:53:52 +053043 delete_cancelled_entry(sl_entries[0].get('voucher_type'), sl_entries[0].get('voucher_no'))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053044
Nabin Hait9653f602013-08-20 15:37:33 +053045def set_as_cancel(voucher_type, voucher_no):
Anand Doshie9baaa62014-02-26 12:35:33 +053046 frappe.db.sql("""update `tabStock Ledger Entry` set is_cancelled='Yes',
Nabin Hait9653f602013-08-20 15:37:33 +053047 modified=%s, modified_by=%s
Nabin Haitdc82d4f2014-04-07 12:02:57 +053048 where voucher_no=%s and voucher_type=%s""",
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053049 (now(), frappe.session.user, voucher_type, voucher_no))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053050
Nabin Hait54c865e2015-03-27 15:38:31 +053051def make_entry(args, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Hait74c281c2013-08-19 16:17:18 +053052 args.update({"doctype": "Stock Ledger Entry"})
Rushabh Mehtaa504f062014-04-04 12:16:26 +053053 sle = frappe.get_doc(args)
Anand Doshi6dfd4302015-02-10 14:41:27 +053054 sle.flags.ignore_permissions = 1
Nabin Hait4ccd8d32015-01-23 12:18:01 +053055 sle.allow_negative_stock=allow_negative_stock
Nabin Hait54c865e2015-03-27 15:38:31 +053056 sle.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Hait74c281c2013-08-19 16:17:18 +053057 sle.insert()
Nabin Haitaeba24e2013-08-23 15:17:36 +053058 sle.submit()
Anand Doshif78d1ae2014-03-28 13:55:00 +053059 return sle.name
Nabin Haitdc82d4f2014-04-07 12:02:57 +053060
Nabin Hait9653f602013-08-20 15:37:33 +053061def delete_cancelled_entry(voucher_type, voucher_no):
Nabin Haitdc82d4f2014-04-07 12:02:57 +053062 frappe.db.sql("""delete from `tabStock Ledger Entry`
Nabin Hait9653f602013-08-20 15:37:33 +053063 where voucher_type=%s and voucher_no=%s""", (voucher_type, voucher_no))
Nabin Hait74c281c2013-08-19 16:17:18 +053064
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053065class update_entries_after(object):
Nabin Hait902e8602013-01-08 18:29:24 +053066 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +053067 update valution rate and qty after transaction
Nabin Hait902e8602013-01-08 18:29:24 +053068 from the current time-bucket onwards
Nabin Haitdc82d4f2014-04-07 12:02:57 +053069
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053070 :param args: args as dict
71
72 args = {
73 "item_code": "ABC",
74 "warehouse": "XYZ",
75 "posting_date": "2012-12-12",
76 "posting_time": "12:00"
77 }
Nabin Hait902e8602013-01-08 18:29:24 +053078 """
Anand Doshi0dc79f42015-04-06 12:59:34 +053079 def __init__(self, args, allow_zero_rate=False, allow_negative_stock=None, via_landed_cost_voucher=False, verbose=1):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053080 from frappe.model.meta import get_field_precision
Nabin Haitdc82d4f2014-04-07 12:02:57 +053081
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053082 self.exceptions = []
83 self.verbose = verbose
84 self.allow_zero_rate = allow_zero_rate
85 self.allow_negative_stock = allow_negative_stock
Anand Doshi0dc79f42015-04-06 12:59:34 +053086 self.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Hait43ba7e12015-03-03 14:07:07 +053087 if not self.allow_negative_stock:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053088 self.allow_negative_stock = cint(frappe.db.get_single_value("Stock Settings",
89 "allow_negative_stock"))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053090
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053091 self.args = args
Achilles Rasquinha361366e2018-02-14 17:08:59 +053092 for key, value in iteritems(args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053093 setattr(self, key, value)
Nabin Haitdc82d4f2014-04-07 12:02:57 +053094
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053095 self.previous_sle = self.get_sle_before_datetime()
96 self.previous_sle = self.previous_sle[0] if self.previous_sle else frappe._dict()
Nabin Haitbb777562013-08-29 18:19:37 +053097
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053098 for key in ("qty_after_transaction", "valuation_rate", "stock_value"):
99 setattr(self, key, flt(self.previous_sle.get(key)))
100
101 self.company = frappe.db.get_value("Warehouse", self.warehouse, "company")
102 self.precision = get_field_precision(frappe.get_meta("Stock Ledger Entry").get_field("stock_value"),
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530103 currency=frappe.get_cached_value('Company', self.company, "default_currency"))
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530104
Rushabh Mehtac7a11cc2015-02-19 16:28:35 +0530105 self.prev_stock_value = self.previous_sle.stock_value or 0.0
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530106 self.stock_queue = json.loads(self.previous_sle.stock_queue or "[]")
107 self.valuation_method = get_valuation_method(self.item_code)
108 self.stock_value_difference = 0.0
109 self.build()
110
111 def build(self):
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530112 # includes current entry!
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530113 entries_to_fix = self.get_sle_after_datetime()
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530114
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530115 for sle in entries_to_fix:
116 self.process_sle(sle)
117
118 if self.exceptions:
119 self.raise_exceptions()
120
121 self.update_bin()
122
123 def update_bin(self):
124 # update bin
125 bin_name = frappe.db.get_value("Bin", {
126 "item_code": self.item_code,
127 "warehouse": self.warehouse
128 })
129
130 if not bin_name:
131 bin_doc = frappe.get_doc({
132 "doctype": "Bin",
133 "item_code": self.item_code,
134 "warehouse": self.warehouse
135 })
136 bin_doc.insert(ignore_permissions=True)
137 else:
138 bin_doc = frappe.get_doc("Bin", bin_name)
139
140 bin_doc.update({
141 "valuation_rate": self.valuation_rate,
142 "actual_qty": self.qty_after_transaction,
143 "stock_value": self.stock_value
144 })
Saurabhb166bcf2015-12-28 13:25:35 +0530145 bin_doc.flags.via_stock_ledger_entry = True
Rushabh Mehta538607e2016-06-12 11:03:00 +0530146
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530147 bin_doc.save(ignore_permissions=True)
148
149 def process_sle(self, sle):
Anand Doshi0dc79f42015-04-06 12:59:34 +0530150 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 +0530151 # validate negative stock for serialized items, fifo valuation
Nabin Hait902e8602013-01-08 18:29:24 +0530152 # or when negative stock is not allowed for moving average
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530153 if not self.validate_negative_stock(sle):
154 self.qty_after_transaction += flt(sle.actual_qty)
155 return
Nabin Haitb96c0142014-10-07 11:25:04 +0530156
Anand Doshi1b531862013-01-10 19:29:51 +0530157 if sle.serial_no:
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530158 self.get_serialized_values(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530159 self.qty_after_transaction += flt(sle.actual_qty)
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530160 if sle.voucher_type == "Stock Reconciliation":
161 self.qty_after_transaction = sle.qty_after_transaction
162
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530163 self.stock_value = flt(self.qty_after_transaction) * flt(self.valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530164 else:
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530165 if sle.voucher_type=="Stock Reconciliation" and not sle.batch_no:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530166 # assert
167 self.valuation_rate = sle.valuation_rate
168 self.qty_after_transaction = sle.qty_after_transaction
169 self.stock_queue = [[self.qty_after_transaction, self.valuation_rate]]
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530170 self.stock_value = flt(self.qty_after_transaction) * flt(self.valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530171 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530172 if self.valuation_method == "Moving Average":
173 self.get_moving_average_values(sle)
174 self.qty_after_transaction += flt(sle.actual_qty)
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530175 self.stock_value = flt(self.qty_after_transaction) * flt(self.valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530176 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530177 self.get_fifo_values(sle)
178 self.qty_after_transaction += flt(sle.actual_qty)
179 self.stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in self.stock_queue))
Nabin Haitb96c0142014-10-07 11:25:04 +0530180
Rushabh Mehta54047782013-12-26 11:07:46 +0530181 # rounding as per precision
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530182 self.stock_value = flt(self.stock_value, self.precision)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530183
rohitwaghchaure805b8632019-09-05 12:18:33 +0530184 stock_value_difference = self.stock_value - self.prev_stock_value
Rohit Waghchaure6424f472018-11-21 23:18:41 +0530185
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530186 self.prev_stock_value = self.stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530187
Nabin Hait902e8602013-01-08 18:29:24 +0530188 # update current sle
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530189 sle.qty_after_transaction = self.qty_after_transaction
190 sle.valuation_rate = self.valuation_rate
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530191 sle.stock_value = self.stock_value
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530192 sle.stock_queue = json.dumps(self.stock_queue)
193 sle.stock_value_difference = stock_value_difference
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530194 sle.doctype="Stock Ledger Entry"
195 frappe.get_doc(sle).db_update()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530196
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530197 def validate_negative_stock(self, sle):
198 """
199 validate negative stock for entries current datetime onwards
200 will not consider cancelled entries
201 """
202 diff = self.qty_after_transaction + flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530203
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530204 if diff < 0 and abs(diff) > 0.0001:
205 # negative stock!
206 exc = sle.copy().update({"diff": diff})
207 self.exceptions.append(exc)
208 return False
Nabin Hait902e8602013-01-08 18:29:24 +0530209 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530210 return True
211
212 def get_serialized_values(self, sle):
213 incoming_rate = flt(sle.incoming_rate)
214 actual_qty = flt(sle.actual_qty)
Nabin Hait328c4f92020-01-02 19:00:32 +0530215 serial_nos = cstr(sle.serial_no).split("\n")
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530216
217 if incoming_rate < 0:
218 # wrong incoming rate
219 incoming_rate = self.valuation_rate
Rushabh Mehta538607e2016-06-12 11:03:00 +0530220
Nabin Hait2620bf42016-02-29 11:30:27 +0530221 stock_value_change = 0
222 if incoming_rate:
223 stock_value_change = actual_qty * incoming_rate
224 elif actual_qty < 0:
225 # In case of delivery/stock issue, get average purchase rate
226 # of serial nos of current entry
Nabin Hait328c4f92020-01-02 19:00:32 +0530227 outgoing_value = self.get_incoming_value_for_serial_nos(sle, serial_nos)
228 stock_value_change = -1 * outgoing_value
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530229
Nabin Hait2620bf42016-02-29 11:30:27 +0530230 new_stock_qty = self.qty_after_transaction + actual_qty
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530231
Nabin Hait2620bf42016-02-29 11:30:27 +0530232 if new_stock_qty > 0:
233 new_stock_value = (self.qty_after_transaction * self.valuation_rate) + stock_value_change
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530234 if new_stock_value >= 0:
Nabin Hait2620bf42016-02-29 11:30:27 +0530235 # calculate new valuation rate only if stock value is positive
236 # else it remains the same as that of previous entry
237 self.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530238
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530239 if not self.valuation_rate and sle.voucher_detail_no:
240 allow_zero_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
241 if not allow_zero_rate:
242 self.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
243 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
244 currency=erpnext.get_company_currency(sle.company))
245
Nabin Hait328c4f92020-01-02 19:00:32 +0530246 def get_incoming_value_for_serial_nos(self, sle, serial_nos):
247 # get rate from serial nos within same company
248 all_serial_nos = frappe.get_all("Serial No",
249 fields=["purchase_rate", "name", "company"],
250 filters = {'name': ('in', serial_nos)})
251
252 incoming_values = sum([flt(d.purchase_rate) for d in all_serial_nos if d.company==sle.company])
253
254 # Get rate for serial nos which has been transferred to other company
255 invalid_serial_nos = [d.name for d in all_serial_nos if d.company!=sle.company]
256 for serial_no in invalid_serial_nos:
257 incoming_rate = frappe.db.sql("""
258 select incoming_rate
259 from `tabStock Ledger Entry`
260 where
261 company = %s
262 and actual_qty > 0
263 and (serial_no = %s
264 or serial_no like %s
265 or serial_no like %s
266 or serial_no like %s
267 )
268 order by posting_date desc
269 limit 1
270 """, (sle.company, serial_no, serial_no+'\n%', '%\n'+serial_no, '%\n'+serial_no+'\n%'))
271
272 incoming_values += flt(incoming_rate[0][0]) if incoming_rate else 0
273
274 return incoming_values
275
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530276 def get_moving_average_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530277 actual_qty = flt(sle.actual_qty)
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530278 new_stock_qty = flt(self.qty_after_transaction) + actual_qty
279 if new_stock_qty >= 0:
280 if actual_qty > 0:
281 if flt(self.qty_after_transaction) <= 0:
282 self.valuation_rate = sle.incoming_rate
283 else:
284 new_stock_value = (self.qty_after_transaction * self.valuation_rate) + \
285 (actual_qty * sle.incoming_rate)
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530286
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530287 self.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530288
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530289 elif sle.outgoing_rate:
290 if new_stock_qty:
291 new_stock_value = (self.qty_after_transaction * self.valuation_rate) + \
292 (actual_qty * sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530293
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530294 self.valuation_rate = new_stock_value / new_stock_qty
295 else:
Nabin Hait7590b8f2016-07-27 16:44:17 +0530296 self.valuation_rate = sle.outgoing_rate
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530297
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530298 else:
299 if flt(self.qty_after_transaction) >= 0 and sle.outgoing_rate:
300 self.valuation_rate = sle.outgoing_rate
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530301
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530302 if not self.valuation_rate and actual_qty > 0:
303 self.valuation_rate = sle.incoming_rate
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530304
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530305 # Get valuation rate from previous SLE or Item master, if item does not have the
Javier Wong9b11d9b2017-04-14 18:24:04 +0800306 # allow zero valuration rate flag set
Nabin Haitea8fab52017-02-06 17:13:39 +0530307 if not self.valuation_rate and sle.voucher_detail_no:
Javier Wong9b11d9b2017-04-14 18:24:04 +0800308 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
309 if not allow_zero_valuation_rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530310 self.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
311 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
312 currency=erpnext.get_company_currency(sle.company))
313
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530314 def get_fifo_values(self, sle):
315 incoming_rate = flt(sle.incoming_rate)
316 actual_qty = flt(sle.actual_qty)
Nabin Haitada485f2015-07-17 15:09:56 +0530317 outgoing_rate = flt(sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530318
319 if actual_qty > 0:
320 if not self.stock_queue:
321 self.stock_queue.append([0, 0])
322
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530323 # last row has the same rate, just updated the qty
324 if self.stock_queue[-1][1]==incoming_rate:
325 self.stock_queue[-1][0] += actual_qty
Nabin Hait4d742162014-10-09 19:25:03 +0530326 else:
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530327 if self.stock_queue[-1][0] > 0:
328 self.stock_queue.append([actual_qty, incoming_rate])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530329 else:
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530330 qty = self.stock_queue[-1][0] + actual_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530331 self.stock_queue[-1] = [qty, incoming_rate]
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530332 else:
333 qty_to_pop = abs(actual_qty)
334 while qty_to_pop:
335 if not self.stock_queue:
Nabin Haita0b967f2017-01-18 18:35:58 +0530336 # Get valuation rate from last sle if exists or from valuation rate field in item master
Javier Wong9b11d9b2017-04-14 18:24:04 +0800337 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
338 if not allow_zero_valuation_rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530339 _rate = get_valuation_rate(sle.item_code, sle.warehouse,
340 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
341 currency=erpnext.get_company_currency(sle.company))
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530342 else:
343 _rate = 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530344
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530345 self.stock_queue.append([0, _rate])
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530346
Nabin Haitada485f2015-07-17 15:09:56 +0530347 index = None
348 if outgoing_rate > 0:
349 # Find the entry where rate matched with outgoing rate
350 for i, v in enumerate(self.stock_queue):
351 if v[1] == outgoing_rate:
352 index = i
353 break
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530354
Nabin Haitada485f2015-07-17 15:09:56 +0530355 # If no entry found with outgoing rate, collapse stack
356 if index == None:
357 new_stock_value = sum((d[0]*d[1] for d in self.stock_queue)) - qty_to_pop*outgoing_rate
358 new_stock_qty = sum((d[0] for d in self.stock_queue)) - qty_to_pop
359 self.stock_queue = [[new_stock_qty, new_stock_value/new_stock_qty if new_stock_qty > 0 else outgoing_rate]]
360 break
361 else:
362 index = 0
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530363
Nabin Haitada485f2015-07-17 15:09:56 +0530364 # select first batch or the batch with same rate
365 batch = self.stock_queue[index]
Nabin Hait8142cd22015-08-05 18:57:26 +0530366 if qty_to_pop >= batch[0]:
367 # consume current batch
368 qty_to_pop = qty_to_pop - batch[0]
369 self.stock_queue.pop(index)
370 if not self.stock_queue and qty_to_pop:
371 # stock finished, qty still remains to be withdrawn
372 # negative stock, keep in as a negative batch
373 self.stock_queue.append([-qty_to_pop, outgoing_rate or batch[1]])
374 break
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530375
Nabin Hait8142cd22015-08-05 18:57:26 +0530376 else:
377 # qty found in current batch
378 # consume it and exit
379 batch[0] = batch[0] - qty_to_pop
380 qty_to_pop = 0
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530381
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530382 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in self.stock_queue))
383 stock_qty = sum((flt(batch[0]) for batch in self.stock_queue))
Nabin Hait902e8602013-01-08 18:29:24 +0530384
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530385 if stock_qty:
386 self.valuation_rate = stock_value / flt(stock_qty)
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530387
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530388 if not self.stock_queue:
389 self.stock_queue.append([0, sle.incoming_rate or sle.outgoing_rate or self.valuation_rate])
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530390
Javier Wong9b11d9b2017-04-14 18:24:04 +0800391 def check_if_allow_zero_valuation_rate(self, voucher_type, voucher_detail_no):
deepeshgarg007f9c0ef32019-07-30 18:49:19 +0530392 ref_item_dt = ""
393
394 if voucher_type == "Stock Entry":
395 ref_item_dt = voucher_type + " Detail"
396 elif voucher_type in ["Purchase Invoice", "Sales Invoice", "Delivery Note", "Purchase Receipt"]:
397 ref_item_dt = voucher_type + " Item"
398
399 if ref_item_dt:
400 return frappe.db.get_value(ref_item_dt, voucher_detail_no, "allow_zero_valuation_rate")
401 else:
402 return 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530403
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530404 def get_sle_before_datetime(self):
405 """get previous stock ledger entry before current time-bucket"""
406 return get_stock_ledger_entries(self.args, "<", "desc", "limit 1", for_update=False)
Nabin Hait4d742162014-10-09 19:25:03 +0530407
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530408 def get_sle_after_datetime(self):
409 """get Stock Ledger Entries after a particular datetime, for reposting"""
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530410 return get_stock_ledger_entries(self.previous_sle or frappe._dict({
411 "item_code": self.args.get("item_code"), "warehouse": self.args.get("warehouse") }),
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530412 ">", "asc", for_update=True, check_serial_no=False)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530413
414 def raise_exceptions(self):
415 deficiency = min(e["diff"] for e in self.exceptions)
Rushabh Mehta538607e2016-06-12 11:03:00 +0530416
Rushabh Mehta649e2532016-07-20 15:30:17 +0530417 if ((self.exceptions[0]["voucher_type"], self.exceptions[0]["voucher_no"]) in
418 frappe.local.flags.currently_saving):
Nabin Hait3edefb12016-07-20 16:13:18 +0530419
Rushabh Mehta538607e2016-06-12 11:03:00 +0530420 msg = _("{0} units of {1} needed in {2} to complete this transaction.").format(
421 abs(deficiency), frappe.get_desk_link('Item', self.item_code),
422 frappe.get_desk_link('Warehouse', self.warehouse))
423 else:
424 msg = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
425 abs(deficiency), frappe.get_desk_link('Item', self.item_code),
426 frappe.get_desk_link('Warehouse', self.warehouse),
427 self.exceptions[0]["posting_date"], self.exceptions[0]["posting_time"],
428 frappe.get_desk_link(self.exceptions[0]["voucher_type"], self.exceptions[0]["voucher_no"]))
429
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530430 if self.verbose:
Rushabh Mehta538607e2016-06-12 11:03:00 +0530431 frappe.throw(msg, NegativeStockError, title='Insufficent Stock')
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530432 else:
cclauss68487082017-07-27 07:08:35 +0200433 raise NegativeStockError(msg)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530434
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530435def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530436 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530437 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530438 to get actual qty before transaction, this function
439 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530440
Anand Doshi1b531862013-01-10 19:29:51 +0530441 args = {
442 "item_code": "ABC",
443 "warehouse": "XYZ",
444 "posting_date": "2012-12-12",
445 "posting_time": "12:00",
446 "sle": "name of reference Stock Ledger Entry"
447 }
448 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530449 args["name"] = args.get("sle", None) or ""
450 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530451 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530452
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530453def get_stock_ledger_entries(previous_sle, operator=None,
454 order="desc", limit=None, for_update=False, debug=False, check_serial_no=True):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530455 """get stock ledger entries filtered by specific posting datetime conditions"""
Nabin Haitb9ce1042018-02-01 14:58:50 +0530456 conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
457 if previous_sle.get("warehouse"):
458 conditions += " and warehouse = %(warehouse)s"
459 elif previous_sle.get("warehouse_condition"):
460 conditions += " and " + previous_sle.get("warehouse_condition")
461
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530462 if check_serial_no and previous_sle.get("serial_no"):
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530463 conditions += " and serial_no like {}".format(frappe.db.escape('%{0}%'.format(previous_sle.get("serial_no"))))
464
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530465 if not previous_sle.get("posting_date"):
466 previous_sle["posting_date"] = "1900-01-01"
467 if not previous_sle.get("posting_time"):
468 previous_sle["posting_time"] = "00:00"
469
470 if operator in (">", "<=") and previous_sle.get("name"):
471 conditions += " and name!=%(name)s"
472
473 return frappe.db.sql("""select *, timestamp(posting_date, posting_time) as "timestamp" from `tabStock Ledger Entry`
474 where item_code = %%(item_code)s
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530475 and ifnull(is_cancelled, 'No')='No'
Nabin Haitb9ce1042018-02-01 14:58:50 +0530476 %(conditions)s
Aditya Hase0c164242019-01-07 22:07:13 +0530477 order by timestamp(posting_date, posting_time) %(order)s, creation %(order)s
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530478 %(limit)s %(for_update)s""" % {
479 "conditions": conditions,
480 "limit": limit or "",
481 "for_update": for_update and "for update" or "",
482 "order": order
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530483 }, previous_sle, as_dict=1, debug=debug)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530484
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530485def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no,
Nabin Hait7ba092e2018-02-01 10:51:27 +0530486 allow_zero_rate=False, currency=None, company=None, raise_error_if_no_rate=True):
Nabin Haita0b967f2017-01-18 18:35:58 +0530487 # Get valuation rate from last sle for the same item and warehouse
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530488 if not company:
489 company = erpnext.get_default_company()
490
Nabin Haitfb6e4342014-10-15 11:34:40 +0530491 last_valuation_rate = frappe.db.sql("""select valuation_rate
492 from `tabStock Ledger Entry`
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530493 where
494 item_code = %s
495 AND warehouse = %s
496 AND valuation_rate >= 0
497 AND NOT (voucher_no = %s AND voucher_type = %s)
498 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 +0530499
500 if not last_valuation_rate:
Nabin Haita0b967f2017-01-18 18:35:58 +0530501 # Get valuation rate from last sle for the item against any warehouse
Nabin Haitfb6e4342014-10-15 11:34:40 +0530502 last_valuation_rate = frappe.db.sql("""select valuation_rate
503 from `tabStock Ledger Entry`
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530504 where
505 item_code = %s
506 AND valuation_rate > 0
507 AND NOT(voucher_no = %s AND voucher_type = %s)
508 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 +0530509
Nabin Haita645f362018-03-01 10:31:24 +0530510 if last_valuation_rate:
511 return flt(last_valuation_rate[0][0]) # as there is previous records, it might come with zero rate
512
513 # If negative stock allowed, and item delivered without any incoming entry,
514 # system does not found any SLE, then take valuation rate from Item
515 valuation_rate = frappe.db.get_value("Item", item_code, "valuation_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530516
517 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530518 # try Item Standard rate
519 valuation_rate = frappe.db.get_value("Item", item_code, "standard_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530520
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530521 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530522 # try in price list
523 valuation_rate = frappe.db.get_value('Item Price',
524 dict(item_code=item_code, buying=1, currency=currency),
525 'price_list_rate')
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530526
Nabin Hait7ba092e2018-02-01 10:51:27 +0530527 if not allow_zero_rate and not valuation_rate and raise_error_if_no_rate \
Rohit Waghchauree9ff1912017-06-19 12:54:59 +0530528 and cint(erpnext.is_perpetual_inventory_enabled(company)):
Neil Trini Lasrado193c8912017-03-28 17:39:34 +0530529 frappe.local.message_log = []
Nabin Haitca25b922019-07-22 17:00:32 +0530530 frappe.throw(_("Valuation rate not found for the Item {0}, which is required to do accounting entries for {1} {2}. If the item is transacting as a zero valuation rate item in the {1}, please mention that in the {1} Item table. Otherwise, please create an incoming stock transaction for the item or mention valuation rate in the Item record, and then try submiting / cancelling this entry.")
531 .format(item_code, voucher_type, voucher_no))
Nabin Haitfb6e4342014-10-15 11:34:40 +0530532
533 return valuation_rate