blob: 883ced7f710c4ec0cd4157805572a039c31fa17a [file] [log] [blame]
Nabin Hait902e8602013-01-08 18:29:24 +05301# ERPNext - web based ERP (http://erpnext.com)
2# Copyright (C) 2012 Web Notes Technologies Pvt Ltd
3#
4# This program is free software: you can redistribute it and/or modify
5# it under the terms of the GNU General Public License as published by
6# the Free Software Foundation, either version 3 of the License, or
7# (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License
15# along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17import webnotes
Anand Doshi1b531862013-01-10 19:29:51 +053018from webnotes import msgprint
Nabin Hait26d46552013-01-09 15:23:05 +053019from webnotes.utils import cint, flt, cstr
Anand Doshi1b531862013-01-10 19:29:51 +053020from stock.utils import get_valuation_method
Nabin Hait26d46552013-01-09 15:23:05 +053021import json
Nabin Hait902e8602013-01-08 18:29:24 +053022
23# future reposting
24
25_exceptions = []
26def update_entries_after(args, verbose=1):
27 """
28 update valution rate and qty after transaction
29 from the current time-bucket onwards
30
31 args = {
32 "item_code": "ABC",
33 "warehouse": "XYZ",
34 "posting_date": "2012-12-12",
35 "posting_time": "12:00"
36 }
37 """
38 previous_sle = get_sle_before_datetime(args)
Nabin Hait902e8602013-01-08 18:29:24 +053039 qty_after_transaction = flt(previous_sle.get("qty_after_transaction"))
40 valuation_rate = flt(previous_sle.get("valuation_rate"))
41 stock_queue = json.loads(previous_sle.get("stock_queue") or "[]")
Nabin Hait9514d172013-01-10 10:40:37 +053042 stock_value = 0.0
Nabin Hait902e8602013-01-08 18:29:24 +053043
44 entries_to_fix = get_sle_after_datetime(previous_sle or \
Anand Doshi4dc7caa2013-01-11 11:44:49 +053045 {"item_code": args["item_code"], "warehouse": args["warehouse"]}, for_update=True)
Nabin Hait902e8602013-01-08 18:29:24 +053046
47 valuation_method = get_valuation_method(args["item_code"])
48
49 for sle in entries_to_fix:
Anand Doshi1b531862013-01-10 19:29:51 +053050 if sle.serial_no or not cint(webnotes.conn.get_default("allow_negative_stock")):
Nabin Hait902e8602013-01-08 18:29:24 +053051 # validate negative stock for serialized items, fifo valuation
52 # or when negative stock is not allowed for moving average
53 if not validate_negative_stock(qty_after_transaction, sle):
54 qty_after_transaction += flt(sle.actual_qty)
55 continue
Nabin Hait1b4f56c2013-01-17 17:01:51 +053056
Anand Doshi1b531862013-01-10 19:29:51 +053057 if sle.serial_no:
Nabin Hait1b4f56c2013-01-17 17:01:51 +053058 valuation_rate = get_serialized_values(qty_after_transaction, sle, valuation_rate)
Nabin Hait902e8602013-01-08 18:29:24 +053059 elif valuation_method == "Moving Average":
Nabin Hait1b4f56c2013-01-17 17:01:51 +053060 valuation_rate = get_moving_average_values(qty_after_transaction, sle, valuation_rate)
Nabin Hait902e8602013-01-08 18:29:24 +053061 else:
Nabin Hait1b4f56c2013-01-17 17:01:51 +053062 valuation_rate = get_fifo_values(qty_after_transaction, sle, stock_queue)
Anand Doshi1b531862013-01-10 19:29:51 +053063
Nabin Hait902e8602013-01-08 18:29:24 +053064 qty_after_transaction += flt(sle.actual_qty)
65
66 # get stock value
Anand Doshi1b531862013-01-10 19:29:51 +053067 if sle.serial_no:
Nabin Hait902e8602013-01-08 18:29:24 +053068 stock_value = qty_after_transaction * valuation_rate
69 elif valuation_method == "Moving Average":
70 stock_value = (qty_after_transaction > 0) and \
71 (qty_after_transaction * valuation_rate) or 0
72 else:
73 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
Nabin Hait914c6df2013-01-14 13:15:42 +053074
Nabin Hait902e8602013-01-08 18:29:24 +053075 # update current sle
76 webnotes.conn.sql("""update `tabStock Ledger Entry`
Anand Doshi1b531862013-01-10 19:29:51 +053077 set qty_after_transaction=%s, valuation_rate=%s, stock_queue=%s,
Nabin Hait914c6df2013-01-14 13:15:42 +053078 stock_value=%s where name=%s""",
Anand Doshi1b531862013-01-10 19:29:51 +053079 (qty_after_transaction, valuation_rate,
Nabin Hait914c6df2013-01-14 13:15:42 +053080 json.dumps(stock_queue), stock_value, sle.name))
Anand Doshi1b531862013-01-10 19:29:51 +053081
Nabin Hait902e8602013-01-08 18:29:24 +053082 if _exceptions:
Nabin Hait9514d172013-01-10 10:40:37 +053083 _raise_exceptions(args, verbose)
Nabin Hait902e8602013-01-08 18:29:24 +053084
85 # update bin
Nabin Haitac53b112013-01-11 19:25:46 +053086 if not webnotes.conn.exists({"doctype": "Bin", "item_code": args["item_code"],
87 "warehouse": args["warehouse"]}):
Rushabh Mehtac53231a2013-02-18 18:24:28 +053088 bin_wrapper = webnotes.bean([{
Nabin Haitac53b112013-01-11 19:25:46 +053089 "doctype": "Bin",
90 "item_code": args["item_code"],
91 "warehouse": args["warehouse"],
Anand Doshic313d662013-01-14 15:46:17 +053092 }])
93 bin_wrapper.ignore_permissions = 1
94 bin_wrapper.insert()
Nabin Haitac53b112013-01-11 19:25:46 +053095
Anand Doshi1b531862013-01-10 19:29:51 +053096 webnotes.conn.sql("""update `tabBin` set valuation_rate=%s, actual_qty=%s,
97 stock_value=%s,
Nabin Hait902e8602013-01-08 18:29:24 +053098 projected_qty = (actual_qty + indented_qty + ordered_qty + planned_qty - reserved_qty)
99 where item_code=%s and warehouse=%s""", (valuation_rate, qty_after_transaction,
100 stock_value, args["item_code"], args["warehouse"]))
101
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530102def get_sle_before_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530103 """
104 get previous stock ledger entry before current time-bucket
105
106 Details:
107 get the last sle before the current time-bucket, so that all values
108 are reposted from the current time-bucket onwards.
109 this is necessary because at the time of cancellation, there may be
110 entries between the cancelled entries in the same time-bucket
111 """
112 sle = get_stock_ledger_entries(args,
Nabin Hait26d46552013-01-09 15:23:05 +0530113 ["timestamp(posting_date, posting_time) < timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530114 "desc", "limit 1", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530115
116 return sle and sle[0] or webnotes._dict()
117
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530118def get_sle_after_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530119 """get Stock Ledger Entries after a particular datetime, for reposting"""
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530120 # NOTE: using for update of
Nabin Hait902e8602013-01-08 18:29:24 +0530121 return get_stock_ledger_entries(args,
Nabin Hait9514d172013-01-10 10:40:37 +0530122 ["timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530123 "asc", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530124
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530125def get_stock_ledger_entries(args, conditions=None, order="desc", limit=None, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530126 """get stock ledger entries filtered by specific posting datetime conditions"""
127 if not args.get("posting_date"):
128 args["posting_date"] = "1900-01-01"
129 if not args.get("posting_time"):
130 args["posting_time"] = "12:00"
131
132 return webnotes.conn.sql("""select * from `tabStock Ledger Entry`
133 where item_code = %%(item_code)s
134 and warehouse = %%(warehouse)s
135 and ifnull(is_cancelled, 'No') = 'No'
136 %(conditions)s
Nabin Hait9514d172013-01-10 10:40:37 +0530137 order by timestamp(posting_date, posting_time) %(order)s, name %(order)s
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530138 %(limit)s %(for_update)s""" % {
Nabin Hait902e8602013-01-08 18:29:24 +0530139 "conditions": conditions and ("and " + " and ".join(conditions)) or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530140 "limit": limit or "",
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530141 "for_update": for_update and "for update" or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530142 "order": order
Nabin Hait902e8602013-01-08 18:29:24 +0530143 }, args, as_dict=1)
144
145def validate_negative_stock(qty_after_transaction, sle):
146 """
147 validate negative stock for entries current datetime onwards
148 will not consider cancelled entries
149 """
150 diff = qty_after_transaction + flt(sle.actual_qty)
151
152 if diff < 0 and abs(diff) > 0.0001:
153 # negative stock!
154 global _exceptions
155 exc = sle.copy().update({"diff": diff})
156 _exceptions.append(exc)
157 return False
158 else:
159 return True
160
161def get_serialized_values(qty_after_transaction, sle, valuation_rate):
162 incoming_rate = flt(sle.incoming_rate)
163 actual_qty = flt(sle.actual_qty)
Anand Doshi1b531862013-01-10 19:29:51 +0530164 serial_no = cstr(sle.serial_no).split("\n")
Nabin Hait902e8602013-01-08 18:29:24 +0530165
166 if incoming_rate < 0:
167 # wrong incoming rate
168 incoming_rate = valuation_rate
169 elif incoming_rate == 0 or flt(sle.actual_qty) < 0:
170 # In case of delivery/stock issue, get average purchase rate
171 # of serial nos of current entry
172 incoming_rate = flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0))
Anand Doshi1b531862013-01-10 19:29:51 +0530173 from `tabSerial No` where name in (%s)""" % (", ".join(["%s"]*len(serial_no))),
174 tuple(serial_no))[0][0])
Nabin Hait902e8602013-01-08 18:29:24 +0530175
176 if incoming_rate and not valuation_rate:
177 valuation_rate = incoming_rate
178 else:
179 new_stock_qty = qty_after_transaction + actual_qty
180 if new_stock_qty > 0:
181 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
182 if new_stock_value > 0:
183 # calculate new valuation rate only if stock value is positive
184 # else it remains the same as that of previous entry
185 valuation_rate = new_stock_value / new_stock_qty
Anand Doshi1b531862013-01-10 19:29:51 +0530186
Nabin Hait914c6df2013-01-14 13:15:42 +0530187 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530188
189def get_moving_average_values(qty_after_transaction, sle, valuation_rate):
190 incoming_rate = flt(sle.incoming_rate)
Nabin Hait914c6df2013-01-14 13:15:42 +0530191 actual_qty = flt(sle.actual_qty)
Nabin Hait902e8602013-01-08 18:29:24 +0530192
Anand Doshi1b531862013-01-10 19:29:51 +0530193 if not incoming_rate:
Nabin Hait902e8602013-01-08 18:29:24 +0530194 # In case of delivery/stock issue in_rate = 0 or wrong incoming rate
195 incoming_rate = valuation_rate
196
Anand Doshi1b531862013-01-10 19:29:51 +0530197 elif qty_after_transaction < 0:
198 # if negative stock, take current valuation rate as incoming rate
199 valuation_rate = incoming_rate
200
Nabin Hait902e8602013-01-08 18:29:24 +0530201 new_stock_qty = qty_after_transaction + actual_qty
202 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
Anand Doshi1b531862013-01-10 19:29:51 +0530203
204 if new_stock_qty > 0 and new_stock_value > 0:
Nabin Hait902e8602013-01-08 18:29:24 +0530205 valuation_rate = new_stock_value / flt(new_stock_qty)
206 elif new_stock_qty <= 0:
207 valuation_rate = 0.0
Anand Doshi1b531862013-01-10 19:29:51 +0530208
209 # NOTE: val_rate is same as previous entry if new stock value is negative
210
Nabin Hait914c6df2013-01-14 13:15:42 +0530211 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530212
213def get_fifo_values(qty_after_transaction, sle, stock_queue):
214 incoming_rate = flt(sle.incoming_rate)
215 actual_qty = flt(sle.actual_qty)
Nabin Hait902e8602013-01-08 18:29:24 +0530216 if not stock_queue:
217 stock_queue.append([0, 0])
Nabin Hait9514d172013-01-10 10:40:37 +0530218
Nabin Hait902e8602013-01-08 18:29:24 +0530219 if actual_qty > 0:
220 if stock_queue[-1][0] > 0:
221 stock_queue.append([actual_qty, incoming_rate])
222 else:
223 qty = stock_queue[-1][0] + actual_qty
224 stock_queue[-1] = [qty, qty > 0 and incoming_rate or 0]
225 else:
226 incoming_cost = 0
227 qty_to_pop = abs(actual_qty)
228 while qty_to_pop:
Nabin Hait9514d172013-01-10 10:40:37 +0530229 if not stock_queue:
230 stock_queue.append([0, 0])
231
Nabin Hait902e8602013-01-08 18:29:24 +0530232 batch = stock_queue[0]
233
234 if 0 < batch[0] <= qty_to_pop:
235 # if batch qty > 0
236 # not enough or exactly same qty in current batch, clear batch
237 incoming_cost += flt(batch[0]) * flt(batch[1])
238 qty_to_pop -= batch[0]
239 stock_queue.pop(0)
240 else:
241 # all from current batch
242 incoming_cost += flt(qty_to_pop) * flt(batch[1])
243 batch[0] -= qty_to_pop
244 qty_to_pop = 0
245
Nabin Hait902e8602013-01-08 18:29:24 +0530246 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
247 stock_qty = sum((flt(batch[0]) for batch in stock_queue))
248
249 valuation_rate = stock_qty and (stock_value / flt(stock_qty)) or 0
Nabin Hait9514d172013-01-10 10:40:37 +0530250
Nabin Hait914c6df2013-01-14 13:15:42 +0530251 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530252
Nabin Hait9514d172013-01-10 10:40:37 +0530253def _raise_exceptions(args, verbose=1):
Nabin Hait902e8602013-01-08 18:29:24 +0530254 deficiency = min(e["diff"] for e in _exceptions)
255 msg = """Negative stock error:
256 Cannot complete this transaction because stock will start
257 becoming negative (%s) for Item <b>%s</b> in Warehouse
258 <b>%s</b> on <b>%s %s</b> in Transaction %s %s.
259 Total Quantity Deficiency: <b>%s</b>""" % \
260 (_exceptions[0]["diff"], args.get("item_code"), args.get("warehouse"),
261 _exceptions[0]["posting_date"], _exceptions[0]["posting_time"],
262 _exceptions[0]["voucher_type"], _exceptions[0]["voucher_no"],
263 abs(deficiency))
264 if verbose:
265 msgprint(msg, raise_exception=1)
266 else:
Anand Doshi1b531862013-01-10 19:29:51 +0530267 raise webnotes.ValidationError, msg
268
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530269def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530270 """
271 get the last sle on or before the current time-bucket,
272 to get actual qty before transaction, this function
273 is called from various transaction like stock entry, reco etc
274
275 args = {
276 "item_code": "ABC",
277 "warehouse": "XYZ",
278 "posting_date": "2012-12-12",
279 "posting_time": "12:00",
280 "sle": "name of reference Stock Ledger Entry"
281 }
282 """
283 if not args.get("sle"): args["sle"] = ""
284
285 sle = get_stock_ledger_entries(args, ["name != %(sle)s",
286 "timestamp(posting_date, posting_time) <= timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530287 "desc", "limit 1", for_update=for_update)
Anand Doshi1b531862013-01-10 19:29:51 +0530288 return sle and sle[0] or {}