blob: 954a03b3bf6757021e370953af3a9d98dc0197ab [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 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 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()
112
113 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 })
143 bin_doc.save(ignore_permissions=True)
144
145 def process_sle(self, sle):
Anand Doshi0dc79f42015-04-06 12:59:34 +0530146 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 +0530147 # validate negative stock for serialized items, fifo valuation
Nabin Hait902e8602013-01-08 18:29:24 +0530148 # or when negative stock is not allowed for moving average
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530149 if not self.validate_negative_stock(sle):
150 self.qty_after_transaction += flt(sle.actual_qty)
151 return
Nabin Haitb96c0142014-10-07 11:25:04 +0530152
Anand Doshi1b531862013-01-10 19:29:51 +0530153 if sle.serial_no:
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530154 self.get_serialized_values(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530155 self.qty_after_transaction += flt(sle.actual_qty)
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530156 self.stock_value = flt(self.qty_after_transaction) * flt(self.valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530157 else:
158 if sle.voucher_type=="Stock Reconciliation":
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530159 # assert
160 self.valuation_rate = sle.valuation_rate
161 self.qty_after_transaction = sle.qty_after_transaction
162 self.stock_queue = [[self.qty_after_transaction, self.valuation_rate]]
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530163 self.stock_value = flt(self.qty_after_transaction) * flt(self.valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530164 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530165 if self.valuation_method == "Moving Average":
166 self.get_moving_average_values(sle)
167 self.qty_after_transaction += flt(sle.actual_qty)
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530168 self.stock_value = flt(self.qty_after_transaction) * flt(self.valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530169 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530170 self.get_fifo_values(sle)
171 self.qty_after_transaction += flt(sle.actual_qty)
172 self.stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in self.stock_queue))
Nabin Haitb96c0142014-10-07 11:25:04 +0530173
Rushabh Mehta54047782013-12-26 11:07:46 +0530174 # rounding as per precision
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530175 self.stock_value = flt(self.stock_value, self.precision)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530176
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530177 stock_value_difference = self.stock_value - self.prev_stock_value
178 self.prev_stock_value = self.stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530179
Nabin Hait902e8602013-01-08 18:29:24 +0530180 # update current sle
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530181 sle.qty_after_transaction = self.qty_after_transaction
182 sle.valuation_rate = self.valuation_rate
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530183 sle.stock_value = self.stock_value
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530184 sle.stock_queue = json.dumps(self.stock_queue)
185 sle.stock_value_difference = stock_value_difference
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530186 sle.doctype="Stock Ledger Entry"
187 frappe.get_doc(sle).db_update()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530188
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530189 def validate_negative_stock(self, sle):
190 """
191 validate negative stock for entries current datetime onwards
192 will not consider cancelled entries
193 """
194 diff = self.qty_after_transaction + flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530195
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530196 if diff < 0 and abs(diff) > 0.0001:
197 # negative stock!
198 exc = sle.copy().update({"diff": diff})
199 self.exceptions.append(exc)
200 return False
Nabin Hait902e8602013-01-08 18:29:24 +0530201 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530202 return True
203
204 def get_serialized_values(self, sle):
205 incoming_rate = flt(sle.incoming_rate)
206 actual_qty = flt(sle.actual_qty)
207 serial_no = cstr(sle.serial_no).split("\n")
208
209 if incoming_rate < 0:
210 # wrong incoming rate
211 incoming_rate = self.valuation_rate
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530212
213 elif incoming_rate == 0:
214 if flt(sle.actual_qty) < 0:
215 # In case of delivery/stock issue, get average purchase rate
216 # of serial nos of current entry
217 incoming_rate = flt(frappe.db.sql("""select avg(ifnull(purchase_rate, 0))
218 from `tabSerial No` where name in (%s)""" % (", ".join(["%s"]*len(serial_no))),
219 tuple(serial_no))[0][0])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530220
221 if incoming_rate and not self.valuation_rate:
222 self.valuation_rate = incoming_rate
223 else:
224 new_stock_qty = self.qty_after_transaction + actual_qty
225 if new_stock_qty > 0:
226 new_stock_value = self.qty_after_transaction * self.valuation_rate + actual_qty * incoming_rate
227 if new_stock_value > 0:
228 # calculate new valuation rate only if stock value is positive
229 # else it remains the same as that of previous entry
230 self.valuation_rate = new_stock_value / new_stock_qty
231
232 def get_moving_average_values(self, sle):
233 incoming_rate = flt(sle.incoming_rate)
234 actual_qty = flt(sle.actual_qty)
235
236 if flt(sle.actual_qty) > 0:
237 if self.qty_after_transaction < 0 and not self.valuation_rate:
238 # if negative stock, take current valuation rate as incoming rate
239 self.valuation_rate = incoming_rate
240
241 new_stock_qty = abs(self.qty_after_transaction) + actual_qty
242 new_stock_value = (abs(self.qty_after_transaction) * self.valuation_rate) + (actual_qty * incoming_rate)
243
244 if new_stock_qty:
245 self.valuation_rate = new_stock_value / flt(new_stock_qty)
246 elif not self.valuation_rate and self.qty_after_transaction <= 0:
Rushabh Mehtad54031f2015-02-22 22:32:39 +0530247 self.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse, self.allow_zero_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530248
Rushabh Mehtad54031f2015-02-22 22:32:39 +0530249 return abs(flt(self.valuation_rate))
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530250
251 def get_fifo_values(self, sle):
252 incoming_rate = flt(sle.incoming_rate)
253 actual_qty = flt(sle.actual_qty)
254
255 if actual_qty > 0:
256 if not self.stock_queue:
257 self.stock_queue.append([0, 0])
258
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530259 # last row has the same rate, just updated the qty
260 if self.stock_queue[-1][1]==incoming_rate:
261 self.stock_queue[-1][0] += actual_qty
Nabin Hait4d742162014-10-09 19:25:03 +0530262 else:
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530263 if self.stock_queue[-1][0] > 0:
264 self.stock_queue.append([actual_qty, incoming_rate])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530265 else:
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530266 qty = self.stock_queue[-1][0] + actual_qty
267 if qty == 0:
268 self.stock_queue.pop(-1)
269 else:
270 self.stock_queue[-1] = [qty, incoming_rate]
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530271 else:
272 qty_to_pop = abs(actual_qty)
273 while qty_to_pop:
274 if not self.stock_queue:
275 if self.qty_after_transaction > 0:
276 _rate = get_valuation_rate(sle.item_code, sle.warehouse, self.allow_zero_rate)
277 else:
278 _rate = 0
279 self.stock_queue.append([0, _rate])
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530280
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530281 batch = self.stock_queue[0]
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530282
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530283 if qty_to_pop >= batch[0]:
284 # consume current batch
285 qty_to_pop = qty_to_pop - batch[0]
286 self.stock_queue.pop(0)
287 if not self.stock_queue and qty_to_pop:
288 # stock finished, qty still remains to be withdrawn
289 # negative stock, keep in as a negative batch
290 self.stock_queue.append([-qty_to_pop, batch[1]])
291 break
Nabin Hait4d742162014-10-09 19:25:03 +0530292
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530293 else:
294 # qty found in current batch
295 # consume it and exit
296 batch[0] = batch[0] - qty_to_pop
297 qty_to_pop = 0
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530298
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530299 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in self.stock_queue))
300 stock_qty = sum((flt(batch[0]) for batch in self.stock_queue))
Nabin Hait902e8602013-01-08 18:29:24 +0530301
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530302 self.valuation_rate = (stock_value / flt(stock_qty)) if stock_qty else 0
Nabin Hait9514d172013-01-10 10:40:37 +0530303
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530304 def get_sle_before_datetime(self):
305 """get previous stock ledger entry before current time-bucket"""
306 return get_stock_ledger_entries(self.args, "<", "desc", "limit 1", for_update=False)
Nabin Hait4d742162014-10-09 19:25:03 +0530307
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530308 def get_sle_after_datetime(self):
309 """get Stock Ledger Entries after a particular datetime, for reposting"""
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530310 return get_stock_ledger_entries(self.previous_sle or frappe._dict({
311 "item_code": self.args.get("item_code"), "warehouse": self.args.get("warehouse") }),
312 ">", "asc", for_update=True)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530313
314 def raise_exceptions(self):
315 deficiency = min(e["diff"] for e in self.exceptions)
316 msg = _("Negative Stock Error ({6}) for Item {0} in Warehouse {1} on {2} {3} in {4} {5}").format(self.item_code,
317 self.warehouse, self.exceptions[0]["posting_date"], self.exceptions[0]["posting_time"],
318 _(self.exceptions[0]["voucher_type"]), self.exceptions[0]["voucher_no"], deficiency)
319 if self.verbose:
320 frappe.throw(msg, NegativeStockError)
321 else:
322 raise NegativeStockError, msg
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530323
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530324def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530325 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530326 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530327 to get actual qty before transaction, this function
328 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530329
Anand Doshi1b531862013-01-10 19:29:51 +0530330 args = {
331 "item_code": "ABC",
332 "warehouse": "XYZ",
333 "posting_date": "2012-12-12",
334 "posting_time": "12:00",
335 "sle": "name of reference Stock Ledger Entry"
336 }
337 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530338 args["name"] = args.get("sle", None) or ""
339 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530340 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530341
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530342def get_stock_ledger_entries(previous_sle, operator=None, order="desc", limit=None, for_update=False, debug=False):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530343 """get stock ledger entries filtered by specific posting datetime conditions"""
344 conditions = "timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
345 if not previous_sle.get("posting_date"):
346 previous_sle["posting_date"] = "1900-01-01"
347 if not previous_sle.get("posting_time"):
348 previous_sle["posting_time"] = "00:00"
349
350 if operator in (">", "<=") and previous_sle.get("name"):
351 conditions += " and name!=%(name)s"
352
353 return frappe.db.sql("""select *, timestamp(posting_date, posting_time) as "timestamp" from `tabStock Ledger Entry`
354 where item_code = %%(item_code)s
355 and warehouse = %%(warehouse)s
356 and ifnull(is_cancelled, 'No')='No'
357 and %(conditions)s
358 order by timestamp(posting_date, posting_time) %(order)s, name %(order)s
359 %(limit)s %(for_update)s""" % {
360 "conditions": conditions,
361 "limit": limit or "",
362 "for_update": for_update and "for update" or "",
363 "order": order
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530364 }, previous_sle, as_dict=1, debug=debug)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530365
Nabin Haitf1a07ff2014-10-15 12:23:35 +0530366def get_valuation_rate(item_code, warehouse, allow_zero_rate=False):
Nabin Haitfb6e4342014-10-15 11:34:40 +0530367 last_valuation_rate = frappe.db.sql("""select valuation_rate
368 from `tabStock Ledger Entry`
369 where item_code = %s and warehouse = %s
370 and ifnull(valuation_rate, 0) > 0
371 order by posting_date desc, posting_time desc, name desc limit 1""", (item_code, warehouse))
372
373 if not last_valuation_rate:
374 last_valuation_rate = frappe.db.sql("""select valuation_rate
375 from `tabStock Ledger Entry`
376 where item_code = %s and ifnull(valuation_rate, 0) > 0
377 order by posting_date desc, posting_time desc, name desc limit 1""", item_code)
378
379 valuation_rate = flt(last_valuation_rate[0][0]) if last_valuation_rate else 0
380
381 if not valuation_rate:
382 valuation_rate = frappe.db.get_value("Item Price", {"item_code": item_code, "buying": 1}, "price_list_rate")
383
Nabin Haitf1a07ff2014-10-15 12:23:35 +0530384 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 +0530385 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))
386
387 return valuation_rate