blob: ce5a0c97aa9f2587daca53c3b5af3bd5795862c1 [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()
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 })
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):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530233 actual_qty = flt(sle.actual_qty)
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530234
Nabin Haitada485f2015-07-17 15:09:56 +0530235 if actual_qty > 0 or flt(sle.outgoing_rate) > 0:
236 rate = flt(sle.incoming_rate) if actual_qty > 0 else flt(sle.outgoing_rate)
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530237
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530238 if self.qty_after_transaction < 0 and not self.valuation_rate:
239 # if negative stock, take current valuation rate as incoming rate
Nabin Haitada485f2015-07-17 15:09:56 +0530240 self.valuation_rate = rate
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530241
242 new_stock_qty = abs(self.qty_after_transaction) + actual_qty
Nabin Haitada485f2015-07-17 15:09:56 +0530243 new_stock_value = (abs(self.qty_after_transaction) * self.valuation_rate) + (actual_qty * rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530244
245 if new_stock_qty:
246 self.valuation_rate = new_stock_value / flt(new_stock_qty)
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530247
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530248 elif not self.valuation_rate and self.qty_after_transaction <= 0:
Rushabh Mehtad54031f2015-02-22 22:32:39 +0530249 self.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse, self.allow_zero_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530250
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530251 self.valuation_rate = abs(flt(self.valuation_rate))
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530252
253 def get_fifo_values(self, sle):
254 incoming_rate = flt(sle.incoming_rate)
255 actual_qty = flt(sle.actual_qty)
Nabin Haitada485f2015-07-17 15:09:56 +0530256 outgoing_rate = flt(sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530257
258 if actual_qty > 0:
259 if not self.stock_queue:
260 self.stock_queue.append([0, 0])
261
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530262 # last row has the same rate, just updated the qty
263 if self.stock_queue[-1][1]==incoming_rate:
264 self.stock_queue[-1][0] += actual_qty
Nabin Hait4d742162014-10-09 19:25:03 +0530265 else:
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530266 if self.stock_queue[-1][0] > 0:
267 self.stock_queue.append([actual_qty, incoming_rate])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530268 else:
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530269 qty = self.stock_queue[-1][0] + actual_qty
270 if qty == 0:
271 self.stock_queue.pop(-1)
272 else:
273 self.stock_queue[-1] = [qty, incoming_rate]
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530274 else:
275 qty_to_pop = abs(actual_qty)
276 while qty_to_pop:
277 if not self.stock_queue:
278 if self.qty_after_transaction > 0:
279 _rate = get_valuation_rate(sle.item_code, sle.warehouse, self.allow_zero_rate)
280 else:
281 _rate = 0
282 self.stock_queue.append([0, _rate])
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530283
Nabin Haitada485f2015-07-17 15:09:56 +0530284 index = None
285 if outgoing_rate > 0:
286 # Find the entry where rate matched with outgoing rate
287 for i, v in enumerate(self.stock_queue):
288 if v[1] == outgoing_rate:
289 index = i
290 break
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530291
Nabin Haitada485f2015-07-17 15:09:56 +0530292 # If no entry found with outgoing rate, collapse stack
293 if index == None:
294 new_stock_value = sum((d[0]*d[1] for d in self.stock_queue)) - qty_to_pop*outgoing_rate
295 new_stock_qty = sum((d[0] for d in self.stock_queue)) - qty_to_pop
296 self.stock_queue = [[new_stock_qty, new_stock_value/new_stock_qty if new_stock_qty > 0 else outgoing_rate]]
297 break
298 else:
299 index = 0
300
301 # select first batch or the batch with same rate
302 batch = self.stock_queue[index]
Nabin Hait8142cd22015-08-05 18:57:26 +0530303 if qty_to_pop >= batch[0]:
304 # consume current batch
305 qty_to_pop = qty_to_pop - batch[0]
306 self.stock_queue.pop(index)
307 if not self.stock_queue and qty_to_pop:
308 # stock finished, qty still remains to be withdrawn
309 # negative stock, keep in as a negative batch
310 self.stock_queue.append([-qty_to_pop, outgoing_rate or batch[1]])
311 break
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530312
Nabin Hait8142cd22015-08-05 18:57:26 +0530313 else:
314 # qty found in current batch
315 # consume it and exit
316 batch[0] = batch[0] - qty_to_pop
317 qty_to_pop = 0
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530318
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530319 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in self.stock_queue))
320 stock_qty = sum((flt(batch[0]) for batch in self.stock_queue))
Nabin Hait902e8602013-01-08 18:29:24 +0530321
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530322 self.valuation_rate = (stock_value / flt(stock_qty)) if stock_qty else 0
Nabin Hait9514d172013-01-10 10:40:37 +0530323
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530324 def get_sle_before_datetime(self):
325 """get previous stock ledger entry before current time-bucket"""
326 return get_stock_ledger_entries(self.args, "<", "desc", "limit 1", for_update=False)
Nabin Hait4d742162014-10-09 19:25:03 +0530327
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530328 def get_sle_after_datetime(self):
329 """get Stock Ledger Entries after a particular datetime, for reposting"""
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530330 return get_stock_ledger_entries(self.previous_sle or frappe._dict({
331 "item_code": self.args.get("item_code"), "warehouse": self.args.get("warehouse") }),
332 ">", "asc", for_update=True)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530333
334 def raise_exceptions(self):
335 deficiency = min(e["diff"] for e in self.exceptions)
336 msg = _("Negative Stock Error ({6}) for Item {0} in Warehouse {1} on {2} {3} in {4} {5}").format(self.item_code,
337 self.warehouse, self.exceptions[0]["posting_date"], self.exceptions[0]["posting_time"],
338 _(self.exceptions[0]["voucher_type"]), self.exceptions[0]["voucher_no"], deficiency)
339 if self.verbose:
340 frappe.throw(msg, NegativeStockError)
341 else:
342 raise NegativeStockError, msg
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530343
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530344def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530345 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530346 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530347 to get actual qty before transaction, this function
348 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530349
Anand Doshi1b531862013-01-10 19:29:51 +0530350 args = {
351 "item_code": "ABC",
352 "warehouse": "XYZ",
353 "posting_date": "2012-12-12",
354 "posting_time": "12:00",
355 "sle": "name of reference Stock Ledger Entry"
356 }
357 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530358 args["name"] = args.get("sle", None) or ""
359 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530360 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530361
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530362def get_stock_ledger_entries(previous_sle, operator=None, order="desc", limit=None, for_update=False, debug=False):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530363 """get stock ledger entries filtered by specific posting datetime conditions"""
364 conditions = "timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
365 if not previous_sle.get("posting_date"):
366 previous_sle["posting_date"] = "1900-01-01"
367 if not previous_sle.get("posting_time"):
368 previous_sle["posting_time"] = "00:00"
369
370 if operator in (">", "<=") and previous_sle.get("name"):
371 conditions += " and name!=%(name)s"
372
373 return frappe.db.sql("""select *, timestamp(posting_date, posting_time) as "timestamp" from `tabStock Ledger Entry`
374 where item_code = %%(item_code)s
375 and warehouse = %%(warehouse)s
376 and ifnull(is_cancelled, 'No')='No'
377 and %(conditions)s
378 order by timestamp(posting_date, posting_time) %(order)s, name %(order)s
379 %(limit)s %(for_update)s""" % {
380 "conditions": conditions,
381 "limit": limit or "",
382 "for_update": for_update and "for update" or "",
383 "order": order
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530384 }, previous_sle, as_dict=1, debug=debug)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530385
Nabin Haitf1a07ff2014-10-15 12:23:35 +0530386def get_valuation_rate(item_code, warehouse, allow_zero_rate=False):
Nabin Haitfb6e4342014-10-15 11:34:40 +0530387 last_valuation_rate = frappe.db.sql("""select valuation_rate
388 from `tabStock Ledger Entry`
389 where item_code = %s and warehouse = %s
390 and ifnull(valuation_rate, 0) > 0
391 order by posting_date desc, posting_time desc, name desc limit 1""", (item_code, warehouse))
392
393 if not last_valuation_rate:
394 last_valuation_rate = frappe.db.sql("""select valuation_rate
395 from `tabStock Ledger Entry`
396 where item_code = %s and ifnull(valuation_rate, 0) > 0
397 order by posting_date desc, posting_time desc, name desc limit 1""", item_code)
398
399 valuation_rate = flt(last_valuation_rate[0][0]) if last_valuation_rate else 0
400
401 if not valuation_rate:
402 valuation_rate = frappe.db.get_value("Item Price", {"item_code": item_code, "buying": 1}, "price_list_rate")
403
Nabin Haitf1a07ff2014-10-15 12:23:35 +0530404 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 +0530405 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))
406
407 return valuation_rate