blob: 2956170010a724ebef9d701b2c9eaf2df6d60637 [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 Hait7c6f9902014-10-10 18:03:27 +05309from erpnext.controllers.stock_controller import get_valuation_rate
Nabin Hait26d46552013-01-09 15:23:05 +053010import json
Nabin Hait902e8602013-01-08 18:29:24 +053011
12# future reposting
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053013class NegativeStockError(frappe.ValidationError): pass
Nabin Hait902e8602013-01-08 18:29:24 +053014
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053015_exceptions = frappe.local('stockledger_exceptions')
Pratik Vyas16371b72013-09-18 18:31:03 +053016# _exceptions = []
Anand Doshi5b004ff2013-09-25 19:55:41 +053017
Nabin Hait74c281c2013-08-19 16:17:18 +053018def make_sl_entries(sl_entries, is_amended=None):
Nabin Haitca775742013-09-26 16:16:44 +053019 if sl_entries:
Rushabh Mehta1f847992013-12-12 19:12:19 +053020 from erpnext.stock.utils import update_bin
Nabin Haitdc82d4f2014-04-07 12:02:57 +053021
Nabin Haitca775742013-09-26 16:16:44 +053022 cancel = True if sl_entries[0].get("is_cancelled") == "Yes" else False
23 if cancel:
24 set_as_cancel(sl_entries[0].get('voucher_no'), sl_entries[0].get('voucher_type'))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053025
Nabin Haitca775742013-09-26 16:16:44 +053026 for sle in sl_entries:
27 sle_id = None
28 if sle.get('is_cancelled') == 'Yes':
29 sle['actual_qty'] = -flt(sle['actual_qty'])
Nabin Haitdc82d4f2014-04-07 12:02:57 +053030
Nabin Haitbfa7f172014-10-07 12:17:31 +053031 if sle.get("actual_qty") or sle.voucher_type=="Stock Reconciliation":
Nabin Haitca775742013-09-26 16:16:44 +053032 sle_id = make_entry(sle)
Nabin Haitdc82d4f2014-04-07 12:02:57 +053033
Nabin Haitca775742013-09-26 16:16:44 +053034 args = sle.copy()
35 args.update({
36 "sle_id": sle_id,
37 "is_amended": is_amended
38 })
39 update_bin(args)
Nabin Haitadeb9762014-10-06 11:53:52 +053040
Nabin Haitca775742013-09-26 16:16:44 +053041 if cancel:
Nabin Haitadeb9762014-10-06 11:53:52 +053042 delete_cancelled_entry(sl_entries[0].get('voucher_type'), sl_entries[0].get('voucher_no'))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053043
Nabin Hait9653f602013-08-20 15:37:33 +053044def set_as_cancel(voucher_type, voucher_no):
Anand Doshie9baaa62014-02-26 12:35:33 +053045 frappe.db.sql("""update `tabStock Ledger Entry` set is_cancelled='Yes',
Nabin Hait9653f602013-08-20 15:37:33 +053046 modified=%s, modified_by=%s
Nabin Haitdc82d4f2014-04-07 12:02:57 +053047 where voucher_no=%s and voucher_type=%s""",
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053048 (now(), frappe.session.user, voucher_type, voucher_no))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053049
Nabin Hait74c281c2013-08-19 16:17:18 +053050def make_entry(args):
51 args.update({"doctype": "Stock Ledger Entry"})
Rushabh Mehtaa504f062014-04-04 12:16:26 +053052 sle = frappe.get_doc(args)
Nabin Hait74c281c2013-08-19 16:17:18 +053053 sle.ignore_permissions = 1
54 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 Hait902e8602013-01-08 18:29:24 +053062def update_entries_after(args, verbose=1):
63 """
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 Hait902e8602013-01-08 18:29:24 +053077 previous_sle = get_sle_before_datetime(args)
Nabin Haitdc82d4f2014-04-07 12:02:57 +053078
Nabin Hait902e8602013-01-08 18:29:24 +053079 qty_after_transaction = flt(previous_sle.get("qty_after_transaction"))
80 valuation_rate = flt(previous_sle.get("valuation_rate"))
81 stock_queue = json.loads(previous_sle.get("stock_queue") or "[]")
Nabin Hait27994c22013-08-26 16:53:30 +053082 stock_value = flt(previous_sle.get("stock_value"))
83 prev_stock_value = flt(previous_sle.get("stock_value"))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053084
Nabin Hait902e8602013-01-08 18:29:24 +053085 entries_to_fix = get_sle_after_datetime(previous_sle or \
Anand Doshi4dc7caa2013-01-11 11:44:49 +053086 {"item_code": args["item_code"], "warehouse": args["warehouse"]}, for_update=True)
Nabin Hait902e8602013-01-08 18:29:24 +053087 valuation_method = get_valuation_method(args["item_code"])
Nabin Haitaeba24e2013-08-23 15:17:36 +053088 stock_value_difference = 0.0
Nabin Haitbb777562013-08-29 18:19:37 +053089
Nabin Hait902e8602013-01-08 18:29:24 +053090 for sle in entries_to_fix:
Anand Doshie9baaa62014-02-26 12:35:33 +053091 if sle.serial_no or not cint(frappe.db.get_default("allow_negative_stock")):
Nabin Haitdc82d4f2014-04-07 12:02:57 +053092 # validate negative stock for serialized items, fifo valuation
Nabin Hait902e8602013-01-08 18:29:24 +053093 # or when negative stock is not allowed for moving average
94 if not validate_negative_stock(qty_after_transaction, sle):
95 qty_after_transaction += flt(sle.actual_qty)
96 continue
Nabin Haitbb777562013-08-29 18:19:37 +053097
Nabin Haitb96c0142014-10-07 11:25:04 +053098
Anand Doshi1b531862013-01-10 19:29:51 +053099 if sle.serial_no:
Nabin Hait1b4f56c2013-01-17 17:01:51 +0530100 valuation_rate = get_serialized_values(qty_after_transaction, sle, valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530101 qty_after_transaction += flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530102
Nabin Haitb96c0142014-10-07 11:25:04 +0530103 else:
104 if sle.voucher_type=="Stock Reconciliation":
105 valuation_rate = sle.valuation_rate
106 qty_after_transaction = sle.qty_after_transaction
107 stock_queue = [[qty_after_transaction, valuation_rate]]
108 else:
109 if valuation_method == "Moving Average":
Nabin Hait7c6f9902014-10-10 18:03:27 +0530110 valuation_rate = get_moving_average_values(qty_after_transaction, sle, valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530111 else:
112 valuation_rate = get_fifo_values(qty_after_transaction, sle, stock_queue)
113
Nabin Hait4d742162014-10-09 19:25:03 +0530114
Nabin Haitb96c0142014-10-07 11:25:04 +0530115 qty_after_transaction += flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530116
Nabin Hait902e8602013-01-08 18:29:24 +0530117 # get stock value
Anand Doshi1b531862013-01-10 19:29:51 +0530118 if sle.serial_no:
Nabin Hait902e8602013-01-08 18:29:24 +0530119 stock_value = qty_after_transaction * valuation_rate
120 elif valuation_method == "Moving Average":
Nabin Hait4d742162014-10-09 19:25:03 +0530121 stock_value = qty_after_transaction * valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530122 else:
123 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530124
Rushabh Mehta54047782013-12-26 11:07:46 +0530125 # rounding as per precision
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530126 from frappe.model.meta import get_field_precision
Rushabh Mehtae88bc8b2014-03-27 17:51:41 +0530127 meta = frappe.get_meta("Stock Ledger Entry")
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530128
129 stock_value = flt(stock_value, get_field_precision(meta.get_field("stock_value"),
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530130 frappe._dict({"fields": sle})))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530131
Nabin Haitaeba24e2013-08-23 15:17:36 +0530132 stock_value_difference = stock_value - prev_stock_value
133 prev_stock_value = stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530134
Nabin Hait902e8602013-01-08 18:29:24 +0530135 # update current sle
Anand Doshie9baaa62014-02-26 12:35:33 +0530136 frappe.db.sql("""update `tabStock Ledger Entry`
Anand Doshi1b531862013-01-10 19:29:51 +0530137 set qty_after_transaction=%s, valuation_rate=%s, stock_queue=%s,
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530138 stock_value=%s, stock_value_difference=%s where name=%s""",
Anand Doshi1b531862013-01-10 19:29:51 +0530139 (qty_after_transaction, valuation_rate,
Nabin Haitaeba24e2013-08-23 15:17:36 +0530140 json.dumps(stock_queue), stock_value, stock_value_difference, sle.name))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530141
Nabin Hait902e8602013-01-08 18:29:24 +0530142 if _exceptions:
Nabin Hait9514d172013-01-10 10:40:37 +0530143 _raise_exceptions(args, verbose)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530144
Nabin Hait902e8602013-01-08 18:29:24 +0530145 # update bin
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530146 if not frappe.db.exists({"doctype": "Bin", "item_code": args["item_code"],
Nabin Haitac53b112013-01-11 19:25:46 +0530147 "warehouse": args["warehouse"]}):
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530148 bin_wrapper = frappe.get_doc({
Nabin Haitac53b112013-01-11 19:25:46 +0530149 "doctype": "Bin",
150 "item_code": args["item_code"],
151 "warehouse": args["warehouse"],
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530152 })
Anand Doshic313d662013-01-14 15:46:17 +0530153 bin_wrapper.ignore_permissions = 1
154 bin_wrapper.insert()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530155
Anand Doshie9baaa62014-02-26 12:35:33 +0530156 frappe.db.sql("""update `tabBin` set valuation_rate=%s, actual_qty=%s,
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530157 stock_value=%s,
Nabin Hait902e8602013-01-08 18:29:24 +0530158 projected_qty = (actual_qty + indented_qty + ordered_qty + planned_qty - reserved_qty)
159 where item_code=%s and warehouse=%s""", (valuation_rate, qty_after_transaction,
160 stock_value, args["item_code"], args["warehouse"]))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530161
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530162def get_sle_before_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530163 """
164 get previous stock ledger entry before current time-bucket
165
166 Details:
167 get the last sle before the current time-bucket, so that all values
168 are reposted from the current time-bucket onwards.
169 this is necessary because at the time of cancellation, there may be
170 entries between the cancelled entries in the same time-bucket
171 """
172 sle = get_stock_ledger_entries(args,
Nabin Hait26d46552013-01-09 15:23:05 +0530173 ["timestamp(posting_date, posting_time) < timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530174 "desc", "limit 1", for_update=for_update)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530175
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530176 return sle and sle[0] or frappe._dict()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530177
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530178def get_sle_after_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530179 """get Stock Ledger Entries after a particular datetime, for reposting"""
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530180 # NOTE: using for update of
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530181 conditions = ["timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)"]
182
183 # Excluding name: Workaround for MariaDB timestamp() floating microsecond issue
184 if args.get("name"):
185 conditions.append("name!=%(name)s")
186
187 return get_stock_ledger_entries(args, conditions, "asc", for_update=for_update)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530188
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530189def get_stock_ledger_entries(args, conditions=None, order="desc", limit=None, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530190 """get stock ledger entries filtered by specific posting datetime conditions"""
191 if not args.get("posting_date"):
192 args["posting_date"] = "1900-01-01"
193 if not args.get("posting_time"):
Anand Doshi71bed312013-03-13 12:57:04 +0530194 args["posting_time"] = "00:00"
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530195
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530196 return frappe.db.sql("""select *, timestamp(posting_date, posting_time) as "timestamp" from `tabStock Ledger Entry`
Nabin Hait902e8602013-01-08 18:29:24 +0530197 where item_code = %%(item_code)s
198 and warehouse = %%(warehouse)s
Nabin Haitbb777562013-08-29 18:19:37 +0530199 and ifnull(is_cancelled, 'No')='No'
Nabin Hait902e8602013-01-08 18:29:24 +0530200 %(conditions)s
Nabin Hait9514d172013-01-10 10:40:37 +0530201 order by timestamp(posting_date, posting_time) %(order)s, name %(order)s
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530202 %(limit)s %(for_update)s""" % {
Nabin Hait902e8602013-01-08 18:29:24 +0530203 "conditions": conditions and ("and " + " and ".join(conditions)) or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530204 "limit": limit or "",
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530205 "for_update": for_update and "for update" or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530206 "order": order
Nabin Hait902e8602013-01-08 18:29:24 +0530207 }, args, as_dict=1)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530208
Nabin Hait902e8602013-01-08 18:29:24 +0530209def validate_negative_stock(qty_after_transaction, sle):
210 """
211 validate negative stock for entries current datetime onwards
212 will not consider cancelled entries
213 """
214 diff = qty_after_transaction + flt(sle.actual_qty)
Pratik Vyas16371b72013-09-18 18:31:03 +0530215
216 if not _exceptions:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530217 frappe.local.stockledger_exceptions = []
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530218
Nabin Hait902e8602013-01-08 18:29:24 +0530219 if diff < 0 and abs(diff) > 0.0001:
220 # negative stock!
Nabin Hait902e8602013-01-08 18:29:24 +0530221 exc = sle.copy().update({"diff": diff})
222 _exceptions.append(exc)
223 return False
224 else:
225 return True
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530226
Nabin Hait902e8602013-01-08 18:29:24 +0530227def get_serialized_values(qty_after_transaction, sle, valuation_rate):
228 incoming_rate = flt(sle.incoming_rate)
229 actual_qty = flt(sle.actual_qty)
Anand Doshi1b531862013-01-10 19:29:51 +0530230 serial_no = cstr(sle.serial_no).split("\n")
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530231
Nabin Hait902e8602013-01-08 18:29:24 +0530232 if incoming_rate < 0:
233 # wrong incoming rate
234 incoming_rate = valuation_rate
235 elif incoming_rate == 0 or flt(sle.actual_qty) < 0:
236 # In case of delivery/stock issue, get average purchase rate
237 # of serial nos of current entry
Anand Doshie9baaa62014-02-26 12:35:33 +0530238 incoming_rate = flt(frappe.db.sql("""select avg(ifnull(purchase_rate, 0))
Anand Doshi1b531862013-01-10 19:29:51 +0530239 from `tabSerial No` where name in (%s)""" % (", ".join(["%s"]*len(serial_no))),
240 tuple(serial_no))[0][0])
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530241
Nabin Hait902e8602013-01-08 18:29:24 +0530242 if incoming_rate and not valuation_rate:
243 valuation_rate = incoming_rate
244 else:
245 new_stock_qty = qty_after_transaction + actual_qty
246 if new_stock_qty > 0:
247 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
248 if new_stock_value > 0:
249 # calculate new valuation rate only if stock value is positive
250 # else it remains the same as that of previous entry
251 valuation_rate = new_stock_value / new_stock_qty
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530252
Nabin Hait914c6df2013-01-14 13:15:42 +0530253 return valuation_rate
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530254
Nabin Hait902e8602013-01-08 18:29:24 +0530255def get_moving_average_values(qty_after_transaction, sle, valuation_rate):
256 incoming_rate = flt(sle.incoming_rate)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530257 actual_qty = flt(sle.actual_qty)
258
Nabin Hait7c6f9902014-10-10 18:03:27 +0530259 if flt(sle.actual_qty) > 0:
260 if qty_after_transaction < 0 and not valuation_rate:
261 # if negative stock, take current valuation rate as incoming rate
262 valuation_rate = incoming_rate
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530263
Nabin Hait7c6f9902014-10-10 18:03:27 +0530264 new_stock_qty = abs(qty_after_transaction) + actual_qty
265 new_stock_value = (abs(qty_after_transaction) * valuation_rate) + (actual_qty * incoming_rate)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530266
Nabin Hait7c6f9902014-10-10 18:03:27 +0530267 if new_stock_qty:
268 valuation_rate = new_stock_value / flt(new_stock_qty)
269 elif not valuation_rate:
270 valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530271
Nabin Haitbf492122014-10-14 16:09:14 +0530272 return abs(flt(valuation_rate))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530273
Nabin Hait902e8602013-01-08 18:29:24 +0530274def get_fifo_values(qty_after_transaction, sle, stock_queue):
275 incoming_rate = flt(sle.incoming_rate)
276 actual_qty = flt(sle.actual_qty)
Nabin Hait4d742162014-10-09 19:25:03 +0530277
278 intialize_stock_queue(stock_queue, sle.item_code, sle.warehouse)
Nabin Hait9514d172013-01-10 10:40:37 +0530279
Nabin Hait902e8602013-01-08 18:29:24 +0530280 if actual_qty > 0:
281 if stock_queue[-1][0] > 0:
282 stock_queue.append([actual_qty, incoming_rate])
283 else:
284 qty = stock_queue[-1][0] + actual_qty
Nabin Hait4d742162014-10-09 19:25:03 +0530285 if qty == 0:
286 stock_queue.pop(-1)
287 else:
288 stock_queue[-1] = [qty, incoming_rate]
Nabin Hait902e8602013-01-08 18:29:24 +0530289 else:
Nabin Hait902e8602013-01-08 18:29:24 +0530290 qty_to_pop = abs(actual_qty)
291 while qty_to_pop:
Nabin Hait4d742162014-10-09 19:25:03 +0530292 intialize_stock_queue(stock_queue, sle.item_code, sle.warehouse)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530293
Nabin Hait902e8602013-01-08 18:29:24 +0530294 batch = stock_queue[0]
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530295
Nabin Hait4d742162014-10-09 19:25:03 +0530296 # print qty_to_pop, batch
297
298 if qty_to_pop >= batch[0]:
299 # consume current batch
300 qty_to_pop = qty_to_pop - batch[0]
Nabin Hait902e8602013-01-08 18:29:24 +0530301 stock_queue.pop(0)
Nabin Hait4d742162014-10-09 19:25:03 +0530302 if not stock_queue and qty_to_pop:
303 # stock finished, qty still remains to be withdrawn
304 # negative stock, keep in as a negative batch
305 stock_queue.append([-qty_to_pop, batch[1]])
306 break
307
Nabin Hait902e8602013-01-08 18:29:24 +0530308 else:
Nabin Hait4d742162014-10-09 19:25:03 +0530309 # qty found in current batch
310 # consume it and exit
311 batch[0] = batch[0] - qty_to_pop
Nabin Hait902e8602013-01-08 18:29:24 +0530312 qty_to_pop = 0
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530313
Nabin Hait902e8602013-01-08 18:29:24 +0530314 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
315 stock_qty = sum((flt(batch[0]) for batch in stock_queue))
316
Nabin Hait4d742162014-10-09 19:25:03 +0530317 valuation_rate = (stock_value / flt(stock_qty)) if stock_qty else 0
Nabin Hait9514d172013-01-10 10:40:37 +0530318
Nabin Hait4d742162014-10-09 19:25:03 +0530319 return abs(valuation_rate)
320
321def intialize_stock_queue(stock_queue, item_code, warehouse):
322 if not stock_queue:
Nabin Hait4d742162014-10-09 19:25:03 +0530323 estimated_val_rate = get_valuation_rate(item_code, warehouse)
324 stock_queue.append([0, estimated_val_rate])
Nabin Hait902e8602013-01-08 18:29:24 +0530325
Nabin Hait9514d172013-01-10 10:40:37 +0530326def _raise_exceptions(args, verbose=1):
Nabin Hait902e8602013-01-08 18:29:24 +0530327 deficiency = min(e["diff"] for e in _exceptions)
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530328 msg = _("Negative Stock Error ({6}) for Item {0} in Warehouse {1} on {2} {3} in {4} {5}").format(args["item_code"],
329 args.get("warehouse"), _exceptions[0]["posting_date"], _exceptions[0]["posting_time"],
330 _(_exceptions[0]["voucher_type"]), _exceptions[0]["voucher_no"], deficiency)
Nabin Hait902e8602013-01-08 18:29:24 +0530331 if verbose:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530332 frappe.throw(msg, NegativeStockError)
Nabin Hait902e8602013-01-08 18:29:24 +0530333 else:
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530334 raise NegativeStockError, msg
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530335
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530336def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530337 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530338 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530339 to get actual qty before transaction, this function
340 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530341
Anand Doshi1b531862013-01-10 19:29:51 +0530342 args = {
343 "item_code": "ABC",
344 "warehouse": "XYZ",
345 "posting_date": "2012-12-12",
346 "posting_time": "12:00",
347 "sle": "name of reference Stock Ledger Entry"
348 }
349 """
350 if not args.get("sle"): args["sle"] = ""
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530351
Anand Doshi1b531862013-01-10 19:29:51 +0530352 sle = get_stock_ledger_entries(args, ["name != %(sle)s",
353 "timestamp(posting_date, posting_time) <= timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530354 "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530355 return sle and sle[0] or {}