blob: a3af5ade8180d6e1f637f589491358a4062812fc [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
Nabin Hait74c281c2013-08-19 16:17:18 +053013def make_sl_entries(sl_entries, is_amended=None):
14 from stock.utils import update_bin
Nabin Hait9653f602013-08-20 15:37:33 +053015
16 cancel = True if sl_entries[0].get("is_cancelled") == "Yes" else False
17 if cancel:
18 set_as_cancel(sl_entries[0].get('voucher_no'), sl_entries[0].get('voucher_type'))
19
Nabin Hait74c281c2013-08-19 16:17:18 +053020 for sle in sl_entries:
Nabin Hait9653f602013-08-20 15:37:33 +053021 sle_id = None
22 if sle.get('is_cancelled') == 'Yes':
23 sle['actual_qty'] = -flt(sle['actual_qty'])
24
Nabin Hait74c281c2013-08-19 16:17:18 +053025 if sle.get("actual_qty"):
26 sle_id = make_entry(sle)
27
28 args = sle.copy()
29 args.update({
30 "sle_id": sle_id,
31 "is_amended": is_amended
32 })
33 update_bin(args)
34
Nabin Hait9653f602013-08-20 15:37:33 +053035 if cancel:
Nabin Hait27994c22013-08-26 16:53:30 +053036 delete_cancelled_entry(sl_entries[0].get('voucher_type'), sl_entries[0].get('voucher_no'))
Nabin Hait9653f602013-08-20 15:37:33 +053037
38def set_as_cancel(voucher_type, voucher_no):
39 webnotes.conn.sql("""update `tabStock Ledger Entry` set is_cancelled='Yes',
40 modified=%s, modified_by=%s
41 where voucher_no=%s and voucher_type=%s""",
42 (now(), webnotes.session.user, voucher_type, voucher_no))
43
Nabin Hait74c281c2013-08-19 16:17:18 +053044def make_entry(args):
45 args.update({"doctype": "Stock Ledger Entry"})
46 sle = webnotes.bean([args])
47 sle.ignore_permissions = 1
48 sle.insert()
Nabin Haitaeba24e2013-08-23 15:17:36 +053049 sle.submit()
Nabin Hait74c281c2013-08-19 16:17:18 +053050 return sle.doc.name
Nabin Hait9653f602013-08-20 15:37:33 +053051
52def delete_cancelled_entry(voucher_type, voucher_no):
53 webnotes.conn.sql("""delete from `tabStock Ledger Entry`
54 where voucher_type=%s and voucher_no=%s""", (voucher_type, voucher_no))
Nabin Hait74c281c2013-08-19 16:17:18 +053055
Nabin Hait902e8602013-01-08 18:29:24 +053056_exceptions = []
57def update_entries_after(args, verbose=1):
58 """
59 update valution rate and qty after transaction
60 from the current time-bucket onwards
61
62 args = {
63 "item_code": "ABC",
64 "warehouse": "XYZ",
65 "posting_date": "2012-12-12",
66 "posting_time": "12:00"
67 }
68 """
Nabin Haitf4591ec2013-05-23 19:07:10 +053069 global _exceptions
70 _exceptions = []
71
Nabin Hait902e8602013-01-08 18:29:24 +053072 previous_sle = get_sle_before_datetime(args)
Anand Doshi71bed312013-03-13 12:57:04 +053073
Nabin Hait902e8602013-01-08 18:29:24 +053074 qty_after_transaction = flt(previous_sle.get("qty_after_transaction"))
75 valuation_rate = flt(previous_sle.get("valuation_rate"))
76 stock_queue = json.loads(previous_sle.get("stock_queue") or "[]")
Nabin Hait27994c22013-08-26 16:53:30 +053077 stock_value = flt(previous_sle.get("stock_value"))
78 prev_stock_value = flt(previous_sle.get("stock_value"))
79
Nabin Hait902e8602013-01-08 18:29:24 +053080 entries_to_fix = get_sle_after_datetime(previous_sle or \
Anand Doshi4dc7caa2013-01-11 11:44:49 +053081 {"item_code": args["item_code"], "warehouse": args["warehouse"]}, for_update=True)
Nabin Hait469ee712013-08-07 12:33:37 +053082
Nabin Hait902e8602013-01-08 18:29:24 +053083 valuation_method = get_valuation_method(args["item_code"])
Nabin Haitaeba24e2013-08-23 15:17:36 +053084 stock_value_difference = 0.0
Nabin Haitbb777562013-08-29 18:19:37 +053085
Nabin Hait902e8602013-01-08 18:29:24 +053086 for sle in entries_to_fix:
Anand Doshi1b531862013-01-10 19:29:51 +053087 if sle.serial_no or not cint(webnotes.conn.get_default("allow_negative_stock")):
Nabin Hait902e8602013-01-08 18:29:24 +053088 # validate negative stock for serialized items, fifo valuation
89 # or when negative stock is not allowed for moving average
90 if not validate_negative_stock(qty_after_transaction, sle):
91 qty_after_transaction += flt(sle.actual_qty)
92 continue
Nabin Haitbb777562013-08-29 18:19:37 +053093
Anand Doshi1b531862013-01-10 19:29:51 +053094 if sle.serial_no:
Nabin Hait1b4f56c2013-01-17 17:01:51 +053095 valuation_rate = get_serialized_values(qty_after_transaction, sle, valuation_rate)
Nabin Hait902e8602013-01-08 18:29:24 +053096 elif valuation_method == "Moving Average":
Nabin Hait1b4f56c2013-01-17 17:01:51 +053097 valuation_rate = get_moving_average_values(qty_after_transaction, sle, valuation_rate)
Nabin Hait902e8602013-01-08 18:29:24 +053098 else:
Nabin Hait1b4f56c2013-01-17 17:01:51 +053099 valuation_rate = get_fifo_values(qty_after_transaction, sle, stock_queue)
Anand Doshi1b531862013-01-10 19:29:51 +0530100
Nabin Hait902e8602013-01-08 18:29:24 +0530101 qty_after_transaction += flt(sle.actual_qty)
102
103 # get stock value
Anand Doshi1b531862013-01-10 19:29:51 +0530104 if sle.serial_no:
Nabin Hait902e8602013-01-08 18:29:24 +0530105 stock_value = qty_after_transaction * valuation_rate
106 elif valuation_method == "Moving Average":
107 stock_value = (qty_after_transaction > 0) and \
108 (qty_after_transaction * valuation_rate) or 0
109 else:
110 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
Nabin Hait815a49e2013-08-07 17:00:01 +0530111
Nabin Haitaeba24e2013-08-23 15:17:36 +0530112 stock_value_difference = stock_value - prev_stock_value
113 prev_stock_value = stock_value
114
Nabin Hait902e8602013-01-08 18:29:24 +0530115 # update current sle
116 webnotes.conn.sql("""update `tabStock Ledger Entry`
Anand Doshi1b531862013-01-10 19:29:51 +0530117 set qty_after_transaction=%s, valuation_rate=%s, stock_queue=%s,
Nabin Haitaeba24e2013-08-23 15:17:36 +0530118 stock_value=%s, stock_value_difference=%s where name=%s""",
Anand Doshi1b531862013-01-10 19:29:51 +0530119 (qty_after_transaction, valuation_rate,
Nabin Haitaeba24e2013-08-23 15:17:36 +0530120 json.dumps(stock_queue), stock_value, stock_value_difference, sle.name))
Anand Doshi1b531862013-01-10 19:29:51 +0530121
Nabin Hait902e8602013-01-08 18:29:24 +0530122 if _exceptions:
Nabin Hait9514d172013-01-10 10:40:37 +0530123 _raise_exceptions(args, verbose)
Nabin Hait902e8602013-01-08 18:29:24 +0530124
125 # update bin
Nabin Haitac53b112013-01-11 19:25:46 +0530126 if not webnotes.conn.exists({"doctype": "Bin", "item_code": args["item_code"],
127 "warehouse": args["warehouse"]}):
Rushabh Mehtac53231a2013-02-18 18:24:28 +0530128 bin_wrapper = webnotes.bean([{
Nabin Haitac53b112013-01-11 19:25:46 +0530129 "doctype": "Bin",
130 "item_code": args["item_code"],
131 "warehouse": args["warehouse"],
Anand Doshic313d662013-01-14 15:46:17 +0530132 }])
133 bin_wrapper.ignore_permissions = 1
134 bin_wrapper.insert()
Nabin Haitac53b112013-01-11 19:25:46 +0530135
Anand Doshi1b531862013-01-10 19:29:51 +0530136 webnotes.conn.sql("""update `tabBin` set valuation_rate=%s, actual_qty=%s,
137 stock_value=%s,
Nabin Hait902e8602013-01-08 18:29:24 +0530138 projected_qty = (actual_qty + indented_qty + ordered_qty + planned_qty - reserved_qty)
139 where item_code=%s and warehouse=%s""", (valuation_rate, qty_after_transaction,
140 stock_value, args["item_code"], args["warehouse"]))
141
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530142def get_sle_before_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530143 """
144 get previous stock ledger entry before current time-bucket
145
146 Details:
147 get the last sle before the current time-bucket, so that all values
148 are reposted from the current time-bucket onwards.
149 this is necessary because at the time of cancellation, there may be
150 entries between the cancelled entries in the same time-bucket
151 """
152 sle = get_stock_ledger_entries(args,
Nabin Hait26d46552013-01-09 15:23:05 +0530153 ["timestamp(posting_date, posting_time) < timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530154 "desc", "limit 1", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530155
156 return sle and sle[0] or webnotes._dict()
157
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530158def get_sle_after_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530159 """get Stock Ledger Entries after a particular datetime, for reposting"""
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530160 # NOTE: using for update of
Nabin Hait902e8602013-01-08 18:29:24 +0530161 return get_stock_ledger_entries(args,
Nabin Hait9514d172013-01-10 10:40:37 +0530162 ["timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530163 "asc", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530164
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530165def get_stock_ledger_entries(args, conditions=None, order="desc", limit=None, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530166 """get stock ledger entries filtered by specific posting datetime conditions"""
167 if not args.get("posting_date"):
168 args["posting_date"] = "1900-01-01"
169 if not args.get("posting_time"):
Anand Doshi71bed312013-03-13 12:57:04 +0530170 args["posting_time"] = "00:00"
Nabin Hait902e8602013-01-08 18:29:24 +0530171
172 return webnotes.conn.sql("""select * from `tabStock Ledger Entry`
173 where item_code = %%(item_code)s
174 and warehouse = %%(warehouse)s
Nabin Haitbb777562013-08-29 18:19:37 +0530175 and ifnull(is_cancelled, 'No')='No'
Nabin Hait902e8602013-01-08 18:29:24 +0530176 %(conditions)s
Nabin Hait9514d172013-01-10 10:40:37 +0530177 order by timestamp(posting_date, posting_time) %(order)s, name %(order)s
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530178 %(limit)s %(for_update)s""" % {
Nabin Hait902e8602013-01-08 18:29:24 +0530179 "conditions": conditions and ("and " + " and ".join(conditions)) or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530180 "limit": limit or "",
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530181 "for_update": for_update and "for update" or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530182 "order": order
Nabin Hait902e8602013-01-08 18:29:24 +0530183 }, args, as_dict=1)
184
185def validate_negative_stock(qty_after_transaction, sle):
186 """
187 validate negative stock for entries current datetime onwards
188 will not consider cancelled entries
189 """
190 diff = qty_after_transaction + flt(sle.actual_qty)
191
192 if diff < 0 and abs(diff) > 0.0001:
193 # negative stock!
194 global _exceptions
195 exc = sle.copy().update({"diff": diff})
196 _exceptions.append(exc)
197 return False
198 else:
199 return True
200
201def get_serialized_values(qty_after_transaction, sle, valuation_rate):
202 incoming_rate = flt(sle.incoming_rate)
203 actual_qty = flt(sle.actual_qty)
Anand Doshi1b531862013-01-10 19:29:51 +0530204 serial_no = cstr(sle.serial_no).split("\n")
Nabin Hait902e8602013-01-08 18:29:24 +0530205
206 if incoming_rate < 0:
207 # wrong incoming rate
208 incoming_rate = valuation_rate
209 elif incoming_rate == 0 or flt(sle.actual_qty) < 0:
210 # In case of delivery/stock issue, get average purchase rate
211 # of serial nos of current entry
212 incoming_rate = flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0))
Anand Doshi1b531862013-01-10 19:29:51 +0530213 from `tabSerial No` where name in (%s)""" % (", ".join(["%s"]*len(serial_no))),
214 tuple(serial_no))[0][0])
Nabin Hait902e8602013-01-08 18:29:24 +0530215
216 if incoming_rate and not valuation_rate:
217 valuation_rate = incoming_rate
218 else:
219 new_stock_qty = qty_after_transaction + actual_qty
220 if new_stock_qty > 0:
221 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
222 if new_stock_value > 0:
223 # calculate new valuation rate only if stock value is positive
224 # else it remains the same as that of previous entry
225 valuation_rate = new_stock_value / new_stock_qty
Anand Doshi1b531862013-01-10 19:29:51 +0530226
Nabin Hait914c6df2013-01-14 13:15:42 +0530227 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530228
229def get_moving_average_values(qty_after_transaction, sle, valuation_rate):
230 incoming_rate = flt(sle.incoming_rate)
Nabin Hait914c6df2013-01-14 13:15:42 +0530231 actual_qty = flt(sle.actual_qty)
Nabin Hait902e8602013-01-08 18:29:24 +0530232
Anand Doshi1b531862013-01-10 19:29:51 +0530233 if not incoming_rate:
Nabin Hait902e8602013-01-08 18:29:24 +0530234 # In case of delivery/stock issue in_rate = 0 or wrong incoming rate
235 incoming_rate = valuation_rate
236
Anand Doshi1b531862013-01-10 19:29:51 +0530237 elif qty_after_transaction < 0:
238 # if negative stock, take current valuation rate as incoming rate
239 valuation_rate = incoming_rate
240
Nabin Hait902e8602013-01-08 18:29:24 +0530241 new_stock_qty = qty_after_transaction + actual_qty
242 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
Anand Doshi1b531862013-01-10 19:29:51 +0530243
244 if new_stock_qty > 0 and new_stock_value > 0:
Nabin Hait902e8602013-01-08 18:29:24 +0530245 valuation_rate = new_stock_value / flt(new_stock_qty)
246 elif new_stock_qty <= 0:
247 valuation_rate = 0.0
Anand Doshi1b531862013-01-10 19:29:51 +0530248
249 # NOTE: val_rate is same as previous entry if new stock value is negative
250
Nabin Hait914c6df2013-01-14 13:15:42 +0530251 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530252
253def get_fifo_values(qty_after_transaction, sle, stock_queue):
254 incoming_rate = flt(sle.incoming_rate)
255 actual_qty = flt(sle.actual_qty)
Nabin Hait902e8602013-01-08 18:29:24 +0530256 if not stock_queue:
257 stock_queue.append([0, 0])
Nabin Hait9514d172013-01-10 10:40:37 +0530258
Nabin Hait902e8602013-01-08 18:29:24 +0530259 if actual_qty > 0:
260 if stock_queue[-1][0] > 0:
261 stock_queue.append([actual_qty, incoming_rate])
262 else:
263 qty = stock_queue[-1][0] + actual_qty
264 stock_queue[-1] = [qty, qty > 0 and incoming_rate or 0]
265 else:
266 incoming_cost = 0
267 qty_to_pop = abs(actual_qty)
268 while qty_to_pop:
Nabin Hait9514d172013-01-10 10:40:37 +0530269 if not stock_queue:
270 stock_queue.append([0, 0])
271
Nabin Hait902e8602013-01-08 18:29:24 +0530272 batch = stock_queue[0]
273
274 if 0 < batch[0] <= qty_to_pop:
275 # if batch qty > 0
276 # not enough or exactly same qty in current batch, clear batch
277 incoming_cost += flt(batch[0]) * flt(batch[1])
278 qty_to_pop -= batch[0]
279 stock_queue.pop(0)
280 else:
281 # all from current batch
282 incoming_cost += flt(qty_to_pop) * flt(batch[1])
283 batch[0] -= qty_to_pop
284 qty_to_pop = 0
285
Nabin Hait902e8602013-01-08 18:29:24 +0530286 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
287 stock_qty = sum((flt(batch[0]) for batch in stock_queue))
288
289 valuation_rate = stock_qty and (stock_value / flt(stock_qty)) or 0
Nabin Hait9514d172013-01-10 10:40:37 +0530290
Nabin Hait914c6df2013-01-14 13:15:42 +0530291 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530292
Nabin Hait9514d172013-01-10 10:40:37 +0530293def _raise_exceptions(args, verbose=1):
Nabin Hait902e8602013-01-08 18:29:24 +0530294 deficiency = min(e["diff"] for e in _exceptions)
295 msg = """Negative stock error:
296 Cannot complete this transaction because stock will start
297 becoming negative (%s) for Item <b>%s</b> in Warehouse
298 <b>%s</b> on <b>%s %s</b> in Transaction %s %s.
299 Total Quantity Deficiency: <b>%s</b>""" % \
300 (_exceptions[0]["diff"], args.get("item_code"), args.get("warehouse"),
301 _exceptions[0]["posting_date"], _exceptions[0]["posting_time"],
302 _exceptions[0]["voucher_type"], _exceptions[0]["voucher_no"],
303 abs(deficiency))
304 if verbose:
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530305 msgprint(msg, raise_exception=NegativeStockError)
Nabin Hait902e8602013-01-08 18:29:24 +0530306 else:
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530307 raise NegativeStockError, msg
Anand Doshi1b531862013-01-10 19:29:51 +0530308
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530309def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530310 """
311 get the last sle on or before the current time-bucket,
312 to get actual qty before transaction, this function
313 is called from various transaction like stock entry, reco etc
314
315 args = {
316 "item_code": "ABC",
317 "warehouse": "XYZ",
318 "posting_date": "2012-12-12",
319 "posting_time": "12:00",
320 "sle": "name of reference Stock Ledger Entry"
321 }
322 """
323 if not args.get("sle"): args["sle"] = ""
324
325 sle = get_stock_ledger_entries(args, ["name != %(sle)s",
326 "timestamp(posting_date, posting_time) <= timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530327 "desc", "limit 1", for_update=for_update)
Anand Doshi1b531862013-01-10 19:29:51 +0530328 return sle and sle[0] or {}