blob: 1555dab0bd83f785dc7e3e6076d67164c9139f0e [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):
Nabin Haitca775742013-09-26 16:16:44 +053017 if sl_entries:
18 from stock.utils import update_bin
Nabin Hait9653f602013-08-20 15:37:33 +053019
Nabin Haitca775742013-09-26 16:16:44 +053020 cancel = True if sl_entries[0].get("is_cancelled") == "Yes" else False
21 if cancel:
22 set_as_cancel(sl_entries[0].get('voucher_no'), sl_entries[0].get('voucher_type'))
Nabin Hait9653f602013-08-20 15:37:33 +053023
Nabin Haitca775742013-09-26 16:16:44 +053024 for sle in sl_entries:
25 sle_id = None
26 if sle.get('is_cancelled') == 'Yes':
27 sle['actual_qty'] = -flt(sle['actual_qty'])
Nabin Hait9653f602013-08-20 15:37:33 +053028
Nabin Haitca775742013-09-26 16:16:44 +053029 if sle.get("actual_qty"):
30 sle_id = make_entry(sle)
Nabin Hait74c281c2013-08-19 16:17:18 +053031
Nabin Haitca775742013-09-26 16:16:44 +053032 args = sle.copy()
33 args.update({
34 "sle_id": sle_id,
35 "is_amended": is_amended
36 })
37 update_bin(args)
Nabin Hait74c281c2013-08-19 16:17:18 +053038
Nabin Haitca775742013-09-26 16:16:44 +053039 if cancel:
40 delete_cancelled_entry(sl_entries[0].get('voucher_type'),
41 sl_entries[0].get('voucher_no'))
Nabin Hait9653f602013-08-20 15:37:33 +053042
43def set_as_cancel(voucher_type, voucher_no):
44 webnotes.conn.sql("""update `tabStock Ledger Entry` set is_cancelled='Yes',
45 modified=%s, modified_by=%s
46 where voucher_no=%s and voucher_type=%s""",
47 (now(), webnotes.session.user, voucher_type, voucher_no))
48
Nabin Hait74c281c2013-08-19 16:17:18 +053049def make_entry(args):
50 args.update({"doctype": "Stock Ledger Entry"})
51 sle = webnotes.bean([args])
52 sle.ignore_permissions = 1
53 sle.insert()
Nabin Haitaeba24e2013-08-23 15:17:36 +053054 sle.submit()
Nabin Hait74c281c2013-08-19 16:17:18 +053055 return sle.doc.name
Nabin Hait9653f602013-08-20 15:37:33 +053056
57def delete_cancelled_entry(voucher_type, voucher_no):
58 webnotes.conn.sql("""delete from `tabStock Ledger Entry`
59 where voucher_type=%s and voucher_no=%s""", (voucher_type, voucher_no))
Nabin Hait74c281c2013-08-19 16:17:18 +053060
Nabin Hait902e8602013-01-08 18:29:24 +053061def update_entries_after(args, verbose=1):
62 """
63 update valution rate and qty after transaction
64 from the current time-bucket onwards
65
66 args = {
67 "item_code": "ABC",
68 "warehouse": "XYZ",
69 "posting_date": "2012-12-12",
70 "posting_time": "12:00"
71 }
72 """
Pratik Vyas16371b72013-09-18 18:31:03 +053073 if not _exceptions:
74 webnotes.local.stockledger_exceptions = []
Nabin Haitf4591ec2013-05-23 19:07:10 +053075
Nabin Hait902e8602013-01-08 18:29:24 +053076 previous_sle = get_sle_before_datetime(args)
Anand Doshi71bed312013-03-13 12:57:04 +053077
Nabin Hait902e8602013-01-08 18:29:24 +053078 qty_after_transaction = flt(previous_sle.get("qty_after_transaction"))
79 valuation_rate = flt(previous_sle.get("valuation_rate"))
80 stock_queue = json.loads(previous_sle.get("stock_queue") or "[]")
Nabin Hait27994c22013-08-26 16:53:30 +053081 stock_value = flt(previous_sle.get("stock_value"))
82 prev_stock_value = flt(previous_sle.get("stock_value"))
83
Nabin Hait902e8602013-01-08 18:29:24 +053084 entries_to_fix = get_sle_after_datetime(previous_sle or \
Anand Doshi4dc7caa2013-01-11 11:44:49 +053085 {"item_code": args["item_code"], "warehouse": args["warehouse"]}, for_update=True)
Nabin Hait469ee712013-08-07 12:33:37 +053086
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 Doshi1b531862013-01-10 19:29:51 +053091 if sle.serial_no or not cint(webnotes.conn.get_default("allow_negative_stock")):
Nabin Hait902e8602013-01-08 18:29:24 +053092 # validate negative stock for serialized items, fifo valuation
93 # 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
Anand Doshi1b531862013-01-10 19:29:51 +053098 if sle.serial_no:
Nabin Hait1b4f56c2013-01-17 17:01:51 +053099 valuation_rate = get_serialized_values(qty_after_transaction, sle, valuation_rate)
Nabin Hait902e8602013-01-08 18:29:24 +0530100 elif valuation_method == "Moving Average":
Nabin Hait1b4f56c2013-01-17 17:01:51 +0530101 valuation_rate = get_moving_average_values(qty_after_transaction, sle, valuation_rate)
Nabin Hait902e8602013-01-08 18:29:24 +0530102 else:
Nabin Hait1b4f56c2013-01-17 17:01:51 +0530103 valuation_rate = get_fifo_values(qty_after_transaction, sle, stock_queue)
Anand Doshi1b531862013-01-10 19:29:51 +0530104
Nabin Hait902e8602013-01-08 18:29:24 +0530105 qty_after_transaction += flt(sle.actual_qty)
106
107 # get stock value
Anand Doshi1b531862013-01-10 19:29:51 +0530108 if sle.serial_no:
Nabin Hait902e8602013-01-08 18:29:24 +0530109 stock_value = qty_after_transaction * valuation_rate
110 elif valuation_method == "Moving Average":
111 stock_value = (qty_after_transaction > 0) and \
112 (qty_after_transaction * valuation_rate) or 0
113 else:
114 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
Nabin Hait815a49e2013-08-07 17:00:01 +0530115
Nabin Haitaeba24e2013-08-23 15:17:36 +0530116 stock_value_difference = stock_value - prev_stock_value
117 prev_stock_value = stock_value
118
Nabin Hait902e8602013-01-08 18:29:24 +0530119 # update current sle
120 webnotes.conn.sql("""update `tabStock Ledger Entry`
Anand Doshi1b531862013-01-10 19:29:51 +0530121 set qty_after_transaction=%s, valuation_rate=%s, stock_queue=%s,
Nabin Haitaeba24e2013-08-23 15:17:36 +0530122 stock_value=%s, stock_value_difference=%s where name=%s""",
Anand Doshi1b531862013-01-10 19:29:51 +0530123 (qty_after_transaction, valuation_rate,
Nabin Haitaeba24e2013-08-23 15:17:36 +0530124 json.dumps(stock_queue), stock_value, stock_value_difference, sle.name))
Anand Doshi1b531862013-01-10 19:29:51 +0530125
Nabin Hait902e8602013-01-08 18:29:24 +0530126 if _exceptions:
Nabin Hait9514d172013-01-10 10:40:37 +0530127 _raise_exceptions(args, verbose)
Nabin Hait902e8602013-01-08 18:29:24 +0530128
129 # update bin
Nabin Haitac53b112013-01-11 19:25:46 +0530130 if not webnotes.conn.exists({"doctype": "Bin", "item_code": args["item_code"],
131 "warehouse": args["warehouse"]}):
Rushabh Mehtac53231a2013-02-18 18:24:28 +0530132 bin_wrapper = webnotes.bean([{
Nabin Haitac53b112013-01-11 19:25:46 +0530133 "doctype": "Bin",
134 "item_code": args["item_code"],
135 "warehouse": args["warehouse"],
Anand Doshic313d662013-01-14 15:46:17 +0530136 }])
137 bin_wrapper.ignore_permissions = 1
138 bin_wrapper.insert()
Nabin Haitac53b112013-01-11 19:25:46 +0530139
Anand Doshi1b531862013-01-10 19:29:51 +0530140 webnotes.conn.sql("""update `tabBin` set valuation_rate=%s, actual_qty=%s,
141 stock_value=%s,
Nabin Hait902e8602013-01-08 18:29:24 +0530142 projected_qty = (actual_qty + indented_qty + ordered_qty + planned_qty - reserved_qty)
143 where item_code=%s and warehouse=%s""", (valuation_rate, qty_after_transaction,
144 stock_value, args["item_code"], args["warehouse"]))
145
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530146def get_sle_before_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530147 """
148 get previous stock ledger entry before current time-bucket
149
150 Details:
151 get the last sle before the current time-bucket, so that all values
152 are reposted from the current time-bucket onwards.
153 this is necessary because at the time of cancellation, there may be
154 entries between the cancelled entries in the same time-bucket
155 """
156 sle = get_stock_ledger_entries(args,
Nabin Hait26d46552013-01-09 15:23:05 +0530157 ["timestamp(posting_date, posting_time) < timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530158 "desc", "limit 1", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530159
160 return sle and sle[0] or webnotes._dict()
161
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530162def get_sle_after_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530163 """get Stock Ledger Entries after a particular datetime, for reposting"""
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530164 # NOTE: using for update of
Nabin Hait902e8602013-01-08 18:29:24 +0530165 return get_stock_ledger_entries(args,
Nabin Hait9514d172013-01-10 10:40:37 +0530166 ["timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530167 "asc", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530168
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530169def get_stock_ledger_entries(args, conditions=None, order="desc", limit=None, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530170 """get stock ledger entries filtered by specific posting datetime conditions"""
171 if not args.get("posting_date"):
172 args["posting_date"] = "1900-01-01"
173 if not args.get("posting_time"):
Anand Doshi71bed312013-03-13 12:57:04 +0530174 args["posting_time"] = "00:00"
Nabin Hait902e8602013-01-08 18:29:24 +0530175
176 return webnotes.conn.sql("""select * from `tabStock Ledger Entry`
177 where item_code = %%(item_code)s
178 and warehouse = %%(warehouse)s
Nabin Haitbb777562013-08-29 18:19:37 +0530179 and ifnull(is_cancelled, 'No')='No'
Nabin Hait902e8602013-01-08 18:29:24 +0530180 %(conditions)s
Nabin Hait9514d172013-01-10 10:40:37 +0530181 order by timestamp(posting_date, posting_time) %(order)s, name %(order)s
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530182 %(limit)s %(for_update)s""" % {
Nabin Hait902e8602013-01-08 18:29:24 +0530183 "conditions": conditions and ("and " + " and ".join(conditions)) or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530184 "limit": limit or "",
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530185 "for_update": for_update and "for update" or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530186 "order": order
Nabin Hait902e8602013-01-08 18:29:24 +0530187 }, args, as_dict=1)
188
189def validate_negative_stock(qty_after_transaction, sle):
190 """
191 validate negative stock for entries current datetime onwards
192 will not consider cancelled entries
193 """
194 diff = qty_after_transaction + flt(sle.actual_qty)
Pratik Vyas16371b72013-09-18 18:31:03 +0530195
196 if not _exceptions:
197 webnotes.local.stockledger_exceptions = []
Nabin Hait902e8602013-01-08 18:29:24 +0530198
199 if diff < 0 and abs(diff) > 0.0001:
200 # negative stock!
Nabin Hait902e8602013-01-08 18:29:24 +0530201 exc = sle.copy().update({"diff": diff})
202 _exceptions.append(exc)
203 return False
204 else:
205 return True
206
207def get_serialized_values(qty_after_transaction, sle, valuation_rate):
208 incoming_rate = flt(sle.incoming_rate)
209 actual_qty = flt(sle.actual_qty)
Anand Doshi1b531862013-01-10 19:29:51 +0530210 serial_no = cstr(sle.serial_no).split("\n")
Nabin Hait902e8602013-01-08 18:29:24 +0530211
212 if incoming_rate < 0:
213 # wrong incoming rate
214 incoming_rate = valuation_rate
215 elif incoming_rate == 0 or flt(sle.actual_qty) < 0:
216 # In case of delivery/stock issue, get average purchase rate
217 # of serial nos of current entry
218 incoming_rate = flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0))
Anand Doshi1b531862013-01-10 19:29:51 +0530219 from `tabSerial No` where name in (%s)""" % (", ".join(["%s"]*len(serial_no))),
220 tuple(serial_no))[0][0])
Nabin Hait902e8602013-01-08 18:29:24 +0530221
222 if incoming_rate and not valuation_rate:
223 valuation_rate = incoming_rate
224 else:
225 new_stock_qty = qty_after_transaction + actual_qty
226 if new_stock_qty > 0:
227 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
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 valuation_rate = new_stock_value / new_stock_qty
Anand Doshi1b531862013-01-10 19:29:51 +0530232
Nabin Hait914c6df2013-01-14 13:15:42 +0530233 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530234
235def get_moving_average_values(qty_after_transaction, sle, valuation_rate):
236 incoming_rate = flt(sle.incoming_rate)
Nabin Hait914c6df2013-01-14 13:15:42 +0530237 actual_qty = flt(sle.actual_qty)
Nabin Hait902e8602013-01-08 18:29:24 +0530238
Anand Doshi1b531862013-01-10 19:29:51 +0530239 if not incoming_rate:
Nabin Hait902e8602013-01-08 18:29:24 +0530240 # In case of delivery/stock issue in_rate = 0 or wrong incoming rate
241 incoming_rate = valuation_rate
242
Anand Doshi1b531862013-01-10 19:29:51 +0530243 elif qty_after_transaction < 0:
244 # if negative stock, take current valuation rate as incoming rate
245 valuation_rate = incoming_rate
246
Nabin Hait902e8602013-01-08 18:29:24 +0530247 new_stock_qty = qty_after_transaction + actual_qty
248 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
Anand Doshi1b531862013-01-10 19:29:51 +0530249
250 if new_stock_qty > 0 and new_stock_value > 0:
Nabin Hait902e8602013-01-08 18:29:24 +0530251 valuation_rate = new_stock_value / flt(new_stock_qty)
252 elif new_stock_qty <= 0:
253 valuation_rate = 0.0
Anand Doshi1b531862013-01-10 19:29:51 +0530254
255 # NOTE: val_rate is same as previous entry if new stock value is negative
256
Nabin Hait914c6df2013-01-14 13:15:42 +0530257 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530258
259def get_fifo_values(qty_after_transaction, sle, stock_queue):
260 incoming_rate = flt(sle.incoming_rate)
261 actual_qty = flt(sle.actual_qty)
Nabin Hait902e8602013-01-08 18:29:24 +0530262 if not stock_queue:
263 stock_queue.append([0, 0])
Nabin Hait9514d172013-01-10 10:40:37 +0530264
Nabin Hait902e8602013-01-08 18:29:24 +0530265 if actual_qty > 0:
266 if stock_queue[-1][0] > 0:
267 stock_queue.append([actual_qty, incoming_rate])
268 else:
269 qty = stock_queue[-1][0] + actual_qty
270 stock_queue[-1] = [qty, qty > 0 and incoming_rate or 0]
271 else:
272 incoming_cost = 0
273 qty_to_pop = abs(actual_qty)
274 while qty_to_pop:
Nabin Hait9514d172013-01-10 10:40:37 +0530275 if not stock_queue:
276 stock_queue.append([0, 0])
277
Nabin Hait902e8602013-01-08 18:29:24 +0530278 batch = stock_queue[0]
279
280 if 0 < batch[0] <= qty_to_pop:
281 # if batch qty > 0
282 # not enough or exactly same qty in current batch, clear batch
283 incoming_cost += flt(batch[0]) * flt(batch[1])
284 qty_to_pop -= batch[0]
285 stock_queue.pop(0)
286 else:
287 # all from current batch
288 incoming_cost += flt(qty_to_pop) * flt(batch[1])
289 batch[0] -= qty_to_pop
290 qty_to_pop = 0
291
Nabin Hait902e8602013-01-08 18:29:24 +0530292 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
293 stock_qty = sum((flt(batch[0]) for batch in stock_queue))
294
295 valuation_rate = stock_qty and (stock_value / flt(stock_qty)) or 0
Nabin Hait9514d172013-01-10 10:40:37 +0530296
Nabin Hait914c6df2013-01-14 13:15:42 +0530297 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530298
Nabin Hait9514d172013-01-10 10:40:37 +0530299def _raise_exceptions(args, verbose=1):
Nabin Hait902e8602013-01-08 18:29:24 +0530300 deficiency = min(e["diff"] for e in _exceptions)
301 msg = """Negative stock error:
302 Cannot complete this transaction because stock will start
303 becoming negative (%s) for Item <b>%s</b> in Warehouse
304 <b>%s</b> on <b>%s %s</b> in Transaction %s %s.
305 Total Quantity Deficiency: <b>%s</b>""" % \
306 (_exceptions[0]["diff"], args.get("item_code"), args.get("warehouse"),
307 _exceptions[0]["posting_date"], _exceptions[0]["posting_time"],
308 _exceptions[0]["voucher_type"], _exceptions[0]["voucher_no"],
309 abs(deficiency))
310 if verbose:
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530311 msgprint(msg, raise_exception=NegativeStockError)
Nabin Hait902e8602013-01-08 18:29:24 +0530312 else:
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530313 raise NegativeStockError, msg
Anand Doshi1b531862013-01-10 19:29:51 +0530314
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530315def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530316 """
317 get the last sle on or before the current time-bucket,
318 to get actual qty before transaction, this function
319 is called from various transaction like stock entry, reco etc
320
321 args = {
322 "item_code": "ABC",
323 "warehouse": "XYZ",
324 "posting_date": "2012-12-12",
325 "posting_time": "12:00",
326 "sle": "name of reference Stock Ledger Entry"
327 }
328 """
329 if not args.get("sle"): args["sle"] = ""
330
331 sle = get_stock_ledger_entries(args, ["name != %(sle)s",
332 "timestamp(posting_date, posting_time) <= timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530333 "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530334 return sle and sle[0] or {}