blob: c73cbf29421599a299afa00cba53969e1792af47 [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
11# future reposting
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053012class NegativeStockError(frappe.ValidationError): pass
Nabin Hait902e8602013-01-08 18:29:24 +053013
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053014_exceptions = frappe.local('stockledger_exceptions')
Pratik Vyas16371b72013-09-18 18:31:03 +053015# _exceptions = []
Anand Doshi5b004ff2013-09-25 19:55:41 +053016
Nabin Hait54c865e2015-03-27 15:38:31 +053017def make_sl_entries(sl_entries, is_amended=None, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Haitca775742013-09-26 16:16:44 +053018 if sl_entries:
Rushabh Mehta1f847992013-12-12 19:12:19 +053019 from erpnext.stock.utils import update_bin
Nabin Haitdc82d4f2014-04-07 12:02:57 +053020
Nabin Haitca775742013-09-26 16:16:44 +053021 cancel = True if sl_entries[0].get("is_cancelled") == "Yes" else False
22 if cancel:
23 set_as_cancel(sl_entries[0].get('voucher_no'), sl_entries[0].get('voucher_type'))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053024
Nabin Haitca775742013-09-26 16:16:44 +053025 for sle in sl_entries:
26 sle_id = None
27 if sle.get('is_cancelled') == 'Yes':
28 sle['actual_qty'] = -flt(sle['actual_qty'])
Nabin Haitdc82d4f2014-04-07 12:02:57 +053029
Nabin Hait5288bde2014-11-03 15:08:21 +053030 if sle.get("actual_qty") or sle.get("voucher_type")=="Stock Reconciliation":
Nabin Hait54c865e2015-03-27 15:38:31 +053031 sle_id = make_entry(sle, allow_negative_stock, via_landed_cost_voucher)
Nabin Haitdc82d4f2014-04-07 12:02:57 +053032
Nabin Haitca775742013-09-26 16:16:44 +053033 args = sle.copy()
34 args.update({
35 "sle_id": sle_id,
36 "is_amended": is_amended
37 })
Nabin Hait54c865e2015-03-27 15:38:31 +053038 update_bin(args, allow_negative_stock, via_landed_cost_voucher)
Nabin Haitadeb9762014-10-06 11:53:52 +053039
Nabin Haitca775742013-09-26 16:16:44 +053040 if cancel:
Nabin Haitadeb9762014-10-06 11:53:52 +053041 delete_cancelled_entry(sl_entries[0].get('voucher_type'), sl_entries[0].get('voucher_no'))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053042
Nabin Hait9653f602013-08-20 15:37:33 +053043def set_as_cancel(voucher_type, voucher_no):
Anand Doshie9baaa62014-02-26 12:35:33 +053044 frappe.db.sql("""update `tabStock Ledger Entry` set is_cancelled='Yes',
Nabin Hait9653f602013-08-20 15:37:33 +053045 modified=%s, modified_by=%s
Nabin Haitdc82d4f2014-04-07 12:02:57 +053046 where voucher_no=%s and voucher_type=%s""",
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053047 (now(), frappe.session.user, voucher_type, voucher_no))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053048
Nabin Hait54c865e2015-03-27 15:38:31 +053049def make_entry(args, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Hait74c281c2013-08-19 16:17:18 +053050 args.update({"doctype": "Stock Ledger Entry"})
Rushabh Mehtaa504f062014-04-04 12:16:26 +053051 sle = frappe.get_doc(args)
Anand Doshi6dfd4302015-02-10 14:41:27 +053052 sle.flags.ignore_permissions = 1
Nabin Hait4ccd8d32015-01-23 12:18:01 +053053 sle.allow_negative_stock=allow_negative_stock
Nabin Hait54c865e2015-03-27 15:38:31 +053054 sle.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Hait74c281c2013-08-19 16:17:18 +053055 sle.insert()
Nabin Haitaeba24e2013-08-23 15:17:36 +053056 sle.submit()
Anand Doshif78d1ae2014-03-28 13:55:00 +053057 return sle.name
Nabin Haitdc82d4f2014-04-07 12:02:57 +053058
Nabin Hait9653f602013-08-20 15:37:33 +053059def delete_cancelled_entry(voucher_type, voucher_no):
Nabin Haitdc82d4f2014-04-07 12:02:57 +053060 frappe.db.sql("""delete from `tabStock Ledger Entry`
Nabin Hait9653f602013-08-20 15:37:33 +053061 where voucher_type=%s and voucher_no=%s""", (voucher_type, voucher_no))
Nabin Hait74c281c2013-08-19 16:17:18 +053062
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053063class update_entries_after(object):
Nabin Hait902e8602013-01-08 18:29:24 +053064 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +053065 update valution rate and qty after transaction
Nabin Hait902e8602013-01-08 18:29:24 +053066 from the current time-bucket onwards
Nabin Haitdc82d4f2014-04-07 12:02:57 +053067
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053068 :param args: args as dict
69
70 args = {
71 "item_code": "ABC",
72 "warehouse": "XYZ",
73 "posting_date": "2012-12-12",
74 "posting_time": "12:00"
75 }
Nabin Hait902e8602013-01-08 18:29:24 +053076 """
Anand Doshi0dc79f42015-04-06 12:59:34 +053077 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 +053078 from frappe.model.meta import get_field_precision
Nabin Haitdc82d4f2014-04-07 12:02:57 +053079
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053080 self.exceptions = []
81 self.verbose = verbose
82 self.allow_zero_rate = allow_zero_rate
83 self.allow_negative_stock = allow_negative_stock
Anand Doshi0dc79f42015-04-06 12:59:34 +053084 self.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Hait43ba7e12015-03-03 14:07:07 +053085 if not self.allow_negative_stock:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053086 self.allow_negative_stock = cint(frappe.db.get_single_value("Stock Settings",
87 "allow_negative_stock"))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053088
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053089 self.args = args
90 for key, value in args.iteritems():
91 setattr(self, key, value)
Nabin Haitdc82d4f2014-04-07 12:02:57 +053092
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053093 self.previous_sle = self.get_sle_before_datetime()
94 self.previous_sle = self.previous_sle[0] if self.previous_sle else frappe._dict()
Nabin Haitbb777562013-08-29 18:19:37 +053095
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053096 for key in ("qty_after_transaction", "valuation_rate", "stock_value"):
97 setattr(self, key, flt(self.previous_sle.get(key)))
98
99 self.company = frappe.db.get_value("Warehouse", self.warehouse, "company")
100 self.precision = get_field_precision(frappe.get_meta("Stock Ledger Entry").get_field("stock_value"),
Rushabh Mehta50ce9752015-04-27 13:13:38 +0530101 currency=frappe.db.get_value("Company", self.company, "default_currency", cache=True))
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530102
Rushabh Mehtac7a11cc2015-02-19 16:28:35 +0530103 self.prev_stock_value = self.previous_sle.stock_value or 0.0
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530104 self.stock_queue = json.loads(self.previous_sle.stock_queue or "[]")
105 self.valuation_method = get_valuation_method(self.item_code)
106 self.stock_value_difference = 0.0
107 self.build()
108
109 def build(self):
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530110 # includes current entry!
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530111 entries_to_fix = self.get_sle_after_datetime()
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530112
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530113 for sle in entries_to_fix:
114 self.process_sle(sle)
115
116 if self.exceptions:
117 self.raise_exceptions()
118
119 self.update_bin()
120
121 def update_bin(self):
122 # update bin
123 bin_name = frappe.db.get_value("Bin", {
124 "item_code": self.item_code,
125 "warehouse": self.warehouse
126 })
127
128 if not bin_name:
129 bin_doc = frappe.get_doc({
130 "doctype": "Bin",
131 "item_code": self.item_code,
132 "warehouse": self.warehouse
133 })
134 bin_doc.insert(ignore_permissions=True)
135 else:
136 bin_doc = frappe.get_doc("Bin", bin_name)
137
138 bin_doc.update({
139 "valuation_rate": self.valuation_rate,
140 "actual_qty": self.qty_after_transaction,
141 "stock_value": self.stock_value
142 })
Saurabhb166bcf2015-12-28 13:25:35 +0530143 bin_doc.flags.via_stock_ledger_entry = True
Rushabh Mehta538607e2016-06-12 11:03:00 +0530144
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530145 bin_doc.save(ignore_permissions=True)
146
147 def process_sle(self, sle):
Anand Doshi0dc79f42015-04-06 12:59:34 +0530148 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 +0530149 # validate negative stock for serialized items, fifo valuation
Nabin Hait902e8602013-01-08 18:29:24 +0530150 # or when negative stock is not allowed for moving average
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530151 if not self.validate_negative_stock(sle):
152 self.qty_after_transaction += flt(sle.actual_qty)
153 return
Nabin Haitb96c0142014-10-07 11:25:04 +0530154
Anand Doshi1b531862013-01-10 19:29:51 +0530155 if sle.serial_no:
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530156 self.get_serialized_values(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530157 self.qty_after_transaction += flt(sle.actual_qty)
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530158 self.stock_value = flt(self.qty_after_transaction) * flt(self.valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530159 else:
160 if sle.voucher_type=="Stock Reconciliation":
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530161 # assert
162 self.valuation_rate = sle.valuation_rate
163 self.qty_after_transaction = sle.qty_after_transaction
164 self.stock_queue = [[self.qty_after_transaction, self.valuation_rate]]
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530165 self.stock_value = flt(self.qty_after_transaction) * flt(self.valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530166 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530167 if self.valuation_method == "Moving Average":
168 self.get_moving_average_values(sle)
169 self.qty_after_transaction += flt(sle.actual_qty)
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 self.get_fifo_values(sle)
173 self.qty_after_transaction += flt(sle.actual_qty)
174 self.stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in self.stock_queue))
Nabin Haitb96c0142014-10-07 11:25:04 +0530175
Rushabh Mehta54047782013-12-26 11:07:46 +0530176 # rounding as per precision
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530177 self.stock_value = flt(self.stock_value, self.precision)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530178
Rohit Waghchaure16b8ecb2018-11-30 16:20:52 +0530179 if self.prev_stock_value < 0 and self.stock_value >= 0 and sle.voucher_type != 'Stock Reconciliation':
Rohit Waghchaure6424f472018-11-21 23:18:41 +0530180 stock_value_difference = sle.actual_qty * self.valuation_rate
181 else:
182 stock_value_difference = self.stock_value - self.prev_stock_value
183
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530184 self.prev_stock_value = self.stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530185
Nabin Hait902e8602013-01-08 18:29:24 +0530186 # update current sle
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530187 sle.qty_after_transaction = self.qty_after_transaction
188 sle.valuation_rate = self.valuation_rate
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530189 sle.stock_value = self.stock_value
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530190 sle.stock_queue = json.dumps(self.stock_queue)
191 sle.stock_value_difference = stock_value_difference
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530192 sle.doctype="Stock Ledger Entry"
193 frappe.get_doc(sle).db_update()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530194
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530195 def validate_negative_stock(self, sle):
196 """
197 validate negative stock for entries current datetime onwards
198 will not consider cancelled entries
199 """
200 diff = self.qty_after_transaction + flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530201
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530202 if diff < 0 and abs(diff) > 0.0001:
203 # negative stock!
204 exc = sle.copy().update({"diff": diff})
205 self.exceptions.append(exc)
206 return False
Nabin Hait902e8602013-01-08 18:29:24 +0530207 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530208 return True
209
210 def get_serialized_values(self, sle):
211 incoming_rate = flt(sle.incoming_rate)
212 actual_qty = flt(sle.actual_qty)
213 serial_no = cstr(sle.serial_no).split("\n")
214
215 if incoming_rate < 0:
216 # wrong incoming rate
217 incoming_rate = self.valuation_rate
Rushabh Mehta538607e2016-06-12 11:03:00 +0530218
Nabin Hait2620bf42016-02-29 11:30:27 +0530219 stock_value_change = 0
220 if incoming_rate:
221 stock_value_change = actual_qty * incoming_rate
222 elif actual_qty < 0:
223 # In case of delivery/stock issue, get average purchase rate
224 # of serial nos of current entry
225 stock_value_change = -1 * flt(frappe.db.sql("""select sum(purchase_rate)
226 from `tabSerial No` where name in (%s)""" % (", ".join(["%s"]*len(serial_no))),
227 tuple(serial_no))[0][0])
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530228
Nabin Hait2620bf42016-02-29 11:30:27 +0530229 new_stock_qty = self.qty_after_transaction + actual_qty
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530230
Nabin Hait2620bf42016-02-29 11:30:27 +0530231 if new_stock_qty > 0:
232 new_stock_value = (self.qty_after_transaction * self.valuation_rate) + stock_value_change
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530233 if new_stock_value >= 0:
Nabin Hait2620bf42016-02-29 11:30:27 +0530234 # calculate new valuation rate only if stock value is positive
235 # else it remains the same as that of previous entry
236 self.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530237
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530238 if not self.valuation_rate and sle.voucher_detail_no:
239 allow_zero_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
240 if not allow_zero_rate:
241 self.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
242 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
243 currency=erpnext.get_company_currency(sle.company))
244
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530245 def get_moving_average_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530246 actual_qty = flt(sle.actual_qty)
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530247 new_stock_qty = flt(self.qty_after_transaction) + actual_qty
248 if new_stock_qty >= 0:
249 if actual_qty > 0:
250 if flt(self.qty_after_transaction) <= 0:
251 self.valuation_rate = sle.incoming_rate
252 else:
253 new_stock_value = (self.qty_after_transaction * self.valuation_rate) + \
254 (actual_qty * sle.incoming_rate)
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530255
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530256 self.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530257
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530258 elif sle.outgoing_rate:
259 if new_stock_qty:
260 new_stock_value = (self.qty_after_transaction * self.valuation_rate) + \
261 (actual_qty * sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530262
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530263 self.valuation_rate = new_stock_value / new_stock_qty
264 else:
Nabin Hait7590b8f2016-07-27 16:44:17 +0530265 self.valuation_rate = sle.outgoing_rate
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530266
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530267 else:
268 if flt(self.qty_after_transaction) >= 0 and sle.outgoing_rate:
269 self.valuation_rate = sle.outgoing_rate
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530270
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530271 if not self.valuation_rate and actual_qty > 0:
272 self.valuation_rate = sle.incoming_rate
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530273
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530274 # Get valuation rate from previous SLE or Item master, if item does not have the
Javier Wong9b11d9b2017-04-14 18:24:04 +0800275 # allow zero valuration rate flag set
Nabin Haitea8fab52017-02-06 17:13:39 +0530276 if not self.valuation_rate and sle.voucher_detail_no:
Javier Wong9b11d9b2017-04-14 18:24:04 +0800277 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
278 if not allow_zero_valuation_rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530279 self.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
280 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
281 currency=erpnext.get_company_currency(sle.company))
282
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530283 def get_fifo_values(self, sle):
284 incoming_rate = flt(sle.incoming_rate)
285 actual_qty = flt(sle.actual_qty)
Nabin Haitada485f2015-07-17 15:09:56 +0530286 outgoing_rate = flt(sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530287
288 if actual_qty > 0:
289 if not self.stock_queue:
290 self.stock_queue.append([0, 0])
291
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530292 # last row has the same rate, just updated the qty
293 if self.stock_queue[-1][1]==incoming_rate:
294 self.stock_queue[-1][0] += actual_qty
Nabin Hait4d742162014-10-09 19:25:03 +0530295 else:
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530296 if self.stock_queue[-1][0] > 0:
297 self.stock_queue.append([actual_qty, incoming_rate])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530298 else:
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530299 qty = self.stock_queue[-1][0] + actual_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530300 self.stock_queue[-1] = [qty, incoming_rate]
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530301 else:
302 qty_to_pop = abs(actual_qty)
303 while qty_to_pop:
304 if not self.stock_queue:
Nabin Haita0b967f2017-01-18 18:35:58 +0530305 # Get valuation rate from last sle if exists or from valuation rate field in item master
Javier Wong9b11d9b2017-04-14 18:24:04 +0800306 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
307 if not allow_zero_valuation_rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530308 _rate = get_valuation_rate(sle.item_code, sle.warehouse,
309 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
310 currency=erpnext.get_company_currency(sle.company))
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530311 else:
312 _rate = 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530313
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530314 self.stock_queue.append([0, _rate])
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530315
Nabin Haitada485f2015-07-17 15:09:56 +0530316 index = None
317 if outgoing_rate > 0:
318 # Find the entry where rate matched with outgoing rate
319 for i, v in enumerate(self.stock_queue):
320 if v[1] == outgoing_rate:
321 index = i
322 break
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530323
Nabin Haitada485f2015-07-17 15:09:56 +0530324 # If no entry found with outgoing rate, collapse stack
325 if index == None:
326 new_stock_value = sum((d[0]*d[1] for d in self.stock_queue)) - qty_to_pop*outgoing_rate
327 new_stock_qty = sum((d[0] for d in self.stock_queue)) - qty_to_pop
328 self.stock_queue = [[new_stock_qty, new_stock_value/new_stock_qty if new_stock_qty > 0 else outgoing_rate]]
329 break
330 else:
331 index = 0
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530332
Nabin Haitada485f2015-07-17 15:09:56 +0530333 # select first batch or the batch with same rate
334 batch = self.stock_queue[index]
Nabin Hait8142cd22015-08-05 18:57:26 +0530335 if qty_to_pop >= batch[0]:
336 # consume current batch
337 qty_to_pop = qty_to_pop - batch[0]
338 self.stock_queue.pop(index)
339 if not self.stock_queue and qty_to_pop:
340 # stock finished, qty still remains to be withdrawn
341 # negative stock, keep in as a negative batch
342 self.stock_queue.append([-qty_to_pop, outgoing_rate or batch[1]])
343 break
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530344
Nabin Hait8142cd22015-08-05 18:57:26 +0530345 else:
346 # qty found in current batch
347 # consume it and exit
348 batch[0] = batch[0] - qty_to_pop
349 qty_to_pop = 0
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530350
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530351 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in self.stock_queue))
352 stock_qty = sum((flt(batch[0]) for batch in self.stock_queue))
Nabin Hait902e8602013-01-08 18:29:24 +0530353
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530354 if stock_qty:
355 self.valuation_rate = stock_value / flt(stock_qty)
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530356
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530357 if not self.stock_queue:
358 self.stock_queue.append([0, sle.incoming_rate or sle.outgoing_rate or self.valuation_rate])
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530359
Javier Wong9b11d9b2017-04-14 18:24:04 +0800360 def check_if_allow_zero_valuation_rate(self, voucher_type, voucher_detail_no):
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530361 ref_item_dt = voucher_type + (" Detail" if voucher_type == "Stock Entry" else " Item")
Javier Wong9b11d9b2017-04-14 18:24:04 +0800362 return frappe.db.get_value(ref_item_dt, voucher_detail_no, "allow_zero_valuation_rate")
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530363
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530364 def get_sle_before_datetime(self):
365 """get previous stock ledger entry before current time-bucket"""
366 return get_stock_ledger_entries(self.args, "<", "desc", "limit 1", for_update=False)
Nabin Hait4d742162014-10-09 19:25:03 +0530367
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530368 def get_sle_after_datetime(self):
369 """get Stock Ledger Entries after a particular datetime, for reposting"""
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530370 return get_stock_ledger_entries(self.previous_sle or frappe._dict({
371 "item_code": self.args.get("item_code"), "warehouse": self.args.get("warehouse") }),
372 ">", "asc", for_update=True)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530373
374 def raise_exceptions(self):
375 deficiency = min(e["diff"] for e in self.exceptions)
Rushabh Mehta538607e2016-06-12 11:03:00 +0530376
Rushabh Mehta649e2532016-07-20 15:30:17 +0530377 if ((self.exceptions[0]["voucher_type"], self.exceptions[0]["voucher_no"]) in
378 frappe.local.flags.currently_saving):
Nabin Hait3edefb12016-07-20 16:13:18 +0530379
Rushabh Mehta538607e2016-06-12 11:03:00 +0530380 msg = _("{0} units of {1} needed in {2} to complete this transaction.").format(
381 abs(deficiency), frappe.get_desk_link('Item', self.item_code),
382 frappe.get_desk_link('Warehouse', self.warehouse))
383 else:
384 msg = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
385 abs(deficiency), frappe.get_desk_link('Item', self.item_code),
386 frappe.get_desk_link('Warehouse', self.warehouse),
387 self.exceptions[0]["posting_date"], self.exceptions[0]["posting_time"],
388 frappe.get_desk_link(self.exceptions[0]["voucher_type"], self.exceptions[0]["voucher_no"]))
389
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530390 if self.verbose:
Rushabh Mehta538607e2016-06-12 11:03:00 +0530391 frappe.throw(msg, NegativeStockError, title='Insufficent Stock')
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530392 else:
cclauss68487082017-07-27 07:08:35 +0200393 raise NegativeStockError(msg)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530394
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530395def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530396 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530397 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530398 to get actual qty before transaction, this function
399 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530400
Anand Doshi1b531862013-01-10 19:29:51 +0530401 args = {
402 "item_code": "ABC",
403 "warehouse": "XYZ",
404 "posting_date": "2012-12-12",
405 "posting_time": "12:00",
406 "sle": "name of reference Stock Ledger Entry"
407 }
408 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530409 args["name"] = args.get("sle", None) or ""
410 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530411 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530412
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530413def get_stock_ledger_entries(previous_sle, operator=None, order="desc", limit=None, for_update=False, debug=False):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530414 """get stock ledger entries filtered by specific posting datetime conditions"""
Nabin Haitb9ce1042018-02-01 14:58:50 +0530415 conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
416 if previous_sle.get("warehouse"):
417 conditions += " and warehouse = %(warehouse)s"
418 elif previous_sle.get("warehouse_condition"):
419 conditions += " and " + previous_sle.get("warehouse_condition")
420
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530421 if not previous_sle.get("posting_date"):
422 previous_sle["posting_date"] = "1900-01-01"
423 if not previous_sle.get("posting_time"):
424 previous_sle["posting_time"] = "00:00"
425
426 if operator in (">", "<=") and previous_sle.get("name"):
427 conditions += " and name!=%(name)s"
428
429 return frappe.db.sql("""select *, timestamp(posting_date, posting_time) as "timestamp" from `tabStock Ledger Entry`
430 where item_code = %%(item_code)s
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530431 and ifnull(is_cancelled, 'No')='No'
Nabin Haitb9ce1042018-02-01 14:58:50 +0530432 %(conditions)s
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530433 order by timestamp(posting_date, posting_time) %(order)s, name %(order)s
434 %(limit)s %(for_update)s""" % {
435 "conditions": conditions,
436 "limit": limit or "",
437 "for_update": for_update and "for update" or "",
438 "order": order
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530439 }, previous_sle, as_dict=1, debug=debug)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530440
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530441def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no,
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530442 allow_zero_rate=False, currency=None, company=None):
Nabin Haita0b967f2017-01-18 18:35:58 +0530443 # Get valuation rate from last sle for the same item and warehouse
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530444 if not company:
445 company = erpnext.get_default_company()
446
Nabin Haitfb6e4342014-10-15 11:34:40 +0530447 last_valuation_rate = frappe.db.sql("""select valuation_rate
448 from `tabStock Ledger Entry`
449 where item_code = %s and warehouse = %s
rohitwaghchaure40a5a302018-04-02 10:14:49 +0530450 and valuation_rate >= 0
Nabin Hait4c952f42017-01-20 12:50:18 +0530451 order by posting_date desc, posting_time desc, name desc limit 1""", (item_code, warehouse))
Nabin Haitfb6e4342014-10-15 11:34:40 +0530452
453 if not last_valuation_rate:
Nabin Haita0b967f2017-01-18 18:35:58 +0530454 # Get valuation rate from last sle for the item against any warehouse
Nabin Haitfb6e4342014-10-15 11:34:40 +0530455 last_valuation_rate = frappe.db.sql("""select valuation_rate
456 from `tabStock Ledger Entry`
Anand Doshi602e8252015-11-16 19:05:46 +0530457 where item_code = %s and valuation_rate > 0
Nabin Hait4c952f42017-01-20 12:50:18 +0530458 order by posting_date desc, posting_time desc, name desc limit 1""", item_code)
Nabin Haitfb6e4342014-10-15 11:34:40 +0530459
Nabin Haita645f362018-03-01 10:31:24 +0530460 if last_valuation_rate:
461 return flt(last_valuation_rate[0][0]) # as there is previous records, it might come with zero rate
462
463 # If negative stock allowed, and item delivered without any incoming entry,
464 # system does not found any SLE, then take valuation rate from Item
465 valuation_rate = frappe.db.get_value("Item", item_code, "valuation_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530466
467 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530468 # try Item Standard rate
469 valuation_rate = frappe.db.get_value("Item", item_code, "standard_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530470
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530471 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530472 # try in price list
473 valuation_rate = frappe.db.get_value('Item Price',
474 dict(item_code=item_code, buying=1, currency=currency),
475 'price_list_rate')
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530476
Nabin Haita0b967f2017-01-18 18:35:58 +0530477 if not allow_zero_rate and not valuation_rate \
Rohit Waghchauree9ff1912017-06-19 12:54:59 +0530478 and cint(erpnext.is_perpetual_inventory_enabled(company)):
Neil Trini Lasrado193c8912017-03-28 17:39:34 +0530479 frappe.local.message_log = []
Javier Wong61287e32017-10-04 18:31:34 +0800480 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 +0530481
482 return valuation_rate