blob: f0619c7384d507f11e2c08926699ccdacfe7e2c8 [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
Rushabh Mehta4c17f942013-08-12 14:18:09 +053011class NegativeStockError(webnotes.ValidationError): pass
Nabin Hait902e8602013-01-08 18:29:24 +053012
13_exceptions = []
14def update_entries_after(args, verbose=1):
15 """
16 update valution rate and qty after transaction
17 from the current time-bucket onwards
18
19 args = {
20 "item_code": "ABC",
21 "warehouse": "XYZ",
22 "posting_date": "2012-12-12",
23 "posting_time": "12:00"
24 }
25 """
Nabin Haitf4591ec2013-05-23 19:07:10 +053026 global _exceptions
27 _exceptions = []
28
Nabin Hait902e8602013-01-08 18:29:24 +053029 previous_sle = get_sle_before_datetime(args)
Anand Doshi71bed312013-03-13 12:57:04 +053030
Nabin Hait902e8602013-01-08 18:29:24 +053031 qty_after_transaction = flt(previous_sle.get("qty_after_transaction"))
32 valuation_rate = flt(previous_sle.get("valuation_rate"))
33 stock_queue = json.loads(previous_sle.get("stock_queue") or "[]")
Nabin Hait9514d172013-01-10 10:40:37 +053034 stock_value = 0.0
Nabin Hait902e8602013-01-08 18:29:24 +053035
36 entries_to_fix = get_sle_after_datetime(previous_sle or \
Anand Doshi4dc7caa2013-01-11 11:44:49 +053037 {"item_code": args["item_code"], "warehouse": args["warehouse"]}, for_update=True)
Anand Doshi71bed312013-03-13 12:57:04 +053038
Nabin Hait902e8602013-01-08 18:29:24 +053039 valuation_method = get_valuation_method(args["item_code"])
40
41 for sle in entries_to_fix:
Anand Doshi1b531862013-01-10 19:29:51 +053042 if sle.serial_no or not cint(webnotes.conn.get_default("allow_negative_stock")):
Nabin Hait902e8602013-01-08 18:29:24 +053043 # validate negative stock for serialized items, fifo valuation
44 # or when negative stock is not allowed for moving average
45 if not validate_negative_stock(qty_after_transaction, sle):
46 qty_after_transaction += flt(sle.actual_qty)
47 continue
Nabin Hait1b4f56c2013-01-17 17:01:51 +053048
Anand Doshi1b531862013-01-10 19:29:51 +053049 if sle.serial_no:
Nabin Hait1b4f56c2013-01-17 17:01:51 +053050 valuation_rate = get_serialized_values(qty_after_transaction, sle, valuation_rate)
Nabin Hait902e8602013-01-08 18:29:24 +053051 elif valuation_method == "Moving Average":
Nabin Hait1b4f56c2013-01-17 17:01:51 +053052 valuation_rate = get_moving_average_values(qty_after_transaction, sle, valuation_rate)
Nabin Hait902e8602013-01-08 18:29:24 +053053 else:
Nabin Hait1b4f56c2013-01-17 17:01:51 +053054 valuation_rate = get_fifo_values(qty_after_transaction, sle, stock_queue)
Anand Doshi1b531862013-01-10 19:29:51 +053055
Nabin Hait902e8602013-01-08 18:29:24 +053056 qty_after_transaction += flt(sle.actual_qty)
57
58 # get stock value
Anand Doshi1b531862013-01-10 19:29:51 +053059 if sle.serial_no:
Nabin Hait902e8602013-01-08 18:29:24 +053060 stock_value = qty_after_transaction * valuation_rate
61 elif valuation_method == "Moving Average":
62 stock_value = (qty_after_transaction > 0) and \
63 (qty_after_transaction * valuation_rate) or 0
64 else:
65 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
Nabin Haitc3afb252013-03-19 12:01:24 +053066 # print sle.posting_date, sle.actual_qty, sle.incoming_rate, stock_queue, stock_value
Nabin Hait902e8602013-01-08 18:29:24 +053067 # update current sle
68 webnotes.conn.sql("""update `tabStock Ledger Entry`
Anand Doshi1b531862013-01-10 19:29:51 +053069 set qty_after_transaction=%s, valuation_rate=%s, stock_queue=%s,
Nabin Hait914c6df2013-01-14 13:15:42 +053070 stock_value=%s where name=%s""",
Anand Doshi1b531862013-01-10 19:29:51 +053071 (qty_after_transaction, valuation_rate,
Nabin Hait914c6df2013-01-14 13:15:42 +053072 json.dumps(stock_queue), stock_value, sle.name))
Anand Doshi1b531862013-01-10 19:29:51 +053073
Nabin Hait902e8602013-01-08 18:29:24 +053074 if _exceptions:
Nabin Hait9514d172013-01-10 10:40:37 +053075 _raise_exceptions(args, verbose)
Nabin Hait902e8602013-01-08 18:29:24 +053076
77 # update bin
Nabin Haitac53b112013-01-11 19:25:46 +053078 if not webnotes.conn.exists({"doctype": "Bin", "item_code": args["item_code"],
79 "warehouse": args["warehouse"]}):
Rushabh Mehtac53231a2013-02-18 18:24:28 +053080 bin_wrapper = webnotes.bean([{
Nabin Haitac53b112013-01-11 19:25:46 +053081 "doctype": "Bin",
82 "item_code": args["item_code"],
83 "warehouse": args["warehouse"],
Anand Doshic313d662013-01-14 15:46:17 +053084 }])
85 bin_wrapper.ignore_permissions = 1
86 bin_wrapper.insert()
Nabin Haitac53b112013-01-11 19:25:46 +053087
Anand Doshi1b531862013-01-10 19:29:51 +053088 webnotes.conn.sql("""update `tabBin` set valuation_rate=%s, actual_qty=%s,
89 stock_value=%s,
Nabin Hait902e8602013-01-08 18:29:24 +053090 projected_qty = (actual_qty + indented_qty + ordered_qty + planned_qty - reserved_qty)
91 where item_code=%s and warehouse=%s""", (valuation_rate, qty_after_transaction,
92 stock_value, args["item_code"], args["warehouse"]))
93
Anand Doshi4dc7caa2013-01-11 11:44:49 +053094def get_sle_before_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +053095 """
96 get previous stock ledger entry before current time-bucket
97
98 Details:
99 get the last sle before the current time-bucket, so that all values
100 are reposted from the current time-bucket onwards.
101 this is necessary because at the time of cancellation, there may be
102 entries between the cancelled entries in the same time-bucket
103 """
104 sle = get_stock_ledger_entries(args,
Nabin Hait26d46552013-01-09 15:23:05 +0530105 ["timestamp(posting_date, posting_time) < timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530106 "desc", "limit 1", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530107
108 return sle and sle[0] or webnotes._dict()
109
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530110def get_sle_after_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530111 """get Stock Ledger Entries after a particular datetime, for reposting"""
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530112 # NOTE: using for update of
Nabin Hait902e8602013-01-08 18:29:24 +0530113 return get_stock_ledger_entries(args,
Nabin Hait9514d172013-01-10 10:40:37 +0530114 ["timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530115 "asc", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530116
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530117def get_stock_ledger_entries(args, conditions=None, order="desc", limit=None, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530118 """get stock ledger entries filtered by specific posting datetime conditions"""
119 if not args.get("posting_date"):
120 args["posting_date"] = "1900-01-01"
121 if not args.get("posting_time"):
Anand Doshi71bed312013-03-13 12:57:04 +0530122 args["posting_time"] = "00:00"
Nabin Hait902e8602013-01-08 18:29:24 +0530123
124 return webnotes.conn.sql("""select * from `tabStock Ledger Entry`
125 where item_code = %%(item_code)s
126 and warehouse = %%(warehouse)s
127 and ifnull(is_cancelled, 'No') = 'No'
128 %(conditions)s
Nabin Hait9514d172013-01-10 10:40:37 +0530129 order by timestamp(posting_date, posting_time) %(order)s, name %(order)s
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530130 %(limit)s %(for_update)s""" % {
Nabin Hait902e8602013-01-08 18:29:24 +0530131 "conditions": conditions and ("and " + " and ".join(conditions)) or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530132 "limit": limit or "",
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530133 "for_update": for_update and "for update" or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530134 "order": order
Nabin Hait902e8602013-01-08 18:29:24 +0530135 }, args, as_dict=1)
136
137def validate_negative_stock(qty_after_transaction, sle):
138 """
139 validate negative stock for entries current datetime onwards
140 will not consider cancelled entries
141 """
142 diff = qty_after_transaction + flt(sle.actual_qty)
143
144 if diff < 0 and abs(diff) > 0.0001:
145 # negative stock!
146 global _exceptions
147 exc = sle.copy().update({"diff": diff})
148 _exceptions.append(exc)
149 return False
150 else:
151 return True
152
153def get_serialized_values(qty_after_transaction, sle, valuation_rate):
154 incoming_rate = flt(sle.incoming_rate)
155 actual_qty = flt(sle.actual_qty)
Anand Doshi1b531862013-01-10 19:29:51 +0530156 serial_no = cstr(sle.serial_no).split("\n")
Nabin Hait902e8602013-01-08 18:29:24 +0530157
158 if incoming_rate < 0:
159 # wrong incoming rate
160 incoming_rate = valuation_rate
161 elif incoming_rate == 0 or flt(sle.actual_qty) < 0:
162 # In case of delivery/stock issue, get average purchase rate
163 # of serial nos of current entry
164 incoming_rate = flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0))
Anand Doshi1b531862013-01-10 19:29:51 +0530165 from `tabSerial No` where name in (%s)""" % (", ".join(["%s"]*len(serial_no))),
166 tuple(serial_no))[0][0])
Nabin Hait902e8602013-01-08 18:29:24 +0530167
168 if incoming_rate and not valuation_rate:
169 valuation_rate = incoming_rate
170 else:
171 new_stock_qty = qty_after_transaction + actual_qty
172 if new_stock_qty > 0:
173 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
174 if new_stock_value > 0:
175 # calculate new valuation rate only if stock value is positive
176 # else it remains the same as that of previous entry
177 valuation_rate = new_stock_value / new_stock_qty
Anand Doshi1b531862013-01-10 19:29:51 +0530178
Nabin Hait914c6df2013-01-14 13:15:42 +0530179 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530180
181def get_moving_average_values(qty_after_transaction, sle, valuation_rate):
182 incoming_rate = flt(sle.incoming_rate)
Nabin Hait914c6df2013-01-14 13:15:42 +0530183 actual_qty = flt(sle.actual_qty)
Nabin Hait902e8602013-01-08 18:29:24 +0530184
Anand Doshi1b531862013-01-10 19:29:51 +0530185 if not incoming_rate:
Nabin Hait902e8602013-01-08 18:29:24 +0530186 # In case of delivery/stock issue in_rate = 0 or wrong incoming rate
187 incoming_rate = valuation_rate
188
Anand Doshi1b531862013-01-10 19:29:51 +0530189 elif qty_after_transaction < 0:
190 # if negative stock, take current valuation rate as incoming rate
191 valuation_rate = incoming_rate
192
Nabin Hait902e8602013-01-08 18:29:24 +0530193 new_stock_qty = qty_after_transaction + actual_qty
194 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
Anand Doshi1b531862013-01-10 19:29:51 +0530195
196 if new_stock_qty > 0 and new_stock_value > 0:
Nabin Hait902e8602013-01-08 18:29:24 +0530197 valuation_rate = new_stock_value / flt(new_stock_qty)
198 elif new_stock_qty <= 0:
199 valuation_rate = 0.0
Anand Doshi1b531862013-01-10 19:29:51 +0530200
201 # NOTE: val_rate is same as previous entry if new stock value is negative
202
Nabin Hait914c6df2013-01-14 13:15:42 +0530203 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530204
205def get_fifo_values(qty_after_transaction, sle, stock_queue):
206 incoming_rate = flt(sle.incoming_rate)
207 actual_qty = flt(sle.actual_qty)
Nabin Hait902e8602013-01-08 18:29:24 +0530208 if not stock_queue:
209 stock_queue.append([0, 0])
Nabin Hait9514d172013-01-10 10:40:37 +0530210
Nabin Hait902e8602013-01-08 18:29:24 +0530211 if actual_qty > 0:
212 if stock_queue[-1][0] > 0:
213 stock_queue.append([actual_qty, incoming_rate])
214 else:
215 qty = stock_queue[-1][0] + actual_qty
216 stock_queue[-1] = [qty, qty > 0 and incoming_rate or 0]
217 else:
218 incoming_cost = 0
219 qty_to_pop = abs(actual_qty)
220 while qty_to_pop:
Nabin Hait9514d172013-01-10 10:40:37 +0530221 if not stock_queue:
222 stock_queue.append([0, 0])
223
Nabin Hait902e8602013-01-08 18:29:24 +0530224 batch = stock_queue[0]
225
226 if 0 < batch[0] <= qty_to_pop:
227 # if batch qty > 0
228 # not enough or exactly same qty in current batch, clear batch
229 incoming_cost += flt(batch[0]) * flt(batch[1])
230 qty_to_pop -= batch[0]
231 stock_queue.pop(0)
232 else:
233 # all from current batch
234 incoming_cost += flt(qty_to_pop) * flt(batch[1])
235 batch[0] -= qty_to_pop
236 qty_to_pop = 0
237
Nabin Hait902e8602013-01-08 18:29:24 +0530238 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
239 stock_qty = sum((flt(batch[0]) for batch in stock_queue))
240
241 valuation_rate = stock_qty and (stock_value / flt(stock_qty)) or 0
Nabin Hait9514d172013-01-10 10:40:37 +0530242
Nabin Hait914c6df2013-01-14 13:15:42 +0530243 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530244
Nabin Hait9514d172013-01-10 10:40:37 +0530245def _raise_exceptions(args, verbose=1):
Nabin Hait902e8602013-01-08 18:29:24 +0530246 deficiency = min(e["diff"] for e in _exceptions)
247 msg = """Negative stock error:
248 Cannot complete this transaction because stock will start
249 becoming negative (%s) for Item <b>%s</b> in Warehouse
250 <b>%s</b> on <b>%s %s</b> in Transaction %s %s.
251 Total Quantity Deficiency: <b>%s</b>""" % \
252 (_exceptions[0]["diff"], args.get("item_code"), args.get("warehouse"),
253 _exceptions[0]["posting_date"], _exceptions[0]["posting_time"],
254 _exceptions[0]["voucher_type"], _exceptions[0]["voucher_no"],
255 abs(deficiency))
256 if verbose:
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530257 msgprint(msg, raise_exception=NegativeStockError)
Nabin Hait902e8602013-01-08 18:29:24 +0530258 else:
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530259 raise NegativeStockError, msg
Anand Doshi1b531862013-01-10 19:29:51 +0530260
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530261def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530262 """
263 get the last sle on or before the current time-bucket,
264 to get actual qty before transaction, this function
265 is called from various transaction like stock entry, reco etc
266
267 args = {
268 "item_code": "ABC",
269 "warehouse": "XYZ",
270 "posting_date": "2012-12-12",
271 "posting_time": "12:00",
272 "sle": "name of reference Stock Ledger Entry"
273 }
274 """
275 if not args.get("sle"): args["sle"] = ""
276
277 sle = get_stock_ledger_entries(args, ["name != %(sle)s",
278 "timestamp(posting_date, posting_time) <= timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530279 "desc", "limit 1", for_update=for_update)
Anand Doshi1b531862013-01-10 19:29:51 +0530280 return sle and sle[0] or {}