blob: d51a89b7cec11c64a5631629235a7bb703f4193a [file] [log] [blame]
Rushabh Mehtaad45e312013-11-20 12:59:58 +05301# Copyright (c) 2013, Web Notes 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 Mehta793ba6b2014-02-14 15:47:51 +05305import frappe
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 Hait9c47efb2015-01-21 16:22:45 +053017def make_sl_entries(sl_entries, is_amended=None, allow_negative_stock=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 Hait4ccd8d32015-01-23 12:18:01 +053031 sle_id = make_entry(sle, allow_negative_stock)
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 Hait9c47efb2015-01-21 16:22:45 +053038 update_bin(args, allow_negative_stock)
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 Hait4ccd8d32015-01-23 12:18:01 +053049def make_entry(args, allow_negative_stock=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 Hait74c281c2013-08-19 16:17:18 +053054 sle.insert()
Nabin Haitaeba24e2013-08-23 15:17:36 +053055 sle.submit()
Anand Doshif78d1ae2014-03-28 13:55:00 +053056 return sle.name
Nabin Haitdc82d4f2014-04-07 12:02:57 +053057
Nabin Hait9653f602013-08-20 15:37:33 +053058def delete_cancelled_entry(voucher_type, voucher_no):
Nabin Haitdc82d4f2014-04-07 12:02:57 +053059 frappe.db.sql("""delete from `tabStock Ledger Entry`
Nabin Hait9653f602013-08-20 15:37:33 +053060 where voucher_type=%s and voucher_no=%s""", (voucher_type, voucher_no))
Nabin Hait74c281c2013-08-19 16:17:18 +053061
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053062class update_entries_after(object):
Nabin Hait902e8602013-01-08 18:29:24 +053063 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +053064 update valution rate and qty after transaction
Nabin Hait902e8602013-01-08 18:29:24 +053065 from the current time-bucket onwards
Nabin Haitdc82d4f2014-04-07 12:02:57 +053066
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053067 :param args: args as dict
68
69 args = {
70 "item_code": "ABC",
71 "warehouse": "XYZ",
72 "posting_date": "2012-12-12",
73 "posting_time": "12:00"
74 }
Nabin Hait902e8602013-01-08 18:29:24 +053075 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053076 def __init__(self, args, allow_zero_rate=False, allow_negative_stock=None, verbose=1):
77 from frappe.model.meta import get_field_precision
Nabin Haitdc82d4f2014-04-07 12:02:57 +053078
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053079 self.exceptions = []
80 self.verbose = verbose
81 self.allow_zero_rate = allow_zero_rate
82 self.allow_negative_stock = allow_negative_stock
Nabin Hait9c47efb2015-01-21 16:22:45 +053083
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053084 if self.allow_negative_stock==None:
85 self.allow_negative_stock = cint(frappe.db.get_single_value("Stock Settings",
86 "allow_negative_stock"))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053087
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053088 self.args = args
89 for key, value in args.iteritems():
90 setattr(self, key, value)
Nabin Haitdc82d4f2014-04-07 12:02:57 +053091
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053092 self.previous_sle = self.get_sle_before_datetime()
93 self.previous_sle = self.previous_sle[0] if self.previous_sle else frappe._dict()
Nabin Haitbb777562013-08-29 18:19:37 +053094
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053095 for key in ("qty_after_transaction", "valuation_rate", "stock_value"):
96 setattr(self, key, flt(self.previous_sle.get(key)))
97
98 self.company = frappe.db.get_value("Warehouse", self.warehouse, "company")
99 self.precision = get_field_precision(frappe.get_meta("Stock Ledger Entry").get_field("stock_value"),
100 currency=frappe.db.get_value("Company", self.company, "default_currency"))
101
Rushabh Mehtac7a11cc2015-02-19 16:28:35 +0530102 self.prev_stock_value = self.previous_sle.stock_value or 0.0
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530103 self.stock_queue = json.loads(self.previous_sle.stock_queue or "[]")
104 self.valuation_method = get_valuation_method(self.item_code)
105 self.stock_value_difference = 0.0
106 self.build()
107
108 def build(self):
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530109 # includes current entry!
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530110 entries_to_fix = self.get_sle_after_datetime()
111
112 for sle in entries_to_fix:
113 self.process_sle(sle)
114
115 if self.exceptions:
116 self.raise_exceptions()
117
118 self.update_bin()
119
120 def update_bin(self):
121 # update bin
122 bin_name = frappe.db.get_value("Bin", {
123 "item_code": self.item_code,
124 "warehouse": self.warehouse
125 })
126
127 if not bin_name:
128 bin_doc = frappe.get_doc({
129 "doctype": "Bin",
130 "item_code": self.item_code,
131 "warehouse": self.warehouse
132 })
133 bin_doc.insert(ignore_permissions=True)
134 else:
135 bin_doc = frappe.get_doc("Bin", bin_name)
136
137 bin_doc.update({
138 "valuation_rate": self.valuation_rate,
139 "actual_qty": self.qty_after_transaction,
140 "stock_value": self.stock_value
141 })
142 bin_doc.save(ignore_permissions=True)
143
144 def process_sle(self, sle):
145 if sle.serial_no or not cint(self.allow_negative_stock):
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530146 # validate negative stock for serialized items, fifo valuation
Nabin Hait902e8602013-01-08 18:29:24 +0530147 # or when negative stock is not allowed for moving average
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530148 if not self.validate_negative_stock(sle):
149 self.qty_after_transaction += flt(sle.actual_qty)
150 return
Nabin Haitb96c0142014-10-07 11:25:04 +0530151
Anand Doshi1b531862013-01-10 19:29:51 +0530152 if sle.serial_no:
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530153 self.get_serialized_values(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530154 self.qty_after_transaction += flt(sle.actual_qty)
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530155 self.stock_value = flt(self.qty_after_transaction) * flt(self.valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530156 else:
157 if sle.voucher_type=="Stock Reconciliation":
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530158 # assert
159 self.valuation_rate = sle.valuation_rate
160 self.qty_after_transaction = sle.qty_after_transaction
161 self.stock_queue = [[self.qty_after_transaction, self.valuation_rate]]
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530162 self.stock_value = flt(self.qty_after_transaction) * flt(self.valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530163 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530164 if self.valuation_method == "Moving Average":
165 self.get_moving_average_values(sle)
166 self.qty_after_transaction += flt(sle.actual_qty)
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 self.get_fifo_values(sle)
170 self.qty_after_transaction += flt(sle.actual_qty)
171 self.stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in self.stock_queue))
Nabin Haitb96c0142014-10-07 11:25:04 +0530172
Rushabh Mehta54047782013-12-26 11:07:46 +0530173 # rounding as per precision
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530174 self.stock_value = flt(self.stock_value, self.precision)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530175
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530176 stock_value_difference = self.stock_value - self.prev_stock_value
177 self.prev_stock_value = self.stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530178
Nabin Hait902e8602013-01-08 18:29:24 +0530179 # update current sle
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530180 sle.qty_after_transaction = self.qty_after_transaction
181 sle.valuation_rate = self.valuation_rate
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530182 sle.stock_value = self.stock_value
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530183 sle.stock_queue = json.dumps(self.stock_queue)
184 sle.stock_value_difference = stock_value_difference
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530185 sle.doctype="Stock Ledger Entry"
186 frappe.get_doc(sle).db_update()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530187
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530188 def validate_negative_stock(self, sle):
189 """
190 validate negative stock for entries current datetime onwards
191 will not consider cancelled entries
192 """
193 diff = self.qty_after_transaction + flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530194
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530195 if diff < 0 and abs(diff) > 0.0001:
196 # negative stock!
197 exc = sle.copy().update({"diff": diff})
198 self.exceptions.append(exc)
199 return False
Nabin Hait902e8602013-01-08 18:29:24 +0530200 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530201 return True
202
203 def get_serialized_values(self, sle):
204 incoming_rate = flt(sle.incoming_rate)
205 actual_qty = flt(sle.actual_qty)
206 serial_no = cstr(sle.serial_no).split("\n")
207
208 if incoming_rate < 0:
209 # wrong incoming rate
210 incoming_rate = self.valuation_rate
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530211
212 elif incoming_rate == 0:
213 if flt(sle.actual_qty) < 0:
214 # In case of delivery/stock issue, get average purchase rate
215 # of serial nos of current entry
216 incoming_rate = flt(frappe.db.sql("""select avg(ifnull(purchase_rate, 0))
217 from `tabSerial No` where name in (%s)""" % (", ".join(["%s"]*len(serial_no))),
218 tuple(serial_no))[0][0])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530219
220 if incoming_rate and not self.valuation_rate:
221 self.valuation_rate = incoming_rate
222 else:
223 new_stock_qty = self.qty_after_transaction + actual_qty
224 if new_stock_qty > 0:
225 new_stock_value = self.qty_after_transaction * self.valuation_rate + actual_qty * incoming_rate
226 if new_stock_value > 0:
227 # calculate new valuation rate only if stock value is positive
228 # else it remains the same as that of previous entry
229 self.valuation_rate = new_stock_value / new_stock_qty
230
231 def get_moving_average_values(self, sle):
232 incoming_rate = flt(sle.incoming_rate)
233 actual_qty = flt(sle.actual_qty)
234
235 if flt(sle.actual_qty) > 0:
236 if self.qty_after_transaction < 0 and not self.valuation_rate:
237 # if negative stock, take current valuation rate as incoming rate
238 self.valuation_rate = incoming_rate
239
240 new_stock_qty = abs(self.qty_after_transaction) + actual_qty
241 new_stock_value = (abs(self.qty_after_transaction) * self.valuation_rate) + (actual_qty * incoming_rate)
242
243 if new_stock_qty:
244 self.valuation_rate = new_stock_value / flt(new_stock_qty)
245 elif not self.valuation_rate and self.qty_after_transaction <= 0:
Rushabh Mehtad54031f2015-02-22 22:32:39 +0530246 self.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse, self.allow_zero_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530247
Rushabh Mehtad54031f2015-02-22 22:32:39 +0530248 return abs(flt(self.valuation_rate))
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530249
250 def get_fifo_values(self, sle):
251 incoming_rate = flt(sle.incoming_rate)
252 actual_qty = flt(sle.actual_qty)
253
254 if actual_qty > 0:
255 if not self.stock_queue:
256 self.stock_queue.append([0, 0])
257
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530258 # last row has the same rate, just updated the qty
259 if self.stock_queue[-1][1]==incoming_rate:
260 self.stock_queue[-1][0] += actual_qty
Nabin Hait4d742162014-10-09 19:25:03 +0530261 else:
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530262 if self.stock_queue[-1][0] > 0:
263 self.stock_queue.append([actual_qty, incoming_rate])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530264 else:
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530265 qty = self.stock_queue[-1][0] + actual_qty
266 if qty == 0:
267 self.stock_queue.pop(-1)
268 else:
269 self.stock_queue[-1] = [qty, incoming_rate]
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530270 else:
271 qty_to_pop = abs(actual_qty)
272 while qty_to_pop:
273 if not self.stock_queue:
274 if self.qty_after_transaction > 0:
275 _rate = get_valuation_rate(sle.item_code, sle.warehouse, self.allow_zero_rate)
276 else:
277 _rate = 0
278 self.stock_queue.append([0, _rate])
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530279
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530280 batch = self.stock_queue[0]
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530281
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530282 if qty_to_pop >= batch[0]:
283 # consume current batch
284 qty_to_pop = qty_to_pop - batch[0]
285 self.stock_queue.pop(0)
286 if not self.stock_queue and qty_to_pop:
287 # stock finished, qty still remains to be withdrawn
288 # negative stock, keep in as a negative batch
289 self.stock_queue.append([-qty_to_pop, batch[1]])
290 break
Nabin Hait4d742162014-10-09 19:25:03 +0530291
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530292 else:
293 # qty found in current batch
294 # consume it and exit
295 batch[0] = batch[0] - qty_to_pop
296 qty_to_pop = 0
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530297
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530298 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in self.stock_queue))
299 stock_qty = sum((flt(batch[0]) for batch in self.stock_queue))
Nabin Hait902e8602013-01-08 18:29:24 +0530300
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530301 self.valuation_rate = (stock_value / flt(stock_qty)) if stock_qty else 0
Nabin Hait9514d172013-01-10 10:40:37 +0530302
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530303 def get_sle_before_datetime(self):
304 """get previous stock ledger entry before current time-bucket"""
305 return get_stock_ledger_entries(self.args, "<", "desc", "limit 1", for_update=False)
Nabin Hait4d742162014-10-09 19:25:03 +0530306
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530307 def get_sle_after_datetime(self):
308 """get Stock Ledger Entries after a particular datetime, for reposting"""
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530309 return get_stock_ledger_entries(self.previous_sle or frappe._dict({
310 "item_code": self.args.get("item_code"), "warehouse": self.args.get("warehouse") }),
311 ">", "asc", for_update=True)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530312
313 def raise_exceptions(self):
314 deficiency = min(e["diff"] for e in self.exceptions)
315 msg = _("Negative Stock Error ({6}) for Item {0} in Warehouse {1} on {2} {3} in {4} {5}").format(self.item_code,
316 self.warehouse, self.exceptions[0]["posting_date"], self.exceptions[0]["posting_time"],
317 _(self.exceptions[0]["voucher_type"]), self.exceptions[0]["voucher_no"], deficiency)
318 if self.verbose:
319 frappe.throw(msg, NegativeStockError)
320 else:
321 raise NegativeStockError, msg
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530322
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530323def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530324 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530325 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530326 to get actual qty before transaction, this function
327 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530328
Anand Doshi1b531862013-01-10 19:29:51 +0530329 args = {
330 "item_code": "ABC",
331 "warehouse": "XYZ",
332 "posting_date": "2012-12-12",
333 "posting_time": "12:00",
334 "sle": "name of reference Stock Ledger Entry"
335 }
336 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530337 args["name"] = args.get("sle", None) or ""
338 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530339 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530340
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530341def get_stock_ledger_entries(previous_sle, operator=None, order="desc", limit=None, for_update=False, debug=False):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530342 """get stock ledger entries filtered by specific posting datetime conditions"""
343 conditions = "timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
344 if not previous_sle.get("posting_date"):
345 previous_sle["posting_date"] = "1900-01-01"
346 if not previous_sle.get("posting_time"):
347 previous_sle["posting_time"] = "00:00"
348
349 if operator in (">", "<=") and previous_sle.get("name"):
350 conditions += " and name!=%(name)s"
351
352 return frappe.db.sql("""select *, timestamp(posting_date, posting_time) as "timestamp" from `tabStock Ledger Entry`
353 where item_code = %%(item_code)s
354 and warehouse = %%(warehouse)s
355 and ifnull(is_cancelled, 'No')='No'
356 and %(conditions)s
357 order by timestamp(posting_date, posting_time) %(order)s, name %(order)s
358 %(limit)s %(for_update)s""" % {
359 "conditions": conditions,
360 "limit": limit or "",
361 "for_update": for_update and "for update" or "",
362 "order": order
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530363 }, previous_sle, as_dict=1, debug=debug)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530364
Nabin Haitf1a07ff2014-10-15 12:23:35 +0530365def get_valuation_rate(item_code, warehouse, allow_zero_rate=False):
Nabin Haitfb6e4342014-10-15 11:34:40 +0530366 last_valuation_rate = frappe.db.sql("""select valuation_rate
367 from `tabStock Ledger Entry`
368 where item_code = %s and warehouse = %s
369 and ifnull(valuation_rate, 0) > 0
370 order by posting_date desc, posting_time desc, name desc limit 1""", (item_code, warehouse))
371
372 if not last_valuation_rate:
373 last_valuation_rate = frappe.db.sql("""select valuation_rate
374 from `tabStock Ledger Entry`
375 where item_code = %s and ifnull(valuation_rate, 0) > 0
376 order by posting_date desc, posting_time desc, name desc limit 1""", item_code)
377
378 valuation_rate = flt(last_valuation_rate[0][0]) if last_valuation_rate else 0
379
380 if not valuation_rate:
381 valuation_rate = frappe.db.get_value("Item Price", {"item_code": item_code, "buying": 1}, "price_list_rate")
382
Nabin Haitf1a07ff2014-10-15 12:23:35 +0530383 if not allow_zero_rate and not valuation_rate and cint(frappe.db.get_value("Accounts Settings", None, "auto_accounting_for_stock")):
Nabin Haitfb6e4342014-10-15 11:34:40 +0530384 frappe.throw(_("Purchase rate for item: {0} not found, which is required to book accounting entry (expense). Please mention item price against a buying price list.").format(item_code))
385
386 return valuation_rate