blob: 4d4435ef823eea9e379a89ee9355b8a0f7206e81 [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 Mehta50ce9752015-04-27 13:13:38 +0530103 currency=frappe.db.get_value("Company", self.company, "default_currency", cache=True))
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
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530181 stock_value_difference = self.stock_value - self.prev_stock_value
182 self.prev_stock_value = self.stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530183
Nabin Hait902e8602013-01-08 18:29:24 +0530184 # update current sle
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530185 sle.qty_after_transaction = self.qty_after_transaction
186 sle.valuation_rate = self.valuation_rate
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530187 sle.stock_value = self.stock_value
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530188 sle.stock_queue = json.dumps(self.stock_queue)
189 sle.stock_value_difference = stock_value_difference
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530190 sle.doctype="Stock Ledger Entry"
191 frappe.get_doc(sle).db_update()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530192
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530193 def validate_negative_stock(self, sle):
194 """
195 validate negative stock for entries current datetime onwards
196 will not consider cancelled entries
197 """
198 diff = self.qty_after_transaction + flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530199
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530200 if diff < 0 and abs(diff) > 0.0001:
201 # negative stock!
202 exc = sle.copy().update({"diff": diff})
203 self.exceptions.append(exc)
204 return False
Nabin Hait902e8602013-01-08 18:29:24 +0530205 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530206 return True
207
208 def get_serialized_values(self, sle):
209 incoming_rate = flt(sle.incoming_rate)
210 actual_qty = flt(sle.actual_qty)
211 serial_no = cstr(sle.serial_no).split("\n")
212
213 if incoming_rate < 0:
214 # wrong incoming rate
215 incoming_rate = self.valuation_rate
Rushabh Mehta538607e2016-06-12 11:03:00 +0530216
Nabin Hait2620bf42016-02-29 11:30:27 +0530217 stock_value_change = 0
218 if incoming_rate:
219 stock_value_change = actual_qty * incoming_rate
220 elif actual_qty < 0:
221 # In case of delivery/stock issue, get average purchase rate
222 # of serial nos of current entry
223 stock_value_change = -1 * flt(frappe.db.sql("""select sum(purchase_rate)
224 from `tabSerial No` where name in (%s)""" % (", ".join(["%s"]*len(serial_no))),
225 tuple(serial_no))[0][0])
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530226
Nabin Hait2620bf42016-02-29 11:30:27 +0530227 new_stock_qty = self.qty_after_transaction + actual_qty
228 if new_stock_qty > 0:
229 new_stock_value = (self.qty_after_transaction * self.valuation_rate) + stock_value_change
230 if new_stock_value > 0:
231 # calculate new valuation rate only if stock value is positive
232 # else it remains the same as that of previous entry
233 self.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530234
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530235 if not self.valuation_rate and sle.voucher_detail_no:
236 allow_zero_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
237 if not allow_zero_rate:
238 self.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
239 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
240 currency=erpnext.get_company_currency(sle.company))
241
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530242 def get_moving_average_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530243 actual_qty = flt(sle.actual_qty)
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530244 new_stock_qty = flt(self.qty_after_transaction) + actual_qty
245 if new_stock_qty >= 0:
246 if actual_qty > 0:
247 if flt(self.qty_after_transaction) <= 0:
248 self.valuation_rate = sle.incoming_rate
249 else:
250 new_stock_value = (self.qty_after_transaction * self.valuation_rate) + \
251 (actual_qty * sle.incoming_rate)
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530252
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530253 self.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530254
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530255 elif sle.outgoing_rate:
256 if new_stock_qty:
257 new_stock_value = (self.qty_after_transaction * self.valuation_rate) + \
258 (actual_qty * sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530259
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530260 self.valuation_rate = new_stock_value / new_stock_qty
261 else:
Nabin Hait7590b8f2016-07-27 16:44:17 +0530262 self.valuation_rate = sle.outgoing_rate
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530263
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530264 else:
265 if flt(self.qty_after_transaction) >= 0 and sle.outgoing_rate:
266 self.valuation_rate = sle.outgoing_rate
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530267
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530268 if not self.valuation_rate and actual_qty > 0:
269 self.valuation_rate = sle.incoming_rate
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530270
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530271 # Get valuation rate from previous SLE or Item master, if item does not have the
Javier Wong9b11d9b2017-04-14 18:24:04 +0800272 # allow zero valuration rate flag set
Nabin Haitea8fab52017-02-06 17:13:39 +0530273 if not self.valuation_rate and sle.voucher_detail_no:
Javier Wong9b11d9b2017-04-14 18:24:04 +0800274 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
275 if not allow_zero_valuation_rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530276 self.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
277 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
278 currency=erpnext.get_company_currency(sle.company))
279
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530280 def get_fifo_values(self, sle):
281 incoming_rate = flt(sle.incoming_rate)
282 actual_qty = flt(sle.actual_qty)
Nabin Haitada485f2015-07-17 15:09:56 +0530283 outgoing_rate = flt(sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530284
285 if actual_qty > 0:
286 if not self.stock_queue:
287 self.stock_queue.append([0, 0])
288
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530289 # last row has the same rate, just updated the qty
290 if self.stock_queue[-1][1]==incoming_rate:
291 self.stock_queue[-1][0] += actual_qty
Nabin Hait4d742162014-10-09 19:25:03 +0530292 else:
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530293 if self.stock_queue[-1][0] > 0:
294 self.stock_queue.append([actual_qty, incoming_rate])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530295 else:
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530296 qty = self.stock_queue[-1][0] + actual_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530297 self.stock_queue[-1] = [qty, incoming_rate]
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530298 else:
299 qty_to_pop = abs(actual_qty)
300 while qty_to_pop:
301 if not self.stock_queue:
Nabin Haita0b967f2017-01-18 18:35:58 +0530302 # Get valuation rate from last sle if exists or from valuation rate field in item master
Javier Wong9b11d9b2017-04-14 18:24:04 +0800303 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
304 if not allow_zero_valuation_rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530305 _rate = get_valuation_rate(sle.item_code, sle.warehouse,
306 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
307 currency=erpnext.get_company_currency(sle.company))
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530308 else:
309 _rate = 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530310
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530311 self.stock_queue.append([0, _rate])
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530312
Nabin Haitada485f2015-07-17 15:09:56 +0530313 index = None
314 if outgoing_rate > 0:
315 # Find the entry where rate matched with outgoing rate
316 for i, v in enumerate(self.stock_queue):
317 if v[1] == outgoing_rate:
318 index = i
319 break
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530320
Nabin Haitada485f2015-07-17 15:09:56 +0530321 # If no entry found with outgoing rate, collapse stack
322 if index == None:
323 new_stock_value = sum((d[0]*d[1] for d in self.stock_queue)) - qty_to_pop*outgoing_rate
324 new_stock_qty = sum((d[0] for d in self.stock_queue)) - qty_to_pop
325 self.stock_queue = [[new_stock_qty, new_stock_value/new_stock_qty if new_stock_qty > 0 else outgoing_rate]]
326 break
327 else:
328 index = 0
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530329
Nabin Haitada485f2015-07-17 15:09:56 +0530330 # select first batch or the batch with same rate
331 batch = self.stock_queue[index]
Nabin Hait8142cd22015-08-05 18:57:26 +0530332 if qty_to_pop >= batch[0]:
333 # consume current batch
334 qty_to_pop = qty_to_pop - batch[0]
335 self.stock_queue.pop(index)
336 if not self.stock_queue and qty_to_pop:
337 # stock finished, qty still remains to be withdrawn
338 # negative stock, keep in as a negative batch
339 self.stock_queue.append([-qty_to_pop, outgoing_rate or batch[1]])
340 break
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530341
Nabin Hait8142cd22015-08-05 18:57:26 +0530342 else:
343 # qty found in current batch
344 # consume it and exit
345 batch[0] = batch[0] - qty_to_pop
346 qty_to_pop = 0
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530347
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530348 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in self.stock_queue))
349 stock_qty = sum((flt(batch[0]) for batch in self.stock_queue))
Nabin Hait902e8602013-01-08 18:29:24 +0530350
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530351 if stock_qty:
352 self.valuation_rate = stock_value / flt(stock_qty)
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530353
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530354 if not self.stock_queue:
355 self.stock_queue.append([0, sle.incoming_rate or sle.outgoing_rate or self.valuation_rate])
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530356
Javier Wong9b11d9b2017-04-14 18:24:04 +0800357 def check_if_allow_zero_valuation_rate(self, voucher_type, voucher_detail_no):
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530358 ref_item_dt = voucher_type + (" Detail" if voucher_type == "Stock Entry" else " Item")
Javier Wong9b11d9b2017-04-14 18:24:04 +0800359 return frappe.db.get_value(ref_item_dt, voucher_detail_no, "allow_zero_valuation_rate")
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530360
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530361 def get_sle_before_datetime(self):
362 """get previous stock ledger entry before current time-bucket"""
363 return get_stock_ledger_entries(self.args, "<", "desc", "limit 1", for_update=False)
Nabin Hait4d742162014-10-09 19:25:03 +0530364
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530365 def get_sle_after_datetime(self):
366 """get Stock Ledger Entries after a particular datetime, for reposting"""
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530367 return get_stock_ledger_entries(self.previous_sle or frappe._dict({
368 "item_code": self.args.get("item_code"), "warehouse": self.args.get("warehouse") }),
369 ">", "asc", for_update=True)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530370
371 def raise_exceptions(self):
372 deficiency = min(e["diff"] for e in self.exceptions)
Rushabh Mehta538607e2016-06-12 11:03:00 +0530373
Rushabh Mehta649e2532016-07-20 15:30:17 +0530374 if ((self.exceptions[0]["voucher_type"], self.exceptions[0]["voucher_no"]) in
375 frappe.local.flags.currently_saving):
Nabin Hait3edefb12016-07-20 16:13:18 +0530376
Rushabh Mehta538607e2016-06-12 11:03:00 +0530377 msg = _("{0} units of {1} needed in {2} to complete this transaction.").format(
378 abs(deficiency), frappe.get_desk_link('Item', self.item_code),
379 frappe.get_desk_link('Warehouse', self.warehouse))
380 else:
381 msg = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
382 abs(deficiency), frappe.get_desk_link('Item', self.item_code),
383 frappe.get_desk_link('Warehouse', self.warehouse),
384 self.exceptions[0]["posting_date"], self.exceptions[0]["posting_time"],
385 frappe.get_desk_link(self.exceptions[0]["voucher_type"], self.exceptions[0]["voucher_no"]))
386
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530387 if self.verbose:
Rushabh Mehta538607e2016-06-12 11:03:00 +0530388 frappe.throw(msg, NegativeStockError, title='Insufficent Stock')
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530389 else:
cclauss68487082017-07-27 07:08:35 +0200390 raise NegativeStockError(msg)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530391
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530392def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530393 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530394 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530395 to get actual qty before transaction, this function
396 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530397
Anand Doshi1b531862013-01-10 19:29:51 +0530398 args = {
399 "item_code": "ABC",
400 "warehouse": "XYZ",
401 "posting_date": "2012-12-12",
402 "posting_time": "12:00",
403 "sle": "name of reference Stock Ledger Entry"
404 }
405 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530406 args["name"] = args.get("sle", None) or ""
407 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530408 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530409
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530410def get_stock_ledger_entries(previous_sle, operator=None, order="desc", limit=None, for_update=False, debug=False):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530411 """get stock ledger entries filtered by specific posting datetime conditions"""
Nabin Haitb9ce1042018-02-01 14:58:50 +0530412 conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
413 if previous_sle.get("warehouse"):
414 conditions += " and warehouse = %(warehouse)s"
415 elif previous_sle.get("warehouse_condition"):
416 conditions += " and " + previous_sle.get("warehouse_condition")
417
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530418 if not previous_sle.get("posting_date"):
419 previous_sle["posting_date"] = "1900-01-01"
420 if not previous_sle.get("posting_time"):
421 previous_sle["posting_time"] = "00:00"
422
423 if operator in (">", "<=") and previous_sle.get("name"):
424 conditions += " and name!=%(name)s"
425
426 return frappe.db.sql("""select *, timestamp(posting_date, posting_time) as "timestamp" from `tabStock Ledger Entry`
427 where item_code = %%(item_code)s
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530428 and ifnull(is_cancelled, 'No')='No'
Nabin Haitb9ce1042018-02-01 14:58:50 +0530429 %(conditions)s
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530430 order by timestamp(posting_date, posting_time) %(order)s, name %(order)s
431 %(limit)s %(for_update)s""" % {
432 "conditions": conditions,
433 "limit": limit or "",
434 "for_update": for_update and "for update" or "",
435 "order": order
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530436 }, previous_sle, as_dict=1, debug=debug)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530437
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530438def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no,
Nabin Hait7ba092e2018-02-01 10:51:27 +0530439 allow_zero_rate=False, currency=None, company=None, raise_error_if_no_rate=True):
Nabin Haita0b967f2017-01-18 18:35:58 +0530440 # Get valuation rate from last sle for the same item and warehouse
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530441 if not company:
442 company = erpnext.get_default_company()
443
Nabin Haitfb6e4342014-10-15 11:34:40 +0530444 last_valuation_rate = frappe.db.sql("""select valuation_rate
445 from `tabStock Ledger Entry`
446 where item_code = %s and warehouse = %s
Anand Doshi602e8252015-11-16 19:05:46 +0530447 and valuation_rate > 0
Nabin Hait4c952f42017-01-20 12:50:18 +0530448 order by posting_date desc, posting_time desc, name desc limit 1""", (item_code, warehouse))
Nabin Haitfb6e4342014-10-15 11:34:40 +0530449
450 if not last_valuation_rate:
Nabin Haita0b967f2017-01-18 18:35:58 +0530451 # Get valuation rate from last sle for the item against any warehouse
Nabin Haitfb6e4342014-10-15 11:34:40 +0530452 last_valuation_rate = frappe.db.sql("""select valuation_rate
453 from `tabStock Ledger Entry`
Anand Doshi602e8252015-11-16 19:05:46 +0530454 where item_code = %s and valuation_rate > 0
Nabin Hait4c952f42017-01-20 12:50:18 +0530455 order by posting_date desc, posting_time desc, name desc limit 1""", item_code)
Nabin Haitfb6e4342014-10-15 11:34:40 +0530456
457 valuation_rate = flt(last_valuation_rate[0][0]) if last_valuation_rate else 0
458
459 if not valuation_rate:
Nabin Haita0b967f2017-01-18 18:35:58 +0530460 # If negative stock allowed, and item delivered without any incoming entry,
461 # syste does not found any SLE, then take valuation rate from Item
Nabin Hait4c952f42017-01-20 12:50:18 +0530462 valuation_rate = frappe.db.get_value("Item", item_code, "valuation_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530463
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530464 if not valuation_rate:
465 # try Item Standard rate
466 valuation_rate = frappe.db.get_value("Item", item_code, "standard_rate")
467
468 if not valuation_rate:
469 # try in price list
470 valuation_rate = frappe.db.get_value('Item Price',
471 dict(item_code=item_code, buying=1, currency=currency),
472 'price_list_rate')
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530473
Nabin Hait7ba092e2018-02-01 10:51:27 +0530474 if not allow_zero_rate and not valuation_rate and raise_error_if_no_rate \
Rohit Waghchauree9ff1912017-06-19 12:54:59 +0530475 and cint(erpnext.is_perpetual_inventory_enabled(company)):
Neil Trini Lasrado193c8912017-03-28 17:39:34 +0530476 frappe.local.message_log = []
Javier Wong61287e32017-10-04 18:31:34 +0800477 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 +0530478
479 return valuation_rate