blob: cf95845cc8e1d3488499f8a0cdb52b86a444e972 [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
6from frappe import msgprint
7from 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 Hait74c281c2013-08-19 16:17:18 +053017def make_sl_entries(sl_entries, is_amended=None):
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 Hait9653f602013-08-20 15:37:33 +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 Hait9653f602013-08-20 15:37:33 +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 Hait9653f602013-08-20 15:37:33 +053029
Nabin Haitca775742013-09-26 16:16:44 +053030 if sle.get("actual_qty"):
31 sle_id = make_entry(sle)
Nabin Hait74c281c2013-08-19 16:17:18 +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 })
38 update_bin(args)
Nabin Hait74c281c2013-08-19 16:17:18 +053039
Nabin Haitca775742013-09-26 16:16:44 +053040 if cancel:
41 delete_cancelled_entry(sl_entries[0].get('voucher_type'),
42 sl_entries[0].get('voucher_no'))
Nabin Hait9653f602013-08-20 15:37:33 +053043
44def 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
47 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 Hait9653f602013-08-20 15:37:33 +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 Hait9653f602013-08-20 15:37:33 +053057
58def delete_cancelled_entry(voucher_type, voucher_no):
Anand Doshie9baaa62014-02-26 12:35:33 +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 """
64 update valution rate and qty after transaction
65 from the current time-bucket onwards
66
67 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 Haitf4591ec2013-05-23 19:07:10 +053076
Nabin Hait902e8602013-01-08 18:29:24 +053077 previous_sle = get_sle_before_datetime(args)
Anand Doshi71bed312013-03-13 12:57:04 +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"))
84
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 Hait469ee712013-08-07 12:33:37 +053087
Nabin Hait902e8602013-01-08 18:29:24 +053088 valuation_method = get_valuation_method(args["item_code"])
Nabin Haitaeba24e2013-08-23 15:17:36 +053089 stock_value_difference = 0.0
Nabin Haitbb777562013-08-29 18:19:37 +053090
Nabin Hait902e8602013-01-08 18:29:24 +053091 for sle in entries_to_fix:
Anand Doshie9baaa62014-02-26 12:35:33 +053092 if sle.serial_no or not cint(frappe.db.get_default("allow_negative_stock")):
Nabin Hait902e8602013-01-08 18:29:24 +053093 # validate negative stock for serialized items, fifo valuation
94 # or when negative stock is not allowed for moving average
95 if not validate_negative_stock(qty_after_transaction, sle):
96 qty_after_transaction += flt(sle.actual_qty)
97 continue
Nabin Haitbb777562013-08-29 18:19:37 +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 Hait902e8602013-01-08 18:29:24 +0530101 elif valuation_method == "Moving Average":
Nabin Hait1b4f56c2013-01-17 17:01:51 +0530102 valuation_rate = get_moving_average_values(qty_after_transaction, sle, valuation_rate)
Nabin Hait902e8602013-01-08 18:29:24 +0530103 else:
Nabin Hait1b4f56c2013-01-17 17:01:51 +0530104 valuation_rate = get_fifo_values(qty_after_transaction, sle, stock_queue)
Anand Doshi1b531862013-01-10 19:29:51 +0530105
Nabin Hait902e8602013-01-08 18:29:24 +0530106 qty_after_transaction += flt(sle.actual_qty)
107
108 # get stock value
Anand Doshi1b531862013-01-10 19:29:51 +0530109 if sle.serial_no:
Nabin Hait902e8602013-01-08 18:29:24 +0530110 stock_value = qty_after_transaction * valuation_rate
111 elif valuation_method == "Moving Average":
112 stock_value = (qty_after_transaction > 0) and \
113 (qty_after_transaction * valuation_rate) or 0
114 else:
115 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
Rushabh Mehta54047782013-12-26 11:07:46 +0530116
117 # rounding as per precision
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530118 from frappe.model.meta import get_field_precision
Rushabh Mehtae88bc8b2014-03-27 17:51:41 +0530119 meta = frappe.get_meta("Stock Ledger Entry")
Rushabh Mehta54047782013-12-26 11:07:46 +0530120
121 stock_value = flt(stock_value, get_field_precision(meta.get_field("stock_value"),
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530122 frappe._dict({"fields": sle})))
Rushabh Mehta54047782013-12-26 11:07:46 +0530123
Nabin Haitaeba24e2013-08-23 15:17:36 +0530124 stock_value_difference = stock_value - prev_stock_value
125 prev_stock_value = stock_value
126
Nabin Hait902e8602013-01-08 18:29:24 +0530127 # update current sle
Anand Doshie9baaa62014-02-26 12:35:33 +0530128 frappe.db.sql("""update `tabStock Ledger Entry`
Anand Doshi1b531862013-01-10 19:29:51 +0530129 set qty_after_transaction=%s, valuation_rate=%s, stock_queue=%s,
Nabin Haitaeba24e2013-08-23 15:17:36 +0530130 stock_value=%s, stock_value_difference=%s where name=%s""",
Anand Doshi1b531862013-01-10 19:29:51 +0530131 (qty_after_transaction, valuation_rate,
Nabin Haitaeba24e2013-08-23 15:17:36 +0530132 json.dumps(stock_queue), stock_value, stock_value_difference, sle.name))
Anand Doshi1b531862013-01-10 19:29:51 +0530133
Nabin Hait902e8602013-01-08 18:29:24 +0530134 if _exceptions:
Nabin Hait9514d172013-01-10 10:40:37 +0530135 _raise_exceptions(args, verbose)
Nabin Hait902e8602013-01-08 18:29:24 +0530136
137 # update bin
Anand Doshie9baaa62014-02-26 12:35:33 +0530138 if not frappe.db.exists({"doctype": "Bin", "item_code": args["item_code"],
Nabin Haitac53b112013-01-11 19:25:46 +0530139 "warehouse": args["warehouse"]}):
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530140 bin_wrapper = frappe.get_doc({
Nabin Haitac53b112013-01-11 19:25:46 +0530141 "doctype": "Bin",
142 "item_code": args["item_code"],
143 "warehouse": args["warehouse"],
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530144 })
Anand Doshic313d662013-01-14 15:46:17 +0530145 bin_wrapper.ignore_permissions = 1
146 bin_wrapper.insert()
Nabin Haitac53b112013-01-11 19:25:46 +0530147
Anand Doshie9baaa62014-02-26 12:35:33 +0530148 frappe.db.sql("""update `tabBin` set valuation_rate=%s, actual_qty=%s,
Anand Doshi1b531862013-01-10 19:29:51 +0530149 stock_value=%s,
Nabin Hait902e8602013-01-08 18:29:24 +0530150 projected_qty = (actual_qty + indented_qty + ordered_qty + planned_qty - reserved_qty)
151 where item_code=%s and warehouse=%s""", (valuation_rate, qty_after_transaction,
152 stock_value, args["item_code"], args["warehouse"]))
153
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530154def get_sle_before_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530155 """
156 get previous stock ledger entry before current time-bucket
157
158 Details:
159 get the last sle before the current time-bucket, so that all values
160 are reposted from the current time-bucket onwards.
161 this is necessary because at the time of cancellation, there may be
162 entries between the cancelled entries in the same time-bucket
163 """
164 sle = get_stock_ledger_entries(args,
Nabin Hait26d46552013-01-09 15:23:05 +0530165 ["timestamp(posting_date, posting_time) < timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530166 "desc", "limit 1", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530167
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530168 return sle and sle[0] or frappe._dict()
Nabin Hait902e8602013-01-08 18:29:24 +0530169
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530170def get_sle_after_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530171 """get Stock Ledger Entries after a particular datetime, for reposting"""
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530172 # NOTE: using for update of
Nabin Hait902e8602013-01-08 18:29:24 +0530173 return get_stock_ledger_entries(args,
Nabin Hait9514d172013-01-10 10:40:37 +0530174 ["timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530175 "asc", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530176
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530177def get_stock_ledger_entries(args, conditions=None, order="desc", limit=None, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530178 """get stock ledger entries filtered by specific posting datetime conditions"""
179 if not args.get("posting_date"):
180 args["posting_date"] = "1900-01-01"
181 if not args.get("posting_time"):
Anand Doshi71bed312013-03-13 12:57:04 +0530182 args["posting_time"] = "00:00"
Nabin Hait902e8602013-01-08 18:29:24 +0530183
Anand Doshie9baaa62014-02-26 12:35:33 +0530184 return frappe.db.sql("""select * from `tabStock Ledger Entry`
Nabin Hait902e8602013-01-08 18:29:24 +0530185 where item_code = %%(item_code)s
186 and warehouse = %%(warehouse)s
Nabin Haitbb777562013-08-29 18:19:37 +0530187 and ifnull(is_cancelled, 'No')='No'
Nabin Hait902e8602013-01-08 18:29:24 +0530188 %(conditions)s
Nabin Hait9514d172013-01-10 10:40:37 +0530189 order by timestamp(posting_date, posting_time) %(order)s, name %(order)s
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530190 %(limit)s %(for_update)s""" % {
Nabin Hait902e8602013-01-08 18:29:24 +0530191 "conditions": conditions and ("and " + " and ".join(conditions)) or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530192 "limit": limit or "",
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530193 "for_update": for_update and "for update" or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530194 "order": order
Nabin Hait902e8602013-01-08 18:29:24 +0530195 }, args, as_dict=1)
196
197def validate_negative_stock(qty_after_transaction, sle):
198 """
199 validate negative stock for entries current datetime onwards
200 will not consider cancelled entries
201 """
202 diff = qty_after_transaction + flt(sle.actual_qty)
Pratik Vyas16371b72013-09-18 18:31:03 +0530203
204 if not _exceptions:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530205 frappe.local.stockledger_exceptions = []
Nabin Hait902e8602013-01-08 18:29:24 +0530206
207 if diff < 0 and abs(diff) > 0.0001:
208 # negative stock!
Nabin Hait902e8602013-01-08 18:29:24 +0530209 exc = sle.copy().update({"diff": diff})
210 _exceptions.append(exc)
211 return False
212 else:
213 return True
214
215def get_serialized_values(qty_after_transaction, sle, valuation_rate):
216 incoming_rate = flt(sle.incoming_rate)
217 actual_qty = flt(sle.actual_qty)
Anand Doshi1b531862013-01-10 19:29:51 +0530218 serial_no = cstr(sle.serial_no).split("\n")
Nabin Hait902e8602013-01-08 18:29:24 +0530219
220 if incoming_rate < 0:
221 # wrong incoming rate
222 incoming_rate = valuation_rate
223 elif incoming_rate == 0 or flt(sle.actual_qty) < 0:
224 # In case of delivery/stock issue, get average purchase rate
225 # of serial nos of current entry
Anand Doshie9baaa62014-02-26 12:35:33 +0530226 incoming_rate = flt(frappe.db.sql("""select avg(ifnull(purchase_rate, 0))
Anand Doshi1b531862013-01-10 19:29:51 +0530227 from `tabSerial No` where name in (%s)""" % (", ".join(["%s"]*len(serial_no))),
228 tuple(serial_no))[0][0])
Nabin Hait902e8602013-01-08 18:29:24 +0530229
230 if incoming_rate and not valuation_rate:
231 valuation_rate = incoming_rate
232 else:
233 new_stock_qty = qty_after_transaction + actual_qty
234 if new_stock_qty > 0:
235 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
236 if new_stock_value > 0:
237 # calculate new valuation rate only if stock value is positive
238 # else it remains the same as that of previous entry
239 valuation_rate = new_stock_value / new_stock_qty
Anand Doshi1b531862013-01-10 19:29:51 +0530240
Nabin Hait914c6df2013-01-14 13:15:42 +0530241 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530242
243def get_moving_average_values(qty_after_transaction, sle, valuation_rate):
244 incoming_rate = flt(sle.incoming_rate)
Nabin Hait914c6df2013-01-14 13:15:42 +0530245 actual_qty = flt(sle.actual_qty)
Nabin Hait902e8602013-01-08 18:29:24 +0530246
Anand Doshi1b531862013-01-10 19:29:51 +0530247 if not incoming_rate:
Nabin Hait902e8602013-01-08 18:29:24 +0530248 # In case of delivery/stock issue in_rate = 0 or wrong incoming rate
249 incoming_rate = valuation_rate
250
Anand Doshi1b531862013-01-10 19:29:51 +0530251 elif qty_after_transaction < 0:
252 # if negative stock, take current valuation rate as incoming rate
253 valuation_rate = incoming_rate
254
Nabin Hait902e8602013-01-08 18:29:24 +0530255 new_stock_qty = qty_after_transaction + actual_qty
256 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
Anand Doshi1b531862013-01-10 19:29:51 +0530257
258 if new_stock_qty > 0 and new_stock_value > 0:
Nabin Hait902e8602013-01-08 18:29:24 +0530259 valuation_rate = new_stock_value / flt(new_stock_qty)
260 elif new_stock_qty <= 0:
261 valuation_rate = 0.0
Anand Doshi1b531862013-01-10 19:29:51 +0530262
263 # NOTE: val_rate is same as previous entry if new stock value is negative
264
Nabin Hait914c6df2013-01-14 13:15:42 +0530265 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530266
267def get_fifo_values(qty_after_transaction, sle, stock_queue):
268 incoming_rate = flt(sle.incoming_rate)
269 actual_qty = flt(sle.actual_qty)
Nabin Hait902e8602013-01-08 18:29:24 +0530270 if not stock_queue:
271 stock_queue.append([0, 0])
Nabin Hait9514d172013-01-10 10:40:37 +0530272
Nabin Hait902e8602013-01-08 18:29:24 +0530273 if actual_qty > 0:
274 if stock_queue[-1][0] > 0:
275 stock_queue.append([actual_qty, incoming_rate])
276 else:
277 qty = stock_queue[-1][0] + actual_qty
278 stock_queue[-1] = [qty, qty > 0 and incoming_rate or 0]
279 else:
280 incoming_cost = 0
281 qty_to_pop = abs(actual_qty)
282 while qty_to_pop:
Nabin Hait9514d172013-01-10 10:40:37 +0530283 if not stock_queue:
284 stock_queue.append([0, 0])
285
Nabin Hait902e8602013-01-08 18:29:24 +0530286 batch = stock_queue[0]
287
288 if 0 < batch[0] <= qty_to_pop:
289 # if batch qty > 0
290 # not enough or exactly same qty in current batch, clear batch
291 incoming_cost += flt(batch[0]) * flt(batch[1])
292 qty_to_pop -= batch[0]
293 stock_queue.pop(0)
294 else:
295 # all from current batch
296 incoming_cost += flt(qty_to_pop) * flt(batch[1])
297 batch[0] -= qty_to_pop
298 qty_to_pop = 0
299
Nabin Hait902e8602013-01-08 18:29:24 +0530300 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
301 stock_qty = sum((flt(batch[0]) for batch in stock_queue))
302
303 valuation_rate = stock_qty and (stock_value / flt(stock_qty)) or 0
Nabin Hait9514d172013-01-10 10:40:37 +0530304
Nabin Hait914c6df2013-01-14 13:15:42 +0530305 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530306
Nabin Hait9514d172013-01-10 10:40:37 +0530307def _raise_exceptions(args, verbose=1):
Nabin Hait902e8602013-01-08 18:29:24 +0530308 deficiency = min(e["diff"] for e in _exceptions)
309 msg = """Negative stock error:
310 Cannot complete this transaction because stock will start
311 becoming negative (%s) for Item <b>%s</b> in Warehouse
312 <b>%s</b> on <b>%s %s</b> in Transaction %s %s.
313 Total Quantity Deficiency: <b>%s</b>""" % \
314 (_exceptions[0]["diff"], args.get("item_code"), args.get("warehouse"),
315 _exceptions[0]["posting_date"], _exceptions[0]["posting_time"],
316 _exceptions[0]["voucher_type"], _exceptions[0]["voucher_no"],
317 abs(deficiency))
318 if verbose:
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530319 msgprint(msg, raise_exception=NegativeStockError)
Nabin Hait902e8602013-01-08 18:29:24 +0530320 else:
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530321 raise NegativeStockError, msg
Anand Doshi1b531862013-01-10 19:29:51 +0530322
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530323def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530324 """
325 get the last sle on or before the current time-bucket,
326 to get actual qty before transaction, this function
327 is called from various transaction like stock entry, reco etc
328
329 args = {
330 "item_code": "ABC",
331 "warehouse": "XYZ",
332 "posting_date": "2012-12-12",
333 "posting_time": "12:00",
334 "sle": "name of reference Stock Ledger Entry"
335 }
336 """
337 if not args.get("sle"): args["sle"] = ""
338
339 sle = get_stock_ledger_entries(args, ["name != %(sle)s",
340 "timestamp(posting_date, posting_time) <= timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530341 "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530342 return sle and sle[0] or {}