blob: fa6dd3c6bf57eb921276c3e209dc2d18f2491e69 [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 })
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
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530233 def get_moving_average_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530234 actual_qty = flt(sle.actual_qty)
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530235 new_stock_qty = flt(self.qty_after_transaction) + actual_qty
236 if new_stock_qty >= 0:
237 if actual_qty > 0:
238 if flt(self.qty_after_transaction) <= 0:
239 self.valuation_rate = sle.incoming_rate
240 else:
241 new_stock_value = (self.qty_after_transaction * self.valuation_rate) + \
242 (actual_qty * sle.incoming_rate)
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530243
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530244 self.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530245
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530246 elif sle.outgoing_rate:
247 if new_stock_qty:
248 new_stock_value = (self.qty_after_transaction * self.valuation_rate) + \
249 (actual_qty * sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530250
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530251 self.valuation_rate = new_stock_value / new_stock_qty
252 else:
253 self.valuation_rate = self.outgoing_rate
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530254
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530255 else:
256 if flt(self.qty_after_transaction) >= 0 and sle.outgoing_rate:
257 self.valuation_rate = sle.outgoing_rate
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530258
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530259 if not self.valuation_rate and actual_qty > 0:
260 self.valuation_rate = sle.incoming_rate
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530261
262 def get_fifo_values(self, sle):
263 incoming_rate = flt(sle.incoming_rate)
264 actual_qty = flt(sle.actual_qty)
Nabin Haitada485f2015-07-17 15:09:56 +0530265 outgoing_rate = flt(sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530266
267 if actual_qty > 0:
268 if not self.stock_queue:
269 self.stock_queue.append([0, 0])
270
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530271 # last row has the same rate, just updated the qty
272 if self.stock_queue[-1][1]==incoming_rate:
273 self.stock_queue[-1][0] += actual_qty
Nabin Hait4d742162014-10-09 19:25:03 +0530274 else:
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530275 if self.stock_queue[-1][0] > 0:
276 self.stock_queue.append([actual_qty, incoming_rate])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530277 else:
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530278 qty = self.stock_queue[-1][0] + actual_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530279 self.stock_queue[-1] = [qty, incoming_rate]
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530280 else:
281 qty_to_pop = abs(actual_qty)
282 while qty_to_pop:
283 if not self.stock_queue:
284 if self.qty_after_transaction > 0:
285 _rate = get_valuation_rate(sle.item_code, sle.warehouse, self.allow_zero_rate)
286 else:
287 _rate = 0
288 self.stock_queue.append([0, _rate])
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530289
Nabin Haitada485f2015-07-17 15:09:56 +0530290 index = None
291 if outgoing_rate > 0:
292 # Find the entry where rate matched with outgoing rate
293 for i, v in enumerate(self.stock_queue):
294 if v[1] == outgoing_rate:
295 index = i
296 break
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530297
Nabin Haitada485f2015-07-17 15:09:56 +0530298 # If no entry found with outgoing rate, collapse stack
299 if index == None:
300 new_stock_value = sum((d[0]*d[1] for d in self.stock_queue)) - qty_to_pop*outgoing_rate
301 new_stock_qty = sum((d[0] for d in self.stock_queue)) - qty_to_pop
302 self.stock_queue = [[new_stock_qty, new_stock_value/new_stock_qty if new_stock_qty > 0 else outgoing_rate]]
303 break
304 else:
305 index = 0
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530306
Nabin Haitada485f2015-07-17 15:09:56 +0530307 # select first batch or the batch with same rate
308 batch = self.stock_queue[index]
Nabin Hait8142cd22015-08-05 18:57:26 +0530309 if qty_to_pop >= batch[0]:
310 # consume current batch
311 qty_to_pop = qty_to_pop - batch[0]
312 self.stock_queue.pop(index)
313 if not self.stock_queue and qty_to_pop:
314 # stock finished, qty still remains to be withdrawn
315 # negative stock, keep in as a negative batch
316 self.stock_queue.append([-qty_to_pop, outgoing_rate or batch[1]])
317 break
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530318
Nabin Hait8142cd22015-08-05 18:57:26 +0530319 else:
320 # qty found in current batch
321 # consume it and exit
322 batch[0] = batch[0] - qty_to_pop
323 qty_to_pop = 0
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530324
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530325 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in self.stock_queue))
326 stock_qty = sum((flt(batch[0]) for batch in self.stock_queue))
Nabin Hait902e8602013-01-08 18:29:24 +0530327
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530328 if stock_qty:
329 self.valuation_rate = stock_value / flt(stock_qty)
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530330
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530331 if not self.stock_queue:
332 self.stock_queue.append([0, sle.incoming_rate or sle.outgoing_rate or self.valuation_rate])
Nabin Hait9514d172013-01-10 10:40:37 +0530333
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530334 def get_sle_before_datetime(self):
335 """get previous stock ledger entry before current time-bucket"""
336 return get_stock_ledger_entries(self.args, "<", "desc", "limit 1", for_update=False)
Nabin Hait4d742162014-10-09 19:25:03 +0530337
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530338 def get_sle_after_datetime(self):
339 """get Stock Ledger Entries after a particular datetime, for reposting"""
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530340 return get_stock_ledger_entries(self.previous_sle or frappe._dict({
341 "item_code": self.args.get("item_code"), "warehouse": self.args.get("warehouse") }),
342 ">", "asc", for_update=True)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530343
344 def raise_exceptions(self):
345 deficiency = min(e["diff"] for e in self.exceptions)
Rushabh Mehta538607e2016-06-12 11:03:00 +0530346
347
348
Rushabh Mehta649e2532016-07-20 15:30:17 +0530349 if ((self.exceptions[0]["voucher_type"], self.exceptions[0]["voucher_no"]) in
350 frappe.local.flags.currently_saving):
Rushabh Mehta538607e2016-06-12 11:03:00 +0530351 msg = _("{0} units of {1} needed in {2} to complete this transaction.").format(
352 abs(deficiency), frappe.get_desk_link('Item', self.item_code),
353 frappe.get_desk_link('Warehouse', self.warehouse))
354 else:
355 msg = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
356 abs(deficiency), frappe.get_desk_link('Item', self.item_code),
357 frappe.get_desk_link('Warehouse', self.warehouse),
358 self.exceptions[0]["posting_date"], self.exceptions[0]["posting_time"],
359 frappe.get_desk_link(self.exceptions[0]["voucher_type"], self.exceptions[0]["voucher_no"]))
360
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530361 if self.verbose:
Rushabh Mehta538607e2016-06-12 11:03:00 +0530362 frappe.throw(msg, NegativeStockError, title='Insufficent Stock')
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530363 else:
364 raise NegativeStockError, msg
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530365
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530366def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530367 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530368 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530369 to get actual qty before transaction, this function
370 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530371
Anand Doshi1b531862013-01-10 19:29:51 +0530372 args = {
373 "item_code": "ABC",
374 "warehouse": "XYZ",
375 "posting_date": "2012-12-12",
376 "posting_time": "12:00",
377 "sle": "name of reference Stock Ledger Entry"
378 }
379 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530380 args["name"] = args.get("sle", None) or ""
381 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530382 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530383
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530384def get_stock_ledger_entries(previous_sle, operator=None, order="desc", limit=None, for_update=False, debug=False):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530385 """get stock ledger entries filtered by specific posting datetime conditions"""
386 conditions = "timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
387 if not previous_sle.get("posting_date"):
388 previous_sle["posting_date"] = "1900-01-01"
389 if not previous_sle.get("posting_time"):
390 previous_sle["posting_time"] = "00:00"
391
392 if operator in (">", "<=") and previous_sle.get("name"):
393 conditions += " and name!=%(name)s"
394
395 return frappe.db.sql("""select *, timestamp(posting_date, posting_time) as "timestamp" from `tabStock Ledger Entry`
396 where item_code = %%(item_code)s
397 and warehouse = %%(warehouse)s
398 and ifnull(is_cancelled, 'No')='No'
399 and %(conditions)s
400 order by timestamp(posting_date, posting_time) %(order)s, name %(order)s
401 %(limit)s %(for_update)s""" % {
402 "conditions": conditions,
403 "limit": limit or "",
404 "for_update": for_update and "for update" or "",
405 "order": order
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530406 }, previous_sle, as_dict=1, debug=debug)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530407
Nabin Haitf1a07ff2014-10-15 12:23:35 +0530408def get_valuation_rate(item_code, warehouse, allow_zero_rate=False):
Nabin Haitfb6e4342014-10-15 11:34:40 +0530409 last_valuation_rate = frappe.db.sql("""select valuation_rate
410 from `tabStock Ledger Entry`
411 where item_code = %s and warehouse = %s
Anand Doshi602e8252015-11-16 19:05:46 +0530412 and valuation_rate > 0
Nabin Haitfb6e4342014-10-15 11:34:40 +0530413 order by posting_date desc, posting_time desc, name desc limit 1""", (item_code, warehouse))
414
415 if not last_valuation_rate:
416 last_valuation_rate = frappe.db.sql("""select valuation_rate
417 from `tabStock Ledger Entry`
Anand Doshi602e8252015-11-16 19:05:46 +0530418 where item_code = %s and valuation_rate > 0
Nabin Haitfb6e4342014-10-15 11:34:40 +0530419 order by posting_date desc, posting_time desc, name desc limit 1""", item_code)
420
421 valuation_rate = flt(last_valuation_rate[0][0]) if last_valuation_rate else 0
422
423 if not valuation_rate:
424 valuation_rate = frappe.db.get_value("Item Price", {"item_code": item_code, "buying": 1}, "price_list_rate")
425
Nabin Haitf1a07ff2014-10-15 12:23:35 +0530426 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 +0530427 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))
428
429 return valuation_rate