blob: bb02f8cd33e073530b05bdedd58a7764253b22af [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
18from webnotes import msgprint, _
Nabin Hait26d46552013-01-09 15:23:05 +053019from webnotes.utils import cint, flt, cstr
Nabin Hait902e8602013-01-08 18:29:24 +053020from stock.utils import _msgprint, 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 "[]")
43
44 entries_to_fix = get_sle_after_datetime(previous_sle or \
45 {"item_code": args["item_code"], "warehouse": args["warehouse"]})
46
47 valuation_method = get_valuation_method(args["item_code"])
48
49 for sle in entries_to_fix:
50 if sle.serial_nos or valuation_method == "FIFO" or \
51 not cint(webnotes.conn.get_default("allow_negative_stock")):
52 # 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
58 if sle.serial_nos:
59 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)
67
68 qty_after_transaction += flt(sle.actual_qty)
69
70 # get stock value
Nabin Hait26d46552013-01-09 15:23:05 +053071 if sle.serial_nos:
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))
78
79 # update current sle
80 webnotes.conn.sql("""update `tabStock Ledger Entry`
81 set qty_after_transaction=%s, valuation_rate=%s, stock_queue=%s, stock_value=%s,
82 incoming_rate = %s where name=%s""", (qty_after_transaction, valuation_rate,
83 json.dumps(stock_queue), stock_value, incoming_rate, sle.name))
84
85 if _exceptions:
86 _raise_exceptions(args)
87
88 # update bin
89 webnotes.conn.sql("""update `tabBin` set valuation_rate=%s, actual_qty=%s, stock_value=%s,
90 projected_qty = (actual_qty + indented_qty + ordered_qty + planned_qty - reserved_qty)
91 where item_code=%s and warehouse=%s""", (valuation_rate, qty_after_transaction,
92 stock_value, args["item_code"], args["warehouse"]))
93
94def get_sle_before_datetime(args):
95 """
96 get previous stock ledger entry before current time-bucket
97
98 Details:
99 get the last sle before the current time-bucket, so that all values
100 are reposted from the current time-bucket onwards.
101 this is necessary because at the time of cancellation, there may be
102 entries between the cancelled entries in the same time-bucket
103 """
104 sle = get_stock_ledger_entries(args,
Nabin Hait26d46552013-01-09 15:23:05 +0530105 ["timestamp(posting_date, posting_time) < timestamp(%(posting_date)s, %(posting_time)s)"],
Nabin Hait902e8602013-01-08 18:29:24 +0530106 "limit 1")
107
108 return sle and sle[0] or webnotes._dict()
109
110def get_sle_after_datetime(args):
111 """get Stock Ledger Entries after a particular datetime, for reposting"""
112 return 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)"])
Nabin Hait902e8602013-01-08 18:29:24 +0530114
115def get_stock_ledger_entries(args, conditions=None, limit=None):
116 """get stock ledger entries filtered by specific posting datetime conditions"""
117 if not args.get("posting_date"):
118 args["posting_date"] = "1900-01-01"
119 if not args.get("posting_time"):
120 args["posting_time"] = "12:00"
121
122 return webnotes.conn.sql("""select * from `tabStock Ledger Entry`
123 where item_code = %%(item_code)s
124 and warehouse = %%(warehouse)s
125 and ifnull(is_cancelled, 'No') = 'No'
126 %(conditions)s
127 order by timestamp(posting_date, posting_time) desc, name desc
128 %(limit)s""" % {
129 "conditions": conditions and ("and " + " and ".join(conditions)) or "",
130 "limit": limit or ""
131 }, args, as_dict=1)
132
133def validate_negative_stock(qty_after_transaction, sle):
134 """
135 validate negative stock for entries current datetime onwards
136 will not consider cancelled entries
137 """
138 diff = qty_after_transaction + flt(sle.actual_qty)
139
140 if diff < 0 and abs(diff) > 0.0001:
141 # negative stock!
142 global _exceptions
143 exc = sle.copy().update({"diff": diff})
144 _exceptions.append(exc)
145 return False
146 else:
147 return True
148
149def get_serialized_values(qty_after_transaction, sle, valuation_rate):
150 incoming_rate = flt(sle.incoming_rate)
151 actual_qty = flt(sle.actual_qty)
152 serial_nos = cstr(sle.serial_nos).split("\n")
153
154 if incoming_rate < 0:
155 # wrong incoming rate
156 incoming_rate = valuation_rate
157 elif incoming_rate == 0 or flt(sle.actual_qty) < 0:
158 # In case of delivery/stock issue, get average purchase rate
159 # of serial nos of current entry
160 incoming_rate = flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0))
161 from `tabSerial No` where name in (%s)""" % (", ".join(["%s"]*len(serial_nos))),
162 tuple(serial_nos))[0][0])
163
164 if incoming_rate and not valuation_rate:
165 valuation_rate = incoming_rate
166 else:
167 new_stock_qty = qty_after_transaction + actual_qty
168 if new_stock_qty > 0:
169 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
170 if new_stock_value > 0:
171 # calculate new valuation rate only if stock value is positive
172 # else it remains the same as that of previous entry
173 valuation_rate = new_stock_value / new_stock_qty
174
175 return valuation_rate, incoming_rate
176
177def get_moving_average_values(qty_after_transaction, sle, valuation_rate):
178 incoming_rate = flt(sle.incoming_rate)
179 actual_qty = flt(sle.actual_qty)
180
181 if not incoming_rate or actual_qty < 0:
182 # In case of delivery/stock issue in_rate = 0 or wrong incoming rate
183 incoming_rate = valuation_rate
184
185 # val_rate is same as previous entry if :
186 # 1. actual qty is negative(delivery note / stock entry)
187 # 2. cancelled entry
188 # 3. val_rate is negative
189 # Otherwise it will be calculated as per moving average
190 new_stock_qty = qty_after_transaction + actual_qty
191 new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate
192 if actual_qty > 0 and new_stock_qty > 0 and new_stock_value > 0:
193 valuation_rate = new_stock_value / flt(new_stock_qty)
194 elif new_stock_qty <= 0:
195 valuation_rate = 0.0
196
197 return valuation_rate, incoming_rate
198
199def get_fifo_values(qty_after_transaction, sle, stock_queue):
200 incoming_rate = flt(sle.incoming_rate)
201 actual_qty = flt(sle.actual_qty)
202
203 if not stock_queue:
204 stock_queue.append([0, 0])
205
206 if actual_qty > 0:
207 if stock_queue[-1][0] > 0:
208 stock_queue.append([actual_qty, incoming_rate])
209 else:
210 qty = stock_queue[-1][0] + actual_qty
211 stock_queue[-1] = [qty, qty > 0 and incoming_rate or 0]
212 else:
213 incoming_cost = 0
214 qty_to_pop = abs(actual_qty)
215 while qty_to_pop:
216 batch = stock_queue[0]
217
218 if 0 < batch[0] <= qty_to_pop:
219 # if batch qty > 0
220 # not enough or exactly same qty in current batch, clear batch
221 incoming_cost += flt(batch[0]) * flt(batch[1])
222 qty_to_pop -= batch[0]
223 stock_queue.pop(0)
224 else:
225 # all from current batch
226 incoming_cost += flt(qty_to_pop) * flt(batch[1])
227 batch[0] -= qty_to_pop
228 qty_to_pop = 0
229
230 incoming_rate = incoming_cost / flt(abs(actual_qty))
231
232 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue))
233 stock_qty = sum((flt(batch[0]) for batch in stock_queue))
234
235 valuation_rate = stock_qty and (stock_value / flt(stock_qty)) or 0
236
237 return valuation_rate, incoming_rate
238
239def _raise_exceptions(args):
240 deficiency = min(e["diff"] for e in _exceptions)
241 msg = """Negative stock error:
242 Cannot complete this transaction because stock will start
243 becoming negative (%s) for Item <b>%s</b> in Warehouse
244 <b>%s</b> on <b>%s %s</b> in Transaction %s %s.
245 Total Quantity Deficiency: <b>%s</b>""" % \
246 (_exceptions[0]["diff"], args.get("item_code"), args.get("warehouse"),
247 _exceptions[0]["posting_date"], _exceptions[0]["posting_time"],
248 _exceptions[0]["voucher_type"], _exceptions[0]["voucher_no"],
249 abs(deficiency))
250 if verbose:
251 msgprint(msg, raise_exception=1)
252 else:
253 raise webnotes.ValidationError, msg