blob: 2480263c1f98325f618cef3dfe7558f6180d9606 [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)
Anand Doshi71bed312013-03-13 12:57:04 +053039
Nabin Hait902e8602013-01-08 18:29:24 +053040 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)
Anand Doshi71bed312013-03-13 12:57:04 +053047
Nabin Hait902e8602013-01-08 18:29:24 +053048 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
Nabin Hait1b4f56c2013-01-17 17:01:51 +053057
Anand Doshi1b531862013-01-10 19:29:51 +053058 if sle.serial_no:
Nabin Hait1b4f56c2013-01-17 17:01:51 +053059 valuation_rate = get_serialized_values(qty_after_transaction, sle, valuation_rate)
Nabin Hait902e8602013-01-08 18:29:24 +053060 elif valuation_method == "Moving Average":
Nabin Hait1b4f56c2013-01-17 17:01:51 +053061 valuation_rate = get_moving_average_values(qty_after_transaction, sle, valuation_rate)
Nabin Hait902e8602013-01-08 18:29:24 +053062 else:
Nabin Hait1b4f56c2013-01-17 17:01:51 +053063 valuation_rate = get_fifo_values(qty_after_transaction, sle, stock_queue)
Anand Doshi1b531862013-01-10 19:29:51 +053064
Nabin Hait902e8602013-01-08 18:29:24 +053065 qty_after_transaction += flt(sle.actual_qty)
66
67 # get stock value
Anand Doshi1b531862013-01-10 19:29:51 +053068 if sle.serial_no:
Nabin Hait902e8602013-01-08 18:29:24 +053069 stock_value = qty_after_transaction * valuation_rate
70 elif valuation_method == "Moving Average":
71 stock_value = (qty_after_transaction > 0) and \
72 (qty_after_transaction * valuation_rate) or 0
73 else:
74 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
Nabin Haitc3afb252013-03-19 12:01:24 +053075 # print sle.posting_date, sle.actual_qty, sle.incoming_rate, stock_queue, stock_value
Nabin Hait902e8602013-01-08 18:29:24 +053076 # update current sle
77 webnotes.conn.sql("""update `tabStock Ledger Entry`
Anand Doshi1b531862013-01-10 19:29:51 +053078 set qty_after_transaction=%s, valuation_rate=%s, stock_queue=%s,
Nabin Hait914c6df2013-01-14 13:15:42 +053079 stock_value=%s where name=%s""",
Anand Doshi1b531862013-01-10 19:29:51 +053080 (qty_after_transaction, valuation_rate,
Nabin Hait914c6df2013-01-14 13:15:42 +053081 json.dumps(stock_queue), stock_value, sle.name))
Anand Doshi1b531862013-01-10 19:29:51 +053082
Nabin Hait902e8602013-01-08 18:29:24 +053083 if _exceptions:
Nabin Hait9514d172013-01-10 10:40:37 +053084 _raise_exceptions(args, verbose)
Nabin Hait902e8602013-01-08 18:29:24 +053085
86 # update bin
Nabin Haitac53b112013-01-11 19:25:46 +053087 if not webnotes.conn.exists({"doctype": "Bin", "item_code": args["item_code"],
88 "warehouse": args["warehouse"]}):
Rushabh Mehtac53231a2013-02-18 18:24:28 +053089 bin_wrapper = webnotes.bean([{
Nabin Haitac53b112013-01-11 19:25:46 +053090 "doctype": "Bin",
91 "item_code": args["item_code"],
92 "warehouse": args["warehouse"],
Anand Doshic313d662013-01-14 15:46:17 +053093 }])
94 bin_wrapper.ignore_permissions = 1
95 bin_wrapper.insert()
Nabin Haitac53b112013-01-11 19:25:46 +053096
Anand Doshi1b531862013-01-10 19:29:51 +053097 webnotes.conn.sql("""update `tabBin` set valuation_rate=%s, actual_qty=%s,
98 stock_value=%s,
Nabin Hait902e8602013-01-08 18:29:24 +053099 projected_qty = (actual_qty + indented_qty + ordered_qty + planned_qty - reserved_qty)
100 where item_code=%s and warehouse=%s""", (valuation_rate, qty_after_transaction,
101 stock_value, args["item_code"], args["warehouse"]))
102
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530103def get_sle_before_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530104 """
105 get previous stock ledger entry before current time-bucket
106
107 Details:
108 get the last sle before the current time-bucket, so that all values
109 are reposted from the current time-bucket onwards.
110 this is necessary because at the time of cancellation, there may be
111 entries between the cancelled entries in the same time-bucket
112 """
113 sle = get_stock_ledger_entries(args,
Nabin Hait26d46552013-01-09 15:23:05 +0530114 ["timestamp(posting_date, posting_time) < timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530115 "desc", "limit 1", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530116
117 return sle and sle[0] or webnotes._dict()
118
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530119def get_sle_after_datetime(args, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530120 """get Stock Ledger Entries after a particular datetime, for reposting"""
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530121 # NOTE: using for update of
Nabin Hait902e8602013-01-08 18:29:24 +0530122 return get_stock_ledger_entries(args,
Nabin Hait9514d172013-01-10 10:40:37 +0530123 ["timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530124 "asc", for_update=for_update)
Nabin Hait902e8602013-01-08 18:29:24 +0530125
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530126def get_stock_ledger_entries(args, conditions=None, order="desc", limit=None, for_update=False):
Nabin Hait902e8602013-01-08 18:29:24 +0530127 """get stock ledger entries filtered by specific posting datetime conditions"""
128 if not args.get("posting_date"):
129 args["posting_date"] = "1900-01-01"
130 if not args.get("posting_time"):
Anand Doshi71bed312013-03-13 12:57:04 +0530131 args["posting_time"] = "00:00"
Nabin Hait902e8602013-01-08 18:29:24 +0530132
133 return webnotes.conn.sql("""select * from `tabStock Ledger Entry`
134 where item_code = %%(item_code)s
135 and warehouse = %%(warehouse)s
136 and ifnull(is_cancelled, 'No') = 'No'
137 %(conditions)s
Nabin Hait9514d172013-01-10 10:40:37 +0530138 order by timestamp(posting_date, posting_time) %(order)s, name %(order)s
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530139 %(limit)s %(for_update)s""" % {
Nabin Hait902e8602013-01-08 18:29:24 +0530140 "conditions": conditions and ("and " + " and ".join(conditions)) or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530141 "limit": limit or "",
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530142 "for_update": for_update and "for update" or "",
Nabin Hait9514d172013-01-10 10:40:37 +0530143 "order": order
Nabin Hait902e8602013-01-08 18:29:24 +0530144 }, args, as_dict=1)
145
146def validate_negative_stock(qty_after_transaction, sle):
147 """
148 validate negative stock for entries current datetime onwards
149 will not consider cancelled entries
150 """
151 diff = qty_after_transaction + flt(sle.actual_qty)
152
153 if diff < 0 and abs(diff) > 0.0001:
154 # negative stock!
155 global _exceptions
156 exc = sle.copy().update({"diff": diff})
157 _exceptions.append(exc)
158 return False
159 else:
160 return True
161
162def get_serialized_values(qty_after_transaction, sle, valuation_rate):
163 incoming_rate = flt(sle.incoming_rate)
164 actual_qty = flt(sle.actual_qty)
Anand Doshi1b531862013-01-10 19:29:51 +0530165 serial_no = cstr(sle.serial_no).split("\n")
Nabin Hait902e8602013-01-08 18:29:24 +0530166
167 if incoming_rate < 0:
168 # wrong incoming rate
169 incoming_rate = valuation_rate
170 elif incoming_rate == 0 or flt(sle.actual_qty) < 0:
171 # In case of delivery/stock issue, get average purchase rate
172 # of serial nos of current entry
173 incoming_rate = flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0))
Anand Doshi1b531862013-01-10 19:29:51 +0530174 from `tabSerial No` where name in (%s)""" % (", ".join(["%s"]*len(serial_no))),
175 tuple(serial_no))[0][0])
Nabin Hait902e8602013-01-08 18:29:24 +0530176
177 if incoming_rate and not valuation_rate:
178 valuation_rate = incoming_rate
179 else:
180 new_stock_qty = qty_after_transaction + actual_qty
181 if new_stock_qty > 0:
182 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
183 if new_stock_value > 0:
184 # calculate new valuation rate only if stock value is positive
185 # else it remains the same as that of previous entry
186 valuation_rate = new_stock_value / new_stock_qty
Anand Doshi1b531862013-01-10 19:29:51 +0530187
Nabin Hait914c6df2013-01-14 13:15:42 +0530188 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530189
190def get_moving_average_values(qty_after_transaction, sle, valuation_rate):
191 incoming_rate = flt(sle.incoming_rate)
Nabin Hait914c6df2013-01-14 13:15:42 +0530192 actual_qty = flt(sle.actual_qty)
Nabin Hait902e8602013-01-08 18:29:24 +0530193
Anand Doshi1b531862013-01-10 19:29:51 +0530194 if not incoming_rate:
Nabin Hait902e8602013-01-08 18:29:24 +0530195 # In case of delivery/stock issue in_rate = 0 or wrong incoming rate
196 incoming_rate = valuation_rate
197
Anand Doshi1b531862013-01-10 19:29:51 +0530198 elif qty_after_transaction < 0:
199 # if negative stock, take current valuation rate as incoming rate
200 valuation_rate = incoming_rate
201
Nabin Hait902e8602013-01-08 18:29:24 +0530202 new_stock_qty = qty_after_transaction + actual_qty
203 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
Anand Doshi1b531862013-01-10 19:29:51 +0530204
205 if new_stock_qty > 0 and new_stock_value > 0:
Nabin Hait902e8602013-01-08 18:29:24 +0530206 valuation_rate = new_stock_value / flt(new_stock_qty)
207 elif new_stock_qty <= 0:
208 valuation_rate = 0.0
Anand Doshi1b531862013-01-10 19:29:51 +0530209
210 # NOTE: val_rate is same as previous entry if new stock value is negative
211
Nabin Hait914c6df2013-01-14 13:15:42 +0530212 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530213
214def get_fifo_values(qty_after_transaction, sle, stock_queue):
215 incoming_rate = flt(sle.incoming_rate)
216 actual_qty = flt(sle.actual_qty)
Nabin Hait902e8602013-01-08 18:29:24 +0530217 if not stock_queue:
218 stock_queue.append([0, 0])
Nabin Hait9514d172013-01-10 10:40:37 +0530219
Nabin Hait902e8602013-01-08 18:29:24 +0530220 if actual_qty > 0:
221 if stock_queue[-1][0] > 0:
222 stock_queue.append([actual_qty, incoming_rate])
223 else:
224 qty = stock_queue[-1][0] + actual_qty
225 stock_queue[-1] = [qty, qty > 0 and incoming_rate or 0]
226 else:
227 incoming_cost = 0
228 qty_to_pop = abs(actual_qty)
229 while qty_to_pop:
Nabin Hait9514d172013-01-10 10:40:37 +0530230 if not stock_queue:
231 stock_queue.append([0, 0])
232
Nabin Hait902e8602013-01-08 18:29:24 +0530233 batch = stock_queue[0]
234
235 if 0 < batch[0] <= qty_to_pop:
236 # if batch qty > 0
237 # not enough or exactly same qty in current batch, clear batch
238 incoming_cost += flt(batch[0]) * flt(batch[1])
239 qty_to_pop -= batch[0]
240 stock_queue.pop(0)
241 else:
242 # all from current batch
243 incoming_cost += flt(qty_to_pop) * flt(batch[1])
244 batch[0] -= qty_to_pop
245 qty_to_pop = 0
246
Nabin Hait902e8602013-01-08 18:29:24 +0530247 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
248 stock_qty = sum((flt(batch[0]) for batch in stock_queue))
249
250 valuation_rate = stock_qty and (stock_value / flt(stock_qty)) or 0
Nabin Hait9514d172013-01-10 10:40:37 +0530251
Nabin Hait914c6df2013-01-14 13:15:42 +0530252 return valuation_rate
Nabin Hait902e8602013-01-08 18:29:24 +0530253
Nabin Hait9514d172013-01-10 10:40:37 +0530254def _raise_exceptions(args, verbose=1):
Nabin Hait902e8602013-01-08 18:29:24 +0530255 deficiency = min(e["diff"] for e in _exceptions)
256 msg = """Negative stock error:
257 Cannot complete this transaction because stock will start
258 becoming negative (%s) for Item <b>%s</b> in Warehouse
259 <b>%s</b> on <b>%s %s</b> in Transaction %s %s.
260 Total Quantity Deficiency: <b>%s</b>""" % \
261 (_exceptions[0]["diff"], args.get("item_code"), args.get("warehouse"),
262 _exceptions[0]["posting_date"], _exceptions[0]["posting_time"],
263 _exceptions[0]["voucher_type"], _exceptions[0]["voucher_no"],
264 abs(deficiency))
265 if verbose:
266 msgprint(msg, raise_exception=1)
267 else:
Anand Doshi1b531862013-01-10 19:29:51 +0530268 raise webnotes.ValidationError, msg
269
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530270def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530271 """
272 get the last sle on or before the current time-bucket,
273 to get actual qty before transaction, this function
274 is called from various transaction like stock entry, reco etc
275
276 args = {
277 "item_code": "ABC",
278 "warehouse": "XYZ",
279 "posting_date": "2012-12-12",
280 "posting_time": "12:00",
281 "sle": "name of reference Stock Ledger Entry"
282 }
283 """
284 if not args.get("sle"): args["sle"] = ""
285
286 sle = get_stock_ledger_entries(args, ["name != %(sle)s",
287 "timestamp(posting_date, posting_time) <= timestamp(%(posting_date)s, %(posting_time)s)"],
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530288 "desc", "limit 1", for_update=for_update)
Anand Doshi1b531862013-01-10 19:29:51 +0530289 return sle and sle[0] or {}