blob: c8706b291e08e35c35a29b8348d01cfa6b8300a9 [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)
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530160 self.stock_value = flt(self.qty_after_transaction) * flt(self.valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530161 else:
162 if sle.voucher_type=="Stock Reconciliation":
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530163 # assert
164 self.valuation_rate = sle.valuation_rate
165 self.qty_after_transaction = sle.qty_after_transaction
166 self.stock_queue = [[self.qty_after_transaction, self.valuation_rate]]
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530167 self.stock_value = flt(self.qty_after_transaction) * flt(self.valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530168 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530169 if self.valuation_method == "Moving Average":
170 self.get_moving_average_values(sle)
171 self.qty_after_transaction += flt(sle.actual_qty)
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530172 self.stock_value = flt(self.qty_after_transaction) * flt(self.valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530173 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530174 self.get_fifo_values(sle)
175 self.qty_after_transaction += flt(sle.actual_qty)
176 self.stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in self.stock_queue))
Nabin Haitb96c0142014-10-07 11:25:04 +0530177
Rushabh Mehta54047782013-12-26 11:07:46 +0530178 # rounding as per precision
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530179 self.stock_value = flt(self.stock_value, self.precision)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530180
Rohit Waghchaure16b8ecb2018-11-30 16:20:52 +0530181 if self.prev_stock_value < 0 and self.stock_value >= 0 and sle.voucher_type != 'Stock Reconciliation':
Rohit Waghchaure6424f472018-11-21 23:18:41 +0530182 stock_value_difference = sle.actual_qty * self.valuation_rate
183 else:
184 stock_value_difference = self.stock_value - self.prev_stock_value
185
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)
215 serial_no = cstr(sle.serial_no).split("\n")
216
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
227 stock_value_change = -1 * flt(frappe.db.sql("""select sum(purchase_rate)
228 from `tabSerial No` where name in (%s)""" % (", ".join(["%s"]*len(serial_no))),
229 tuple(serial_no))[0][0])
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530230
Nabin Hait2620bf42016-02-29 11:30:27 +0530231 new_stock_qty = self.qty_after_transaction + actual_qty
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530232
Nabin Hait2620bf42016-02-29 11:30:27 +0530233 if new_stock_qty > 0:
234 new_stock_value = (self.qty_after_transaction * self.valuation_rate) + stock_value_change
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530235 if new_stock_value >= 0:
Nabin Hait2620bf42016-02-29 11:30:27 +0530236 # calculate new valuation rate only if stock value is positive
237 # else it remains the same as that of previous entry
238 self.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530239
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530240 if not self.valuation_rate and sle.voucher_detail_no:
241 allow_zero_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
242 if not allow_zero_rate:
243 self.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
244 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
245 currency=erpnext.get_company_currency(sle.company))
246
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530247 def get_moving_average_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530248 actual_qty = flt(sle.actual_qty)
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530249 new_stock_qty = flt(self.qty_after_transaction) + actual_qty
250 if new_stock_qty >= 0:
251 if actual_qty > 0:
252 if flt(self.qty_after_transaction) <= 0:
253 self.valuation_rate = sle.incoming_rate
254 else:
255 new_stock_value = (self.qty_after_transaction * self.valuation_rate) + \
256 (actual_qty * sle.incoming_rate)
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530257
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530258 self.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530259
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530260 elif sle.outgoing_rate:
261 if new_stock_qty:
262 new_stock_value = (self.qty_after_transaction * self.valuation_rate) + \
263 (actual_qty * sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530264
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530265 self.valuation_rate = new_stock_value / new_stock_qty
266 else:
Nabin Hait7590b8f2016-07-27 16:44:17 +0530267 self.valuation_rate = sle.outgoing_rate
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530268
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530269 else:
270 if flt(self.qty_after_transaction) >= 0 and sle.outgoing_rate:
271 self.valuation_rate = sle.outgoing_rate
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530272
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530273 if not self.valuation_rate and actual_qty > 0:
274 self.valuation_rate = sle.incoming_rate
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530275
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530276 # Get valuation rate from previous SLE or Item master, if item does not have the
Javier Wong9b11d9b2017-04-14 18:24:04 +0800277 # allow zero valuration rate flag set
Nabin Haitea8fab52017-02-06 17:13:39 +0530278 if not self.valuation_rate and sle.voucher_detail_no:
Javier Wong9b11d9b2017-04-14 18:24:04 +0800279 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
280 if not allow_zero_valuation_rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530281 self.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
282 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
283 currency=erpnext.get_company_currency(sle.company))
284
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530285 def get_fifo_values(self, sle):
286 incoming_rate = flt(sle.incoming_rate)
287 actual_qty = flt(sle.actual_qty)
Nabin Haitada485f2015-07-17 15:09:56 +0530288 outgoing_rate = flt(sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530289
290 if actual_qty > 0:
291 if not self.stock_queue:
292 self.stock_queue.append([0, 0])
293
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530294 # last row has the same rate, just updated the qty
295 if self.stock_queue[-1][1]==incoming_rate:
296 self.stock_queue[-1][0] += actual_qty
Nabin Hait4d742162014-10-09 19:25:03 +0530297 else:
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530298 if self.stock_queue[-1][0] > 0:
299 self.stock_queue.append([actual_qty, incoming_rate])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530300 else:
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530301 qty = self.stock_queue[-1][0] + actual_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530302 self.stock_queue[-1] = [qty, incoming_rate]
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530303 else:
304 qty_to_pop = abs(actual_qty)
305 while qty_to_pop:
306 if not self.stock_queue:
Nabin Haita0b967f2017-01-18 18:35:58 +0530307 # Get valuation rate from last sle if exists or from valuation rate field in item master
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 _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))
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530313 else:
314 _rate = 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530315
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530316 self.stock_queue.append([0, _rate])
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530317
Nabin Haitada485f2015-07-17 15:09:56 +0530318 index = None
319 if outgoing_rate > 0:
320 # Find the entry where rate matched with outgoing rate
321 for i, v in enumerate(self.stock_queue):
322 if v[1] == outgoing_rate:
323 index = i
324 break
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530325
Nabin Haitada485f2015-07-17 15:09:56 +0530326 # If no entry found with outgoing rate, collapse stack
327 if index == None:
328 new_stock_value = sum((d[0]*d[1] for d in self.stock_queue)) - qty_to_pop*outgoing_rate
329 new_stock_qty = sum((d[0] for d in self.stock_queue)) - qty_to_pop
330 self.stock_queue = [[new_stock_qty, new_stock_value/new_stock_qty if new_stock_qty > 0 else outgoing_rate]]
331 break
332 else:
333 index = 0
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530334
Nabin Haitada485f2015-07-17 15:09:56 +0530335 # select first batch or the batch with same rate
336 batch = self.stock_queue[index]
Nabin Hait8142cd22015-08-05 18:57:26 +0530337 if qty_to_pop >= batch[0]:
338 # consume current batch
339 qty_to_pop = qty_to_pop - batch[0]
340 self.stock_queue.pop(index)
341 if not self.stock_queue and qty_to_pop:
342 # stock finished, qty still remains to be withdrawn
343 # negative stock, keep in as a negative batch
344 self.stock_queue.append([-qty_to_pop, outgoing_rate or batch[1]])
345 break
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530346
Nabin Hait8142cd22015-08-05 18:57:26 +0530347 else:
348 # qty found in current batch
349 # consume it and exit
350 batch[0] = batch[0] - qty_to_pop
351 qty_to_pop = 0
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530352
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530353 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in self.stock_queue))
354 stock_qty = sum((flt(batch[0]) for batch in self.stock_queue))
Nabin Hait902e8602013-01-08 18:29:24 +0530355
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530356 if stock_qty:
357 self.valuation_rate = stock_value / flt(stock_qty)
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530358
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530359 if not self.stock_queue:
360 self.stock_queue.append([0, sle.incoming_rate or sle.outgoing_rate or self.valuation_rate])
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530361
Javier Wong9b11d9b2017-04-14 18:24:04 +0800362 def check_if_allow_zero_valuation_rate(self, voucher_type, voucher_detail_no):
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530363 ref_item_dt = voucher_type + (" Detail" if voucher_type == "Stock Entry" else " Item")
Javier Wong9b11d9b2017-04-14 18:24:04 +0800364 return frappe.db.get_value(ref_item_dt, voucher_detail_no, "allow_zero_valuation_rate")
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530365
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530366 def get_sle_before_datetime(self):
367 """get previous stock ledger entry before current time-bucket"""
368 return get_stock_ledger_entries(self.args, "<", "desc", "limit 1", for_update=False)
Nabin Hait4d742162014-10-09 19:25:03 +0530369
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530370 def get_sle_after_datetime(self):
371 """get Stock Ledger Entries after a particular datetime, for reposting"""
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530372 return get_stock_ledger_entries(self.previous_sle or frappe._dict({
373 "item_code": self.args.get("item_code"), "warehouse": self.args.get("warehouse") }),
374 ">", "asc", for_update=True)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530375
376 def raise_exceptions(self):
377 deficiency = min(e["diff"] for e in self.exceptions)
Rushabh Mehta538607e2016-06-12 11:03:00 +0530378
Rushabh Mehta649e2532016-07-20 15:30:17 +0530379 if ((self.exceptions[0]["voucher_type"], self.exceptions[0]["voucher_no"]) in
380 frappe.local.flags.currently_saving):
Nabin Hait3edefb12016-07-20 16:13:18 +0530381
Rushabh Mehta538607e2016-06-12 11:03:00 +0530382 msg = _("{0} units of {1} needed in {2} to complete this transaction.").format(
383 abs(deficiency), frappe.get_desk_link('Item', self.item_code),
384 frappe.get_desk_link('Warehouse', self.warehouse))
385 else:
386 msg = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
387 abs(deficiency), frappe.get_desk_link('Item', self.item_code),
388 frappe.get_desk_link('Warehouse', self.warehouse),
389 self.exceptions[0]["posting_date"], self.exceptions[0]["posting_time"],
390 frappe.get_desk_link(self.exceptions[0]["voucher_type"], self.exceptions[0]["voucher_no"]))
391
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530392 if self.verbose:
Rushabh Mehta538607e2016-06-12 11:03:00 +0530393 frappe.throw(msg, NegativeStockError, title='Insufficent Stock')
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530394 else:
cclauss68487082017-07-27 07:08:35 +0200395 raise NegativeStockError(msg)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530396
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530397def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530398 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530399 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530400 to get actual qty before transaction, this function
401 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530402
Anand Doshi1b531862013-01-10 19:29:51 +0530403 args = {
404 "item_code": "ABC",
405 "warehouse": "XYZ",
406 "posting_date": "2012-12-12",
407 "posting_time": "12:00",
408 "sle": "name of reference Stock Ledger Entry"
409 }
410 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530411 args["name"] = args.get("sle", None) or ""
412 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530413 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530414
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530415def get_stock_ledger_entries(previous_sle, operator=None, order="desc", limit=None, for_update=False, debug=False):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530416 """get stock ledger entries filtered by specific posting datetime conditions"""
Nabin Haitb9ce1042018-02-01 14:58:50 +0530417 conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
418 if previous_sle.get("warehouse"):
419 conditions += " and warehouse = %(warehouse)s"
420 elif previous_sle.get("warehouse_condition"):
421 conditions += " and " + previous_sle.get("warehouse_condition")
422
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530423 if not previous_sle.get("posting_date"):
424 previous_sle["posting_date"] = "1900-01-01"
425 if not previous_sle.get("posting_time"):
426 previous_sle["posting_time"] = "00:00"
427
428 if operator in (">", "<=") and previous_sle.get("name"):
429 conditions += " and name!=%(name)s"
430
431 return frappe.db.sql("""select *, timestamp(posting_date, posting_time) as "timestamp" from `tabStock Ledger Entry`
432 where item_code = %%(item_code)s
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530433 and ifnull(is_cancelled, 'No')='No'
Nabin Haitb9ce1042018-02-01 14:58:50 +0530434 %(conditions)s
Aditya Hase0c164242019-01-07 22:07:13 +0530435 order by timestamp(posting_date, posting_time) %(order)s, creation %(order)s
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530436 %(limit)s %(for_update)s""" % {
437 "conditions": conditions,
438 "limit": limit or "",
439 "for_update": for_update and "for update" or "",
440 "order": order
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530441 }, previous_sle, as_dict=1, debug=debug)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530442
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530443def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no,
Nabin Hait7ba092e2018-02-01 10:51:27 +0530444 allow_zero_rate=False, currency=None, company=None, raise_error_if_no_rate=True):
Nabin Haita0b967f2017-01-18 18:35:58 +0530445 # Get valuation rate from last sle for the same item and warehouse
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530446 if not company:
447 company = erpnext.get_default_company()
448
Nabin Haitfb6e4342014-10-15 11:34:40 +0530449 last_valuation_rate = frappe.db.sql("""select valuation_rate
450 from `tabStock Ledger Entry`
451 where item_code = %s and warehouse = %s
rohitwaghchaure40a5a302018-04-02 10:14:49 +0530452 and valuation_rate >= 0
Aditya Hase0c164242019-01-07 22:07:13 +0530453 order by posting_date desc, posting_time desc, creation desc limit 1""", (item_code, warehouse))
Nabin Haitfb6e4342014-10-15 11:34:40 +0530454
455 if not last_valuation_rate:
Nabin Haita0b967f2017-01-18 18:35:58 +0530456 # Get valuation rate from last sle for the item against any warehouse
Nabin Haitfb6e4342014-10-15 11:34:40 +0530457 last_valuation_rate = frappe.db.sql("""select valuation_rate
458 from `tabStock Ledger Entry`
Anand Doshi602e8252015-11-16 19:05:46 +0530459 where item_code = %s and valuation_rate > 0
Aditya Hase0c164242019-01-07 22:07:13 +0530460 order by posting_date desc, posting_time desc, creation desc limit 1""", item_code)
Nabin Haitfb6e4342014-10-15 11:34:40 +0530461
Nabin Haita645f362018-03-01 10:31:24 +0530462 if last_valuation_rate:
463 return flt(last_valuation_rate[0][0]) # as there is previous records, it might come with zero rate
464
465 # If negative stock allowed, and item delivered without any incoming entry,
466 # system does not found any SLE, then take valuation rate from Item
467 valuation_rate = frappe.db.get_value("Item", item_code, "valuation_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530468
469 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530470 # try Item Standard rate
471 valuation_rate = frappe.db.get_value("Item", item_code, "standard_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530472
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530473 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530474 # try in price list
475 valuation_rate = frappe.db.get_value('Item Price',
476 dict(item_code=item_code, buying=1, currency=currency),
477 'price_list_rate')
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530478
Nabin Hait7ba092e2018-02-01 10:51:27 +0530479 if not allow_zero_rate and not valuation_rate and raise_error_if_no_rate \
Rohit Waghchauree9ff1912017-06-19 12:54:59 +0530480 and cint(erpnext.is_perpetual_inventory_enabled(company)):
Neil Trini Lasrado193c8912017-03-28 17:39:34 +0530481 frappe.local.message_log = []
Javier Wong61287e32017-10-04 18:31:34 +0800482 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").format(item_code, voucher_type, voucher_no))
Nabin Haitfb6e4342014-10-15 11:34:40 +0530483
484 return valuation_rate