blob: fe5b685f444fb6657b3cc373173446dd4d9c4ed8 [file] [log] [blame]
Rushabh Mehtae67d1fb2013-08-05 14:59:54 +05301# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
2# License: GNU General Public License v3. See license.txt
Nabin Hait902e8602013-01-08 18:29:24 +05303
4import webnotes
Anand Doshi1b531862013-01-10 19:29:51 +05305from webnotes import msgprint
Nabin Hait74c281c2013-08-19 16:17:18 +05306from webnotes.utils import cint, flt, cstr, now
Anand Doshi1b531862013-01-10 19:29:51 +05307from stock.utils import get_valuation_method
Nabin Hait26d46552013-01-09 15:23:05 +05308import json
Nabin Hait902e8602013-01-08 18:29:24 +05309
10# future reposting
Rushabh Mehta4c17f942013-08-12 14:18:09 +053011class NegativeStockError(webnotes.ValidationError): pass
Nabin Hait902e8602013-01-08 18:29:24 +053012
Pratik Vyas16371b72013-09-18 18:31:03 +053013_exceptions = webnotes.local('stockledger_exceptions')
Pratik Vyas16371b72013-09-18 18:31:03 +053014# _exceptions = []
Anand Doshi5b004ff2013-09-25 19:55:41 +053015
Nabin Hait74c281c2013-08-19 16:17:18 +053016def make_sl_entries(sl_entries, is_amended=None):
17 from stock.utils import update_bin
Nabin Hait9653f602013-08-20 15:37:33 +053018
19 cancel = True if sl_entries[0].get("is_cancelled") == "Yes" else False
20 if cancel:
21 set_as_cancel(sl_entries[0].get('voucher_no'), sl_entries[0].get('voucher_type'))
22
Nabin Hait74c281c2013-08-19 16:17:18 +053023 for sle in sl_entries:
Nabin Hait9653f602013-08-20 15:37:33 +053024 sle_id = None
25 if sle.get('is_cancelled') == 'Yes':
26 sle['actual_qty'] = -flt(sle['actual_qty'])
27
Nabin Hait74c281c2013-08-19 16:17:18 +053028 if sle.get("actual_qty"):
29 sle_id = make_entry(sle)
30
31 args = sle.copy()
32 args.update({
33 "sle_id": sle_id,
34 "is_amended": is_amended
35 })
36 update_bin(args)
37
Nabin Hait9653f602013-08-20 15:37:33 +053038 if cancel:
Nabin Hait27994c22013-08-26 16:53:30 +053039 delete_cancelled_entry(sl_entries[0].get('voucher_type'), sl_entries[0].get('voucher_no'))
Nabin Hait9653f602013-08-20 15:37:33 +053040
41def set_as_cancel(voucher_type, voucher_no):
42 webnotes.conn.sql("""update `tabStock Ledger Entry` set is_cancelled='Yes',
43 modified=%s, modified_by=%s
44 where voucher_no=%s and voucher_type=%s""",
45 (now(), webnotes.session.user, voucher_type, voucher_no))
46
Nabin Hait74c281c2013-08-19 16:17:18 +053047def make_entry(args):
48 args.update({"doctype": "Stock Ledger Entry"})
49 sle = webnotes.bean([args])
50 sle.ignore_permissions = 1
51 sle.insert()
Nabin Haitaeba24e2013-08-23 15:17:36 +053052 sle.submit()
Nabin Hait74c281c2013-08-19 16:17:18 +053053 return sle.doc.name
Nabin Hait9653f602013-08-20 15:37:33 +053054
55def delete_cancelled_entry(voucher_type, voucher_no):
56 webnotes.conn.sql("""delete from `tabStock Ledger Entry`
57 where voucher_type=%s and voucher_no=%s""", (voucher_type, voucher_no))
Nabin Hait74c281c2013-08-19 16:17:18 +053058
Nabin Hait902e8602013-01-08 18:29:24 +053059def update_entries_after(args, verbose=1):
60 """
61 update valution rate and qty after transaction
62 from the current time-bucket onwards
63
64 args = {
65 "item_code": "ABC",
66 "warehouse": "XYZ",
67 "posting_date": "2012-12-12",
68 "posting_time": "12:00"
69 }
70 """
Pratik Vyas16371b72013-09-18 18:31:03 +053071 if not _exceptions:
72 webnotes.local.stockledger_exceptions = []
Nabin Haitf4591ec2013-05-23 19:07:10 +053073
Nabin Hait902e8602013-01-08 18:29:24 +053074 previous_sle = get_sle_before_datetime(args)
Anand Doshi71bed312013-03-13 12:57:04 +053075
Nabin Hait902e8602013-01-08 18:29:24 +053076 qty_after_transaction = flt(previous_sle.get("qty_after_transaction"))
77 valuation_rate = flt(previous_sle.get("valuation_rate"))
78 stock_queue = json.loads(previous_sle.get("stock_queue") or "[]")
Nabin Hait27994c22013-08-26 16:53:30 +053079 stock_value = flt(previous_sle.get("stock_value"))
80 prev_stock_value = flt(previous_sle.get("stock_value"))
81
Nabin Hait902e8602013-01-08 18:29:24 +053082 entries_to_fix = get_sle_after_datetime(previous_sle or \
Anand Doshi4dc7caa2013-01-11 11:44:49 +053083 {"item_code": args["item_code"], "warehouse": args["warehouse"]}, for_update=True)
Nabin Hait469ee712013-08-07 12:33:37 +053084
Nabin Hait902e8602013-01-08 18:29:24 +053085 valuation_method = get_valuation_method(args["item_code"])
Nabin Haitaeba24e2013-08-23 15:17:36 +053086 stock_value_difference = 0.0
Nabin Haitbb777562013-08-29 18:19:37 +053087
Nabin Hait902e8602013-01-08 18:29:24 +053088 for sle in entries_to_fix:
Anand Doshi1b531862013-01-10 19:29:51 +053089 if sle.serial_no or not cint(webnotes.conn.get_default("allow_negative_stock")):
Nabin Hait902e8602013-01-08 18:29:24 +053090 # validate negative stock for serialized items, fifo valuation
91 # or when negative stock is not allowed for moving average
92 if not validate_negative_stock(qty_after_transaction, sle):
93 qty_after_transaction += flt(sle.actual_qty)
94 continue
Nabin Haitbb777562013-08-29 18:19:37 +053095
Anand Doshi1b531862013-01-10 19:29:51 +053096 if sle.serial_no:
Nabin Hait1b4f56c2013-01-17 17:01:51 +053097 valuation_rate = get_serialized_values(qty_after_transaction, sle, valuation_rate)
Nabin Hait902e8602013-01-08 18:29:24 +053098 elif valuation_method == "Moving Average":
Nabin Hait1b4f56c2013-01-17 17:01:51 +053099 valuation_rate = get_moving_average_values(qty_after_transaction, sle, valuation_rate)
Nabin Hait902e8602013-01-08 18:29:24 +0530100 else:
Nabin Hait1b4f56c2013-01-17 17:01:51 +0530101 valuation_rate = get_fifo_values(qty_after_transaction, sle, stock_queue)
Anand Doshi1b531862013-01-10 19:29:51 +0530102
Nabin Hait902e8602013-01-08 18:29:24 +0530103 qty_after_transaction += flt(sle.actual_qty)
104
105 # get stock value
Anand Doshi1b531862013-01-10 19:29:51 +0530106 if sle.serial_no:
Nabin Hait902e8602013-01-08 18:29:24 +0530107 stock_value = qty_after_transaction * valuation_rate
108 elif valuation_method == "Moving Average":
109 stock_value = (qty_after_transaction > 0) and \
110 (qty_after_transaction * valuation_rate) or 0
111 else:
112 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
Nabin Hait815a49e2013-08-07 17:00:01 +0530113
Nabin Haitaeba24e2013-08-23 15:17:36 +0530114 stock_value_difference = stock_value - prev_stock_value
115 prev_stock_value = stock_value
116
Nabin Hait902e8602013-01-08 18:29:24 +0530117 # update current sle
118 webnotes.conn.sql("""update `tabStock Ledger Entry`
Anand Doshi1b531862013-01-10 19:29:51 +0530119 set qty_after_transaction=%s, valuation_rate=%s, stock_queue=%s,
Nabin Haitaeba24e2013-08-23 15:17:36 +0530120 stock_value=%s, stock_value_difference=%s where name=%s""",
Anand Doshi1b531862013-01-10 19:29:51 +0530121 (qty_after_transaction, valuation_rate,
Nabin Haitaeba24e2013-08-23 15:17:36 +0530122 json.dumps(stock_queue), stock_value, stock_value_difference, sle.name))
Anand Doshi1b531862013-01-10 19:29:51 +0530123
Nabin Hait902e8602013-01-08 18:29:24 +0530124 if _exceptions:
Nabin Hait9514d172013-01-10 10:40:37 +0530125 _raise_exceptions(args, verbose)
Nabin Hait902e8602013-01-08 18:29:24 +0530126
127 # update bin
Nabin Haitac53b112013-01-11 19:25:46 +0530128 if not webnotes.conn.exists({"doctype": "Bin", "item_code": args["item_code"],
129 "warehouse": args["warehouse"]}):
Rushabh Mehtac53231a2013-02-18 18:24:28 +0530130 bin_wrapper = webnotes.bean([{
Nabin Haitac53b112013-01-11 19:25:46 +0530131 "doctype": "Bin",
132 "item_code": args["item_code"],
133 "warehouse": args["warehouse"],
Anand Doshic313d662013-01-14 15:46:17 +0530134 }])
135 bin_wrapper.ignore_permissions = 1
136 bin_wrapper.insert()
Nabin Haitac53b112013-01-11 19:25:46 +0530137
Anand Doshi1b531862013-01-10 19:29:51 +0530138 webnotes.conn.sql("""update `tabBin` set valuation_rate=%s, actual_qty=%s,
139 stock_value=%s,
Nabin Hait902e8602013-01-08 18:29:24 +0530140 projected_qty = (actual_qty + indented_qty + ordered_qty + planned_qty - reserved_qty)
141 where item_code=%s and warehouse=%s""", (valuation_rate, qty_after_transaction,
142 stock_value, args["item_code"], args["warehouse"]))
143
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530144def get_sle_before_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530145 """
146 get previous stock ledger entry before current time-bucket
147
148 Details:
149 get the last sle before the current time-bucket, so that all values
150 are reposted from the current time-bucket onwards.
151 this is necessary because at the time of cancellation, there may be
152 entries between the cancelled entries in the same time-bucket
153 """
154 sle = get_stock_ledger_entries(args,
Nabin Hait26d46552013-01-09 15:23:05 +0530155 ["timestamp(posting_date, posting_time) < timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530156 "desc", "limit 1", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530157
158 return sle and sle[0] or webnotes._dict()
159
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530160def get_sle_after_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530161 """get Stock Ledger Entries after a particular datetime, for reposting"""
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530162 # NOTE: using for update of
Nabin Hait902e8602013-01-08 18:29:24 +0530163 return get_stock_ledger_entries(args,
Nabin Hait9514d172013-01-10 10:40:37 +0530164 ["timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530165 "asc", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530166
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530167def get_stock_ledger_entries(args, conditions=None, order="desc", limit=None, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530168 """get stock ledger entries filtered by specific posting datetime conditions"""
169 if not args.get("posting_date"):
170 args["posting_date"] = "1900-01-01"
171 if not args.get("posting_time"):
Anand Doshi71bed312013-03-13 12:57:04 +0530172 args["posting_time"] = "00:00"
Nabin Hait902e8602013-01-08 18:29:24 +0530173
174 return webnotes.conn.sql("""select * from `tabStock Ledger Entry`
175 where item_code = %%(item_code)s
176 and warehouse = %%(warehouse)s
Nabin Haitbb777562013-08-29 18:19:37 +0530177 and ifnull(is_cancelled, 'No')='No'
Nabin Hait902e8602013-01-08 18:29:24 +0530178 %(conditions)s
Nabin Hait9514d172013-01-10 10:40:37 +0530179 order by timestamp(posting_date, posting_time) %(order)s, name %(order)s
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530180 %(limit)s %(for_update)s""" % {
Nabin Hait902e8602013-01-08 18:29:24 +0530181 "conditions": conditions and ("and " + " and ".join(conditions)) or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530182 "limit": limit or "",
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530183 "for_update": for_update and "for update" or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530184 "order": order
Nabin Hait902e8602013-01-08 18:29:24 +0530185 }, args, as_dict=1)
186
187def validate_negative_stock(qty_after_transaction, sle):
188 """
189 validate negative stock for entries current datetime onwards
190 will not consider cancelled entries
191 """
192 diff = qty_after_transaction + flt(sle.actual_qty)
Pratik Vyas16371b72013-09-18 18:31:03 +0530193
194 if not _exceptions:
195 webnotes.local.stockledger_exceptions = []
Nabin Hait902e8602013-01-08 18:29:24 +0530196
197 if diff < 0 and abs(diff) > 0.0001:
198 # negative stock!
Nabin Hait902e8602013-01-08 18:29:24 +0530199 exc = sle.copy().update({"diff": diff})
200 _exceptions.append(exc)
201 return False
202 else:
203 return True
204
205def get_serialized_values(qty_after_transaction, sle, valuation_rate):
206 incoming_rate = flt(sle.incoming_rate)
207 actual_qty = flt(sle.actual_qty)
Anand Doshi1b531862013-01-10 19:29:51 +0530208 serial_no = cstr(sle.serial_no).split("\n")
Nabin Hait902e8602013-01-08 18:29:24 +0530209
210 if incoming_rate < 0:
211 # wrong incoming rate
212 incoming_rate = valuation_rate
213 elif incoming_rate == 0 or flt(sle.actual_qty) < 0:
214 # In case of delivery/stock issue, get average purchase rate
215 # of serial nos of current entry
216 incoming_rate = flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0))
Anand Doshi1b531862013-01-10 19:29:51 +0530217 from `tabSerial No` where name in (%s)""" % (", ".join(["%s"]*len(serial_no))),
218 tuple(serial_no))[0][0])
Nabin Hait902e8602013-01-08 18:29:24 +0530219
220 if incoming_rate and not valuation_rate:
221 valuation_rate = incoming_rate
222 else:
223 new_stock_qty = qty_after_transaction + actual_qty
224 if new_stock_qty > 0:
225 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
226 if new_stock_value > 0:
227 # calculate new valuation rate only if stock value is positive
228 # else it remains the same as that of previous entry
229 valuation_rate = new_stock_value / new_stock_qty
Anand Doshi1b531862013-01-10 19:29:51 +0530230
Nabin Hait914c6df2013-01-14 13:15:42 +0530231 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530232
233def get_moving_average_values(qty_after_transaction, sle, valuation_rate):
234 incoming_rate = flt(sle.incoming_rate)
Nabin Hait914c6df2013-01-14 13:15:42 +0530235 actual_qty = flt(sle.actual_qty)
Nabin Hait902e8602013-01-08 18:29:24 +0530236
Anand Doshi1b531862013-01-10 19:29:51 +0530237 if not incoming_rate:
Nabin Hait902e8602013-01-08 18:29:24 +0530238 # In case of delivery/stock issue in_rate = 0 or wrong incoming rate
239 incoming_rate = valuation_rate
240
Anand Doshi1b531862013-01-10 19:29:51 +0530241 elif qty_after_transaction < 0:
242 # if negative stock, take current valuation rate as incoming rate
243 valuation_rate = incoming_rate
244
Nabin Hait902e8602013-01-08 18:29:24 +0530245 new_stock_qty = qty_after_transaction + actual_qty
246 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
Anand Doshi1b531862013-01-10 19:29:51 +0530247
248 if new_stock_qty > 0 and new_stock_value > 0:
Nabin Hait902e8602013-01-08 18:29:24 +0530249 valuation_rate = new_stock_value / flt(new_stock_qty)
250 elif new_stock_qty <= 0:
251 valuation_rate = 0.0
Anand Doshi1b531862013-01-10 19:29:51 +0530252
253 # NOTE: val_rate is same as previous entry if new stock value is negative
254
Nabin Hait914c6df2013-01-14 13:15:42 +0530255 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530256
257def get_fifo_values(qty_after_transaction, sle, stock_queue):
258 incoming_rate = flt(sle.incoming_rate)
259 actual_qty = flt(sle.actual_qty)
Nabin Hait902e8602013-01-08 18:29:24 +0530260 if not stock_queue:
261 stock_queue.append([0, 0])
Nabin Hait9514d172013-01-10 10:40:37 +0530262
Nabin Hait902e8602013-01-08 18:29:24 +0530263 if actual_qty > 0:
264 if stock_queue[-1][0] > 0:
265 stock_queue.append([actual_qty, incoming_rate])
266 else:
267 qty = stock_queue[-1][0] + actual_qty
268 stock_queue[-1] = [qty, qty > 0 and incoming_rate or 0]
269 else:
270 incoming_cost = 0
271 qty_to_pop = abs(actual_qty)
272 while qty_to_pop:
Nabin Hait9514d172013-01-10 10:40:37 +0530273 if not stock_queue:
274 stock_queue.append([0, 0])
275
Nabin Hait902e8602013-01-08 18:29:24 +0530276 batch = stock_queue[0]
277
278 if 0 < batch[0] <= qty_to_pop:
279 # if batch qty > 0
280 # not enough or exactly same qty in current batch, clear batch
281 incoming_cost += flt(batch[0]) * flt(batch[1])
282 qty_to_pop -= batch[0]
283 stock_queue.pop(0)
284 else:
285 # all from current batch
286 incoming_cost += flt(qty_to_pop) * flt(batch[1])
287 batch[0] -= qty_to_pop
288 qty_to_pop = 0
289
Nabin Hait902e8602013-01-08 18:29:24 +0530290 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
291 stock_qty = sum((flt(batch[0]) for batch in stock_queue))
292
293 valuation_rate = stock_qty and (stock_value / flt(stock_qty)) or 0
Nabin Hait9514d172013-01-10 10:40:37 +0530294
Nabin Hait914c6df2013-01-14 13:15:42 +0530295 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530296
Nabin Hait9514d172013-01-10 10:40:37 +0530297def _raise_exceptions(args, verbose=1):
Nabin Hait902e8602013-01-08 18:29:24 +0530298 deficiency = min(e["diff"] for e in _exceptions)
299 msg = """Negative stock error:
300 Cannot complete this transaction because stock will start
301 becoming negative (%s) for Item <b>%s</b> in Warehouse
302 <b>%s</b> on <b>%s %s</b> in Transaction %s %s.
303 Total Quantity Deficiency: <b>%s</b>""" % \
304 (_exceptions[0]["diff"], args.get("item_code"), args.get("warehouse"),
305 _exceptions[0]["posting_date"], _exceptions[0]["posting_time"],
306 _exceptions[0]["voucher_type"], _exceptions[0]["voucher_no"],
307 abs(deficiency))
308 if verbose:
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530309 msgprint(msg, raise_exception=NegativeStockError)
Nabin Hait902e8602013-01-08 18:29:24 +0530310 else:
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530311 raise NegativeStockError, msg
Anand Doshi1b531862013-01-10 19:29:51 +0530312
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530313def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530314 """
315 get the last sle on or before the current time-bucket,
316 to get actual qty before transaction, this function
317 is called from various transaction like stock entry, reco etc
318
319 args = {
320 "item_code": "ABC",
321 "warehouse": "XYZ",
322 "posting_date": "2012-12-12",
323 "posting_time": "12:00",
324 "sle": "name of reference Stock Ledger Entry"
325 }
326 """
327 if not args.get("sle"): args["sle"] = ""
328
329 sle = get_stock_ledger_entries(args, ["name != %(sle)s",
330 "timestamp(posting_date, posting_time) <= timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530331 "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530332 return sle and sle[0] or {}