blob: 3bb3a00faae6ed6615d5c6d8ca01a7227c4c89f6 [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
15 for sle in sl_entries:
16 if sle.get("actual_qty"):
17 sle_id = make_entry(sle)
18
19 args = sle.copy()
20 args.update({
21 "sle_id": sle_id,
22 "is_amended": is_amended
23 })
24 update_bin(args)
25
26def make_entry(args):
27 args.update({"doctype": "Stock Ledger Entry"})
28 sle = webnotes.bean([args])
29 sle.ignore_permissions = 1
30 sle.insert()
Nabin Haitc13c1932013-08-20 12:28:44 +053031 # sle.submit()
Nabin Hait74c281c2013-08-19 16:17:18 +053032 return sle.doc.name
33
Nabin Hait902e8602013-01-08 18:29:24 +053034_exceptions = []
35def update_entries_after(args, verbose=1):
36 """
37 update valution rate and qty after transaction
38 from the current time-bucket onwards
39
40 args = {
41 "item_code": "ABC",
42 "warehouse": "XYZ",
43 "posting_date": "2012-12-12",
44 "posting_time": "12:00"
45 }
46 """
Nabin Haitf4591ec2013-05-23 19:07:10 +053047 global _exceptions
48 _exceptions = []
49
Nabin Hait902e8602013-01-08 18:29:24 +053050 previous_sle = get_sle_before_datetime(args)
Anand Doshi71bed312013-03-13 12:57:04 +053051
Nabin Hait902e8602013-01-08 18:29:24 +053052 qty_after_transaction = flt(previous_sle.get("qty_after_transaction"))
53 valuation_rate = flt(previous_sle.get("valuation_rate"))
54 stock_queue = json.loads(previous_sle.get("stock_queue") or "[]")
Nabin Hait469ee712013-08-07 12:33:37 +053055 stock_value = flt(previous_sle.get("stock_value"))
Nabin Hait902e8602013-01-08 18:29:24 +053056
57 entries_to_fix = get_sle_after_datetime(previous_sle or \
Anand Doshi4dc7caa2013-01-11 11:44:49 +053058 {"item_code": args["item_code"], "warehouse": args["warehouse"]}, for_update=True)
Nabin Hait469ee712013-08-07 12:33:37 +053059
Nabin Hait902e8602013-01-08 18:29:24 +053060 valuation_method = get_valuation_method(args["item_code"])
61
62 for sle in entries_to_fix:
Anand Doshi1b531862013-01-10 19:29:51 +053063 if sle.serial_no or not cint(webnotes.conn.get_default("allow_negative_stock")):
Nabin Hait902e8602013-01-08 18:29:24 +053064 # validate negative stock for serialized items, fifo valuation
65 # or when negative stock is not allowed for moving average
66 if not validate_negative_stock(qty_after_transaction, sle):
67 qty_after_transaction += flt(sle.actual_qty)
68 continue
Nabin Hait1b4f56c2013-01-17 17:01:51 +053069
Anand Doshi1b531862013-01-10 19:29:51 +053070 if sle.serial_no:
Nabin Hait1b4f56c2013-01-17 17:01:51 +053071 valuation_rate = get_serialized_values(qty_after_transaction, sle, valuation_rate)
Nabin Hait902e8602013-01-08 18:29:24 +053072 elif valuation_method == "Moving Average":
Nabin Hait1b4f56c2013-01-17 17:01:51 +053073 valuation_rate = get_moving_average_values(qty_after_transaction, sle, valuation_rate)
Nabin Hait902e8602013-01-08 18:29:24 +053074 else:
Nabin Hait1b4f56c2013-01-17 17:01:51 +053075 valuation_rate = get_fifo_values(qty_after_transaction, sle, stock_queue)
Anand Doshi1b531862013-01-10 19:29:51 +053076
Nabin Hait902e8602013-01-08 18:29:24 +053077 qty_after_transaction += flt(sle.actual_qty)
78
79 # get stock value
Anand Doshi1b531862013-01-10 19:29:51 +053080 if sle.serial_no:
Nabin Hait902e8602013-01-08 18:29:24 +053081 stock_value = qty_after_transaction * valuation_rate
82 elif valuation_method == "Moving Average":
83 stock_value = (qty_after_transaction > 0) and \
84 (qty_after_transaction * valuation_rate) or 0
85 else:
86 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
Nabin Hait815a49e2013-08-07 17:00:01 +053087
Nabin Hait902e8602013-01-08 18:29:24 +053088 # update current sle
89 webnotes.conn.sql("""update `tabStock Ledger Entry`
Anand Doshi1b531862013-01-10 19:29:51 +053090 set qty_after_transaction=%s, valuation_rate=%s, stock_queue=%s,
Nabin Hait914c6df2013-01-14 13:15:42 +053091 stock_value=%s where name=%s""",
Anand Doshi1b531862013-01-10 19:29:51 +053092 (qty_after_transaction, valuation_rate,
Nabin Hait914c6df2013-01-14 13:15:42 +053093 json.dumps(stock_queue), stock_value, sle.name))
Anand Doshi1b531862013-01-10 19:29:51 +053094
Nabin Hait902e8602013-01-08 18:29:24 +053095 if _exceptions:
Nabin Hait9514d172013-01-10 10:40:37 +053096 _raise_exceptions(args, verbose)
Nabin Hait902e8602013-01-08 18:29:24 +053097
98 # update bin
Nabin Haitac53b112013-01-11 19:25:46 +053099 if not webnotes.conn.exists({"doctype": "Bin", "item_code": args["item_code"],
100 "warehouse": args["warehouse"]}):
Rushabh Mehtac53231a2013-02-18 18:24:28 +0530101 bin_wrapper = webnotes.bean([{
Nabin Haitac53b112013-01-11 19:25:46 +0530102 "doctype": "Bin",
103 "item_code": args["item_code"],
104 "warehouse": args["warehouse"],
Anand Doshic313d662013-01-14 15:46:17 +0530105 }])
106 bin_wrapper.ignore_permissions = 1
107 bin_wrapper.insert()
Nabin Haitac53b112013-01-11 19:25:46 +0530108
Anand Doshi1b531862013-01-10 19:29:51 +0530109 webnotes.conn.sql("""update `tabBin` set valuation_rate=%s, actual_qty=%s,
110 stock_value=%s,
Nabin Hait902e8602013-01-08 18:29:24 +0530111 projected_qty = (actual_qty + indented_qty + ordered_qty + planned_qty - reserved_qty)
112 where item_code=%s and warehouse=%s""", (valuation_rate, qty_after_transaction,
113 stock_value, args["item_code"], args["warehouse"]))
114
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530115def get_sle_before_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530116 """
117 get previous stock ledger entry before current time-bucket
118
119 Details:
120 get the last sle before the current time-bucket, so that all values
121 are reposted from the current time-bucket onwards.
122 this is necessary because at the time of cancellation, there may be
123 entries between the cancelled entries in the same time-bucket
124 """
125 sle = get_stock_ledger_entries(args,
Nabin Hait26d46552013-01-09 15:23:05 +0530126 ["timestamp(posting_date, posting_time) < timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530127 "desc", "limit 1", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530128
129 return sle and sle[0] or webnotes._dict()
130
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530131def get_sle_after_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530132 """get Stock Ledger Entries after a particular datetime, for reposting"""
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530133 # NOTE: using for update of
Nabin Hait902e8602013-01-08 18:29:24 +0530134 return get_stock_ledger_entries(args,
Nabin Hait9514d172013-01-10 10:40:37 +0530135 ["timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530136 "asc", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530137
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530138def get_stock_ledger_entries(args, conditions=None, order="desc", limit=None, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530139 """get stock ledger entries filtered by specific posting datetime conditions"""
140 if not args.get("posting_date"):
141 args["posting_date"] = "1900-01-01"
142 if not args.get("posting_time"):
Anand Doshi71bed312013-03-13 12:57:04 +0530143 args["posting_time"] = "00:00"
Nabin Hait902e8602013-01-08 18:29:24 +0530144
145 return webnotes.conn.sql("""select * from `tabStock Ledger Entry`
146 where item_code = %%(item_code)s
147 and warehouse = %%(warehouse)s
Nabin Hait902e8602013-01-08 18:29:24 +0530148 %(conditions)s
Nabin Hait9514d172013-01-10 10:40:37 +0530149 order by timestamp(posting_date, posting_time) %(order)s, name %(order)s
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530150 %(limit)s %(for_update)s""" % {
Nabin Hait902e8602013-01-08 18:29:24 +0530151 "conditions": conditions and ("and " + " and ".join(conditions)) or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530152 "limit": limit or "",
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530153 "for_update": for_update and "for update" or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530154 "order": order
Nabin Hait902e8602013-01-08 18:29:24 +0530155 }, args, as_dict=1)
156
157def validate_negative_stock(qty_after_transaction, sle):
158 """
159 validate negative stock for entries current datetime onwards
160 will not consider cancelled entries
161 """
162 diff = qty_after_transaction + flt(sle.actual_qty)
163
164 if diff < 0 and abs(diff) > 0.0001:
165 # negative stock!
166 global _exceptions
167 exc = sle.copy().update({"diff": diff})
168 _exceptions.append(exc)
169 return False
170 else:
171 return True
172
173def get_serialized_values(qty_after_transaction, sle, valuation_rate):
174 incoming_rate = flt(sle.incoming_rate)
175 actual_qty = flt(sle.actual_qty)
Anand Doshi1b531862013-01-10 19:29:51 +0530176 serial_no = cstr(sle.serial_no).split("\n")
Nabin Hait902e8602013-01-08 18:29:24 +0530177
178 if incoming_rate < 0:
179 # wrong incoming rate
180 incoming_rate = valuation_rate
181 elif incoming_rate == 0 or flt(sle.actual_qty) < 0:
182 # In case of delivery/stock issue, get average purchase rate
183 # of serial nos of current entry
184 incoming_rate = flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0))
Anand Doshi1b531862013-01-10 19:29:51 +0530185 from `tabSerial No` where name in (%s)""" % (", ".join(["%s"]*len(serial_no))),
186 tuple(serial_no))[0][0])
Nabin Hait902e8602013-01-08 18:29:24 +0530187
188 if incoming_rate and not valuation_rate:
189 valuation_rate = incoming_rate
190 else:
191 new_stock_qty = qty_after_transaction + actual_qty
192 if new_stock_qty > 0:
193 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
194 if new_stock_value > 0:
195 # calculate new valuation rate only if stock value is positive
196 # else it remains the same as that of previous entry
197 valuation_rate = new_stock_value / new_stock_qty
Anand Doshi1b531862013-01-10 19:29:51 +0530198
Nabin Hait914c6df2013-01-14 13:15:42 +0530199 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530200
201def get_moving_average_values(qty_after_transaction, sle, valuation_rate):
202 incoming_rate = flt(sle.incoming_rate)
Nabin Hait914c6df2013-01-14 13:15:42 +0530203 actual_qty = flt(sle.actual_qty)
Nabin Hait902e8602013-01-08 18:29:24 +0530204
Anand Doshi1b531862013-01-10 19:29:51 +0530205 if not incoming_rate:
Nabin Hait902e8602013-01-08 18:29:24 +0530206 # In case of delivery/stock issue in_rate = 0 or wrong incoming rate
207 incoming_rate = valuation_rate
208
Anand Doshi1b531862013-01-10 19:29:51 +0530209 elif qty_after_transaction < 0:
210 # if negative stock, take current valuation rate as incoming rate
211 valuation_rate = incoming_rate
212
Nabin Hait902e8602013-01-08 18:29:24 +0530213 new_stock_qty = qty_after_transaction + actual_qty
214 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
Anand Doshi1b531862013-01-10 19:29:51 +0530215
216 if new_stock_qty > 0 and new_stock_value > 0:
Nabin Hait902e8602013-01-08 18:29:24 +0530217 valuation_rate = new_stock_value / flt(new_stock_qty)
218 elif new_stock_qty <= 0:
219 valuation_rate = 0.0
Anand Doshi1b531862013-01-10 19:29:51 +0530220
221 # NOTE: val_rate is same as previous entry if new stock value is negative
222
Nabin Hait914c6df2013-01-14 13:15:42 +0530223 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530224
225def get_fifo_values(qty_after_transaction, sle, stock_queue):
226 incoming_rate = flt(sle.incoming_rate)
227 actual_qty = flt(sle.actual_qty)
Nabin Hait902e8602013-01-08 18:29:24 +0530228 if not stock_queue:
229 stock_queue.append([0, 0])
Nabin Hait9514d172013-01-10 10:40:37 +0530230
Nabin Hait902e8602013-01-08 18:29:24 +0530231 if actual_qty > 0:
232 if stock_queue[-1][0] > 0:
233 stock_queue.append([actual_qty, incoming_rate])
234 else:
235 qty = stock_queue[-1][0] + actual_qty
236 stock_queue[-1] = [qty, qty > 0 and incoming_rate or 0]
237 else:
238 incoming_cost = 0
239 qty_to_pop = abs(actual_qty)
240 while qty_to_pop:
Nabin Hait9514d172013-01-10 10:40:37 +0530241 if not stock_queue:
242 stock_queue.append([0, 0])
243
Nabin Hait902e8602013-01-08 18:29:24 +0530244 batch = stock_queue[0]
245
246 if 0 < batch[0] <= qty_to_pop:
247 # if batch qty > 0
248 # not enough or exactly same qty in current batch, clear batch
249 incoming_cost += flt(batch[0]) * flt(batch[1])
250 qty_to_pop -= batch[0]
251 stock_queue.pop(0)
252 else:
253 # all from current batch
254 incoming_cost += flt(qty_to_pop) * flt(batch[1])
255 batch[0] -= qty_to_pop
256 qty_to_pop = 0
257
Nabin Hait902e8602013-01-08 18:29:24 +0530258 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
259 stock_qty = sum((flt(batch[0]) for batch in stock_queue))
260
261 valuation_rate = stock_qty and (stock_value / flt(stock_qty)) or 0
Nabin Hait9514d172013-01-10 10:40:37 +0530262
Nabin Hait914c6df2013-01-14 13:15:42 +0530263 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530264
Nabin Hait9514d172013-01-10 10:40:37 +0530265def _raise_exceptions(args, verbose=1):
Nabin Hait902e8602013-01-08 18:29:24 +0530266 deficiency = min(e["diff"] for e in _exceptions)
267 msg = """Negative stock error:
268 Cannot complete this transaction because stock will start
269 becoming negative (%s) for Item <b>%s</b> in Warehouse
270 <b>%s</b> on <b>%s %s</b> in Transaction %s %s.
271 Total Quantity Deficiency: <b>%s</b>""" % \
272 (_exceptions[0]["diff"], args.get("item_code"), args.get("warehouse"),
273 _exceptions[0]["posting_date"], _exceptions[0]["posting_time"],
274 _exceptions[0]["voucher_type"], _exceptions[0]["voucher_no"],
275 abs(deficiency))
276 if verbose:
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530277 msgprint(msg, raise_exception=NegativeStockError)
Nabin Hait902e8602013-01-08 18:29:24 +0530278 else:
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530279 raise NegativeStockError, msg
Anand Doshi1b531862013-01-10 19:29:51 +0530280
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530281def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530282 """
283 get the last sle on or before the current time-bucket,
284 to get actual qty before transaction, this function
285 is called from various transaction like stock entry, reco etc
286
287 args = {
288 "item_code": "ABC",
289 "warehouse": "XYZ",
290 "posting_date": "2012-12-12",
291 "posting_time": "12:00",
292 "sle": "name of reference Stock Ledger Entry"
293 }
294 """
295 if not args.get("sle"): args["sle"] = ""
296
297 sle = get_stock_ledger_entries(args, ["name != %(sle)s",
298 "timestamp(posting_date, posting_time) <= timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530299 "desc", "limit 1", for_update=for_update)
Anand Doshi1b531862013-01-10 19:29:51 +0530300 return sle and sle[0] or {}