blob: 9a843ed549d800de85a8a352f6c69f9cf1ac9489 [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:
36 delete_cancelled_entry(sl_entries[0].get('voucher_no'), sl_entries[0].get('voucher_type'))
37
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 Haitaeba24e2013-08-23 15:17:36 +053077 prev_stock_value = stock_value = flt(previous_sle.get("stock_value"))
Nabin Hait902e8602013-01-08 18:29:24 +053078
79 entries_to_fix = get_sle_after_datetime(previous_sle or \
Anand Doshi4dc7caa2013-01-11 11:44:49 +053080 {"item_code": args["item_code"], "warehouse": args["warehouse"]}, for_update=True)
Nabin Hait469ee712013-08-07 12:33:37 +053081
Nabin Hait902e8602013-01-08 18:29:24 +053082 valuation_method = get_valuation_method(args["item_code"])
Nabin Haitaeba24e2013-08-23 15:17:36 +053083 stock_value_difference = 0.0
Nabin Hait902e8602013-01-08 18:29:24 +053084
85 for sle in entries_to_fix:
Anand Doshi1b531862013-01-10 19:29:51 +053086 if sle.serial_no or not cint(webnotes.conn.get_default("allow_negative_stock")):
Nabin Hait902e8602013-01-08 18:29:24 +053087 # validate negative stock for serialized items, fifo valuation
88 # or when negative stock is not allowed for moving average
89 if not validate_negative_stock(qty_after_transaction, sle):
90 qty_after_transaction += flt(sle.actual_qty)
91 continue
Nabin Hait1b4f56c2013-01-17 17:01:51 +053092
Anand Doshi1b531862013-01-10 19:29:51 +053093 if sle.serial_no:
Nabin Hait1b4f56c2013-01-17 17:01:51 +053094 valuation_rate = get_serialized_values(qty_after_transaction, sle, valuation_rate)
Nabin Hait902e8602013-01-08 18:29:24 +053095 elif valuation_method == "Moving Average":
Nabin Hait1b4f56c2013-01-17 17:01:51 +053096 valuation_rate = get_moving_average_values(qty_after_transaction, sle, valuation_rate)
Nabin Hait902e8602013-01-08 18:29:24 +053097 else:
Nabin Hait1b4f56c2013-01-17 17:01:51 +053098 valuation_rate = get_fifo_values(qty_after_transaction, sle, stock_queue)
Anand Doshi1b531862013-01-10 19:29:51 +053099
Nabin Hait902e8602013-01-08 18:29:24 +0530100 qty_after_transaction += flt(sle.actual_qty)
101
102 # get stock value
Anand Doshi1b531862013-01-10 19:29:51 +0530103 if sle.serial_no:
Nabin Hait902e8602013-01-08 18:29:24 +0530104 stock_value = qty_after_transaction * valuation_rate
105 elif valuation_method == "Moving Average":
106 stock_value = (qty_after_transaction > 0) and \
107 (qty_after_transaction * valuation_rate) or 0
108 else:
109 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
Nabin Hait815a49e2013-08-07 17:00:01 +0530110
Nabin Haitaeba24e2013-08-23 15:17:36 +0530111 stock_value_difference = stock_value - prev_stock_value
112 prev_stock_value = stock_value
113
Nabin Hait902e8602013-01-08 18:29:24 +0530114 # update current sle
115 webnotes.conn.sql("""update `tabStock Ledger Entry`
Anand Doshi1b531862013-01-10 19:29:51 +0530116 set qty_after_transaction=%s, valuation_rate=%s, stock_queue=%s,
Nabin Haitaeba24e2013-08-23 15:17:36 +0530117 stock_value=%s, stock_value_difference=%s where name=%s""",
Anand Doshi1b531862013-01-10 19:29:51 +0530118 (qty_after_transaction, valuation_rate,
Nabin Haitaeba24e2013-08-23 15:17:36 +0530119 json.dumps(stock_queue), stock_value, stock_value_difference, sle.name))
Anand Doshi1b531862013-01-10 19:29:51 +0530120
Nabin Hait902e8602013-01-08 18:29:24 +0530121 if _exceptions:
Nabin Hait9514d172013-01-10 10:40:37 +0530122 _raise_exceptions(args, verbose)
Nabin Hait902e8602013-01-08 18:29:24 +0530123
124 # update bin
Nabin Haitac53b112013-01-11 19:25:46 +0530125 if not webnotes.conn.exists({"doctype": "Bin", "item_code": args["item_code"],
126 "warehouse": args["warehouse"]}):
Rushabh Mehtac53231a2013-02-18 18:24:28 +0530127 bin_wrapper = webnotes.bean([{
Nabin Haitac53b112013-01-11 19:25:46 +0530128 "doctype": "Bin",
129 "item_code": args["item_code"],
130 "warehouse": args["warehouse"],
Anand Doshic313d662013-01-14 15:46:17 +0530131 }])
132 bin_wrapper.ignore_permissions = 1
133 bin_wrapper.insert()
Nabin Haitac53b112013-01-11 19:25:46 +0530134
Anand Doshi1b531862013-01-10 19:29:51 +0530135 webnotes.conn.sql("""update `tabBin` set valuation_rate=%s, actual_qty=%s,
136 stock_value=%s,
Nabin Hait902e8602013-01-08 18:29:24 +0530137 projected_qty = (actual_qty + indented_qty + ordered_qty + planned_qty - reserved_qty)
138 where item_code=%s and warehouse=%s""", (valuation_rate, qty_after_transaction,
139 stock_value, args["item_code"], args["warehouse"]))
140
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530141def get_sle_before_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530142 """
143 get previous stock ledger entry before current time-bucket
144
145 Details:
146 get the last sle before the current time-bucket, so that all values
147 are reposted from the current time-bucket onwards.
148 this is necessary because at the time of cancellation, there may be
149 entries between the cancelled entries in the same time-bucket
150 """
151 sle = get_stock_ledger_entries(args,
Nabin Hait26d46552013-01-09 15:23:05 +0530152 ["timestamp(posting_date, posting_time) < timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530153 "desc", "limit 1", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530154
155 return sle and sle[0] or webnotes._dict()
156
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530157def get_sle_after_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530158 """get Stock Ledger Entries after a particular datetime, for reposting"""
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530159 # NOTE: using for update of
Nabin Hait902e8602013-01-08 18:29:24 +0530160 return get_stock_ledger_entries(args,
Nabin Hait9514d172013-01-10 10:40:37 +0530161 ["timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530162 "asc", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530163
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530164def get_stock_ledger_entries(args, conditions=None, order="desc", limit=None, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530165 """get stock ledger entries filtered by specific posting datetime conditions"""
166 if not args.get("posting_date"):
167 args["posting_date"] = "1900-01-01"
168 if not args.get("posting_time"):
Anand Doshi71bed312013-03-13 12:57:04 +0530169 args["posting_time"] = "00:00"
Nabin Hait902e8602013-01-08 18:29:24 +0530170
171 return webnotes.conn.sql("""select * from `tabStock Ledger Entry`
172 where item_code = %%(item_code)s
173 and warehouse = %%(warehouse)s
Nabin Hait902e8602013-01-08 18:29:24 +0530174 %(conditions)s
Nabin Hait9514d172013-01-10 10:40:37 +0530175 order by timestamp(posting_date, posting_time) %(order)s, name %(order)s
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530176 %(limit)s %(for_update)s""" % {
Nabin Hait902e8602013-01-08 18:29:24 +0530177 "conditions": conditions and ("and " + " and ".join(conditions)) or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530178 "limit": limit or "",
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530179 "for_update": for_update and "for update" or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530180 "order": order
Nabin Hait902e8602013-01-08 18:29:24 +0530181 }, args, as_dict=1)
182
183def validate_negative_stock(qty_after_transaction, sle):
184 """
185 validate negative stock for entries current datetime onwards
186 will not consider cancelled entries
187 """
188 diff = qty_after_transaction + flt(sle.actual_qty)
189
190 if diff < 0 and abs(diff) > 0.0001:
191 # negative stock!
192 global _exceptions
193 exc = sle.copy().update({"diff": diff})
194 _exceptions.append(exc)
195 return False
196 else:
197 return True
198
199def get_serialized_values(qty_after_transaction, sle, valuation_rate):
200 incoming_rate = flt(sle.incoming_rate)
201 actual_qty = flt(sle.actual_qty)
Anand Doshi1b531862013-01-10 19:29:51 +0530202 serial_no = cstr(sle.serial_no).split("\n")
Nabin Hait902e8602013-01-08 18:29:24 +0530203
204 if incoming_rate < 0:
205 # wrong incoming rate
206 incoming_rate = valuation_rate
207 elif incoming_rate == 0 or flt(sle.actual_qty) < 0:
208 # In case of delivery/stock issue, get average purchase rate
209 # of serial nos of current entry
210 incoming_rate = flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0))
Anand Doshi1b531862013-01-10 19:29:51 +0530211 from `tabSerial No` where name in (%s)""" % (", ".join(["%s"]*len(serial_no))),
212 tuple(serial_no))[0][0])
Nabin Hait902e8602013-01-08 18:29:24 +0530213
214 if incoming_rate and not valuation_rate:
215 valuation_rate = incoming_rate
216 else:
217 new_stock_qty = qty_after_transaction + actual_qty
218 if new_stock_qty > 0:
219 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
220 if new_stock_value > 0:
221 # calculate new valuation rate only if stock value is positive
222 # else it remains the same as that of previous entry
223 valuation_rate = new_stock_value / new_stock_qty
Anand Doshi1b531862013-01-10 19:29:51 +0530224
Nabin Hait914c6df2013-01-14 13:15:42 +0530225 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530226
227def get_moving_average_values(qty_after_transaction, sle, valuation_rate):
228 incoming_rate = flt(sle.incoming_rate)
Nabin Hait914c6df2013-01-14 13:15:42 +0530229 actual_qty = flt(sle.actual_qty)
Nabin Hait902e8602013-01-08 18:29:24 +0530230
Anand Doshi1b531862013-01-10 19:29:51 +0530231 if not incoming_rate:
Nabin Hait902e8602013-01-08 18:29:24 +0530232 # In case of delivery/stock issue in_rate = 0 or wrong incoming rate
233 incoming_rate = valuation_rate
234
Anand Doshi1b531862013-01-10 19:29:51 +0530235 elif qty_after_transaction < 0:
236 # if negative stock, take current valuation rate as incoming rate
237 valuation_rate = incoming_rate
238
Nabin Hait902e8602013-01-08 18:29:24 +0530239 new_stock_qty = qty_after_transaction + actual_qty
240 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
Anand Doshi1b531862013-01-10 19:29:51 +0530241
242 if new_stock_qty > 0 and new_stock_value > 0:
Nabin Hait902e8602013-01-08 18:29:24 +0530243 valuation_rate = new_stock_value / flt(new_stock_qty)
244 elif new_stock_qty <= 0:
245 valuation_rate = 0.0
Anand Doshi1b531862013-01-10 19:29:51 +0530246
247 # NOTE: val_rate is same as previous entry if new stock value is negative
248
Nabin Hait914c6df2013-01-14 13:15:42 +0530249 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530250
251def get_fifo_values(qty_after_transaction, sle, stock_queue):
252 incoming_rate = flt(sle.incoming_rate)
253 actual_qty = flt(sle.actual_qty)
Nabin Hait902e8602013-01-08 18:29:24 +0530254 if not stock_queue:
255 stock_queue.append([0, 0])
Nabin Hait9514d172013-01-10 10:40:37 +0530256
Nabin Hait902e8602013-01-08 18:29:24 +0530257 if actual_qty > 0:
258 if stock_queue[-1][0] > 0:
259 stock_queue.append([actual_qty, incoming_rate])
260 else:
261 qty = stock_queue[-1][0] + actual_qty
262 stock_queue[-1] = [qty, qty > 0 and incoming_rate or 0]
263 else:
264 incoming_cost = 0
265 qty_to_pop = abs(actual_qty)
266 while qty_to_pop:
Nabin Hait9514d172013-01-10 10:40:37 +0530267 if not stock_queue:
268 stock_queue.append([0, 0])
269
Nabin Hait902e8602013-01-08 18:29:24 +0530270 batch = stock_queue[0]
271
272 if 0 < batch[0] <= qty_to_pop:
273 # if batch qty > 0
274 # not enough or exactly same qty in current batch, clear batch
275 incoming_cost += flt(batch[0]) * flt(batch[1])
276 qty_to_pop -= batch[0]
277 stock_queue.pop(0)
278 else:
279 # all from current batch
280 incoming_cost += flt(qty_to_pop) * flt(batch[1])
281 batch[0] -= qty_to_pop
282 qty_to_pop = 0
283
Nabin Hait902e8602013-01-08 18:29:24 +0530284 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
285 stock_qty = sum((flt(batch[0]) for batch in stock_queue))
286
287 valuation_rate = stock_qty and (stock_value / flt(stock_qty)) or 0
Nabin Hait9514d172013-01-10 10:40:37 +0530288
Nabin Hait914c6df2013-01-14 13:15:42 +0530289 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530290
Nabin Hait9514d172013-01-10 10:40:37 +0530291def _raise_exceptions(args, verbose=1):
Nabin Hait902e8602013-01-08 18:29:24 +0530292 deficiency = min(e["diff"] for e in _exceptions)
293 msg = """Negative stock error:
294 Cannot complete this transaction because stock will start
295 becoming negative (%s) for Item <b>%s</b> in Warehouse
296 <b>%s</b> on <b>%s %s</b> in Transaction %s %s.
297 Total Quantity Deficiency: <b>%s</b>""" % \
298 (_exceptions[0]["diff"], args.get("item_code"), args.get("warehouse"),
299 _exceptions[0]["posting_date"], _exceptions[0]["posting_time"],
300 _exceptions[0]["voucher_type"], _exceptions[0]["voucher_no"],
301 abs(deficiency))
302 if verbose:
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530303 msgprint(msg, raise_exception=NegativeStockError)
Nabin Hait902e8602013-01-08 18:29:24 +0530304 else:
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530305 raise NegativeStockError, msg
Anand Doshi1b531862013-01-10 19:29:51 +0530306
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530307def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530308 """
309 get the last sle on or before the current time-bucket,
310 to get actual qty before transaction, this function
311 is called from various transaction like stock entry, reco etc
312
313 args = {
314 "item_code": "ABC",
315 "warehouse": "XYZ",
316 "posting_date": "2012-12-12",
317 "posting_time": "12:00",
318 "sle": "name of reference Stock Ledger Entry"
319 }
320 """
321 if not args.get("sle"): args["sle"] = ""
322
323 sle = get_stock_ledger_entries(args, ["name != %(sle)s",
324 "timestamp(posting_date, posting_time) <= timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530325 "desc", "limit 1", for_update=for_update)
Anand Doshi1b531862013-01-10 19:29:51 +0530326 return sle and sle[0] or {}