blob: 40461dc869bd96ac8d77c4ff58a7b74652ea7066 [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 Hait26d46552013-01-09 15:23:05 +05306from webnotes.utils import cint, flt, cstr
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
11
12_exceptions = []
13def update_entries_after(args, verbose=1):
14 """
15 update valution rate and qty after transaction
16 from the current time-bucket onwards
17
18 args = {
19 "item_code": "ABC",
20 "warehouse": "XYZ",
21 "posting_date": "2012-12-12",
22 "posting_time": "12:00"
23 }
24 """
Nabin Haitf4591ec2013-05-23 19:07:10 +053025 global _exceptions
26 _exceptions = []
27
Nabin Hait902e8602013-01-08 18:29:24 +053028 previous_sle = get_sle_before_datetime(args)
Anand Doshi71bed312013-03-13 12:57:04 +053029
Nabin Hait902e8602013-01-08 18:29:24 +053030 qty_after_transaction = flt(previous_sle.get("qty_after_transaction"))
31 valuation_rate = flt(previous_sle.get("valuation_rate"))
32 stock_queue = json.loads(previous_sle.get("stock_queue") or "[]")
Nabin Hait469ee712013-08-07 12:33:37 +053033 stock_value = flt(previous_sle.get("stock_value"))
Nabin Hait902e8602013-01-08 18:29:24 +053034
35 entries_to_fix = get_sle_after_datetime(previous_sle or \
Anand Doshi4dc7caa2013-01-11 11:44:49 +053036 {"item_code": args["item_code"], "warehouse": args["warehouse"]}, for_update=True)
Nabin Hait469ee712013-08-07 12:33:37 +053037
Nabin Hait902e8602013-01-08 18:29:24 +053038 valuation_method = get_valuation_method(args["item_code"])
39
40 for sle in entries_to_fix:
Anand Doshi1b531862013-01-10 19:29:51 +053041 if sle.serial_no or not cint(webnotes.conn.get_default("allow_negative_stock")):
Nabin Hait902e8602013-01-08 18:29:24 +053042 # validate negative stock for serialized items, fifo valuation
43 # or when negative stock is not allowed for moving average
44 if not validate_negative_stock(qty_after_transaction, sle):
45 qty_after_transaction += flt(sle.actual_qty)
46 continue
Nabin Hait1b4f56c2013-01-17 17:01:51 +053047
Anand Doshi1b531862013-01-10 19:29:51 +053048 if sle.serial_no:
Nabin Hait1b4f56c2013-01-17 17:01:51 +053049 valuation_rate = get_serialized_values(qty_after_transaction, sle, valuation_rate)
Nabin Hait902e8602013-01-08 18:29:24 +053050 elif valuation_method == "Moving Average":
Nabin Hait1b4f56c2013-01-17 17:01:51 +053051 valuation_rate = get_moving_average_values(qty_after_transaction, sle, valuation_rate)
Nabin Hait902e8602013-01-08 18:29:24 +053052 else:
Nabin Hait1b4f56c2013-01-17 17:01:51 +053053 valuation_rate = get_fifo_values(qty_after_transaction, sle, stock_queue)
Anand Doshi1b531862013-01-10 19:29:51 +053054
Nabin Hait902e8602013-01-08 18:29:24 +053055 qty_after_transaction += flt(sle.actual_qty)
56
57 # get stock value
Anand Doshi1b531862013-01-10 19:29:51 +053058 if sle.serial_no:
Nabin Hait902e8602013-01-08 18:29:24 +053059 stock_value = qty_after_transaction * valuation_rate
60 elif valuation_method == "Moving Average":
61 stock_value = (qty_after_transaction > 0) and \
62 (qty_after_transaction * valuation_rate) or 0
63 else:
64 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
Nabin Hait815a49e2013-08-07 17:00:01 +053065
Nabin Hait902e8602013-01-08 18:29:24 +053066 # update current sle
67 webnotes.conn.sql("""update `tabStock Ledger Entry`
Anand Doshi1b531862013-01-10 19:29:51 +053068 set qty_after_transaction=%s, valuation_rate=%s, stock_queue=%s,
Nabin Hait914c6df2013-01-14 13:15:42 +053069 stock_value=%s where name=%s""",
Anand Doshi1b531862013-01-10 19:29:51 +053070 (qty_after_transaction, valuation_rate,
Nabin Hait914c6df2013-01-14 13:15:42 +053071 json.dumps(stock_queue), stock_value, sle.name))
Anand Doshi1b531862013-01-10 19:29:51 +053072
Nabin Hait902e8602013-01-08 18:29:24 +053073 if _exceptions:
Nabin Hait9514d172013-01-10 10:40:37 +053074 _raise_exceptions(args, verbose)
Nabin Hait902e8602013-01-08 18:29:24 +053075
76 # update bin
Nabin Haitac53b112013-01-11 19:25:46 +053077 if not webnotes.conn.exists({"doctype": "Bin", "item_code": args["item_code"],
78 "warehouse": args["warehouse"]}):
Rushabh Mehtac53231a2013-02-18 18:24:28 +053079 bin_wrapper = webnotes.bean([{
Nabin Haitac53b112013-01-11 19:25:46 +053080 "doctype": "Bin",
81 "item_code": args["item_code"],
82 "warehouse": args["warehouse"],
Anand Doshic313d662013-01-14 15:46:17 +053083 }])
84 bin_wrapper.ignore_permissions = 1
85 bin_wrapper.insert()
Nabin Haitac53b112013-01-11 19:25:46 +053086
Anand Doshi1b531862013-01-10 19:29:51 +053087 webnotes.conn.sql("""update `tabBin` set valuation_rate=%s, actual_qty=%s,
88 stock_value=%s,
Nabin Hait902e8602013-01-08 18:29:24 +053089 projected_qty = (actual_qty + indented_qty + ordered_qty + planned_qty - reserved_qty)
90 where item_code=%s and warehouse=%s""", (valuation_rate, qty_after_transaction,
91 stock_value, args["item_code"], args["warehouse"]))
92
Anand Doshi4dc7caa2013-01-11 11:44:49 +053093def get_sle_before_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +053094 """
95 get previous stock ledger entry before current time-bucket
96
97 Details:
98 get the last sle before the current time-bucket, so that all values
99 are reposted from the current time-bucket onwards.
100 this is necessary because at the time of cancellation, there may be
101 entries between the cancelled entries in the same time-bucket
102 """
103 sle = get_stock_ledger_entries(args,
Nabin Hait26d46552013-01-09 15:23:05 +0530104 ["timestamp(posting_date, posting_time) < timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530105 "desc", "limit 1", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530106
107 return sle and sle[0] or webnotes._dict()
108
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530109def get_sle_after_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530110 """get Stock Ledger Entries after a particular datetime, for reposting"""
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530111 # NOTE: using for update of
Nabin Hait902e8602013-01-08 18:29:24 +0530112 return get_stock_ledger_entries(args,
Nabin Hait9514d172013-01-10 10:40:37 +0530113 ["timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530114 "asc", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530115
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530116def get_stock_ledger_entries(args, conditions=None, order="desc", limit=None, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530117 """get stock ledger entries filtered by specific posting datetime conditions"""
118 if not args.get("posting_date"):
119 args["posting_date"] = "1900-01-01"
120 if not args.get("posting_time"):
Anand Doshi71bed312013-03-13 12:57:04 +0530121 args["posting_time"] = "00:00"
Nabin Hait902e8602013-01-08 18:29:24 +0530122
123 return webnotes.conn.sql("""select * from `tabStock Ledger Entry`
124 where item_code = %%(item_code)s
125 and warehouse = %%(warehouse)s
126 and ifnull(is_cancelled, 'No') = 'No'
127 %(conditions)s
Nabin Hait9514d172013-01-10 10:40:37 +0530128 order by timestamp(posting_date, posting_time) %(order)s, name %(order)s
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530129 %(limit)s %(for_update)s""" % {
Nabin Hait902e8602013-01-08 18:29:24 +0530130 "conditions": conditions and ("and " + " and ".join(conditions)) or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530131 "limit": limit or "",
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530132 "for_update": for_update and "for update" or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530133 "order": order
Nabin Hait902e8602013-01-08 18:29:24 +0530134 }, args, as_dict=1)
135
136def validate_negative_stock(qty_after_transaction, sle):
137 """
138 validate negative stock for entries current datetime onwards
139 will not consider cancelled entries
140 """
141 diff = qty_after_transaction + flt(sle.actual_qty)
142
143 if diff < 0 and abs(diff) > 0.0001:
144 # negative stock!
145 global _exceptions
146 exc = sle.copy().update({"diff": diff})
147 _exceptions.append(exc)
148 return False
149 else:
150 return True
151
152def get_serialized_values(qty_after_transaction, sle, valuation_rate):
153 incoming_rate = flt(sle.incoming_rate)
154 actual_qty = flt(sle.actual_qty)
Anand Doshi1b531862013-01-10 19:29:51 +0530155 serial_no = cstr(sle.serial_no).split("\n")
Nabin Hait902e8602013-01-08 18:29:24 +0530156
157 if incoming_rate < 0:
158 # wrong incoming rate
159 incoming_rate = valuation_rate
160 elif incoming_rate == 0 or flt(sle.actual_qty) < 0:
161 # In case of delivery/stock issue, get average purchase rate
162 # of serial nos of current entry
163 incoming_rate = flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0))
Anand Doshi1b531862013-01-10 19:29:51 +0530164 from `tabSerial No` where name in (%s)""" % (", ".join(["%s"]*len(serial_no))),
165 tuple(serial_no))[0][0])
Nabin Hait902e8602013-01-08 18:29:24 +0530166
167 if incoming_rate and not valuation_rate:
168 valuation_rate = incoming_rate
169 else:
170 new_stock_qty = qty_after_transaction + actual_qty
171 if new_stock_qty > 0:
172 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
173 if new_stock_value > 0:
174 # calculate new valuation rate only if stock value is positive
175 # else it remains the same as that of previous entry
176 valuation_rate = new_stock_value / new_stock_qty
Anand Doshi1b531862013-01-10 19:29:51 +0530177
Nabin Hait914c6df2013-01-14 13:15:42 +0530178 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530179
180def get_moving_average_values(qty_after_transaction, sle, valuation_rate):
181 incoming_rate = flt(sle.incoming_rate)
Nabin Hait914c6df2013-01-14 13:15:42 +0530182 actual_qty = flt(sle.actual_qty)
Nabin Hait902e8602013-01-08 18:29:24 +0530183
Anand Doshi1b531862013-01-10 19:29:51 +0530184 if not incoming_rate:
Nabin Hait902e8602013-01-08 18:29:24 +0530185 # In case of delivery/stock issue in_rate = 0 or wrong incoming rate
186 incoming_rate = valuation_rate
187
Anand Doshi1b531862013-01-10 19:29:51 +0530188 elif qty_after_transaction < 0:
189 # if negative stock, take current valuation rate as incoming rate
190 valuation_rate = incoming_rate
191
Nabin Hait902e8602013-01-08 18:29:24 +0530192 new_stock_qty = qty_after_transaction + actual_qty
193 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
Anand Doshi1b531862013-01-10 19:29:51 +0530194
195 if new_stock_qty > 0 and new_stock_value > 0:
Nabin Hait902e8602013-01-08 18:29:24 +0530196 valuation_rate = new_stock_value / flt(new_stock_qty)
197 elif new_stock_qty <= 0:
198 valuation_rate = 0.0
Anand Doshi1b531862013-01-10 19:29:51 +0530199
200 # NOTE: val_rate is same as previous entry if new stock value is negative
201
Nabin Hait914c6df2013-01-14 13:15:42 +0530202 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530203
204def get_fifo_values(qty_after_transaction, sle, stock_queue):
205 incoming_rate = flt(sle.incoming_rate)
206 actual_qty = flt(sle.actual_qty)
Nabin Hait902e8602013-01-08 18:29:24 +0530207 if not stock_queue:
208 stock_queue.append([0, 0])
Nabin Hait9514d172013-01-10 10:40:37 +0530209
Nabin Hait902e8602013-01-08 18:29:24 +0530210 if actual_qty > 0:
211 if stock_queue[-1][0] > 0:
212 stock_queue.append([actual_qty, incoming_rate])
213 else:
214 qty = stock_queue[-1][0] + actual_qty
215 stock_queue[-1] = [qty, qty > 0 and incoming_rate or 0]
216 else:
217 incoming_cost = 0
218 qty_to_pop = abs(actual_qty)
219 while qty_to_pop:
Nabin Hait9514d172013-01-10 10:40:37 +0530220 if not stock_queue:
221 stock_queue.append([0, 0])
222
Nabin Hait902e8602013-01-08 18:29:24 +0530223 batch = stock_queue[0]
224
225 if 0 < batch[0] <= qty_to_pop:
226 # if batch qty > 0
227 # not enough or exactly same qty in current batch, clear batch
228 incoming_cost += flt(batch[0]) * flt(batch[1])
229 qty_to_pop -= batch[0]
230 stock_queue.pop(0)
231 else:
232 # all from current batch
233 incoming_cost += flt(qty_to_pop) * flt(batch[1])
234 batch[0] -= qty_to_pop
235 qty_to_pop = 0
236
Nabin Hait902e8602013-01-08 18:29:24 +0530237 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
238 stock_qty = sum((flt(batch[0]) for batch in stock_queue))
239
240 valuation_rate = stock_qty and (stock_value / flt(stock_qty)) or 0
Nabin Hait9514d172013-01-10 10:40:37 +0530241
Nabin Hait914c6df2013-01-14 13:15:42 +0530242 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530243
Nabin Hait9514d172013-01-10 10:40:37 +0530244def _raise_exceptions(args, verbose=1):
Nabin Hait902e8602013-01-08 18:29:24 +0530245 deficiency = min(e["diff"] for e in _exceptions)
246 msg = """Negative stock error:
247 Cannot complete this transaction because stock will start
248 becoming negative (%s) for Item <b>%s</b> in Warehouse
249 <b>%s</b> on <b>%s %s</b> in Transaction %s %s.
250 Total Quantity Deficiency: <b>%s</b>""" % \
251 (_exceptions[0]["diff"], args.get("item_code"), args.get("warehouse"),
252 _exceptions[0]["posting_date"], _exceptions[0]["posting_time"],
253 _exceptions[0]["voucher_type"], _exceptions[0]["voucher_no"],
254 abs(deficiency))
255 if verbose:
256 msgprint(msg, raise_exception=1)
257 else:
Anand Doshi1b531862013-01-10 19:29:51 +0530258 raise webnotes.ValidationError, msg
259
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530260def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530261 """
262 get the last sle on or before the current time-bucket,
263 to get actual qty before transaction, this function
264 is called from various transaction like stock entry, reco etc
265
266 args = {
267 "item_code": "ABC",
268 "warehouse": "XYZ",
269 "posting_date": "2012-12-12",
270 "posting_time": "12:00",
271 "sle": "name of reference Stock Ledger Entry"
272 }
273 """
274 if not args.get("sle"): args["sle"] = ""
275
276 sle = get_stock_ledger_entries(args, ["name != %(sle)s",
277 "timestamp(posting_date, posting_time) <= timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530278 "desc", "limit 1", for_update=for_update)
Anand Doshi1b531862013-01-10 19:29:51 +0530279 return sle and sle[0] or {}