blob: f88ea5d0f687bdd3f665e16be4ccc528a6b469ba [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)
39
40 qty_after_transaction = flt(previous_sle.get("qty_after_transaction"))
41 valuation_rate = flt(previous_sle.get("valuation_rate"))
42 stock_queue = json.loads(previous_sle.get("stock_queue") or "[]")
Nabin Hait9514d172013-01-10 10:40:37 +053043 stock_value = 0.0
Nabin Hait902e8602013-01-08 18:29:24 +053044
45 entries_to_fix = get_sle_after_datetime(previous_sle or \
Anand Doshi4dc7caa2013-01-11 11:44:49 +053046 {"item_code": args["item_code"], "warehouse": args["warehouse"]}, for_update=True)
Nabin Hait902e8602013-01-08 18:29:24 +053047
48 valuation_method = get_valuation_method(args["item_code"])
49
50 for sle in entries_to_fix:
Anand Doshi1b531862013-01-10 19:29:51 +053051 if sle.serial_no or not cint(webnotes.conn.get_default("allow_negative_stock")):
Nabin Hait902e8602013-01-08 18:29:24 +053052 # validate negative stock for serialized items, fifo valuation
53 # or when negative stock is not allowed for moving average
54 if not validate_negative_stock(qty_after_transaction, sle):
55 qty_after_transaction += flt(sle.actual_qty)
56 continue
57
Anand Doshi1b531862013-01-10 19:29:51 +053058 if sle.serial_no:
Nabin Hait902e8602013-01-08 18:29:24 +053059 valuation_rate, incoming_rate = get_serialized_values(qty_after_transaction, sle,
60 valuation_rate)
61 elif valuation_method == "Moving Average":
62 valuation_rate, incoming_rate = get_moving_average_values(qty_after_transaction, sle,
63 valuation_rate)
64 else:
65 valuation_rate, incoming_rate = get_fifo_values(qty_after_transaction, sle,
66 stock_queue)
Anand Doshi1b531862013-01-10 19:29:51 +053067
Nabin Hait902e8602013-01-08 18:29:24 +053068 qty_after_transaction += flt(sle.actual_qty)
69
70 # get stock value
Anand Doshi1b531862013-01-10 19:29:51 +053071 if sle.serial_no:
Nabin Hait902e8602013-01-08 18:29:24 +053072 stock_value = qty_after_transaction * valuation_rate
73 elif valuation_method == "Moving Average":
74 stock_value = (qty_after_transaction > 0) and \
75 (qty_after_transaction * valuation_rate) or 0
76 else:
77 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
Nabin Hait9514d172013-01-10 10:40:37 +053078
Anand Doshi1b531862013-01-10 19:29:51 +053079 # print sle.posting_date, qty_after_transaction, incoming_rate, valuation_rate
80
Nabin Hait902e8602013-01-08 18:29:24 +053081 # update current sle
82 webnotes.conn.sql("""update `tabStock Ledger Entry`
Anand Doshi1b531862013-01-10 19:29:51 +053083 set qty_after_transaction=%s, valuation_rate=%s, stock_queue=%s,
84 stock_value=%s, incoming_rate = %s where name=%s""",
85 (qty_after_transaction, valuation_rate,
Nabin Hait902e8602013-01-08 18:29:24 +053086 json.dumps(stock_queue), stock_value, incoming_rate, sle.name))
Anand Doshi1b531862013-01-10 19:29:51 +053087
Nabin Hait902e8602013-01-08 18:29:24 +053088 if _exceptions:
Nabin Hait9514d172013-01-10 10:40:37 +053089 _raise_exceptions(args, verbose)
Nabin Hait902e8602013-01-08 18:29:24 +053090
91 # update bin
Anand Doshi1b531862013-01-10 19:29:51 +053092 webnotes.conn.sql("""update `tabBin` set valuation_rate=%s, actual_qty=%s,
93 stock_value=%s,
Nabin Hait902e8602013-01-08 18:29:24 +053094 projected_qty = (actual_qty + indented_qty + ordered_qty + planned_qty - reserved_qty)
95 where item_code=%s and warehouse=%s""", (valuation_rate, qty_after_transaction,
96 stock_value, args["item_code"], args["warehouse"]))
97
Anand Doshi4dc7caa2013-01-11 11:44:49 +053098def get_sle_before_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +053099 """
100 get previous stock ledger entry before current time-bucket
101
102 Details:
103 get the last sle before the current time-bucket, so that all values
104 are reposted from the current time-bucket onwards.
105 this is necessary because at the time of cancellation, there may be
106 entries between the cancelled entries in the same time-bucket
107 """
108 sle = get_stock_ledger_entries(args,
Nabin Hait26d46552013-01-09 15:23:05 +0530109 ["timestamp(posting_date, posting_time) < timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530110 "desc", "limit 1", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530111
112 return sle and sle[0] or webnotes._dict()
113
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530114def get_sle_after_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530115 """get Stock Ledger Entries after a particular datetime, for reposting"""
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530116 # NOTE: using for update of
Nabin Hait902e8602013-01-08 18:29:24 +0530117 return get_stock_ledger_entries(args,
Nabin Hait9514d172013-01-10 10:40:37 +0530118 ["timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530119 "asc", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530120
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530121def get_stock_ledger_entries(args, conditions=None, order="desc", limit=None, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530122 """get stock ledger entries filtered by specific posting datetime conditions"""
123 if not args.get("posting_date"):
124 args["posting_date"] = "1900-01-01"
125 if not args.get("posting_time"):
126 args["posting_time"] = "12:00"
127
128 return webnotes.conn.sql("""select * from `tabStock Ledger Entry`
129 where item_code = %%(item_code)s
130 and warehouse = %%(warehouse)s
131 and ifnull(is_cancelled, 'No') = 'No'
132 %(conditions)s
Nabin Hait9514d172013-01-10 10:40:37 +0530133 order by timestamp(posting_date, posting_time) %(order)s, name %(order)s
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530134 %(limit)s %(for_update)s""" % {
Nabin Hait902e8602013-01-08 18:29:24 +0530135 "conditions": conditions and ("and " + " and ".join(conditions)) or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530136 "limit": limit or "",
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530137 "for_update": for_update and "for update" or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530138 "order": order
Nabin Hait902e8602013-01-08 18:29:24 +0530139 }, args, as_dict=1)
140
141def validate_negative_stock(qty_after_transaction, sle):
142 """
143 validate negative stock for entries current datetime onwards
144 will not consider cancelled entries
145 """
146 diff = qty_after_transaction + flt(sle.actual_qty)
147
148 if diff < 0 and abs(diff) > 0.0001:
149 # negative stock!
150 global _exceptions
151 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 Hait902e8602013-01-08 18:29:24 +0530183 return valuation_rate, incoming_rate
184
185def get_moving_average_values(qty_after_transaction, sle, valuation_rate):
186 incoming_rate = flt(sle.incoming_rate)
187 actual_qty = flt(sle.actual_qty)
188
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 Hait902e8602013-01-08 18:29:24 +0530207 return valuation_rate, incoming_rate
208
209def get_fifo_values(qty_after_transaction, sle, stock_queue):
210 incoming_rate = flt(sle.incoming_rate)
211 actual_qty = flt(sle.actual_qty)
212
213 if not stock_queue:
214 stock_queue.append([0, 0])
Nabin Hait9514d172013-01-10 10:40:37 +0530215
Nabin Hait902e8602013-01-08 18:29:24 +0530216 if actual_qty > 0:
217 if stock_queue[-1][0] > 0:
218 stock_queue.append([actual_qty, incoming_rate])
219 else:
220 qty = stock_queue[-1][0] + actual_qty
221 stock_queue[-1] = [qty, qty > 0 and incoming_rate or 0]
222 else:
223 incoming_cost = 0
224 qty_to_pop = abs(actual_qty)
225 while qty_to_pop:
Nabin Hait9514d172013-01-10 10:40:37 +0530226 if not stock_queue:
227 stock_queue.append([0, 0])
228
Nabin Hait902e8602013-01-08 18:29:24 +0530229 batch = stock_queue[0]
230
231 if 0 < batch[0] <= qty_to_pop:
232 # if batch qty > 0
233 # not enough or exactly same qty in current batch, clear batch
234 incoming_cost += flt(batch[0]) * flt(batch[1])
235 qty_to_pop -= batch[0]
236 stock_queue.pop(0)
237 else:
238 # all from current batch
239 incoming_cost += flt(qty_to_pop) * flt(batch[1])
240 batch[0] -= qty_to_pop
241 qty_to_pop = 0
242
243 incoming_rate = incoming_cost / flt(abs(actual_qty))
244
245 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
246 stock_qty = sum((flt(batch[0]) for batch in stock_queue))
247
248 valuation_rate = stock_qty and (stock_value / flt(stock_qty)) or 0
Nabin Hait9514d172013-01-10 10:40:37 +0530249
Nabin Hait902e8602013-01-08 18:29:24 +0530250 return valuation_rate, incoming_rate
251
Nabin Hait9514d172013-01-10 10:40:37 +0530252def _raise_exceptions(args, verbose=1):
Nabin Hait902e8602013-01-08 18:29:24 +0530253 deficiency = min(e["diff"] for e in _exceptions)
254 msg = """Negative stock error:
255 Cannot complete this transaction because stock will start
256 becoming negative (%s) for Item <b>%s</b> in Warehouse
257 <b>%s</b> on <b>%s %s</b> in Transaction %s %s.
258 Total Quantity Deficiency: <b>%s</b>""" % \
259 (_exceptions[0]["diff"], args.get("item_code"), args.get("warehouse"),
260 _exceptions[0]["posting_date"], _exceptions[0]["posting_time"],
261 _exceptions[0]["voucher_type"], _exceptions[0]["voucher_no"],
262 abs(deficiency))
263 if verbose:
264 msgprint(msg, raise_exception=1)
265 else:
Anand Doshi1b531862013-01-10 19:29:51 +0530266 raise webnotes.ValidationError, msg
267
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530268def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530269 """
270 get the last sle on or before the current time-bucket,
271 to get actual qty before transaction, this function
272 is called from various transaction like stock entry, reco etc
273
274 args = {
275 "item_code": "ABC",
276 "warehouse": "XYZ",
277 "posting_date": "2012-12-12",
278 "posting_time": "12:00",
279 "sle": "name of reference Stock Ledger Entry"
280 }
281 """
282 if not args.get("sle"): args["sle"] = ""
283
284 sle = get_stock_ledger_entries(args, ["name != %(sle)s",
285 "timestamp(posting_date, posting_time) <= timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530286 "desc", "limit 1", for_update=for_update)
Anand Doshi1b531862013-01-10 19:29:51 +0530287 return sle and sle[0] or {}