Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 1 | # 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 | |
| 17 | import webnotes |
| 18 | from webnotes import msgprint, _ |
Nabin Hait | 26d4655 | 2013-01-09 15:23:05 +0530 | [diff] [blame] | 19 | from webnotes.utils import cint, flt, cstr |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 20 | from stock.utils import _msgprint, get_valuation_method |
Nabin Hait | 26d4655 | 2013-01-09 15:23:05 +0530 | [diff] [blame] | 21 | import json |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 22 | |
| 23 | # future reposting |
| 24 | |
| 25 | _exceptions = [] |
| 26 | def 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 Hait | 9514d17 | 2013-01-10 10:40:37 +0530 | [diff] [blame] | 43 | stock_value = 0.0 |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 44 | |
| 45 | entries_to_fix = get_sle_after_datetime(previous_sle or \ |
| 46 | {"item_code": args["item_code"], "warehouse": args["warehouse"]}) |
| 47 | |
| 48 | valuation_method = get_valuation_method(args["item_code"]) |
| 49 | |
| 50 | for sle in entries_to_fix: |
Nabin Hait | 9514d17 | 2013-01-10 10:40:37 +0530 | [diff] [blame] | 51 | if sle.serial_nos or not cint(webnotes.conn.get_default("allow_negative_stock")): |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 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 Hait | 26d4655 | 2013-01-09 15:23:05 +0530 | [diff] [blame] | 71 | if sle.serial_nos: |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 72 | 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 Hait | 9514d17 | 2013-01-10 10:40:37 +0530 | [diff] [blame] | 78 | |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 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: |
Nabin Hait | 9514d17 | 2013-01-10 10:40:37 +0530 | [diff] [blame] | 86 | _raise_exceptions(args, verbose) |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 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 | |
| 94 | def 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 Hait | 26d4655 | 2013-01-09 15:23:05 +0530 | [diff] [blame] | 105 | ["timestamp(posting_date, posting_time) < timestamp(%(posting_date)s, %(posting_time)s)"], |
Nabin Hait | 9514d17 | 2013-01-10 10:40:37 +0530 | [diff] [blame] | 106 | "desc", "limit 1") |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 107 | |
| 108 | return sle and sle[0] or webnotes._dict() |
| 109 | |
| 110 | def get_sle_after_datetime(args): |
| 111 | """get Stock Ledger Entries after a particular datetime, for reposting""" |
| 112 | return get_stock_ledger_entries(args, |
Nabin Hait | 9514d17 | 2013-01-10 10:40:37 +0530 | [diff] [blame] | 113 | ["timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)"], |
| 114 | "asc") |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 115 | |
Nabin Hait | 9514d17 | 2013-01-10 10:40:37 +0530 | [diff] [blame] | 116 | def get_stock_ledger_entries(args, conditions=None, order="desc", limit=None): |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 117 | """get stock ledger entries filtered by specific posting datetime conditions""" |
| 118 | if not args.get("posting_date"): |
| 119 | args["posting_date"] = "1900-01-01" |
| 120 | if not args.get("posting_time"): |
| 121 | args["posting_time"] = "12:00" |
| 122 | |
| 123 | return webnotes.conn.sql("""select * from `tabStock Ledger Entry` |
| 124 | where item_code = %%(item_code)s |
| 125 | and warehouse = %%(warehouse)s |
| 126 | and ifnull(is_cancelled, 'No') = 'No' |
| 127 | %(conditions)s |
Nabin Hait | 9514d17 | 2013-01-10 10:40:37 +0530 | [diff] [blame] | 128 | order by timestamp(posting_date, posting_time) %(order)s, name %(order)s |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 129 | %(limit)s""" % { |
| 130 | "conditions": conditions and ("and " + " and ".join(conditions)) or "", |
Nabin Hait | 9514d17 | 2013-01-10 10:40:37 +0530 | [diff] [blame] | 131 | "limit": limit or "", |
| 132 | "order": order |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 133 | }, args, as_dict=1) |
| 134 | |
| 135 | def validate_negative_stock(qty_after_transaction, sle): |
| 136 | """ |
| 137 | validate negative stock for entries current datetime onwards |
| 138 | will not consider cancelled entries |
| 139 | """ |
| 140 | diff = qty_after_transaction + flt(sle.actual_qty) |
| 141 | |
| 142 | if diff < 0 and abs(diff) > 0.0001: |
| 143 | # negative stock! |
| 144 | global _exceptions |
| 145 | exc = sle.copy().update({"diff": diff}) |
| 146 | _exceptions.append(exc) |
| 147 | return False |
| 148 | else: |
| 149 | return True |
| 150 | |
| 151 | def get_serialized_values(qty_after_transaction, sle, valuation_rate): |
| 152 | incoming_rate = flt(sle.incoming_rate) |
| 153 | actual_qty = flt(sle.actual_qty) |
| 154 | serial_nos = cstr(sle.serial_nos).split("\n") |
| 155 | |
| 156 | if incoming_rate < 0: |
| 157 | # wrong incoming rate |
| 158 | incoming_rate = valuation_rate |
| 159 | elif incoming_rate == 0 or flt(sle.actual_qty) < 0: |
| 160 | # In case of delivery/stock issue, get average purchase rate |
| 161 | # of serial nos of current entry |
| 162 | incoming_rate = flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0)) |
| 163 | from `tabSerial No` where name in (%s)""" % (", ".join(["%s"]*len(serial_nos))), |
| 164 | tuple(serial_nos))[0][0]) |
| 165 | |
| 166 | if incoming_rate and not valuation_rate: |
| 167 | valuation_rate = incoming_rate |
| 168 | else: |
| 169 | new_stock_qty = qty_after_transaction + actual_qty |
| 170 | if new_stock_qty > 0: |
| 171 | new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate |
| 172 | if new_stock_value > 0: |
| 173 | # calculate new valuation rate only if stock value is positive |
| 174 | # else it remains the same as that of previous entry |
| 175 | valuation_rate = new_stock_value / new_stock_qty |
| 176 | |
| 177 | return valuation_rate, incoming_rate |
| 178 | |
| 179 | def get_moving_average_values(qty_after_transaction, sle, valuation_rate): |
| 180 | incoming_rate = flt(sle.incoming_rate) |
| 181 | actual_qty = flt(sle.actual_qty) |
| 182 | |
| 183 | if not incoming_rate or actual_qty < 0: |
| 184 | # In case of delivery/stock issue in_rate = 0 or wrong incoming rate |
| 185 | incoming_rate = valuation_rate |
| 186 | |
| 187 | # val_rate is same as previous entry if : |
| 188 | # 1. actual qty is negative(delivery note / stock entry) |
| 189 | # 2. cancelled entry |
| 190 | # 3. val_rate is negative |
| 191 | # Otherwise it will be calculated as per moving average |
| 192 | new_stock_qty = qty_after_transaction + actual_qty |
| 193 | new_stock_value = qty_after_transaction * valuation_rate + actual_qty * incoming_rate |
| 194 | if actual_qty > 0 and new_stock_qty > 0 and new_stock_value > 0: |
| 195 | valuation_rate = new_stock_value / flt(new_stock_qty) |
| 196 | elif new_stock_qty <= 0: |
| 197 | valuation_rate = 0.0 |
| 198 | |
| 199 | return valuation_rate, incoming_rate |
| 200 | |
| 201 | def get_fifo_values(qty_after_transaction, sle, stock_queue): |
| 202 | incoming_rate = flt(sle.incoming_rate) |
| 203 | actual_qty = flt(sle.actual_qty) |
| 204 | |
| 205 | if not stock_queue: |
| 206 | stock_queue.append([0, 0]) |
Nabin Hait | 9514d17 | 2013-01-10 10:40:37 +0530 | [diff] [blame] | 207 | |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 208 | if actual_qty > 0: |
| 209 | if stock_queue[-1][0] > 0: |
| 210 | stock_queue.append([actual_qty, incoming_rate]) |
| 211 | else: |
| 212 | qty = stock_queue[-1][0] + actual_qty |
| 213 | stock_queue[-1] = [qty, qty > 0 and incoming_rate or 0] |
| 214 | else: |
| 215 | incoming_cost = 0 |
| 216 | qty_to_pop = abs(actual_qty) |
| 217 | while qty_to_pop: |
Nabin Hait | 9514d17 | 2013-01-10 10:40:37 +0530 | [diff] [blame] | 218 | if not stock_queue: |
| 219 | stock_queue.append([0, 0]) |
| 220 | |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 221 | batch = stock_queue[0] |
| 222 | |
| 223 | if 0 < batch[0] <= qty_to_pop: |
| 224 | # if batch qty > 0 |
| 225 | # not enough or exactly same qty in current batch, clear batch |
| 226 | incoming_cost += flt(batch[0]) * flt(batch[1]) |
| 227 | qty_to_pop -= batch[0] |
| 228 | stock_queue.pop(0) |
| 229 | else: |
| 230 | # all from current batch |
| 231 | incoming_cost += flt(qty_to_pop) * flt(batch[1]) |
| 232 | batch[0] -= qty_to_pop |
| 233 | qty_to_pop = 0 |
| 234 | |
| 235 | incoming_rate = incoming_cost / flt(abs(actual_qty)) |
| 236 | |
| 237 | stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in stock_queue)) |
| 238 | stock_qty = sum((flt(batch[0]) for batch in stock_queue)) |
| 239 | |
| 240 | valuation_rate = stock_qty and (stock_value / flt(stock_qty)) or 0 |
Nabin Hait | 9514d17 | 2013-01-10 10:40:37 +0530 | [diff] [blame] | 241 | |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 242 | return valuation_rate, incoming_rate |
| 243 | |
Nabin Hait | 9514d17 | 2013-01-10 10:40:37 +0530 | [diff] [blame] | 244 | def _raise_exceptions(args, verbose=1): |
Nabin Hait | 902e860 | 2013-01-08 18:29:24 +0530 | [diff] [blame] | 245 | deficiency = min(e["diff"] for e in _exceptions) |
| 246 | msg = """Negative stock error: |
| 247 | Cannot complete this transaction because stock will start |
| 248 | becoming negative (%s) for Item <b>%s</b> in Warehouse |
| 249 | <b>%s</b> on <b>%s %s</b> in Transaction %s %s. |
| 250 | Total Quantity Deficiency: <b>%s</b>""" % \ |
| 251 | (_exceptions[0]["diff"], args.get("item_code"), args.get("warehouse"), |
| 252 | _exceptions[0]["posting_date"], _exceptions[0]["posting_time"], |
| 253 | _exceptions[0]["voucher_type"], _exceptions[0]["voucher_no"], |
| 254 | abs(deficiency)) |
| 255 | if verbose: |
| 256 | msgprint(msg, raise_exception=1) |
| 257 | else: |
| 258 | raise webnotes.ValidationError, msg |