blob: e1b3730f2f9bcffdd1bf855cc9d83f55a5a97bd0 [file] [log] [blame]
Anand Doshi885e0742015-03-03 14:55:30 +05301# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
Rushabh Mehtae67d1fb2013-08-05 14:59:54 +05302# License: GNU General Public License v3. See license.txt
Anand Doshi56a31652013-11-29 19:15:26 +05303from __future__ import unicode_literals
Nabin Hait902e8602013-01-08 18:29:24 +05304
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +05305import frappe, erpnext
Rushabh Mehta9f0d6252014-04-14 19:20:45 +05306from frappe import _
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05307from frappe.utils import cint, flt, cstr, now, now_datetime
8from erpnext.stock.utils import get_valuation_method, get_incoming_outgoing_rate_for_cancel
Nabin Hait26d46552013-01-09 15:23:05 +05309import json
Nabin Hait902e8602013-01-08 18:29:24 +053010
Achilles Rasquinha361366e2018-02-14 17:08:59 +053011from six import iteritems
12
Nabin Hait902e8602013-01-08 18:29:24 +053013# future reposting
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053014class NegativeStockError(frappe.ValidationError): pass
Nabin Hait902e8602013-01-08 18:29:24 +053015
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053016_exceptions = frappe.local('stockledger_exceptions')
Pratik Vyas16371b72013-09-18 18:31:03 +053017# _exceptions = []
Anand Doshi5b004ff2013-09-25 19:55:41 +053018
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053019def make_sl_entries(sl_entries, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Haitca775742013-09-26 16:16:44 +053020 if sl_entries:
Rushabh Mehta1f847992013-12-12 19:12:19 +053021 from erpnext.stock.utils import update_bin
Nabin Haitdc82d4f2014-04-07 12:02:57 +053022
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053023 cancel = sl_entries[0].get("is_cancelled")
Nabin Haitca775742013-09-26 16:16:44 +053024 if cancel:
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053025 set_as_cancel(sl_entries[0].get('voucher_type'), sl_entries[0].get('voucher_no'))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053026
Nabin Haitca775742013-09-26 16:16:44 +053027 for sle in sl_entries:
28 sle_id = None
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053029 if via_landed_cost_voucher or cancel:
30 sle['posting_date'] = now_datetime().strftime('%Y-%m-%d')
31 sle['posting_time'] = now_datetime().strftime('%H:%M:%S.%f')
32
33 if cancel:
34 sle['actual_qty'] = -flt(sle.get('actual_qty'), 0)
35
36 if sle['actual_qty'] < 0 and not sle.get('outgoing_rate'):
37 sle['outgoing_rate'] = get_incoming_outgoing_rate_for_cancel(sle.item_code,
38 sle.voucher_type, sle.voucher_no, sle.voucher_detail_no)
39 sle['incoming_rate'] = 0.0
40
41 if sle['actual_qty'] > 0 and not sle.get('incoming_rate'):
42 sle['incoming_rate'] = get_incoming_outgoing_rate_for_cancel(sle.item_code,
43 sle.voucher_type, sle.voucher_no, sle.voucher_detail_no)
44 sle['outgoing_rate'] = 0.0
45
Nabin Haitdc82d4f2014-04-07 12:02:57 +053046
Nabin Hait5288bde2014-11-03 15:08:21 +053047 if sle.get("actual_qty") or sle.get("voucher_type")=="Stock Reconciliation":
Nabin Hait54c865e2015-03-27 15:38:31 +053048 sle_id = make_entry(sle, allow_negative_stock, via_landed_cost_voucher)
Nabin Haitdc82d4f2014-04-07 12:02:57 +053049
Nabin Haitca775742013-09-26 16:16:44 +053050 args = sle.copy()
51 args.update({
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053052 "sle_id": sle_id
Nabin Haitca775742013-09-26 16:16:44 +053053 })
Nabin Hait54c865e2015-03-27 15:38:31 +053054 update_bin(args, allow_negative_stock, via_landed_cost_voucher)
Nabin Haitadeb9762014-10-06 11:53:52 +053055
Nabin Haitdc82d4f2014-04-07 12:02:57 +053056
Nabin Hait9653f602013-08-20 15:37:33 +053057def set_as_cancel(voucher_type, voucher_no):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053058 frappe.db.sql("""update `tabStock Ledger Entry` set is_cancelled=1,
Nabin Hait9653f602013-08-20 15:37:33 +053059 modified=%s, modified_by=%s
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053060 where voucher_type=%s and voucher_no=%s and is_cancelled = 0""",
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053061 (now(), frappe.session.user, voucher_type, voucher_no))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053062
Nabin Hait54c865e2015-03-27 15:38:31 +053063def make_entry(args, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Hait74c281c2013-08-19 16:17:18 +053064 args.update({"doctype": "Stock Ledger Entry"})
Rushabh Mehtaa504f062014-04-04 12:16:26 +053065 sle = frappe.get_doc(args)
Anand Doshi6dfd4302015-02-10 14:41:27 +053066 sle.flags.ignore_permissions = 1
Nabin Hait4ccd8d32015-01-23 12:18:01 +053067 sle.allow_negative_stock=allow_negative_stock
Nabin Hait54c865e2015-03-27 15:38:31 +053068 sle.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Hait74c281c2013-08-19 16:17:18 +053069 sle.insert()
Nabin Haitaeba24e2013-08-23 15:17:36 +053070 sle.submit()
Anand Doshif78d1ae2014-03-28 13:55:00 +053071 return sle.name
Nabin Haitdc82d4f2014-04-07 12:02:57 +053072
Nabin Hait74c281c2013-08-19 16:17:18 +053073
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053074class update_entries_after(object):
Nabin Hait902e8602013-01-08 18:29:24 +053075 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +053076 update valution rate and qty after transaction
Nabin Hait902e8602013-01-08 18:29:24 +053077 from the current time-bucket onwards
Nabin Haitdc82d4f2014-04-07 12:02:57 +053078
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053079 :param args: args as dict
80
81 args = {
82 "item_code": "ABC",
83 "warehouse": "XYZ",
84 "posting_date": "2012-12-12",
85 "posting_time": "12:00"
86 }
Nabin Hait902e8602013-01-08 18:29:24 +053087 """
Anand Doshi0dc79f42015-04-06 12:59:34 +053088 def __init__(self, args, allow_zero_rate=False, allow_negative_stock=None, via_landed_cost_voucher=False, verbose=1):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053089 from frappe.model.meta import get_field_precision
Nabin Haitdc82d4f2014-04-07 12:02:57 +053090
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053091 self.exceptions = []
92 self.verbose = verbose
93 self.allow_zero_rate = allow_zero_rate
94 self.allow_negative_stock = allow_negative_stock
Anand Doshi0dc79f42015-04-06 12:59:34 +053095 self.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Hait43ba7e12015-03-03 14:07:07 +053096 if not self.allow_negative_stock:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053097 self.allow_negative_stock = cint(frappe.db.get_single_value("Stock Settings",
98 "allow_negative_stock"))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053099
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530100 self.args = args
Achilles Rasquinha361366e2018-02-14 17:08:59 +0530101 for key, value in iteritems(args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530102 setattr(self, key, value)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530103
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530104 self.previous_sle = self.get_sle_before_datetime()
105 self.previous_sle = self.previous_sle[0] if self.previous_sle else frappe._dict()
Nabin Haitbb777562013-08-29 18:19:37 +0530106
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530107 for key in ("qty_after_transaction", "valuation_rate", "stock_value"):
108 setattr(self, key, flt(self.previous_sle.get(key)))
109
110 self.company = frappe.db.get_value("Warehouse", self.warehouse, "company")
111 self.precision = get_field_precision(frappe.get_meta("Stock Ledger Entry").get_field("stock_value"),
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530112 currency=frappe.get_cached_value('Company', self.company, "default_currency"))
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530113
Rushabh Mehtac7a11cc2015-02-19 16:28:35 +0530114 self.prev_stock_value = self.previous_sle.stock_value or 0.0
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530115 self.stock_queue = json.loads(self.previous_sle.stock_queue or "[]")
116 self.valuation_method = get_valuation_method(self.item_code)
117 self.stock_value_difference = 0.0
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530118 self.build(args.get('sle_id'))
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530119
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530120 def build(self, sle_id):
121 if sle_id:
122 sle = get_sle_by_id(sle_id)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530123 self.process_sle(sle)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530124 else:
125 # includes current entry!
126 entries_to_fix = self.get_sle_after_datetime()
127 for sle in entries_to_fix:
128 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530129
130 if self.exceptions:
131 self.raise_exceptions()
132
133 self.update_bin()
134
135 def update_bin(self):
136 # update bin
137 bin_name = frappe.db.get_value("Bin", {
138 "item_code": self.item_code,
139 "warehouse": self.warehouse
140 })
141
142 if not bin_name:
143 bin_doc = frappe.get_doc({
144 "doctype": "Bin",
145 "item_code": self.item_code,
146 "warehouse": self.warehouse
147 })
148 bin_doc.insert(ignore_permissions=True)
149 else:
150 bin_doc = frappe.get_doc("Bin", bin_name)
151
152 bin_doc.update({
153 "valuation_rate": self.valuation_rate,
154 "actual_qty": self.qty_after_transaction,
155 "stock_value": self.stock_value
156 })
Saurabhb166bcf2015-12-28 13:25:35 +0530157 bin_doc.flags.via_stock_ledger_entry = True
Rushabh Mehta538607e2016-06-12 11:03:00 +0530158
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530159 bin_doc.save(ignore_permissions=True)
160
161 def process_sle(self, sle):
Anand Doshi0dc79f42015-04-06 12:59:34 +0530162 if (sle.serial_no and not self.via_landed_cost_voucher) or not cint(self.allow_negative_stock):
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530163 # validate negative stock for serialized items, fifo valuation
Nabin Hait902e8602013-01-08 18:29:24 +0530164 # or when negative stock is not allowed for moving average
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530165 if not self.validate_negative_stock(sle):
166 self.qty_after_transaction += flt(sle.actual_qty)
167 return
Nabin Haitb96c0142014-10-07 11:25:04 +0530168
Anand Doshi1b531862013-01-10 19:29:51 +0530169 if sle.serial_no:
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530170 self.get_serialized_values(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530171 self.qty_after_transaction += flt(sle.actual_qty)
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530172 if sle.voucher_type == "Stock Reconciliation":
173 self.qty_after_transaction = sle.qty_after_transaction
174
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530175 self.stock_value = flt(self.qty_after_transaction) * flt(self.valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530176 else:
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530177 if sle.voucher_type=="Stock Reconciliation" and not sle.batch_no:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530178 # assert
179 self.valuation_rate = sle.valuation_rate
180 self.qty_after_transaction = sle.qty_after_transaction
181 self.stock_queue = [[self.qty_after_transaction, self.valuation_rate]]
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530182 self.stock_value = flt(self.qty_after_transaction) * flt(self.valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530183 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530184 if self.valuation_method == "Moving Average":
185 self.get_moving_average_values(sle)
186 self.qty_after_transaction += flt(sle.actual_qty)
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530187 self.stock_value = flt(self.qty_after_transaction) * flt(self.valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530188 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530189 self.get_fifo_values(sle)
190 self.qty_after_transaction += flt(sle.actual_qty)
191 self.stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in self.stock_queue))
Nabin Haitb96c0142014-10-07 11:25:04 +0530192
Rushabh Mehta54047782013-12-26 11:07:46 +0530193 # rounding as per precision
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530194 self.stock_value = flt(self.stock_value, self.precision)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530195
rohitwaghchaure805b8632019-09-05 12:18:33 +0530196 stock_value_difference = self.stock_value - self.prev_stock_value
Rohit Waghchaure6424f472018-11-21 23:18:41 +0530197
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530198 self.prev_stock_value = self.stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530199
Nabin Hait902e8602013-01-08 18:29:24 +0530200 # update current sle
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530201 sle.qty_after_transaction = self.qty_after_transaction
202 sle.valuation_rate = self.valuation_rate
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530203 sle.stock_value = self.stock_value
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530204 sle.stock_queue = json.dumps(self.stock_queue)
205 sle.stock_value_difference = stock_value_difference
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530206 sle.doctype="Stock Ledger Entry"
207 frappe.get_doc(sle).db_update()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530208
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530209 def validate_negative_stock(self, sle):
210 """
211 validate negative stock for entries current datetime onwards
212 will not consider cancelled entries
213 """
214 diff = self.qty_after_transaction + flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530215
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530216 if diff < 0 and abs(diff) > 0.0001:
217 # negative stock!
218 exc = sle.copy().update({"diff": diff})
219 self.exceptions.append(exc)
220 return False
Nabin Hait902e8602013-01-08 18:29:24 +0530221 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530222 return True
223
224 def get_serialized_values(self, sle):
225 incoming_rate = flt(sle.incoming_rate)
226 actual_qty = flt(sle.actual_qty)
Nabin Hait328c4f92020-01-02 19:00:32 +0530227 serial_nos = cstr(sle.serial_no).split("\n")
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530228
229 if incoming_rate < 0:
230 # wrong incoming rate
231 incoming_rate = self.valuation_rate
Rushabh Mehta538607e2016-06-12 11:03:00 +0530232
Nabin Hait2620bf42016-02-29 11:30:27 +0530233 stock_value_change = 0
234 if incoming_rate:
235 stock_value_change = actual_qty * incoming_rate
236 elif actual_qty < 0:
237 # In case of delivery/stock issue, get average purchase rate
238 # of serial nos of current entry
Nabin Hait328c4f92020-01-02 19:00:32 +0530239 outgoing_value = self.get_incoming_value_for_serial_nos(sle, serial_nos)
240 stock_value_change = -1 * outgoing_value
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530241
Nabin Hait2620bf42016-02-29 11:30:27 +0530242 new_stock_qty = self.qty_after_transaction + actual_qty
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530243
Nabin Hait2620bf42016-02-29 11:30:27 +0530244 if new_stock_qty > 0:
245 new_stock_value = (self.qty_after_transaction * self.valuation_rate) + stock_value_change
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530246 if new_stock_value >= 0:
Nabin Hait2620bf42016-02-29 11:30:27 +0530247 # calculate new valuation rate only if stock value is positive
248 # else it remains the same as that of previous entry
249 self.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530250
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530251 if not self.valuation_rate and sle.voucher_detail_no:
252 allow_zero_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
253 if not allow_zero_rate:
254 self.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
255 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
256 currency=erpnext.get_company_currency(sle.company))
257
Nabin Hait328c4f92020-01-02 19:00:32 +0530258 def get_incoming_value_for_serial_nos(self, sle, serial_nos):
259 # get rate from serial nos within same company
260 all_serial_nos = frappe.get_all("Serial No",
261 fields=["purchase_rate", "name", "company"],
262 filters = {'name': ('in', serial_nos)})
263
264 incoming_values = sum([flt(d.purchase_rate) for d in all_serial_nos if d.company==sle.company])
265
266 # Get rate for serial nos which has been transferred to other company
267 invalid_serial_nos = [d.name for d in all_serial_nos if d.company!=sle.company]
268 for serial_no in invalid_serial_nos:
269 incoming_rate = frappe.db.sql("""
270 select incoming_rate
271 from `tabStock Ledger Entry`
272 where
273 company = %s
274 and actual_qty > 0
275 and (serial_no = %s
276 or serial_no like %s
277 or serial_no like %s
278 or serial_no like %s
279 )
280 order by posting_date desc
281 limit 1
282 """, (sle.company, serial_no, serial_no+'\n%', '%\n'+serial_no, '%\n'+serial_no+'\n%'))
283
284 incoming_values += flt(incoming_rate[0][0]) if incoming_rate else 0
285
286 return incoming_values
287
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530288 def get_moving_average_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530289 actual_qty = flt(sle.actual_qty)
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530290 new_stock_qty = flt(self.qty_after_transaction) + actual_qty
291 if new_stock_qty >= 0:
292 if actual_qty > 0:
293 if flt(self.qty_after_transaction) <= 0:
294 self.valuation_rate = sle.incoming_rate
295 else:
296 new_stock_value = (self.qty_after_transaction * self.valuation_rate) + \
297 (actual_qty * sle.incoming_rate)
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530298
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530299 self.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530300
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530301 elif sle.outgoing_rate:
302 if new_stock_qty:
303 new_stock_value = (self.qty_after_transaction * self.valuation_rate) + \
304 (actual_qty * sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530305
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530306 self.valuation_rate = new_stock_value / new_stock_qty
307 else:
Nabin Hait7590b8f2016-07-27 16:44:17 +0530308 self.valuation_rate = sle.outgoing_rate
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530309
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530310 else:
311 if flt(self.qty_after_transaction) >= 0 and sle.outgoing_rate:
312 self.valuation_rate = sle.outgoing_rate
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530313
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530314 if not self.valuation_rate and actual_qty > 0:
315 self.valuation_rate = sle.incoming_rate
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530316
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530317 # Get valuation rate from previous SLE or Item master, if item does not have the
Javier Wong9b11d9b2017-04-14 18:24:04 +0800318 # allow zero valuration rate flag set
Nabin Haitea8fab52017-02-06 17:13:39 +0530319 if not self.valuation_rate and sle.voucher_detail_no:
Javier Wong9b11d9b2017-04-14 18:24:04 +0800320 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
321 if not allow_zero_valuation_rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530322 self.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
323 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
324 currency=erpnext.get_company_currency(sle.company))
325
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530326 def get_fifo_values(self, sle):
327 incoming_rate = flt(sle.incoming_rate)
328 actual_qty = flt(sle.actual_qty)
Nabin Haitada485f2015-07-17 15:09:56 +0530329 outgoing_rate = flt(sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530330
331 if actual_qty > 0:
332 if not self.stock_queue:
333 self.stock_queue.append([0, 0])
334
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530335 # last row has the same rate, just updated the qty
336 if self.stock_queue[-1][1]==incoming_rate:
337 self.stock_queue[-1][0] += actual_qty
Nabin Hait4d742162014-10-09 19:25:03 +0530338 else:
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530339 if self.stock_queue[-1][0] > 0:
340 self.stock_queue.append([actual_qty, incoming_rate])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530341 else:
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530342 qty = self.stock_queue[-1][0] + actual_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530343 self.stock_queue[-1] = [qty, incoming_rate]
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530344 else:
345 qty_to_pop = abs(actual_qty)
346 while qty_to_pop:
347 if not self.stock_queue:
Nabin Haita0b967f2017-01-18 18:35:58 +0530348 # Get valuation rate from last sle if exists or from valuation rate field in item master
Javier Wong9b11d9b2017-04-14 18:24:04 +0800349 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
350 if not allow_zero_valuation_rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530351 _rate = get_valuation_rate(sle.item_code, sle.warehouse,
352 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
353 currency=erpnext.get_company_currency(sle.company))
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530354 else:
355 _rate = 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530356
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530357 self.stock_queue.append([0, _rate])
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530358
Nabin Haitada485f2015-07-17 15:09:56 +0530359 index = None
360 if outgoing_rate > 0:
361 # Find the entry where rate matched with outgoing rate
362 for i, v in enumerate(self.stock_queue):
363 if v[1] == outgoing_rate:
364 index = i
365 break
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530366
Nabin Haitada485f2015-07-17 15:09:56 +0530367 # If no entry found with outgoing rate, collapse stack
368 if index == None:
369 new_stock_value = sum((d[0]*d[1] for d in self.stock_queue)) - qty_to_pop*outgoing_rate
370 new_stock_qty = sum((d[0] for d in self.stock_queue)) - qty_to_pop
371 self.stock_queue = [[new_stock_qty, new_stock_value/new_stock_qty if new_stock_qty > 0 else outgoing_rate]]
372 break
373 else:
374 index = 0
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530375
Nabin Haitada485f2015-07-17 15:09:56 +0530376 # select first batch or the batch with same rate
377 batch = self.stock_queue[index]
Nabin Hait8142cd22015-08-05 18:57:26 +0530378 if qty_to_pop >= batch[0]:
379 # consume current batch
380 qty_to_pop = qty_to_pop - batch[0]
381 self.stock_queue.pop(index)
382 if not self.stock_queue and qty_to_pop:
383 # stock finished, qty still remains to be withdrawn
384 # negative stock, keep in as a negative batch
385 self.stock_queue.append([-qty_to_pop, outgoing_rate or batch[1]])
386 break
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530387
Nabin Hait8142cd22015-08-05 18:57:26 +0530388 else:
389 # qty found in current batch
390 # consume it and exit
391 batch[0] = batch[0] - qty_to_pop
392 qty_to_pop = 0
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530393
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530394 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in self.stock_queue))
395 stock_qty = sum((flt(batch[0]) for batch in self.stock_queue))
Nabin Hait902e8602013-01-08 18:29:24 +0530396
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530397 if stock_qty:
398 self.valuation_rate = stock_value / flt(stock_qty)
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530399
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530400 if not self.stock_queue:
401 self.stock_queue.append([0, sle.incoming_rate or sle.outgoing_rate or self.valuation_rate])
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530402
Javier Wong9b11d9b2017-04-14 18:24:04 +0800403 def check_if_allow_zero_valuation_rate(self, voucher_type, voucher_detail_no):
deepeshgarg007f9c0ef32019-07-30 18:49:19 +0530404 ref_item_dt = ""
405
406 if voucher_type == "Stock Entry":
407 ref_item_dt = voucher_type + " Detail"
408 elif voucher_type in ["Purchase Invoice", "Sales Invoice", "Delivery Note", "Purchase Receipt"]:
409 ref_item_dt = voucher_type + " Item"
410
411 if ref_item_dt:
412 return frappe.db.get_value(ref_item_dt, voucher_detail_no, "allow_zero_valuation_rate")
413 else:
414 return 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530415
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530416 def get_sle_before_datetime(self):
417 """get previous stock ledger entry before current time-bucket"""
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530418 if self.args.get('sle_id'):
419 self.args['name'] = self.args.get('sle_id')
420
421 return get_stock_ledger_entries(self.args, "<=", "desc", "limit 1", for_update=False)
Nabin Hait4d742162014-10-09 19:25:03 +0530422
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530423 def get_sle_after_datetime(self):
424 """get Stock Ledger Entries after a particular datetime, for reposting"""
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530425 return get_stock_ledger_entries(self.previous_sle or frappe._dict({
426 "item_code": self.args.get("item_code"), "warehouse": self.args.get("warehouse") }),
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530427 ">", "asc", for_update=True, check_serial_no=False)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530428
429 def raise_exceptions(self):
430 deficiency = min(e["diff"] for e in self.exceptions)
Rushabh Mehta538607e2016-06-12 11:03:00 +0530431
Rushabh Mehta649e2532016-07-20 15:30:17 +0530432 if ((self.exceptions[0]["voucher_type"], self.exceptions[0]["voucher_no"]) in
433 frappe.local.flags.currently_saving):
Nabin Hait3edefb12016-07-20 16:13:18 +0530434
Rushabh Mehta538607e2016-06-12 11:03:00 +0530435 msg = _("{0} units of {1} needed in {2} to complete this transaction.").format(
436 abs(deficiency), frappe.get_desk_link('Item', self.item_code),
437 frappe.get_desk_link('Warehouse', self.warehouse))
438 else:
439 msg = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
440 abs(deficiency), frappe.get_desk_link('Item', self.item_code),
441 frappe.get_desk_link('Warehouse', self.warehouse),
442 self.exceptions[0]["posting_date"], self.exceptions[0]["posting_time"],
443 frappe.get_desk_link(self.exceptions[0]["voucher_type"], self.exceptions[0]["voucher_no"]))
444
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530445 if self.verbose:
marination6f0dc822020-04-01 11:04:14 +0530446 frappe.throw(msg, NegativeStockError, title='Insufficient Stock')
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530447 else:
cclauss68487082017-07-27 07:08:35 +0200448 raise NegativeStockError(msg)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530449
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530450def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530451 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530452 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530453 to get actual qty before transaction, this function
454 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530455
Anand Doshi1b531862013-01-10 19:29:51 +0530456 args = {
457 "item_code": "ABC",
458 "warehouse": "XYZ",
459 "posting_date": "2012-12-12",
460 "posting_time": "12:00",
461 "sle": "name of reference Stock Ledger Entry"
462 }
463 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530464 args["name"] = args.get("sle", None) or ""
465 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530466 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530467
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530468def get_stock_ledger_entries(previous_sle, operator=None,
469 order="desc", limit=None, for_update=False, debug=False, check_serial_no=True):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530470 """get stock ledger entries filtered by specific posting datetime conditions"""
Nabin Haitb9ce1042018-02-01 14:58:50 +0530471 conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
472 if previous_sle.get("warehouse"):
473 conditions += " and warehouse = %(warehouse)s"
474 elif previous_sle.get("warehouse_condition"):
475 conditions += " and " + previous_sle.get("warehouse_condition")
476
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530477 if check_serial_no and previous_sle.get("serial_no"):
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530478 conditions += " and serial_no like {}".format(frappe.db.escape('%{0}%'.format(previous_sle.get("serial_no"))))
479
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530480 if not previous_sle.get("posting_date"):
481 previous_sle["posting_date"] = "1900-01-01"
482 if not previous_sle.get("posting_time"):
483 previous_sle["posting_time"] = "00:00"
484
485 if operator in (">", "<=") and previous_sle.get("name"):
486 conditions += " and name!=%(name)s"
487
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530488 return frappe.db.sql("""
489 select *, timestamp(posting_date, posting_time) as "timestamp"
490 from `tabStock Ledger Entry`
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530491 where item_code = %%(item_code)s
Nabin Haitb9ce1042018-02-01 14:58:50 +0530492 %(conditions)s
Aditya Hase0c164242019-01-07 22:07:13 +0530493 order by timestamp(posting_date, posting_time) %(order)s, creation %(order)s
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530494 %(limit)s %(for_update)s""" % {
495 "conditions": conditions,
496 "limit": limit or "",
497 "for_update": for_update and "for update" or "",
498 "order": order
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530499 }, previous_sle, as_dict=1, debug=debug)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530500
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530501def get_sle_by_id(sle_id):
502 return frappe.db.get_all('Stock Ledger Entry',
503 fields=['*', 'timestamp(posting_date, posting_time) as timestamp'],
504 filters={'name': sle_id})[0]
505
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530506def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no,
Nabin Hait7ba092e2018-02-01 10:51:27 +0530507 allow_zero_rate=False, currency=None, company=None, raise_error_if_no_rate=True):
Nabin Haita0b967f2017-01-18 18:35:58 +0530508 # Get valuation rate from last sle for the same item and warehouse
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530509 if not company:
510 company = erpnext.get_default_company()
511
Nabin Haitfb6e4342014-10-15 11:34:40 +0530512 last_valuation_rate = frappe.db.sql("""select valuation_rate
513 from `tabStock Ledger Entry`
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530514 where
515 item_code = %s
516 AND warehouse = %s
517 AND valuation_rate >= 0
518 AND NOT (voucher_no = %s AND voucher_type = %s)
519 order by posting_date desc, posting_time desc, name desc limit 1""", (item_code, warehouse, voucher_no, voucher_type))
Nabin Haitfb6e4342014-10-15 11:34:40 +0530520
521 if not last_valuation_rate:
Nabin Haita0b967f2017-01-18 18:35:58 +0530522 # Get valuation rate from last sle for the item against any warehouse
Nabin Haitfb6e4342014-10-15 11:34:40 +0530523 last_valuation_rate = frappe.db.sql("""select valuation_rate
524 from `tabStock Ledger Entry`
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530525 where
526 item_code = %s
527 AND valuation_rate > 0
528 AND NOT(voucher_no = %s AND voucher_type = %s)
529 order by posting_date desc, posting_time desc, name desc limit 1""", (item_code, voucher_no, voucher_type))
Nabin Haitfb6e4342014-10-15 11:34:40 +0530530
Nabin Haita645f362018-03-01 10:31:24 +0530531 if last_valuation_rate:
532 return flt(last_valuation_rate[0][0]) # as there is previous records, it might come with zero rate
533
534 # If negative stock allowed, and item delivered without any incoming entry,
535 # system does not found any SLE, then take valuation rate from Item
536 valuation_rate = frappe.db.get_value("Item", item_code, "valuation_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530537
538 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530539 # try Item Standard rate
540 valuation_rate = frappe.db.get_value("Item", item_code, "standard_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530541
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530542 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530543 # try in price list
544 valuation_rate = frappe.db.get_value('Item Price',
545 dict(item_code=item_code, buying=1, currency=currency),
546 'price_list_rate')
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530547
Nabin Hait7ba092e2018-02-01 10:51:27 +0530548 if not allow_zero_rate and not valuation_rate and raise_error_if_no_rate \
Rohit Waghchauree9ff1912017-06-19 12:54:59 +0530549 and cint(erpnext.is_perpetual_inventory_enabled(company)):
Neil Trini Lasrado193c8912017-03-28 17:39:34 +0530550 frappe.local.message_log = []
Marica97715f22020-05-11 20:45:37 +0530551 form_link = frappe.utils.get_link_to_form("Item", item_code)
552
553 message = _("Valuation Rate for the Item {0}, is required to do accounting entries for {1} {2}.").format(form_link, voucher_type, voucher_no)
554 message += "<br><br>" + _(" Here are the options to proceed:")
555 solutions = "<li>" + _("If the item is transacting as a Zero Valuation Rate item in this entry, please enable 'Allow Zero Valuation Rate' in the {0} Item table.").format(voucher_type) + "</li>"
556 solutions += "<li>" + _("If not, you can Cancel / Submit this entry ") + _("{0}").format(frappe.bold("after")) + _(" performing either one below:") + "</li>"
557 sub_solutions = "<ul><li>" + _("Create an incoming stock transaction for the Item.") + "</li>"
558 sub_solutions += "<li>" + _("Mention Valuation Rate in the Item master.") + "</li></ul>"
559 msg = message + solutions + sub_solutions + "</li>"
560
561 frappe.throw(msg=msg, title=_("Valuation Rate Missing"))
Nabin Haitfb6e4342014-10-15 11:34:40 +0530562
563 return valuation_rate