blob: 97a1f82157b0411b52c56a9d11109495aa667f67 [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)
Nabin Hait74c281c2013-08-19 16:17:18 +053052 sle.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
Nabin Hait9c47efb2015-01-21 16:22:45 +053062def update_entries_after(args, allow_zero_rate=False, allow_negative_stock=False, verbose=1):
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
Nabin Hait902e8602013-01-08 18:29:24 +053067 args = {
68 "item_code": "ABC",
69 "warehouse": "XYZ",
70 "posting_date": "2012-12-12",
71 "posting_time": "12:00"
72 }
73 """
Pratik Vyas16371b72013-09-18 18:31:03 +053074 if not _exceptions:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053075 frappe.local.stockledger_exceptions = []
Nabin Haitdc82d4f2014-04-07 12:02:57 +053076
Nabin Hait9c47efb2015-01-21 16:22:45 +053077 if not allow_negative_stock:
78 allow_negative_stock = cint(frappe.db.get_default("allow_negative_stock"))
79
Nabin Hait902e8602013-01-08 18:29:24 +053080 previous_sle = get_sle_before_datetime(args)
Nabin Haitdc82d4f2014-04-07 12:02:57 +053081
Nabin Hait902e8602013-01-08 18:29:24 +053082 qty_after_transaction = flt(previous_sle.get("qty_after_transaction"))
83 valuation_rate = flt(previous_sle.get("valuation_rate"))
84 stock_queue = json.loads(previous_sle.get("stock_queue") or "[]")
Nabin Hait27994c22013-08-26 16:53:30 +053085 stock_value = flt(previous_sle.get("stock_value"))
86 prev_stock_value = flt(previous_sle.get("stock_value"))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053087
Nabin Hait902e8602013-01-08 18:29:24 +053088 entries_to_fix = get_sle_after_datetime(previous_sle or \
Anand Doshi4dc7caa2013-01-11 11:44:49 +053089 {"item_code": args["item_code"], "warehouse": args["warehouse"]}, for_update=True)
Nabin Hait902e8602013-01-08 18:29:24 +053090 valuation_method = get_valuation_method(args["item_code"])
Nabin Haitaeba24e2013-08-23 15:17:36 +053091 stock_value_difference = 0.0
Nabin Haitbb777562013-08-29 18:19:37 +053092
Nabin Hait902e8602013-01-08 18:29:24 +053093 for sle in entries_to_fix:
Nabin Hait9c47efb2015-01-21 16:22:45 +053094 if sle.serial_no or not allow_negative_stock:
Nabin Haitdc82d4f2014-04-07 12:02:57 +053095 # validate negative stock for serialized items, fifo valuation
Nabin Hait902e8602013-01-08 18:29:24 +053096 # or when negative stock is not allowed for moving average
97 if not validate_negative_stock(qty_after_transaction, sle):
98 qty_after_transaction += flt(sle.actual_qty)
99 continue
Nabin Haitbb777562013-08-29 18:19:37 +0530100
Nabin Haitb96c0142014-10-07 11:25:04 +0530101
Anand Doshi1b531862013-01-10 19:29:51 +0530102 if sle.serial_no:
Nabin Hait1b4f56c2013-01-17 17:01:51 +0530103 valuation_rate = get_serialized_values(qty_after_transaction, sle, valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530104 qty_after_transaction += flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530105
Nabin Haitb96c0142014-10-07 11:25:04 +0530106 else:
107 if sle.voucher_type=="Stock Reconciliation":
108 valuation_rate = sle.valuation_rate
109 qty_after_transaction = sle.qty_after_transaction
110 stock_queue = [[qty_after_transaction, valuation_rate]]
111 else:
112 if valuation_method == "Moving Average":
Nabin Haitf1a07ff2014-10-15 12:23:35 +0530113 valuation_rate = get_moving_average_values(qty_after_transaction, sle, valuation_rate, allow_zero_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530114 else:
Nabin Haitf1a07ff2014-10-15 12:23:35 +0530115 valuation_rate = get_fifo_values(qty_after_transaction, sle, stock_queue, allow_zero_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530116
Nabin Hait4d742162014-10-09 19:25:03 +0530117
Nabin Haitb96c0142014-10-07 11:25:04 +0530118 qty_after_transaction += flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530119
Nabin Hait902e8602013-01-08 18:29:24 +0530120 # get stock value
Anand Doshi1b531862013-01-10 19:29:51 +0530121 if sle.serial_no:
Nabin Hait902e8602013-01-08 18:29:24 +0530122 stock_value = qty_after_transaction * valuation_rate
123 elif valuation_method == "Moving Average":
Nabin Hait4d742162014-10-09 19:25:03 +0530124 stock_value = qty_after_transaction * valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530125 else:
126 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530127
Rushabh Mehta54047782013-12-26 11:07:46 +0530128 # rounding as per precision
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530129 from frappe.model.meta import get_field_precision
Rushabh Mehtae88bc8b2014-03-27 17:51:41 +0530130 meta = frappe.get_meta("Stock Ledger Entry")
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530131
132 stock_value = flt(stock_value, get_field_precision(meta.get_field("stock_value"),
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530133 frappe._dict({"fields": sle})))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530134
Nabin Haitaeba24e2013-08-23 15:17:36 +0530135 stock_value_difference = stock_value - prev_stock_value
136 prev_stock_value = stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530137
Nabin Hait902e8602013-01-08 18:29:24 +0530138 # update current sle
Anand Doshie9baaa62014-02-26 12:35:33 +0530139 frappe.db.sql("""update `tabStock Ledger Entry`
Anand Doshi1b531862013-01-10 19:29:51 +0530140 set qty_after_transaction=%s, valuation_rate=%s, stock_queue=%s,
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530141 stock_value=%s, stock_value_difference=%s where name=%s""",
Anand Doshi1b531862013-01-10 19:29:51 +0530142 (qty_after_transaction, valuation_rate,
Nabin Haitaeba24e2013-08-23 15:17:36 +0530143 json.dumps(stock_queue), stock_value, stock_value_difference, sle.name))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530144
Nabin Hait902e8602013-01-08 18:29:24 +0530145 if _exceptions:
Nabin Hait9514d172013-01-10 10:40:37 +0530146 _raise_exceptions(args, verbose)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530147
Nabin Hait902e8602013-01-08 18:29:24 +0530148 # update bin
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530149 if not frappe.db.exists({"doctype": "Bin", "item_code": args["item_code"],
Nabin Haitac53b112013-01-11 19:25:46 +0530150 "warehouse": args["warehouse"]}):
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530151 bin_wrapper = frappe.get_doc({
Nabin Haitac53b112013-01-11 19:25:46 +0530152 "doctype": "Bin",
153 "item_code": args["item_code"],
154 "warehouse": args["warehouse"],
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530155 })
Anand Doshic313d662013-01-14 15:46:17 +0530156 bin_wrapper.ignore_permissions = 1
157 bin_wrapper.insert()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530158
Anand Doshie9baaa62014-02-26 12:35:33 +0530159 frappe.db.sql("""update `tabBin` set valuation_rate=%s, actual_qty=%s,
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530160 stock_value=%s,
Nabin Hait902e8602013-01-08 18:29:24 +0530161 projected_qty = (actual_qty + indented_qty + ordered_qty + planned_qty - reserved_qty)
162 where item_code=%s and warehouse=%s""", (valuation_rate, qty_after_transaction,
163 stock_value, args["item_code"], args["warehouse"]))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530164
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530165def get_sle_before_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530166 """
167 get previous stock ledger entry before current time-bucket
168
169 Details:
170 get the last sle before the current time-bucket, so that all values
171 are reposted from the current time-bucket onwards.
172 this is necessary because at the time of cancellation, there may be
173 entries between the cancelled entries in the same time-bucket
174 """
175 sle = get_stock_ledger_entries(args,
Nabin Hait26d46552013-01-09 15:23:05 +0530176 ["timestamp(posting_date, posting_time) < timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530177 "desc", "limit 1", for_update=for_update)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530178
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530179 return sle and sle[0] or frappe._dict()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530180
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530181def get_sle_after_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530182 """get Stock Ledger Entries after a particular datetime, for reposting"""
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530183 # NOTE: using for update of
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530184 conditions = ["timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)"]
185
186 # Excluding name: Workaround for MariaDB timestamp() floating microsecond issue
187 if args.get("name"):
188 conditions.append("name!=%(name)s")
189
190 return get_stock_ledger_entries(args, conditions, "asc", for_update=for_update)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530191
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530192def get_stock_ledger_entries(args, conditions=None, order="desc", limit=None, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530193 """get stock ledger entries filtered by specific posting datetime conditions"""
194 if not args.get("posting_date"):
195 args["posting_date"] = "1900-01-01"
196 if not args.get("posting_time"):
Anand Doshi71bed312013-03-13 12:57:04 +0530197 args["posting_time"] = "00:00"
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530198
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530199 return frappe.db.sql("""select *, timestamp(posting_date, posting_time) as "timestamp" from `tabStock Ledger Entry`
Nabin Hait902e8602013-01-08 18:29:24 +0530200 where item_code = %%(item_code)s
201 and warehouse = %%(warehouse)s
Nabin Haitbb777562013-08-29 18:19:37 +0530202 and ifnull(is_cancelled, 'No')='No'
Nabin Hait902e8602013-01-08 18:29:24 +0530203 %(conditions)s
Nabin Hait9514d172013-01-10 10:40:37 +0530204 order by timestamp(posting_date, posting_time) %(order)s, name %(order)s
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530205 %(limit)s %(for_update)s""" % {
Nabin Hait902e8602013-01-08 18:29:24 +0530206 "conditions": conditions and ("and " + " and ".join(conditions)) or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530207 "limit": limit or "",
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530208 "for_update": for_update and "for update" or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530209 "order": order
Nabin Hait902e8602013-01-08 18:29:24 +0530210 }, args, as_dict=1)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530211
Nabin Hait902e8602013-01-08 18:29:24 +0530212def validate_negative_stock(qty_after_transaction, sle):
213 """
214 validate negative stock for entries current datetime onwards
215 will not consider cancelled entries
216 """
217 diff = qty_after_transaction + flt(sle.actual_qty)
Pratik Vyas16371b72013-09-18 18:31:03 +0530218
219 if not _exceptions:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530220 frappe.local.stockledger_exceptions = []
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530221
Nabin Hait902e8602013-01-08 18:29:24 +0530222 if diff < 0 and abs(diff) > 0.0001:
223 # negative stock!
Nabin Hait902e8602013-01-08 18:29:24 +0530224 exc = sle.copy().update({"diff": diff})
225 _exceptions.append(exc)
226 return False
227 else:
228 return True
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530229
Nabin Hait902e8602013-01-08 18:29:24 +0530230def get_serialized_values(qty_after_transaction, sle, valuation_rate):
231 incoming_rate = flt(sle.incoming_rate)
232 actual_qty = flt(sle.actual_qty)
Anand Doshi1b531862013-01-10 19:29:51 +0530233 serial_no = cstr(sle.serial_no).split("\n")
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530234
Nabin Hait902e8602013-01-08 18:29:24 +0530235 if incoming_rate < 0:
236 # wrong incoming rate
237 incoming_rate = valuation_rate
238 elif incoming_rate == 0 or flt(sle.actual_qty) < 0:
239 # In case of delivery/stock issue, get average purchase rate
240 # of serial nos of current entry
Anand Doshie9baaa62014-02-26 12:35:33 +0530241 incoming_rate = flt(frappe.db.sql("""select avg(ifnull(purchase_rate, 0))
Anand Doshi1b531862013-01-10 19:29:51 +0530242 from `tabSerial No` where name in (%s)""" % (", ".join(["%s"]*len(serial_no))),
243 tuple(serial_no))[0][0])
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530244
Nabin Hait902e8602013-01-08 18:29:24 +0530245 if incoming_rate and not valuation_rate:
246 valuation_rate = incoming_rate
247 else:
248 new_stock_qty = qty_after_transaction + actual_qty
249 if new_stock_qty > 0:
250 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
251 if new_stock_value > 0:
252 # calculate new valuation rate only if stock value is positive
253 # else it remains the same as that of previous entry
254 valuation_rate = new_stock_value / new_stock_qty
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530255
Nabin Hait914c6df2013-01-14 13:15:42 +0530256 return valuation_rate
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530257
Nabin Haitf1a07ff2014-10-15 12:23:35 +0530258def get_moving_average_values(qty_after_transaction, sle, valuation_rate, allow_zero_rate):
Nabin Hait902e8602013-01-08 18:29:24 +0530259 incoming_rate = flt(sle.incoming_rate)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530260 actual_qty = flt(sle.actual_qty)
261
Nabin Hait7c6f9902014-10-10 18:03:27 +0530262 if flt(sle.actual_qty) > 0:
263 if qty_after_transaction < 0 and not valuation_rate:
264 # if negative stock, take current valuation rate as incoming rate
265 valuation_rate = incoming_rate
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530266
Nabin Hait7c6f9902014-10-10 18:03:27 +0530267 new_stock_qty = abs(qty_after_transaction) + actual_qty
268 new_stock_value = (abs(qty_after_transaction) * valuation_rate) + (actual_qty * incoming_rate)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530269
Nabin Hait7c6f9902014-10-10 18:03:27 +0530270 if new_stock_qty:
271 valuation_rate = new_stock_value / flt(new_stock_qty)
Nabin Haitfb6e4342014-10-15 11:34:40 +0530272 elif not valuation_rate and qty_after_transaction <= 0:
Nabin Haitf1a07ff2014-10-15 12:23:35 +0530273 valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse, allow_zero_rate)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530274
Nabin Haitbf492122014-10-14 16:09:14 +0530275 return abs(flt(valuation_rate))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530276
Nabin Haitf1a07ff2014-10-15 12:23:35 +0530277def get_fifo_values(qty_after_transaction, sle, stock_queue, allow_zero_rate):
Nabin Hait902e8602013-01-08 18:29:24 +0530278 incoming_rate = flt(sle.incoming_rate)
279 actual_qty = flt(sle.actual_qty)
Nabin Hait4d742162014-10-09 19:25:03 +0530280
Nabin Hait902e8602013-01-08 18:29:24 +0530281 if actual_qty > 0:
Nabin Haitfb6e4342014-10-15 11:34:40 +0530282 if not stock_queue:
283 stock_queue.append([0, 0])
284
Nabin Hait902e8602013-01-08 18:29:24 +0530285 if stock_queue[-1][0] > 0:
286 stock_queue.append([actual_qty, incoming_rate])
287 else:
288 qty = stock_queue[-1][0] + actual_qty
Nabin Hait4d742162014-10-09 19:25:03 +0530289 if qty == 0:
290 stock_queue.pop(-1)
291 else:
292 stock_queue[-1] = [qty, incoming_rate]
Nabin Hait902e8602013-01-08 18:29:24 +0530293 else:
Nabin Hait902e8602013-01-08 18:29:24 +0530294 qty_to_pop = abs(actual_qty)
295 while qty_to_pop:
Nabin Haitfb6e4342014-10-15 11:34:40 +0530296 if not stock_queue:
Nabin Haitf1a07ff2014-10-15 12:23:35 +0530297 stock_queue.append([0, get_valuation_rate(sle.item_code, sle.warehouse, allow_zero_rate)
Nabin Haitfb6e4342014-10-15 11:34:40 +0530298 if qty_after_transaction <= 0 else 0])
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530299
Nabin Hait902e8602013-01-08 18:29:24 +0530300 batch = stock_queue[0]
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530301
Nabin Hait4d742162014-10-09 19:25:03 +0530302 if qty_to_pop >= batch[0]:
303 # consume current batch
304 qty_to_pop = qty_to_pop - batch[0]
Nabin Hait902e8602013-01-08 18:29:24 +0530305 stock_queue.pop(0)
Nabin Hait4d742162014-10-09 19:25:03 +0530306 if not stock_queue and qty_to_pop:
307 # stock finished, qty still remains to be withdrawn
308 # negative stock, keep in as a negative batch
309 stock_queue.append([-qty_to_pop, batch[1]])
310 break
311
Nabin Hait902e8602013-01-08 18:29:24 +0530312 else:
Nabin Hait4d742162014-10-09 19:25:03 +0530313 # qty found in current batch
314 # consume it and exit
315 batch[0] = batch[0] - qty_to_pop
Nabin Hait902e8602013-01-08 18:29:24 +0530316 qty_to_pop = 0
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530317
Nabin Hait902e8602013-01-08 18:29:24 +0530318 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
319 stock_qty = sum((flt(batch[0]) for batch in stock_queue))
320
Nabin Hait4d742162014-10-09 19:25:03 +0530321 valuation_rate = (stock_value / flt(stock_qty)) if stock_qty else 0
Nabin Hait9514d172013-01-10 10:40:37 +0530322
Nabin Hait4d742162014-10-09 19:25:03 +0530323 return abs(valuation_rate)
324
Nabin Hait9514d172013-01-10 10:40:37 +0530325def _raise_exceptions(args, verbose=1):
Nabin Hait902e8602013-01-08 18:29:24 +0530326 deficiency = min(e["diff"] for e in _exceptions)
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530327 msg = _("Negative Stock Error ({6}) for Item {0} in Warehouse {1} on {2} {3} in {4} {5}").format(args["item_code"],
328 args.get("warehouse"), _exceptions[0]["posting_date"], _exceptions[0]["posting_time"],
329 _(_exceptions[0]["voucher_type"]), _exceptions[0]["voucher_no"], deficiency)
Nabin Hait902e8602013-01-08 18:29:24 +0530330 if verbose:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530331 frappe.throw(msg, NegativeStockError)
Nabin Hait902e8602013-01-08 18:29:24 +0530332 else:
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530333 raise NegativeStockError, msg
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530334
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530335def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530336 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530337 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530338 to get actual qty before transaction, this function
339 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530340
Anand Doshi1b531862013-01-10 19:29:51 +0530341 args = {
342 "item_code": "ABC",
343 "warehouse": "XYZ",
344 "posting_date": "2012-12-12",
345 "posting_time": "12:00",
346 "sle": "name of reference Stock Ledger Entry"
347 }
348 """
349 if not args.get("sle"): args["sle"] = ""
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530350
Anand Doshi1b531862013-01-10 19:29:51 +0530351 sle = get_stock_ledger_entries(args, ["name != %(sle)s",
352 "timestamp(posting_date, posting_time) <= timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530353 "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530354 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530355
Nabin Haitf1a07ff2014-10-15 12:23:35 +0530356def get_valuation_rate(item_code, warehouse, allow_zero_rate=False):
Nabin Haitfb6e4342014-10-15 11:34:40 +0530357 last_valuation_rate = frappe.db.sql("""select valuation_rate
358 from `tabStock Ledger Entry`
359 where item_code = %s and warehouse = %s
360 and ifnull(valuation_rate, 0) > 0
361 order by posting_date desc, posting_time desc, name desc limit 1""", (item_code, warehouse))
362
363 if not last_valuation_rate:
364 last_valuation_rate = frappe.db.sql("""select valuation_rate
365 from `tabStock Ledger Entry`
366 where item_code = %s and ifnull(valuation_rate, 0) > 0
367 order by posting_date desc, posting_time desc, name desc limit 1""", item_code)
368
369 valuation_rate = flt(last_valuation_rate[0][0]) if last_valuation_rate else 0
370
371 if not valuation_rate:
372 valuation_rate = frappe.db.get_value("Item Price", {"item_code": item_code, "buying": 1}, "price_list_rate")
373
Nabin Haitf1a07ff2014-10-15 12:23:35 +0530374 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 +0530375 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))
376
377 return valuation_rate