blob: 2b2a7a202dd9a61dc6a768b7c5980be02780b36e [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
Nabin Haita77b8c92020-12-21 14:45:50 +05308from frappe.model.meta import get_field_precision
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +05309from erpnext.stock.utils import get_valuation_method, get_incoming_outgoing_rate_for_cancel
Nabin Haita77b8c92020-12-21 14:45:50 +053010from erpnext.stock.utils import get_bin
Nabin Hait26d46552013-01-09 15:23:05 +053011import json
Achilles Rasquinha361366e2018-02-14 17:08:59 +053012from six import iteritems
13
Nabin Hait902e8602013-01-08 18:29:24 +053014# future reposting
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053015class NegativeStockError(frappe.ValidationError): pass
Nabin Hait902e8602013-01-08 18:29:24 +053016
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053017_exceptions = frappe.local('stockledger_exceptions')
Pratik Vyas16371b72013-09-18 18:31:03 +053018# _exceptions = []
Anand Doshi5b004ff2013-09-25 19:55:41 +053019
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053020def make_sl_entries(sl_entries, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Haitca775742013-09-26 16:16:44 +053021 if sl_entries:
Rushabh Mehta1f847992013-12-12 19:12:19 +053022 from erpnext.stock.utils import update_bin
Nabin Haitdc82d4f2014-04-07 12:02:57 +053023
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053024 cancel = sl_entries[0].get("is_cancelled")
Nabin Haitca775742013-09-26 16:16:44 +053025 if cancel:
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053026 set_as_cancel(sl_entries[0].get('voucher_type'), sl_entries[0].get('voucher_no'))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053027
Nabin Haitca775742013-09-26 16:16:44 +053028 for sle in sl_entries:
Nabin Haita77b8c92020-12-21 14:45:50 +053029 if cancel:
30 sle['actual_qty'] = -flt(sle.get('actual_qty'))
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053031
Nabin Haita77b8c92020-12-21 14:45:50 +053032 if sle['actual_qty'] < 0 and not sle.get('outgoing_rate'):
33 sle['outgoing_rate'] = get_incoming_outgoing_rate_for_cancel(sle.item_code,
34 sle.voucher_type, sle.voucher_no, sle.voucher_detail_no)
35 sle['incoming_rate'] = 0.0
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053036
Nabin Haita77b8c92020-12-21 14:45:50 +053037 if sle['actual_qty'] > 0 and not sle.get('incoming_rate'):
38 sle['incoming_rate'] = get_incoming_outgoing_rate_for_cancel(sle.item_code,
39 sle.voucher_type, sle.voucher_no, sle.voucher_detail_no)
40 sle['outgoing_rate'] = 0.0
Nabin Haitdc82d4f2014-04-07 12:02:57 +053041
Nabin Hait5288bde2014-11-03 15:08:21 +053042 if sle.get("actual_qty") or sle.get("voucher_type")=="Stock Reconciliation":
Nabin Haita77b8c92020-12-21 14:45:50 +053043 sle_doc = make_entry(sle, allow_negative_stock, via_landed_cost_voucher)
Deepesh Gargb4be2922021-01-28 13:09:56 +053044
Nabin Haita77b8c92020-12-21 14:45:50 +053045 args = sle_doc.as_dict()
Nabin Hait54c865e2015-03-27 15:38:31 +053046 update_bin(args, allow_negative_stock, via_landed_cost_voucher)
Nabin Haitadeb9762014-10-06 11:53:52 +053047
Nabin Haitdc82d4f2014-04-07 12:02:57 +053048
Nabin Hait9653f602013-08-20 15:37:33 +053049def set_as_cancel(voucher_type, voucher_no):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053050 frappe.db.sql("""update `tabStock Ledger Entry` set is_cancelled=1,
Nabin Hait9653f602013-08-20 15:37:33 +053051 modified=%s, modified_by=%s
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053052 where voucher_type=%s and voucher_no=%s and is_cancelled = 0""",
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053053 (now(), frappe.session.user, voucher_type, voucher_no))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053054
Nabin Hait54c865e2015-03-27 15:38:31 +053055def make_entry(args, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Hait74c281c2013-08-19 16:17:18 +053056 args.update({"doctype": "Stock Ledger Entry"})
Rushabh Mehtaa504f062014-04-04 12:16:26 +053057 sle = frappe.get_doc(args)
Anand Doshi6dfd4302015-02-10 14:41:27 +053058 sle.flags.ignore_permissions = 1
Nabin Hait4ccd8d32015-01-23 12:18:01 +053059 sle.allow_negative_stock=allow_negative_stock
Nabin Hait54c865e2015-03-27 15:38:31 +053060 sle.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Hait74c281c2013-08-19 16:17:18 +053061 sle.insert()
Nabin Haitaeba24e2013-08-23 15:17:36 +053062 sle.submit()
Nabin Haita77b8c92020-12-21 14:45:50 +053063 return sle
Nabin Haitdc82d4f2014-04-07 12:02:57 +053064
Nabin Haita77b8c92020-12-21 14:45:50 +053065def repost_future_sle(args=None, voucher_type=None, voucher_no=None, allow_negative_stock=False, via_landed_cost_voucher=False):
66 if not args and voucher_type and voucher_no:
67 args = get_args_for_voucher(voucher_type, voucher_no)
Deepesh Gargb4be2922021-01-28 13:09:56 +053068
Nabin Haita77b8c92020-12-21 14:45:50 +053069 distinct_item_warehouses = [(d.item_code, d.warehouse) for d in args]
70
71 i = 0
72 while i < len(args):
73 obj = update_entries_after({
74 "item_code": args[i].item_code,
75 "warehouse": args[i].warehouse,
76 "posting_date": args[i].posting_date,
77 "posting_time": args[i].posting_time
78 }, allow_negative_stock=allow_negative_stock, via_landed_cost_voucher=via_landed_cost_voucher)
79
80 for item_wh, new_sle in iteritems(obj.new_items):
81 if item_wh not in distinct_item_warehouses:
82 args.append(new_sle)
Deepesh Gargb4be2922021-01-28 13:09:56 +053083
Nabin Haita77b8c92020-12-21 14:45:50 +053084 i += 1
85
86def get_args_for_voucher(voucher_type, voucher_no):
87 return frappe.db.get_all("Stock Ledger Entry",
88 filters={"voucher_type": voucher_type, "voucher_no": voucher_no},
89 fields=["item_code", "warehouse", "posting_date", "posting_time"],
90 order_by="creation asc",
91 group_by="item_code, warehouse"
92 )
Nabin Hait74c281c2013-08-19 16:17:18 +053093
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053094class update_entries_after(object):
Nabin Hait902e8602013-01-08 18:29:24 +053095 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +053096 update valution rate and qty after transaction
Nabin Hait902e8602013-01-08 18:29:24 +053097 from the current time-bucket onwards
Nabin Haitdc82d4f2014-04-07 12:02:57 +053098
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +053099 :param args: args as dict
100
101 args = {
102 "item_code": "ABC",
103 "warehouse": "XYZ",
104 "posting_date": "2012-12-12",
105 "posting_time": "12:00"
106 }
Nabin Hait902e8602013-01-08 18:29:24 +0530107 """
Anand Doshi0dc79f42015-04-06 12:59:34 +0530108 def __init__(self, args, allow_zero_rate=False, allow_negative_stock=None, via_landed_cost_voucher=False, verbose=1):
Nabin Haita77b8c92020-12-21 14:45:50 +0530109 self.exceptions = {}
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530110 self.verbose = verbose
111 self.allow_zero_rate = allow_zero_rate
Anand Doshi0dc79f42015-04-06 12:59:34 +0530112 self.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Haita77b8c92020-12-21 14:45:50 +0530113 self.allow_negative_stock = allow_negative_stock \
114 or cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530115
Nabin Haita77b8c92020-12-21 14:45:50 +0530116 self.args = frappe._dict(args)
117 self.item_code = args.get("item_code")
118 if self.args.sle_id:
119 self.args['name'] = self.args.sle_id
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530120
Nabin Haita77b8c92020-12-21 14:45:50 +0530121 self.company = frappe.get_cached_value("Warehouse", self.args.warehouse, "company")
122 self.get_precision()
123 self.valuation_method = get_valuation_method(self.item_code)
124 self.new_items = {}
125
126 self.data = frappe._dict()
127 self.initialize_previous_data(self.args)
128
129 self.build()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530130
Nabin Haita77b8c92020-12-21 14:45:50 +0530131 def get_precision(self):
132 company_base_currency = frappe.get_cached_value('Company', self.company, "default_currency")
133 self.precision = get_field_precision(frappe.get_meta("Stock Ledger Entry").get_field("stock_value"),
134 currency=company_base_currency)
135
136 def initialize_previous_data(self, args):
137 """
138 Get previous sl entries for current item for each related warehouse
139 and assigns into self.data dict
140
141 :Data Structure:
142
143 self.data = {
144 warehouse1: {
145 'previus_sle': {},
146 'qty_after_transaction': 10,
147 'valuation_rate': 100,
148 'stock_value': 1000,
149 'prev_stock_value': 1000,
150 'stock_queue': '[[10, 100]]',
151 'stock_value_difference': 1000
152 }
153 }
154
155 """
156 self.data.setdefault(args.warehouse, frappe._dict())
157 warehouse_dict = self.data[args.warehouse]
158 previous_sle = self.get_sle_before_datetime(args)
159 warehouse_dict.previous_sle = previous_sle
Nabin Haitbb777562013-08-29 18:19:37 +0530160
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530161 for key in ("qty_after_transaction", "valuation_rate", "stock_value"):
Nabin Haita77b8c92020-12-21 14:45:50 +0530162 setattr(warehouse_dict, key, flt(previous_sle.get(key)))
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530163
Nabin Haita77b8c92020-12-21 14:45:50 +0530164 warehouse_dict.update({
165 "prev_stock_value": previous_sle.stock_value or 0.0,
166 "stock_queue": json.loads(previous_sle.stock_queue or "[]"),
167 "stock_value_difference": 0.0
168 })
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530169
Nabin Haita77b8c92020-12-21 14:45:50 +0530170 def build(self):
171 if self.args.get("sle_id"):
172 self.process_sle_against_current_voucher()
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530173 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530174 entries_to_fix = self.get_future_entries_to_fix()
175
176 i = 0
177 while i < len(entries_to_fix):
178 sle = entries_to_fix[i]
179 i += 1
180
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530181 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530182
Nabin Haita77b8c92020-12-21 14:45:50 +0530183 if sle.dependant_sle_voucher_detail_no:
184 self.get_dependent_entries_to_fix(entries_to_fix, sle)
185
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530186 if self.exceptions:
187 self.raise_exceptions()
188
189 self.update_bin()
190
Nabin Haita77b8c92020-12-21 14:45:50 +0530191 def process_sle_against_current_voucher(self):
192 sl_entries = self.get_sle_against_current_voucher()
193 for sle in sl_entries:
194 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530195
Nabin Haita77b8c92020-12-21 14:45:50 +0530196 def get_sle_against_current_voucher(self):
197 return frappe.db.sql("""
198 select
199 *, timestamp(posting_date, posting_time) as "timestamp"
200 from
201 `tabStock Ledger Entry`
202 where
203 item_code = %(item_code)s
204 and warehouse = %(warehouse)s
205 and voucher_type = %(voucher_type)s
206 and voucher_no = %(voucher_no)s
207 order by
208 creation ASC
209 for update
210 """, self.args, as_dict=1)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530211
Nabin Haita77b8c92020-12-21 14:45:50 +0530212 def get_future_entries_to_fix(self):
213 # includes current entry!
214 args = self.data[self.args.warehouse].previous_sle \
215 or frappe._dict({"item_code": self.item_code, "warehouse": self.args.warehouse})
Deepesh Gargb4be2922021-01-28 13:09:56 +0530216
Nabin Haita77b8c92020-12-21 14:45:50 +0530217 return list(self.get_sle_after_datetime(args))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530218
Nabin Haita77b8c92020-12-21 14:45:50 +0530219 def get_dependent_entries_to_fix(self, entries_to_fix, sle):
220 dependant_sle = get_sle_by_voucher_detail_no(sle.dependant_sle_voucher_detail_no,
221 excluded_sle=sle.name)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530222
Nabin Haita77b8c92020-12-21 14:45:50 +0530223 if not dependant_sle:
224 return
225 elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse == self.args.warehouse:
226 return
227 elif dependant_sle.item_code != self.item_code \
228 and (dependant_sle.item_code, dependant_sle.warehouse) not in self.new_items:
229 self.new_items[(dependant_sle.item_code, dependant_sle.warehouse)] = dependant_sle
230 return
231
232 self.initialize_previous_data(dependant_sle)
233
234 args = self.data[dependant_sle.warehouse].previous_sle \
235 or frappe._dict({"item_code": self.item_code, "warehouse": dependant_sle.warehouse})
236 future_sle_for_dependant = list(self.get_sle_after_datetime(args))
237
238 entries_to_fix.extend(future_sle_for_dependant)
239 entries_to_fix = sorted(entries_to_fix, key=lambda k: k['timestamp'])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530240
241 def process_sle(self, sle):
Nabin Haita77b8c92020-12-21 14:45:50 +0530242 # previous sle data for this warehouse
243 self.wh_data = self.data[sle.warehouse]
244
Anand Doshi0dc79f42015-04-06 12:59:34 +0530245 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 +0530246 # validate negative stock for serialized items, fifo valuation
Nabin Hait902e8602013-01-08 18:29:24 +0530247 # or when negative stock is not allowed for moving average
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530248 if not self.validate_negative_stock(sle):
Nabin Haita77b8c92020-12-21 14:45:50 +0530249 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530250 return
Nabin Haitb96c0142014-10-07 11:25:04 +0530251
Nabin Haita77b8c92020-12-21 14:45:50 +0530252 # Get dynamic incoming/outgoing rate
253 self.get_dynamic_incoming_outgoing_rate(sle)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530254
Anand Doshi1b531862013-01-10 19:29:51 +0530255 if sle.serial_no:
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530256 self.get_serialized_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530257 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530258 if sle.voucher_type == "Stock Reconciliation":
Nabin Haita77b8c92020-12-21 14:45:50 +0530259 self.wh_data.qty_after_transaction = sle.qty_after_transaction
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530260
Nabin Haita77b8c92020-12-21 14:45:50 +0530261 self.wh_data.stock_value = flt(self.wh_data.qty_after_transaction) * flt(self.wh_data.valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530262 else:
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530263 if sle.voucher_type=="Stock Reconciliation" and not sle.batch_no:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530264 # assert
Nabin Haita77b8c92020-12-21 14:45:50 +0530265 self.wh_data.valuation_rate = sle.valuation_rate
266 self.wh_data.qty_after_transaction = sle.qty_after_transaction
267 self.wh_data.stock_queue = [[self.wh_data.qty_after_transaction, self.wh_data.valuation_rate]]
268 self.wh_data.stock_value = flt(self.wh_data.qty_after_transaction) * flt(self.wh_data.valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530269 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530270 if self.valuation_method == "Moving Average":
271 self.get_moving_average_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530272 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
273 self.wh_data.stock_value = flt(self.wh_data.qty_after_transaction) * flt(self.wh_data.valuation_rate)
Nabin Haitb96c0142014-10-07 11:25:04 +0530274 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530275 self.get_fifo_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530276 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
277 self.wh_data.stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in self.wh_data.stock_queue))
Nabin Haitb96c0142014-10-07 11:25:04 +0530278
Rushabh Mehta54047782013-12-26 11:07:46 +0530279 # rounding as per precision
Nabin Haita77b8c92020-12-21 14:45:50 +0530280 self.wh_data.stock_value = flt(self.wh_data.stock_value, self.precision)
281 stock_value_difference = self.wh_data.stock_value - self.wh_data.prev_stock_value
282 self.wh_data.prev_stock_value = self.wh_data.stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530283
Nabin Hait902e8602013-01-08 18:29:24 +0530284 # update current sle
Nabin Haita77b8c92020-12-21 14:45:50 +0530285 sle.qty_after_transaction = self.wh_data.qty_after_transaction
286 sle.valuation_rate = self.wh_data.valuation_rate
287 sle.stock_value = self.wh_data.stock_value
288 sle.stock_queue = json.dumps(self.wh_data.stock_queue)
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530289 sle.stock_value_difference = stock_value_difference
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530290 sle.doctype="Stock Ledger Entry"
291 frappe.get_doc(sle).db_update()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530292
Nabin Haita77b8c92020-12-21 14:45:50 +0530293 self.update_outgoing_rate_on_transaction(sle)
294
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530295 def validate_negative_stock(self, sle):
296 """
297 validate negative stock for entries current datetime onwards
298 will not consider cancelled entries
299 """
Nabin Haita77b8c92020-12-21 14:45:50 +0530300 diff = self.wh_data.qty_after_transaction + flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530301
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530302 if diff < 0 and abs(diff) > 0.0001:
303 # negative stock!
304 exc = sle.copy().update({"diff": diff})
Nabin Haita77b8c92020-12-21 14:45:50 +0530305 self.exceptions.setdefault(sle.warehouse, []).append(exc)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530306 return False
Nabin Hait902e8602013-01-08 18:29:24 +0530307 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530308 return True
309
Nabin Haita77b8c92020-12-21 14:45:50 +0530310 def get_dynamic_incoming_outgoing_rate(self, sle):
311 # Get updated incoming/outgoing rate from transaction
312 if sle.recalculate_rate:
313 rate = self.get_incoming_outgoing_rate_from_transaction(sle)
314
315 if flt(sle.actual_qty) >= 0:
316 sle.incoming_rate = rate
317 else:
318 sle.outgoing_rate = rate
319
320 def get_incoming_outgoing_rate_from_transaction(self, sle):
321 rate = 0
322 # Material Transfer, Repack, Manufacturing
323 if sle.voucher_type == "Stock Entry":
324 rate = frappe.db.get_value("Stock Entry Detail", sle.voucher_detail_no, "valuation_rate")
325 # Sales and Purchase Return
326 elif sle.voucher_type in ("Purchase Receipt", "Purchase Invoice", "Delivery Note", "Sales Invoice"):
327 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_return"):
328 from erpnext.controllers.sales_and_purchase_return import get_rate_for_return # don't move this import to top
329 rate = get_rate_for_return(sle.voucher_type, sle.voucher_no, sle.item_code, voucher_detail_no=sle.voucher_detail_no)
330 else:
331 if sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530332 rate_field = "valuation_rate"
Nabin Haita77b8c92020-12-21 14:45:50 +0530333 else:
334 rate_field = "incoming_rate"
335
336 # check in item table
337 item_code, incoming_rate = frappe.db.get_value(sle.voucher_type + " Item",
338 sle.voucher_detail_no, ["item_code", rate_field])
339
340 if item_code == sle.item_code:
341 rate = incoming_rate
342 else:
343 if sle.voucher_type in ("Delivery Note", "Sales Invoice"):
344 ref_doctype = "Packed Item"
345 else:
346 ref_doctype = "Purchase Receipt Item Supplied"
Deepesh Gargb4be2922021-01-28 13:09:56 +0530347
Nabin Haita77b8c92020-12-21 14:45:50 +0530348 rate = frappe.db.get_value(ref_doctype, {"parent_detail_docname": sle.voucher_detail_no,
349 "item_code": sle.item_code}, rate_field)
350
351 return rate
352
353 def update_outgoing_rate_on_transaction(self, sle):
354 """
355 Update outgoing rate in Stock Entry, Delivery Note, Sales Invoice and Sales Return
356 In case of Stock Entry, also calculate FG Item rate and total incoming/outgoing amount
357 """
358 if sle.actual_qty and sle.voucher_detail_no:
359 outgoing_rate = abs(flt(sle.stock_value_difference)) / abs(sle.actual_qty)
360
361 if flt(sle.actual_qty) < 0 and sle.voucher_type == "Stock Entry":
362 self.update_rate_on_stock_entry(sle, outgoing_rate)
363 elif sle.voucher_type in ("Delivery Note", "Sales Invoice"):
364 self.update_rate_on_delivery_and_sales_return(sle, outgoing_rate)
365 elif flt(sle.actual_qty) < 0 and sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
366 self.update_rate_on_purchase_receipt(sle, outgoing_rate)
367
368 def update_rate_on_stock_entry(self, sle, outgoing_rate):
369 frappe.db.set_value("Stock Entry Detail", sle.voucher_detail_no, "basic_rate", outgoing_rate)
370
371 # Update outgoing item's rate, recalculate FG Item's rate and total incoming/outgoing amount
372 stock_entry = frappe.get_doc("Stock Entry", sle.voucher_no)
373 stock_entry.calculate_rate_and_amount(reset_outgoing_rate=False, raise_error_if_no_rate=False)
374 stock_entry.db_update()
375 for d in stock_entry.items:
376 d.db_update()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530377
Nabin Haita77b8c92020-12-21 14:45:50 +0530378 def update_rate_on_delivery_and_sales_return(self, sle, outgoing_rate):
379 # Update item's incoming rate on transaction
380 item_code = frappe.db.get_value(sle.voucher_type + " Item", sle.voucher_detail_no, "item_code")
381 if item_code == sle.item_code:
382 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "incoming_rate", outgoing_rate)
383 else:
384 # packed item
385 frappe.db.set_value("Packed Item",
386 {"parent_detail_docname": sle.voucher_detail_no, "item_code": sle.item_code},
387 "incoming_rate", outgoing_rate)
388
389 def update_rate_on_purchase_receipt(self, sle, outgoing_rate):
390 if frappe.db.exists(sle.voucher_type + " Item", sle.voucher_detail_no):
391 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "base_net_rate", outgoing_rate)
392 else:
393 frappe.db.set_value("Purchase Receipt Item Supplied", sle.voucher_detail_no, "rate", outgoing_rate)
394
395 # Recalculate subcontracted item's rate in case of subcontracted purchase receipt/invoice
396 if frappe.db.get_value(sle.voucher_type, sle.voucher_no, "is_subcontracted"):
397 doc = frappe.get_cached_doc(sle.voucher_type, sle.voucher_no)
398 doc.update_valuation_rate(reset_outgoing_rate=False)
399 for d in (doc.items + doc.supplied_items):
400 d.db_update()
401
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530402 def get_serialized_values(self, sle):
403 incoming_rate = flt(sle.incoming_rate)
404 actual_qty = flt(sle.actual_qty)
Nabin Hait328c4f92020-01-02 19:00:32 +0530405 serial_nos = cstr(sle.serial_no).split("\n")
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530406
407 if incoming_rate < 0:
408 # wrong incoming rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530409 incoming_rate = self.wh_data.valuation_rate
Rushabh Mehta538607e2016-06-12 11:03:00 +0530410
Nabin Hait2620bf42016-02-29 11:30:27 +0530411 stock_value_change = 0
412 if incoming_rate:
413 stock_value_change = actual_qty * incoming_rate
414 elif actual_qty < 0:
415 # In case of delivery/stock issue, get average purchase rate
416 # of serial nos of current entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530417 if not sle.is_cancelled:
418 outgoing_value = self.get_incoming_value_for_serial_nos(sle, serial_nos)
419 stock_value_change = -1 * outgoing_value
420 else:
421 stock_value_change = actual_qty * sle.outgoing_rate
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530422
Nabin Haita77b8c92020-12-21 14:45:50 +0530423 new_stock_qty = self.wh_data.qty_after_transaction + actual_qty
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530424
Nabin Hait2620bf42016-02-29 11:30:27 +0530425 if new_stock_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530426 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + stock_value_change
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530427 if new_stock_value >= 0:
Nabin Hait2620bf42016-02-29 11:30:27 +0530428 # calculate new valuation rate only if stock value is positive
429 # else it remains the same as that of previous entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530430 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530431
Nabin Haita77b8c92020-12-21 14:45:50 +0530432 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530433 allow_zero_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
434 if not allow_zero_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530435 self.wh_data.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530436 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
437 currency=erpnext.get_company_currency(sle.company))
438
Nabin Hait328c4f92020-01-02 19:00:32 +0530439 def get_incoming_value_for_serial_nos(self, sle, serial_nos):
440 # get rate from serial nos within same company
441 all_serial_nos = frappe.get_all("Serial No",
442 fields=["purchase_rate", "name", "company"],
443 filters = {'name': ('in', serial_nos)})
444
445 incoming_values = sum([flt(d.purchase_rate) for d in all_serial_nos if d.company==sle.company])
446
447 # Get rate for serial nos which has been transferred to other company
448 invalid_serial_nos = [d.name for d in all_serial_nos if d.company!=sle.company]
449 for serial_no in invalid_serial_nos:
450 incoming_rate = frappe.db.sql("""
451 select incoming_rate
452 from `tabStock Ledger Entry`
453 where
454 company = %s
455 and actual_qty > 0
456 and (serial_no = %s
457 or serial_no like %s
458 or serial_no like %s
459 or serial_no like %s
460 )
461 order by posting_date desc
462 limit 1
463 """, (sle.company, serial_no, serial_no+'\n%', '%\n'+serial_no, '%\n'+serial_no+'\n%'))
464
465 incoming_values += flt(incoming_rate[0][0]) if incoming_rate else 0
466
467 return incoming_values
468
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530469 def get_moving_average_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530470 actual_qty = flt(sle.actual_qty)
Nabin Haita77b8c92020-12-21 14:45:50 +0530471 new_stock_qty = flt(self.wh_data.qty_after_transaction) + actual_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530472 if new_stock_qty >= 0:
473 if actual_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530474 if flt(self.wh_data.qty_after_transaction) <= 0:
475 self.wh_data.valuation_rate = sle.incoming_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530476 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530477 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530478 (actual_qty * sle.incoming_rate)
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530479
Nabin Haita77b8c92020-12-21 14:45:50 +0530480 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530481
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530482 elif sle.outgoing_rate:
483 if new_stock_qty:
Nabin Haita77b8c92020-12-21 14:45:50 +0530484 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530485 (actual_qty * sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530486
Nabin Haita77b8c92020-12-21 14:45:50 +0530487 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530488 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530489 self.wh_data.valuation_rate = sle.outgoing_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530490 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530491 if flt(self.wh_data.qty_after_transaction) >= 0 and sle.outgoing_rate:
492 self.wh_data.valuation_rate = sle.outgoing_rate
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530493
Nabin Haita77b8c92020-12-21 14:45:50 +0530494 if not self.wh_data.valuation_rate and actual_qty > 0:
495 self.wh_data.valuation_rate = sle.incoming_rate
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530496
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530497 # Get valuation rate from previous SLE or Item master, if item does not have the
Javier Wong9b11d9b2017-04-14 18:24:04 +0800498 # allow zero valuration rate flag set
Nabin Haita77b8c92020-12-21 14:45:50 +0530499 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
Javier Wong9b11d9b2017-04-14 18:24:04 +0800500 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
501 if not allow_zero_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530502 self.wh_data.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530503 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
504 currency=erpnext.get_company_currency(sle.company))
505
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530506 def get_fifo_values(self, sle):
507 incoming_rate = flt(sle.incoming_rate)
508 actual_qty = flt(sle.actual_qty)
Nabin Haitada485f2015-07-17 15:09:56 +0530509 outgoing_rate = flt(sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530510
511 if actual_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530512 if not self.wh_data.stock_queue:
513 self.wh_data.stock_queue.append([0, 0])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530514
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530515 # last row has the same rate, just updated the qty
Nabin Haita77b8c92020-12-21 14:45:50 +0530516 if self.wh_data.stock_queue[-1][1]==incoming_rate:
517 self.wh_data.stock_queue[-1][0] += actual_qty
Nabin Hait4d742162014-10-09 19:25:03 +0530518 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530519 if self.wh_data.stock_queue[-1][0] > 0:
520 self.wh_data.stock_queue.append([actual_qty, incoming_rate])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530521 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530522 qty = self.wh_data.stock_queue[-1][0] + actual_qty
523 self.wh_data.stock_queue[-1] = [qty, incoming_rate]
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530524 else:
525 qty_to_pop = abs(actual_qty)
526 while qty_to_pop:
Nabin Haita77b8c92020-12-21 14:45:50 +0530527 if not self.wh_data.stock_queue:
Nabin Haita0b967f2017-01-18 18:35:58 +0530528 # Get valuation rate from last sle if exists or from valuation rate field in item master
Javier Wong9b11d9b2017-04-14 18:24:04 +0800529 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
530 if not allow_zero_valuation_rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530531 _rate = get_valuation_rate(sle.item_code, sle.warehouse,
532 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
533 currency=erpnext.get_company_currency(sle.company))
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530534 else:
535 _rate = 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530536
Nabin Haita77b8c92020-12-21 14:45:50 +0530537 self.wh_data.stock_queue.append([0, _rate])
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530538
Nabin Haitada485f2015-07-17 15:09:56 +0530539 index = None
540 if outgoing_rate > 0:
541 # Find the entry where rate matched with outgoing rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530542 for i, v in enumerate(self.wh_data.stock_queue):
Nabin Haitada485f2015-07-17 15:09:56 +0530543 if v[1] == outgoing_rate:
544 index = i
545 break
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530546
Nabin Haitada485f2015-07-17 15:09:56 +0530547 # If no entry found with outgoing rate, collapse stack
548 if index == None:
Nabin Haita77b8c92020-12-21 14:45:50 +0530549 new_stock_value = sum((d[0]*d[1] for d in self.wh_data.stock_queue)) - qty_to_pop*outgoing_rate
550 new_stock_qty = sum((d[0] for d in self.wh_data.stock_queue)) - qty_to_pop
551 self.wh_data.stock_queue = [[new_stock_qty, new_stock_value/new_stock_qty if new_stock_qty > 0 else outgoing_rate]]
Nabin Haitada485f2015-07-17 15:09:56 +0530552 break
553 else:
554 index = 0
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530555
Nabin Haitada485f2015-07-17 15:09:56 +0530556 # select first batch or the batch with same rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530557 batch = self.wh_data.stock_queue[index]
Nabin Hait8142cd22015-08-05 18:57:26 +0530558 if qty_to_pop >= batch[0]:
559 # consume current batch
560 qty_to_pop = qty_to_pop - batch[0]
Nabin Haita77b8c92020-12-21 14:45:50 +0530561 self.wh_data.stock_queue.pop(index)
562 if not self.wh_data.stock_queue and qty_to_pop:
Nabin Hait8142cd22015-08-05 18:57:26 +0530563 # stock finished, qty still remains to be withdrawn
564 # negative stock, keep in as a negative batch
Nabin Haita77b8c92020-12-21 14:45:50 +0530565 self.wh_data.stock_queue.append([-qty_to_pop, outgoing_rate or batch[1]])
Nabin Hait8142cd22015-08-05 18:57:26 +0530566 break
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530567
Nabin Hait8142cd22015-08-05 18:57:26 +0530568 else:
569 # qty found in current batch
570 # consume it and exit
571 batch[0] = batch[0] - qty_to_pop
572 qty_to_pop = 0
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530573
Nabin Haita77b8c92020-12-21 14:45:50 +0530574 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in self.wh_data.stock_queue))
575 stock_qty = sum((flt(batch[0]) for batch in self.wh_data.stock_queue))
Nabin Hait902e8602013-01-08 18:29:24 +0530576
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530577 if stock_qty:
Nabin Haita77b8c92020-12-21 14:45:50 +0530578 self.wh_data.valuation_rate = stock_value / flt(stock_qty)
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530579
Nabin Haita77b8c92020-12-21 14:45:50 +0530580 if not self.wh_data.stock_queue:
581 self.wh_data.stock_queue.append([0, sle.incoming_rate or sle.outgoing_rate or self.wh_data.valuation_rate])
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530582
Javier Wong9b11d9b2017-04-14 18:24:04 +0800583 def check_if_allow_zero_valuation_rate(self, voucher_type, voucher_detail_no):
deepeshgarg007f9c0ef32019-07-30 18:49:19 +0530584 ref_item_dt = ""
585
586 if voucher_type == "Stock Entry":
587 ref_item_dt = voucher_type + " Detail"
588 elif voucher_type in ["Purchase Invoice", "Sales Invoice", "Delivery Note", "Purchase Receipt"]:
589 ref_item_dt = voucher_type + " Item"
590
591 if ref_item_dt:
592 return frappe.db.get_value(ref_item_dt, voucher_detail_no, "allow_zero_valuation_rate")
593 else:
594 return 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530595
Nabin Haita77b8c92020-12-21 14:45:50 +0530596 def get_sle_before_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530597 """get previous stock ledger entry before current time-bucket"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530598 sle = get_stock_ledger_entries(args, "<", "desc", "limit 1", for_update=False)
599 sle = sle[0] if sle else frappe._dict()
600 return sle
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530601
Nabin Haita77b8c92020-12-21 14:45:50 +0530602 def get_sle_after_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530603 """get Stock Ledger Entries after a particular datetime, for reposting"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530604 return get_stock_ledger_entries(args, ">", "asc", for_update=True, check_serial_no=False)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530605
606 def raise_exceptions(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530607 msg_list = []
608 for warehouse, exceptions in iteritems(self.exceptions):
609 deficiency = min(e["diff"] for e in exceptions)
Rushabh Mehta538607e2016-06-12 11:03:00 +0530610
Nabin Haita77b8c92020-12-21 14:45:50 +0530611 if ((exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]) in
612 frappe.local.flags.currently_saving):
Nabin Hait3edefb12016-07-20 16:13:18 +0530613
Nabin Haita77b8c92020-12-21 14:45:50 +0530614 msg = _("{0} units of {1} needed in {2} to complete this transaction.").format(
615 abs(deficiency), frappe.get_desk_link('Item', self.item_code),
616 frappe.get_desk_link('Warehouse', warehouse))
617 else:
618 msg = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
619 abs(deficiency), frappe.get_desk_link('Item', self.item_code),
620 frappe.get_desk_link('Warehouse', warehouse),
621 exceptions[0]["posting_date"], exceptions[0]["posting_time"],
622 frappe.get_desk_link(exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530623
Nabin Haita77b8c92020-12-21 14:45:50 +0530624 if msg:
625 msg_list.append(msg)
626
627 if msg_list:
628 message = "\n\n".join(msg_list)
629 if self.verbose:
630 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
631 else:
632 raise NegativeStockError(message)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530633
Nabin Haita77b8c92020-12-21 14:45:50 +0530634 def update_bin(self):
635 # update bin for each warehouse
636 for warehouse, data in iteritems(self.data):
637 bin_doc = get_bin(self.item_code, warehouse)
638
639 bin_doc.update({
640 "valuation_rate": data.valuation_rate,
641 "actual_qty": data.qty_after_transaction,
642 "stock_value": data.stock_value
643 })
644 bin_doc.flags.via_stock_ledger_entry = True
645 bin_doc.save(ignore_permissions=True)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530646
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530647def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530648 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530649 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530650 to get actual qty before transaction, this function
651 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530652
Anand Doshi1b531862013-01-10 19:29:51 +0530653 args = {
654 "item_code": "ABC",
655 "warehouse": "XYZ",
656 "posting_date": "2012-12-12",
657 "posting_time": "12:00",
658 "sle": "name of reference Stock Ledger Entry"
659 }
660 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530661 args["name"] = args.get("sle", None) or ""
662 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530663 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530664
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530665def get_stock_ledger_entries(previous_sle, operator=None,
666 order="desc", limit=None, for_update=False, debug=False, check_serial_no=True):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530667 """get stock ledger entries filtered by specific posting datetime conditions"""
Nabin Haitb9ce1042018-02-01 14:58:50 +0530668 conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
669 if previous_sle.get("warehouse"):
670 conditions += " and warehouse = %(warehouse)s"
671 elif previous_sle.get("warehouse_condition"):
672 conditions += " and " + previous_sle.get("warehouse_condition")
673
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530674 if check_serial_no and previous_sle.get("serial_no"):
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530675 conditions += " and serial_no like {}".format(frappe.db.escape('%{0}%'.format(previous_sle.get("serial_no"))))
676
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530677 if not previous_sle.get("posting_date"):
678 previous_sle["posting_date"] = "1900-01-01"
679 if not previous_sle.get("posting_time"):
680 previous_sle["posting_time"] = "00:00"
681
682 if operator in (">", "<=") and previous_sle.get("name"):
683 conditions += " and name!=%(name)s"
684
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530685 return frappe.db.sql("""
686 select *, timestamp(posting_date, posting_time) as "timestamp"
687 from `tabStock Ledger Entry`
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530688 where item_code = %%(item_code)s
Nabin Haita77b8c92020-12-21 14:45:50 +0530689 and is_cancelled = 0
Nabin Haitb9ce1042018-02-01 14:58:50 +0530690 %(conditions)s
Aditya Hase0c164242019-01-07 22:07:13 +0530691 order by timestamp(posting_date, posting_time) %(order)s, creation %(order)s
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530692 %(limit)s %(for_update)s""" % {
693 "conditions": conditions,
694 "limit": limit or "",
695 "for_update": for_update and "for update" or "",
696 "order": order
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530697 }, previous_sle, as_dict=1, debug=debug)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530698
Nabin Haita77b8c92020-12-21 14:45:50 +0530699def get_sle_by_voucher_detail_no(voucher_detail_no, excluded_sle=None):
700 return frappe.db.get_value('Stock Ledger Entry',
701 {'voucher_detail_no': voucher_detail_no, 'name': ['!=', excluded_sle]},
702 ['item_code', 'warehouse', 'posting_date', 'posting_time', 'timestamp(posting_date, posting_time) as timestamp'],
703 as_dict=1)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530704
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530705def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no,
Nabin Hait7ba092e2018-02-01 10:51:27 +0530706 allow_zero_rate=False, currency=None, company=None, raise_error_if_no_rate=True):
Nabin Haita0b967f2017-01-18 18:35:58 +0530707 # Get valuation rate from last sle for the same item and warehouse
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530708 if not company:
709 company = erpnext.get_default_company()
710
Nabin Haitfb6e4342014-10-15 11:34:40 +0530711 last_valuation_rate = frappe.db.sql("""select valuation_rate
712 from `tabStock Ledger Entry`
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530713 where
714 item_code = %s
715 AND warehouse = %s
716 AND valuation_rate >= 0
717 AND NOT (voucher_no = %s AND voucher_type = %s)
718 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 +0530719
720 if not last_valuation_rate:
Nabin Haita0b967f2017-01-18 18:35:58 +0530721 # Get valuation rate from last sle for the item against any warehouse
Nabin Haitfb6e4342014-10-15 11:34:40 +0530722 last_valuation_rate = frappe.db.sql("""select valuation_rate
723 from `tabStock Ledger Entry`
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530724 where
725 item_code = %s
726 AND valuation_rate > 0
727 AND NOT(voucher_no = %s AND voucher_type = %s)
728 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 +0530729
Nabin Haita645f362018-03-01 10:31:24 +0530730 if last_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530731 return flt(last_valuation_rate[0][0])
Nabin Haita645f362018-03-01 10:31:24 +0530732
733 # If negative stock allowed, and item delivered without any incoming entry,
734 # system does not found any SLE, then take valuation rate from Item
735 valuation_rate = frappe.db.get_value("Item", item_code, "valuation_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530736
737 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530738 # try Item Standard rate
739 valuation_rate = frappe.db.get_value("Item", item_code, "standard_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530740
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530741 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530742 # try in price list
743 valuation_rate = frappe.db.get_value('Item Price',
744 dict(item_code=item_code, buying=1, currency=currency),
745 'price_list_rate')
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530746
Nabin Hait7ba092e2018-02-01 10:51:27 +0530747 if not allow_zero_rate and not valuation_rate and raise_error_if_no_rate \
Rohit Waghchauree9ff1912017-06-19 12:54:59 +0530748 and cint(erpnext.is_perpetual_inventory_enabled(company)):
Neil Trini Lasrado193c8912017-03-28 17:39:34 +0530749 frappe.local.message_log = []
Marica97715f22020-05-11 20:45:37 +0530750 form_link = frappe.utils.get_link_to_form("Item", item_code)
751
752 message = _("Valuation Rate for the Item {0}, is required to do accounting entries for {1} {2}.").format(form_link, voucher_type, voucher_no)
753 message += "<br><br>" + _(" Here are the options to proceed:")
754 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>"
755 solutions += "<li>" + _("If not, you can Cancel / Submit this entry ") + _("{0}").format(frappe.bold("after")) + _(" performing either one below:") + "</li>"
756 sub_solutions = "<ul><li>" + _("Create an incoming stock transaction for the Item.") + "</li>"
757 sub_solutions += "<li>" + _("Mention Valuation Rate in the Item master.") + "</li></ul>"
758 msg = message + solutions + sub_solutions + "</li>"
759
760 frappe.throw(msg=msg, title=_("Valuation Rate Missing"))
Nabin Haitfb6e4342014-10-15 11:34:40 +0530761
762 return valuation_rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530763
764def update_qty_in_future_sle(args, allow_negative_stock=None):
765 frappe.db.sql("""
766 update `tabStock Ledger Entry`
767 set qty_after_transaction = qty_after_transaction + {qty}
Deepesh Gargb4be2922021-01-28 13:09:56 +0530768 where
Nabin Haita77b8c92020-12-21 14:45:50 +0530769 item_code = %(item_code)s
770 and warehouse = %(warehouse)s
771 and voucher_no != %(voucher_no)s
772 and is_cancelled = 0
773 and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)
774 or (
775 timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s)
776 and creation > %(creation)s
777 )
778 )
779 """.format(qty=args.actual_qty), args)
780
781 validate_negative_qty_in_future_sle(args, allow_negative_stock)
782
783def validate_negative_qty_in_future_sle(args, allow_negative_stock=None):
784 allow_negative_stock = allow_negative_stock \
785 or cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
786
787 if args.actual_qty < 0 and not allow_negative_stock:
788 sle = get_future_sle_with_negative_qty(args)
789 if sle:
790 message = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
791 abs(sle[0]["qty_after_transaction"]),
792 frappe.get_desk_link('Item', args.item_code),
793 frappe.get_desk_link('Warehouse', args.warehouse),
794 sle[0]["posting_date"], sle[0]["posting_time"],
795 frappe.get_desk_link(sle[0]["voucher_type"], sle[0]["voucher_no"]))
Deepesh Gargb4be2922021-01-28 13:09:56 +0530796
Nabin Haita77b8c92020-12-21 14:45:50 +0530797 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
798
799def get_future_sle_with_negative_qty(args):
800 return frappe.db.sql("""
801 select
802 qty_after_transaction, posting_date, posting_time,
803 voucher_type, voucher_no
804 from `tabStock Ledger Entry`
Deepesh Gargb4be2922021-01-28 13:09:56 +0530805 where
Nabin Haita77b8c92020-12-21 14:45:50 +0530806 item_code = %(item_code)s
807 and warehouse = %(warehouse)s
808 and voucher_no != %(voucher_no)s
809 and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s)
810 and is_cancelled = 0
811 and qty_after_transaction < 0
812 limit 1
813 """, args, as_dict=1)