blob: 0e8a341a4cd9a136d5745ea4ae4d642d627f72f2 [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
Pratik Vyas16371b72013-09-18 18:31:03 +053013_exceptions = webnotes.local('stockledger_exceptions')
14
15# _exceptions = []
Nabin Hait902e8602013-01-08 18:29:24 +053016def update_entries_after(args, verbose=1):
17 """
18 update valution rate and qty after transaction
19 from the current time-bucket onwards
20
21 args = {
22 "item_code": "ABC",
23 "warehouse": "XYZ",
24 "posting_date": "2012-12-12",
25 "posting_time": "12:00"
26 }
27 """
Pratik Vyas16371b72013-09-18 18:31:03 +053028 if not _exceptions:
29 webnotes.local.stockledger_exceptions = []
Nabin Haitf4591ec2013-05-23 19:07:10 +053030
Nabin Hait902e8602013-01-08 18:29:24 +053031 previous_sle = get_sle_before_datetime(args)
Anand Doshi71bed312013-03-13 12:57:04 +053032
Nabin Hait902e8602013-01-08 18:29:24 +053033 qty_after_transaction = flt(previous_sle.get("qty_after_transaction"))
34 valuation_rate = flt(previous_sle.get("valuation_rate"))
35 stock_queue = json.loads(previous_sle.get("stock_queue") or "[]")
Nabin Hait9514d172013-01-10 10:40:37 +053036 stock_value = 0.0
Nabin Hait902e8602013-01-08 18:29:24 +053037
38 entries_to_fix = get_sle_after_datetime(previous_sle or \
Anand Doshi4dc7caa2013-01-11 11:44:49 +053039 {"item_code": args["item_code"], "warehouse": args["warehouse"]}, for_update=True)
Anand Doshi71bed312013-03-13 12:57:04 +053040
Nabin Hait902e8602013-01-08 18:29:24 +053041 valuation_method = get_valuation_method(args["item_code"])
42
43 for sle in entries_to_fix:
Anand Doshi1b531862013-01-10 19:29:51 +053044 if sle.serial_no or not cint(webnotes.conn.get_default("allow_negative_stock")):
Nabin Hait902e8602013-01-08 18:29:24 +053045 # validate negative stock for serialized items, fifo valuation
46 # or when negative stock is not allowed for moving average
47 if not validate_negative_stock(qty_after_transaction, sle):
48 qty_after_transaction += flt(sle.actual_qty)
49 continue
Nabin Hait1b4f56c2013-01-17 17:01:51 +053050
Anand Doshi1b531862013-01-10 19:29:51 +053051 if sle.serial_no:
Nabin Hait1b4f56c2013-01-17 17:01:51 +053052 valuation_rate = get_serialized_values(qty_after_transaction, sle, valuation_rate)
Nabin Hait902e8602013-01-08 18:29:24 +053053 elif valuation_method == "Moving Average":
Nabin Hait1b4f56c2013-01-17 17:01:51 +053054 valuation_rate = get_moving_average_values(qty_after_transaction, sle, valuation_rate)
Nabin Hait902e8602013-01-08 18:29:24 +053055 else:
Nabin Hait1b4f56c2013-01-17 17:01:51 +053056 valuation_rate = get_fifo_values(qty_after_transaction, sle, stock_queue)
Anand Doshi1b531862013-01-10 19:29:51 +053057
Nabin Hait902e8602013-01-08 18:29:24 +053058 qty_after_transaction += flt(sle.actual_qty)
59
60 # get stock value
Anand Doshi1b531862013-01-10 19:29:51 +053061 if sle.serial_no:
Nabin Hait902e8602013-01-08 18:29:24 +053062 stock_value = qty_after_transaction * valuation_rate
63 elif valuation_method == "Moving Average":
64 stock_value = (qty_after_transaction > 0) and \
65 (qty_after_transaction * valuation_rate) or 0
66 else:
67 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
Nabin Haitc3afb252013-03-19 12:01:24 +053068 # print sle.posting_date, sle.actual_qty, sle.incoming_rate, stock_queue, stock_value
Nabin Hait902e8602013-01-08 18:29:24 +053069 # update current sle
70 webnotes.conn.sql("""update `tabStock Ledger Entry`
Anand Doshi1b531862013-01-10 19:29:51 +053071 set qty_after_transaction=%s, valuation_rate=%s, stock_queue=%s,
Nabin Hait914c6df2013-01-14 13:15:42 +053072 stock_value=%s where name=%s""",
Anand Doshi1b531862013-01-10 19:29:51 +053073 (qty_after_transaction, valuation_rate,
Nabin Hait914c6df2013-01-14 13:15:42 +053074 json.dumps(stock_queue), stock_value, sle.name))
Anand Doshi1b531862013-01-10 19:29:51 +053075
Nabin Hait902e8602013-01-08 18:29:24 +053076 if _exceptions:
Nabin Hait9514d172013-01-10 10:40:37 +053077 _raise_exceptions(args, verbose)
Nabin Hait902e8602013-01-08 18:29:24 +053078
79 # update bin
Nabin Haitac53b112013-01-11 19:25:46 +053080 if not webnotes.conn.exists({"doctype": "Bin", "item_code": args["item_code"],
81 "warehouse": args["warehouse"]}):
Rushabh Mehtac53231a2013-02-18 18:24:28 +053082 bin_wrapper = webnotes.bean([{
Nabin Haitac53b112013-01-11 19:25:46 +053083 "doctype": "Bin",
84 "item_code": args["item_code"],
85 "warehouse": args["warehouse"],
Anand Doshic313d662013-01-14 15:46:17 +053086 }])
87 bin_wrapper.ignore_permissions = 1
88 bin_wrapper.insert()
Nabin Haitac53b112013-01-11 19:25:46 +053089
Anand Doshi1b531862013-01-10 19:29:51 +053090 webnotes.conn.sql("""update `tabBin` set valuation_rate=%s, actual_qty=%s,
91 stock_value=%s,
Nabin Hait902e8602013-01-08 18:29:24 +053092 projected_qty = (actual_qty + indented_qty + ordered_qty + planned_qty - reserved_qty)
93 where item_code=%s and warehouse=%s""", (valuation_rate, qty_after_transaction,
94 stock_value, args["item_code"], args["warehouse"]))
95
Anand Doshi4dc7caa2013-01-11 11:44:49 +053096def get_sle_before_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +053097 """
98 get previous stock ledger entry before current time-bucket
99
100 Details:
101 get the last sle before the current time-bucket, so that all values
102 are reposted from the current time-bucket onwards.
103 this is necessary because at the time of cancellation, there may be
104 entries between the cancelled entries in the same time-bucket
105 """
106 sle = get_stock_ledger_entries(args,
Nabin Hait26d46552013-01-09 15:23:05 +0530107 ["timestamp(posting_date, posting_time) < timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530108 "desc", "limit 1", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530109
110 return sle and sle[0] or webnotes._dict()
111
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530112def get_sle_after_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530113 """get Stock Ledger Entries after a particular datetime, for reposting"""
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530114 # NOTE: using for update of
Nabin Hait902e8602013-01-08 18:29:24 +0530115 return get_stock_ledger_entries(args,
Nabin Hait9514d172013-01-10 10:40:37 +0530116 ["timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530117 "asc", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530118
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530119def get_stock_ledger_entries(args, conditions=None, order="desc", limit=None, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530120 """get stock ledger entries filtered by specific posting datetime conditions"""
121 if not args.get("posting_date"):
122 args["posting_date"] = "1900-01-01"
123 if not args.get("posting_time"):
Anand Doshi71bed312013-03-13 12:57:04 +0530124 args["posting_time"] = "00:00"
Nabin Hait902e8602013-01-08 18:29:24 +0530125
126 return webnotes.conn.sql("""select * from `tabStock Ledger Entry`
127 where item_code = %%(item_code)s
128 and warehouse = %%(warehouse)s
129 and ifnull(is_cancelled, 'No') = 'No'
130 %(conditions)s
Nabin Hait9514d172013-01-10 10:40:37 +0530131 order by timestamp(posting_date, posting_time) %(order)s, name %(order)s
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530132 %(limit)s %(for_update)s""" % {
Nabin Hait902e8602013-01-08 18:29:24 +0530133 "conditions": conditions and ("and " + " and ".join(conditions)) or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530134 "limit": limit or "",
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530135 "for_update": for_update and "for update" or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530136 "order": order
Nabin Hait902e8602013-01-08 18:29:24 +0530137 }, args, as_dict=1)
138
139def validate_negative_stock(qty_after_transaction, sle):
140 """
141 validate negative stock for entries current datetime onwards
142 will not consider cancelled entries
143 """
144 diff = qty_after_transaction + flt(sle.actual_qty)
Pratik Vyas16371b72013-09-18 18:31:03 +0530145
146 if not _exceptions:
147 webnotes.local.stockledger_exceptions = []
Nabin Hait902e8602013-01-08 18:29:24 +0530148
149 if diff < 0 and abs(diff) > 0.0001:
150 # negative stock!
Nabin Hait902e8602013-01-08 18:29:24 +0530151 exc = sle.copy().update({"diff": diff})
152 _exceptions.append(exc)
153 return False
154 else:
155 return True
156
157def get_serialized_values(qty_after_transaction, sle, valuation_rate):
158 incoming_rate = flt(sle.incoming_rate)
159 actual_qty = flt(sle.actual_qty)
Anand Doshi1b531862013-01-10 19:29:51 +0530160 serial_no = cstr(sle.serial_no).split("\n")
Nabin Hait902e8602013-01-08 18:29:24 +0530161
162 if incoming_rate < 0:
163 # wrong incoming rate
164 incoming_rate = valuation_rate
165 elif incoming_rate == 0 or flt(sle.actual_qty) < 0:
166 # In case of delivery/stock issue, get average purchase rate
167 # of serial nos of current entry
168 incoming_rate = flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0))
Anand Doshi1b531862013-01-10 19:29:51 +0530169 from `tabSerial No` where name in (%s)""" % (", ".join(["%s"]*len(serial_no))),
170 tuple(serial_no))[0][0])
Nabin Hait902e8602013-01-08 18:29:24 +0530171
172 if incoming_rate and not valuation_rate:
173 valuation_rate = incoming_rate
174 else:
175 new_stock_qty = qty_after_transaction + actual_qty
176 if new_stock_qty > 0:
177 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
178 if new_stock_value > 0:
179 # calculate new valuation rate only if stock value is positive
180 # else it remains the same as that of previous entry
181 valuation_rate = new_stock_value / new_stock_qty
Anand Doshi1b531862013-01-10 19:29:51 +0530182
Nabin Hait914c6df2013-01-14 13:15:42 +0530183 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530184
185def get_moving_average_values(qty_after_transaction, sle, valuation_rate):
186 incoming_rate = flt(sle.incoming_rate)
Nabin Hait914c6df2013-01-14 13:15:42 +0530187 actual_qty = flt(sle.actual_qty)
Nabin Hait902e8602013-01-08 18:29:24 +0530188
Anand Doshi1b531862013-01-10 19:29:51 +0530189 if not incoming_rate:
Nabin Hait902e8602013-01-08 18:29:24 +0530190 # In case of delivery/stock issue in_rate = 0 or wrong incoming rate
191 incoming_rate = valuation_rate
192
Anand Doshi1b531862013-01-10 19:29:51 +0530193 elif qty_after_transaction < 0:
194 # if negative stock, take current valuation rate as incoming rate
195 valuation_rate = incoming_rate
196
Nabin Hait902e8602013-01-08 18:29:24 +0530197 new_stock_qty = qty_after_transaction + actual_qty
198 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
Anand Doshi1b531862013-01-10 19:29:51 +0530199
200 if new_stock_qty > 0 and new_stock_value > 0:
Nabin Hait902e8602013-01-08 18:29:24 +0530201 valuation_rate = new_stock_value / flt(new_stock_qty)
202 elif new_stock_qty <= 0:
203 valuation_rate = 0.0
Anand Doshi1b531862013-01-10 19:29:51 +0530204
205 # NOTE: val_rate is same as previous entry if new stock value is negative
206
Nabin Hait914c6df2013-01-14 13:15:42 +0530207 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530208
209def get_fifo_values(qty_after_transaction, sle, stock_queue):
210 incoming_rate = flt(sle.incoming_rate)
211 actual_qty = flt(sle.actual_qty)
Nabin Hait902e8602013-01-08 18:29:24 +0530212 if not stock_queue:
213 stock_queue.append([0, 0])
Nabin Hait9514d172013-01-10 10:40:37 +0530214
Nabin Hait902e8602013-01-08 18:29:24 +0530215 if actual_qty > 0:
216 if stock_queue[-1][0] > 0:
217 stock_queue.append([actual_qty, incoming_rate])
218 else:
219 qty = stock_queue[-1][0] + actual_qty
220 stock_queue[-1] = [qty, qty > 0 and incoming_rate or 0]
221 else:
222 incoming_cost = 0
223 qty_to_pop = abs(actual_qty)
224 while qty_to_pop:
Nabin Hait9514d172013-01-10 10:40:37 +0530225 if not stock_queue:
226 stock_queue.append([0, 0])
227
Nabin Hait902e8602013-01-08 18:29:24 +0530228 batch = stock_queue[0]
229
230 if 0 < batch[0] <= qty_to_pop:
231 # if batch qty > 0
232 # not enough or exactly same qty in current batch, clear batch
233 incoming_cost += flt(batch[0]) * flt(batch[1])
234 qty_to_pop -= batch[0]
235 stock_queue.pop(0)
236 else:
237 # all from current batch
238 incoming_cost += flt(qty_to_pop) * flt(batch[1])
239 batch[0] -= qty_to_pop
240 qty_to_pop = 0
241
Nabin Hait902e8602013-01-08 18:29:24 +0530242 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
243 stock_qty = sum((flt(batch[0]) for batch in stock_queue))
244
245 valuation_rate = stock_qty and (stock_value / flt(stock_qty)) or 0
Nabin Hait9514d172013-01-10 10:40:37 +0530246
Nabin Hait914c6df2013-01-14 13:15:42 +0530247 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530248
Nabin Hait9514d172013-01-10 10:40:37 +0530249def _raise_exceptions(args, verbose=1):
Nabin Hait902e8602013-01-08 18:29:24 +0530250 deficiency = min(e["diff"] for e in _exceptions)
251 msg = """Negative stock error:
252 Cannot complete this transaction because stock will start
253 becoming negative (%s) for Item <b>%s</b> in Warehouse
254 <b>%s</b> on <b>%s %s</b> in Transaction %s %s.
255 Total Quantity Deficiency: <b>%s</b>""" % \
256 (_exceptions[0]["diff"], args.get("item_code"), args.get("warehouse"),
257 _exceptions[0]["posting_date"], _exceptions[0]["posting_time"],
258 _exceptions[0]["voucher_type"], _exceptions[0]["voucher_no"],
259 abs(deficiency))
260 if verbose:
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530261 msgprint(msg, raise_exception=NegativeStockError)
Nabin Hait902e8602013-01-08 18:29:24 +0530262 else:
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530263 raise NegativeStockError, msg
Anand Doshi1b531862013-01-10 19:29:51 +0530264
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530265def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530266 """
267 get the last sle on or before the current time-bucket,
268 to get actual qty before transaction, this function
269 is called from various transaction like stock entry, reco etc
270
271 args = {
272 "item_code": "ABC",
273 "warehouse": "XYZ",
274 "posting_date": "2012-12-12",
275 "posting_time": "12:00",
276 "sle": "name of reference Stock Ledger Entry"
277 }
278 """
279 if not args.get("sle"): args["sle"] = ""
280
281 sle = get_stock_ledger_entries(args, ["name != %(sle)s",
282 "timestamp(posting_date, posting_time) <= timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530283 "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530284 return sle and sle[0] or {}