blob: 647c9faf02630b2384d3e33828b018474d13f6c7 [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
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530179 stock_value_difference = self.stock_value - self.prev_stock_value
180 self.prev_stock_value = self.stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530181
Nabin Hait902e8602013-01-08 18:29:24 +0530182 # update current sle
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530183 sle.qty_after_transaction = self.qty_after_transaction
184 sle.valuation_rate = self.valuation_rate
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530185 sle.stock_value = self.stock_value
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530186 sle.stock_queue = json.dumps(self.stock_queue)
187 sle.stock_value_difference = stock_value_difference
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530188 sle.doctype="Stock Ledger Entry"
189 frappe.get_doc(sle).db_update()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530190
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530191 def validate_negative_stock(self, sle):
192 """
193 validate negative stock for entries current datetime onwards
194 will not consider cancelled entries
195 """
196 diff = self.qty_after_transaction + flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530197
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530198 if diff < 0 and abs(diff) > 0.0001:
199 # negative stock!
200 exc = sle.copy().update({"diff": diff})
201 self.exceptions.append(exc)
202 return False
Nabin Hait902e8602013-01-08 18:29:24 +0530203 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530204 return True
205
206 def get_serialized_values(self, sle):
207 incoming_rate = flt(sle.incoming_rate)
208 actual_qty = flt(sle.actual_qty)
209 serial_no = cstr(sle.serial_no).split("\n")
210
211 if incoming_rate < 0:
212 # wrong incoming rate
213 incoming_rate = self.valuation_rate
Rushabh Mehta538607e2016-06-12 11:03:00 +0530214
Nabin Hait2620bf42016-02-29 11:30:27 +0530215 stock_value_change = 0
216 if incoming_rate:
217 stock_value_change = actual_qty * incoming_rate
218 elif actual_qty < 0:
219 # In case of delivery/stock issue, get average purchase rate
220 # of serial nos of current entry
221 stock_value_change = -1 * flt(frappe.db.sql("""select sum(purchase_rate)
222 from `tabSerial No` where name in (%s)""" % (", ".join(["%s"]*len(serial_no))),
223 tuple(serial_no))[0][0])
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530224
Nabin Hait2620bf42016-02-29 11:30:27 +0530225 new_stock_qty = self.qty_after_transaction + actual_qty
226 if new_stock_qty > 0:
227 new_stock_value = (self.qty_after_transaction * self.valuation_rate) + stock_value_change
228 if new_stock_value > 0:
229 # calculate new valuation rate only if stock value is positive
230 # else it remains the same as that of previous entry
231 self.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530232
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530233 if not self.valuation_rate and sle.voucher_detail_no:
234 allow_zero_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
235 if not allow_zero_rate:
236 self.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
237 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
238 currency=erpnext.get_company_currency(sle.company))
239
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530240 def get_moving_average_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530241 actual_qty = flt(sle.actual_qty)
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530242 new_stock_qty = flt(self.qty_after_transaction) + actual_qty
243 if new_stock_qty >= 0:
244 if actual_qty > 0:
245 if flt(self.qty_after_transaction) <= 0:
246 self.valuation_rate = sle.incoming_rate
247 else:
248 new_stock_value = (self.qty_after_transaction * self.valuation_rate) + \
249 (actual_qty * sle.incoming_rate)
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530250
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530251 self.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530252
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530253 elif sle.outgoing_rate:
254 if new_stock_qty:
255 new_stock_value = (self.qty_after_transaction * self.valuation_rate) + \
256 (actual_qty * sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530257
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530258 self.valuation_rate = new_stock_value / new_stock_qty
259 else:
Nabin Hait7590b8f2016-07-27 16:44:17 +0530260 self.valuation_rate = sle.outgoing_rate
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530261
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530262 else:
263 if flt(self.qty_after_transaction) >= 0 and sle.outgoing_rate:
264 self.valuation_rate = sle.outgoing_rate
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530265
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530266 if not self.valuation_rate and actual_qty > 0:
267 self.valuation_rate = sle.incoming_rate
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530268
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530269 # Get valuation rate from previous SLE or Item master, if item does not have the
Javier Wong9b11d9b2017-04-14 18:24:04 +0800270 # allow zero valuration rate flag set
Nabin Haitea8fab52017-02-06 17:13:39 +0530271 if not self.valuation_rate and sle.voucher_detail_no:
Javier Wong9b11d9b2017-04-14 18:24:04 +0800272 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
273 if not allow_zero_valuation_rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530274 self.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
275 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
276 currency=erpnext.get_company_currency(sle.company))
277
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530278 def get_fifo_values(self, sle):
279 incoming_rate = flt(sle.incoming_rate)
280 actual_qty = flt(sle.actual_qty)
Nabin Haitada485f2015-07-17 15:09:56 +0530281 outgoing_rate = flt(sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530282
283 if actual_qty > 0:
284 if not self.stock_queue:
285 self.stock_queue.append([0, 0])
286
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530287 # last row has the same rate, just updated the qty
288 if self.stock_queue[-1][1]==incoming_rate:
289 self.stock_queue[-1][0] += actual_qty
Nabin Hait4d742162014-10-09 19:25:03 +0530290 else:
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530291 if self.stock_queue[-1][0] > 0:
292 self.stock_queue.append([actual_qty, incoming_rate])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530293 else:
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530294 qty = self.stock_queue[-1][0] + actual_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530295 self.stock_queue[-1] = [qty, incoming_rate]
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530296 else:
297 qty_to_pop = abs(actual_qty)
298 while qty_to_pop:
299 if not self.stock_queue:
Nabin Haita0b967f2017-01-18 18:35:58 +0530300 # Get valuation rate from last sle if exists or from valuation rate field in item master
Javier Wong9b11d9b2017-04-14 18:24:04 +0800301 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
302 if not allow_zero_valuation_rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530303 _rate = get_valuation_rate(sle.item_code, sle.warehouse,
304 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
305 currency=erpnext.get_company_currency(sle.company))
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530306 else:
307 _rate = 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530308
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530309 self.stock_queue.append([0, _rate])
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530310
Nabin Haitada485f2015-07-17 15:09:56 +0530311 index = None
312 if outgoing_rate > 0:
313 # Find the entry where rate matched with outgoing rate
314 for i, v in enumerate(self.stock_queue):
315 if v[1] == outgoing_rate:
316 index = i
317 break
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530318
Nabin Haitada485f2015-07-17 15:09:56 +0530319 # If no entry found with outgoing rate, collapse stack
320 if index == None:
321 new_stock_value = sum((d[0]*d[1] for d in self.stock_queue)) - qty_to_pop*outgoing_rate
322 new_stock_qty = sum((d[0] for d in self.stock_queue)) - qty_to_pop
323 self.stock_queue = [[new_stock_qty, new_stock_value/new_stock_qty if new_stock_qty > 0 else outgoing_rate]]
324 break
325 else:
326 index = 0
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530327
Nabin Haitada485f2015-07-17 15:09:56 +0530328 # select first batch or the batch with same rate
329 batch = self.stock_queue[index]
Nabin Hait8142cd22015-08-05 18:57:26 +0530330 if qty_to_pop >= batch[0]:
331 # consume current batch
332 qty_to_pop = qty_to_pop - batch[0]
333 self.stock_queue.pop(index)
334 if not self.stock_queue and qty_to_pop:
335 # stock finished, qty still remains to be withdrawn
336 # negative stock, keep in as a negative batch
337 self.stock_queue.append([-qty_to_pop, outgoing_rate or batch[1]])
338 break
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530339
Nabin Hait8142cd22015-08-05 18:57:26 +0530340 else:
341 # qty found in current batch
342 # consume it and exit
343 batch[0] = batch[0] - qty_to_pop
344 qty_to_pop = 0
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530345
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530346 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in self.stock_queue))
347 stock_qty = sum((flt(batch[0]) for batch in self.stock_queue))
Nabin Hait902e8602013-01-08 18:29:24 +0530348
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530349 if stock_qty:
350 self.valuation_rate = stock_value / flt(stock_qty)
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530351
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530352 if not self.stock_queue:
353 self.stock_queue.append([0, sle.incoming_rate or sle.outgoing_rate or self.valuation_rate])
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530354
Javier Wong9b11d9b2017-04-14 18:24:04 +0800355 def check_if_allow_zero_valuation_rate(self, voucher_type, voucher_detail_no):
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530356 ref_item_dt = voucher_type + (" Detail" if voucher_type == "Stock Entry" else " Item")
Javier Wong9b11d9b2017-04-14 18:24:04 +0800357 return frappe.db.get_value(ref_item_dt, voucher_detail_no, "allow_zero_valuation_rate")
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530358
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530359 def get_sle_before_datetime(self):
360 """get previous stock ledger entry before current time-bucket"""
361 return get_stock_ledger_entries(self.args, "<", "desc", "limit 1", for_update=False)
Nabin Hait4d742162014-10-09 19:25:03 +0530362
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530363 def get_sle_after_datetime(self):
364 """get Stock Ledger Entries after a particular datetime, for reposting"""
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530365 return get_stock_ledger_entries(self.previous_sle or frappe._dict({
366 "item_code": self.args.get("item_code"), "warehouse": self.args.get("warehouse") }),
367 ">", "asc", for_update=True)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530368
369 def raise_exceptions(self):
370 deficiency = min(e["diff"] for e in self.exceptions)
Rushabh Mehta538607e2016-06-12 11:03:00 +0530371
Rushabh Mehta649e2532016-07-20 15:30:17 +0530372 if ((self.exceptions[0]["voucher_type"], self.exceptions[0]["voucher_no"]) in
373 frappe.local.flags.currently_saving):
Nabin Hait3edefb12016-07-20 16:13:18 +0530374
Rushabh Mehta538607e2016-06-12 11:03:00 +0530375 msg = _("{0} units of {1} needed in {2} to complete this transaction.").format(
376 abs(deficiency), frappe.get_desk_link('Item', self.item_code),
377 frappe.get_desk_link('Warehouse', self.warehouse))
378 else:
379 msg = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
380 abs(deficiency), frappe.get_desk_link('Item', self.item_code),
381 frappe.get_desk_link('Warehouse', self.warehouse),
382 self.exceptions[0]["posting_date"], self.exceptions[0]["posting_time"],
383 frappe.get_desk_link(self.exceptions[0]["voucher_type"], self.exceptions[0]["voucher_no"]))
384
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530385 if self.verbose:
Rushabh Mehta538607e2016-06-12 11:03:00 +0530386 frappe.throw(msg, NegativeStockError, title='Insufficent Stock')
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530387 else:
cclauss68487082017-07-27 07:08:35 +0200388 raise NegativeStockError(msg)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530389
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530390def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530391 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530392 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530393 to get actual qty before transaction, this function
394 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530395
Anand Doshi1b531862013-01-10 19:29:51 +0530396 args = {
397 "item_code": "ABC",
398 "warehouse": "XYZ",
399 "posting_date": "2012-12-12",
400 "posting_time": "12:00",
401 "sle": "name of reference Stock Ledger Entry"
402 }
403 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530404 args["name"] = args.get("sle", None) or ""
405 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530406 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530407
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530408def get_stock_ledger_entries(previous_sle, operator=None, order="desc", limit=None, for_update=False, debug=False):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530409 """get stock ledger entries filtered by specific posting datetime conditions"""
410 conditions = "timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
411 if not previous_sle.get("posting_date"):
412 previous_sle["posting_date"] = "1900-01-01"
413 if not previous_sle.get("posting_time"):
414 previous_sle["posting_time"] = "00:00"
415
416 if operator in (">", "<=") and previous_sle.get("name"):
417 conditions += " and name!=%(name)s"
418
419 return frappe.db.sql("""select *, timestamp(posting_date, posting_time) as "timestamp" from `tabStock Ledger Entry`
420 where item_code = %%(item_code)s
421 and warehouse = %%(warehouse)s
422 and ifnull(is_cancelled, 'No')='No'
423 and %(conditions)s
424 order by timestamp(posting_date, posting_time) %(order)s, name %(order)s
425 %(limit)s %(for_update)s""" % {
426 "conditions": conditions,
427 "limit": limit or "",
428 "for_update": for_update and "for update" or "",
429 "order": order
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530430 }, previous_sle, as_dict=1, debug=debug)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530431
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530432def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no,
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530433 allow_zero_rate=False, currency=None, company=None):
Nabin Haita0b967f2017-01-18 18:35:58 +0530434 # Get valuation rate from last sle for the same item and warehouse
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530435 if not company:
436 company = erpnext.get_default_company()
437
Nabin Haitfb6e4342014-10-15 11:34:40 +0530438 last_valuation_rate = frappe.db.sql("""select valuation_rate
439 from `tabStock Ledger Entry`
440 where item_code = %s and warehouse = %s
Anand Doshi602e8252015-11-16 19:05:46 +0530441 and valuation_rate > 0
Nabin Hait4c952f42017-01-20 12:50:18 +0530442 order by posting_date desc, posting_time desc, name desc limit 1""", (item_code, warehouse))
Nabin Haitfb6e4342014-10-15 11:34:40 +0530443
444 if not last_valuation_rate:
Nabin Haita0b967f2017-01-18 18:35:58 +0530445 # Get valuation rate from last sle for the item against any warehouse
Nabin Haitfb6e4342014-10-15 11:34:40 +0530446 last_valuation_rate = frappe.db.sql("""select valuation_rate
447 from `tabStock Ledger Entry`
Anand Doshi602e8252015-11-16 19:05:46 +0530448 where item_code = %s and valuation_rate > 0
Nabin Hait4c952f42017-01-20 12:50:18 +0530449 order by posting_date desc, posting_time desc, name desc limit 1""", item_code)
Nabin Haitfb6e4342014-10-15 11:34:40 +0530450
451 valuation_rate = flt(last_valuation_rate[0][0]) if last_valuation_rate else 0
452
453 if not valuation_rate:
Nabin Haita0b967f2017-01-18 18:35:58 +0530454 # If negative stock allowed, and item delivered without any incoming entry,
455 # syste does not found any SLE, then take valuation rate from Item
Nabin Hait4c952f42017-01-20 12:50:18 +0530456 valuation_rate = frappe.db.get_value("Item", item_code, "valuation_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530457
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530458 if not valuation_rate:
459 # try Item Standard rate
460 valuation_rate = frappe.db.get_value("Item", item_code, "standard_rate")
461
462 if not valuation_rate:
463 # try in price list
464 valuation_rate = frappe.db.get_value('Item Price',
465 dict(item_code=item_code, buying=1, currency=currency),
466 'price_list_rate')
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530467
Nabin Haita0b967f2017-01-18 18:35:58 +0530468 if not allow_zero_rate and not valuation_rate \
Rohit Waghchauree9ff1912017-06-19 12:54:59 +0530469 and cint(erpnext.is_perpetual_inventory_enabled(company)):
Neil Trini Lasrado193c8912017-03-28 17:39:34 +0530470 frappe.local.message_log = []
Javier Wong61287e32017-10-04 18:31:34 +0800471 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 +0530472
473 return valuation_rate