blob: f54b3c1bb20b5c95cc936ed3f244a813c4c98195 [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:
Nabin Hait186a0452021-02-18 14:14:21 +053026 validate_cancellation(sl_entries)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053027 set_as_cancel(sl_entries[0].get('voucher_type'), sl_entries[0].get('voucher_no'))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053028
Nabin Haitca775742013-09-26 16:16:44 +053029 for sle in sl_entries:
Nabin Haita77b8c92020-12-21 14:45:50 +053030 if cancel:
31 sle['actual_qty'] = -flt(sle.get('actual_qty'))
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053032
Nabin Haita77b8c92020-12-21 14:45:50 +053033 if sle['actual_qty'] < 0 and not sle.get('outgoing_rate'):
34 sle['outgoing_rate'] = get_incoming_outgoing_rate_for_cancel(sle.item_code,
35 sle.voucher_type, sle.voucher_no, sle.voucher_detail_no)
36 sle['incoming_rate'] = 0.0
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053037
Nabin Haita77b8c92020-12-21 14:45:50 +053038 if sle['actual_qty'] > 0 and not sle.get('incoming_rate'):
39 sle['incoming_rate'] = get_incoming_outgoing_rate_for_cancel(sle.item_code,
40 sle.voucher_type, sle.voucher_no, sle.voucher_detail_no)
41 sle['outgoing_rate'] = 0.0
Nabin Haitdc82d4f2014-04-07 12:02:57 +053042
Nabin Hait5288bde2014-11-03 15:08:21 +053043 if sle.get("actual_qty") or sle.get("voucher_type")=="Stock Reconciliation":
Nabin Haita77b8c92020-12-21 14:45:50 +053044 sle_doc = make_entry(sle, allow_negative_stock, via_landed_cost_voucher)
Deepesh Gargb4be2922021-01-28 13:09:56 +053045
Nabin Haita77b8c92020-12-21 14:45:50 +053046 args = sle_doc.as_dict()
Nabin Hait54c865e2015-03-27 15:38:31 +053047 update_bin(args, allow_negative_stock, via_landed_cost_voucher)
Nabin Haitadeb9762014-10-06 11:53:52 +053048
Nabin Hait186a0452021-02-18 14:14:21 +053049def validate_cancellation(args):
50 if args[0].get("is_cancelled"):
51 repost_entry = frappe.db.get_value("Repost Item Valuation", {
52 'voucher_type': args[0].voucher_type,
53 'voucher_no': args[0].voucher_no,
54 'docstatus': 1
55 }, ['name', 'status'], as_dict=1)
56
57 if repost_entry:
58 if repost_entry.status == 'In Progress':
59 frappe.throw(_("Cannot cancel the transaction. Reposting of item valuation on submission is not completed yet."))
60 if repost_entry.status == 'Queued':
Nabin Haitd46b2362021-02-23 16:38:52 +053061 doc = frappe.get_doc("Repost Item Valuation", repost_entry.name)
62 doc.cancel()
63 doc.delete()
Nabin Haitdc82d4f2014-04-07 12:02:57 +053064
Nabin Hait9653f602013-08-20 15:37:33 +053065def set_as_cancel(voucher_type, voucher_no):
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053066 frappe.db.sql("""update `tabStock Ledger Entry` set is_cancelled=1,
Nabin Hait9653f602013-08-20 15:37:33 +053067 modified=%s, modified_by=%s
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +053068 where voucher_type=%s and voucher_no=%s and is_cancelled = 0""",
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053069 (now(), frappe.session.user, voucher_type, voucher_no))
Nabin Haitdc82d4f2014-04-07 12:02:57 +053070
Nabin Hait54c865e2015-03-27 15:38:31 +053071def make_entry(args, allow_negative_stock=False, via_landed_cost_voucher=False):
Nabin Hait74c281c2013-08-19 16:17:18 +053072 args.update({"doctype": "Stock Ledger Entry"})
Rushabh Mehtaa504f062014-04-04 12:16:26 +053073 sle = frappe.get_doc(args)
Anand Doshi6dfd4302015-02-10 14:41:27 +053074 sle.flags.ignore_permissions = 1
Nabin Hait4ccd8d32015-01-23 12:18:01 +053075 sle.allow_negative_stock=allow_negative_stock
Nabin Hait54c865e2015-03-27 15:38:31 +053076 sle.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Hait74c281c2013-08-19 16:17:18 +053077 sle.insert()
Nabin Haitaeba24e2013-08-23 15:17:36 +053078 sle.submit()
Nabin Haita77b8c92020-12-21 14:45:50 +053079 return sle
Nabin Haitdc82d4f2014-04-07 12:02:57 +053080
Nabin Hait243d59b2021-02-02 16:55:13 +053081def repost_future_sle(args=None, voucher_type=None, voucher_no=None, allow_negative_stock=None, via_landed_cost_voucher=False):
Nabin Haita77b8c92020-12-21 14:45:50 +053082 if not args and voucher_type and voucher_no:
83 args = get_args_for_voucher(voucher_type, voucher_no)
Deepesh Gargb4be2922021-01-28 13:09:56 +053084
Nabin Haita77b8c92020-12-21 14:45:50 +053085 distinct_item_warehouses = [(d.item_code, d.warehouse) for d in args]
86
87 i = 0
88 while i < len(args):
89 obj = update_entries_after({
90 "item_code": args[i].item_code,
91 "warehouse": args[i].warehouse,
92 "posting_date": args[i].posting_date,
Nabin Hait186a0452021-02-18 14:14:21 +053093 "posting_time": args[i].posting_time,
94 "creation": args[i].get("creation")
Nabin Haita77b8c92020-12-21 14:45:50 +053095 }, allow_negative_stock=allow_negative_stock, via_landed_cost_voucher=via_landed_cost_voucher)
96
97 for item_wh, new_sle in iteritems(obj.new_items):
98 if item_wh not in distinct_item_warehouses:
99 args.append(new_sle)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530100
Nabin Haita77b8c92020-12-21 14:45:50 +0530101 i += 1
102
103def get_args_for_voucher(voucher_type, voucher_no):
104 return frappe.db.get_all("Stock Ledger Entry",
105 filters={"voucher_type": voucher_type, "voucher_no": voucher_no},
Nabin Hait186a0452021-02-18 14:14:21 +0530106 fields=["item_code", "warehouse", "posting_date", "posting_time", "creation"],
Nabin Haita77b8c92020-12-21 14:45:50 +0530107 order_by="creation asc",
108 group_by="item_code, warehouse"
109 )
Nabin Hait74c281c2013-08-19 16:17:18 +0530110
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530111class update_entries_after(object):
Nabin Hait902e8602013-01-08 18:29:24 +0530112 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530113 update valution rate and qty after transaction
Nabin Hait902e8602013-01-08 18:29:24 +0530114 from the current time-bucket onwards
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530115
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530116 :param args: args as dict
117
118 args = {
119 "item_code": "ABC",
120 "warehouse": "XYZ",
121 "posting_date": "2012-12-12",
122 "posting_time": "12:00"
123 }
Nabin Hait902e8602013-01-08 18:29:24 +0530124 """
Anand Doshi0dc79f42015-04-06 12:59:34 +0530125 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 +0530126 self.exceptions = {}
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530127 self.verbose = verbose
128 self.allow_zero_rate = allow_zero_rate
Anand Doshi0dc79f42015-04-06 12:59:34 +0530129 self.via_landed_cost_voucher = via_landed_cost_voucher
Nabin Haita77b8c92020-12-21 14:45:50 +0530130 self.allow_negative_stock = allow_negative_stock \
131 or cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530132
Nabin Haita77b8c92020-12-21 14:45:50 +0530133 self.args = frappe._dict(args)
134 self.item_code = args.get("item_code")
135 if self.args.sle_id:
136 self.args['name'] = self.args.sle_id
Nabin Haitd46b2362021-02-23 16:38:52 +0530137
Nabin Haita77b8c92020-12-21 14:45:50 +0530138 self.company = frappe.get_cached_value("Warehouse", self.args.warehouse, "company")
139 self.get_precision()
140 self.valuation_method = get_valuation_method(self.item_code)
141 self.new_items = {}
142
143 self.data = frappe._dict()
144 self.initialize_previous_data(self.args)
145
146 self.build()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530147
Nabin Haita77b8c92020-12-21 14:45:50 +0530148 def get_precision(self):
149 company_base_currency = frappe.get_cached_value('Company', self.company, "default_currency")
150 self.precision = get_field_precision(frappe.get_meta("Stock Ledger Entry").get_field("stock_value"),
151 currency=company_base_currency)
152
153 def initialize_previous_data(self, args):
154 """
155 Get previous sl entries for current item for each related warehouse
156 and assigns into self.data dict
157
158 :Data Structure:
159
160 self.data = {
161 warehouse1: {
162 'previus_sle': {},
163 'qty_after_transaction': 10,
164 'valuation_rate': 100,
165 'stock_value': 1000,
166 'prev_stock_value': 1000,
167 'stock_queue': '[[10, 100]]',
168 'stock_value_difference': 1000
169 }
170 }
171
172 """
173 self.data.setdefault(args.warehouse, frappe._dict())
174 warehouse_dict = self.data[args.warehouse]
Nabin Hait186a0452021-02-18 14:14:21 +0530175 previous_sle = self.get_previous_sle_of_current_voucher(args)
Nabin Haita77b8c92020-12-21 14:45:50 +0530176 warehouse_dict.previous_sle = previous_sle
Nabin Haitbb777562013-08-29 18:19:37 +0530177
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530178 for key in ("qty_after_transaction", "valuation_rate", "stock_value"):
Nabin Haita77b8c92020-12-21 14:45:50 +0530179 setattr(warehouse_dict, key, flt(previous_sle.get(key)))
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530180
Nabin Haita77b8c92020-12-21 14:45:50 +0530181 warehouse_dict.update({
182 "prev_stock_value": previous_sle.stock_value or 0.0,
183 "stock_queue": json.loads(previous_sle.stock_queue or "[]"),
184 "stock_value_difference": 0.0
185 })
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530186
Nabin Hait186a0452021-02-18 14:14:21 +0530187 def get_previous_sle_of_current_voucher(self, args):
188 """get stock ledger entries filtered by specific posting datetime conditions"""
189
190 args['time_format'] = '%H:%i:%s'
191 if not args.get("posting_date"):
192 args["posting_date"] = "1900-01-01"
193 if not args.get("posting_time"):
194 args["posting_time"] = "00:00"
195
196 sle = frappe.db.sql("""
197 select *, timestamp(posting_date, posting_time) as "timestamp"
198 from `tabStock Ledger Entry`
199 where item_code = %(item_code)s
200 and warehouse = %(warehouse)s
201 and is_cancelled = 0
202 and timestamp(posting_date, time_format(posting_time, %(time_format)s)) < timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
203 order by timestamp(posting_date, posting_time) desc, creation desc
204 limit 1""", args, as_dict=1)
Nabin Haitd46b2362021-02-23 16:38:52 +0530205
Nabin Hait186a0452021-02-18 14:14:21 +0530206 return sle[0] if sle else frappe._dict()
207
208
Nabin Haita77b8c92020-12-21 14:45:50 +0530209 def build(self):
Nabin Hait186a0452021-02-18 14:14:21 +0530210 from erpnext.controllers.stock_controller import check_if_future_sle_exists
211
Nabin Haita77b8c92020-12-21 14:45:50 +0530212 if self.args.get("sle_id"):
Nabin Hait186a0452021-02-18 14:14:21 +0530213 self.process_sle_against_current_timestamp()
214 if not check_if_future_sle_exists(self.args):
215 self.update_bin()
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530216 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530217 entries_to_fix = self.get_future_entries_to_fix()
218
219 i = 0
220 while i < len(entries_to_fix):
221 sle = entries_to_fix[i]
222 i += 1
223
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530224 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530225
Nabin Haita77b8c92020-12-21 14:45:50 +0530226 if sle.dependant_sle_voucher_detail_no:
Nabin Hait243d59b2021-02-02 16:55:13 +0530227 entries_to_fix = self.get_dependent_entries_to_fix(entries_to_fix, sle)
Nabin Haitd46b2362021-02-23 16:38:52 +0530228
Nabin Hait186a0452021-02-18 14:14:21 +0530229 self.update_bin()
Nabin Haita77b8c92020-12-21 14:45:50 +0530230
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530231 if self.exceptions:
232 self.raise_exceptions()
233
Nabin Hait186a0452021-02-18 14:14:21 +0530234 def process_sle_against_current_timestamp(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530235 sl_entries = self.get_sle_against_current_voucher()
236 for sle in sl_entries:
237 self.process_sle(sle)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530238
Nabin Haita77b8c92020-12-21 14:45:50 +0530239 def get_sle_against_current_voucher(self):
Nabin Haitf2be0802021-02-15 19:27:49 +0530240 self.args['time_format'] = '%H:%i:%s'
241
Nabin Haita77b8c92020-12-21 14:45:50 +0530242 return frappe.db.sql("""
243 select
244 *, timestamp(posting_date, posting_time) as "timestamp"
245 from
246 `tabStock Ledger Entry`
247 where
248 item_code = %(item_code)s
249 and warehouse = %(warehouse)s
Nabin Hait186a0452021-02-18 14:14:21 +0530250 and timestamp(posting_date, time_format(posting_time, %(time_format)s)) = timestamp(%(posting_date)s, time_format(%(posting_time)s, %(time_format)s))
251
Nabin Haita77b8c92020-12-21 14:45:50 +0530252 order by
253 creation ASC
254 for update
255 """, self.args, as_dict=1)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530256
Nabin Haita77b8c92020-12-21 14:45:50 +0530257 def get_future_entries_to_fix(self):
258 # includes current entry!
259 args = self.data[self.args.warehouse].previous_sle \
260 or frappe._dict({"item_code": self.item_code, "warehouse": self.args.warehouse})
Deepesh Gargb4be2922021-01-28 13:09:56 +0530261
Nabin Haita77b8c92020-12-21 14:45:50 +0530262 return list(self.get_sle_after_datetime(args))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530263
Nabin Haita77b8c92020-12-21 14:45:50 +0530264 def get_dependent_entries_to_fix(self, entries_to_fix, sle):
265 dependant_sle = get_sle_by_voucher_detail_no(sle.dependant_sle_voucher_detail_no,
266 excluded_sle=sle.name)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530267
Nabin Haita77b8c92020-12-21 14:45:50 +0530268 if not dependant_sle:
Nabin Hait243d59b2021-02-02 16:55:13 +0530269 return entries_to_fix
Nabin Haita77b8c92020-12-21 14:45:50 +0530270 elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse == self.args.warehouse:
Nabin Hait243d59b2021-02-02 16:55:13 +0530271 return entries_to_fix
272 elif dependant_sle.item_code != self.item_code:
273 if (dependant_sle.item_code, dependant_sle.warehouse) not in self.new_items:
274 self.new_items[(dependant_sle.item_code, dependant_sle.warehouse)] = dependant_sle
275 return entries_to_fix
276 elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse in self.data:
277 return entries_to_fix
Nabin Haita77b8c92020-12-21 14:45:50 +0530278 self.initialize_previous_data(dependant_sle)
279
280 args = self.data[dependant_sle.warehouse].previous_sle \
281 or frappe._dict({"item_code": self.item_code, "warehouse": dependant_sle.warehouse})
282 future_sle_for_dependant = list(self.get_sle_after_datetime(args))
283
284 entries_to_fix.extend(future_sle_for_dependant)
Nabin Hait243d59b2021-02-02 16:55:13 +0530285 return sorted(entries_to_fix, key=lambda k: k['timestamp'])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530286
287 def process_sle(self, sle):
Nabin Haita77b8c92020-12-21 14:45:50 +0530288 # previous sle data for this warehouse
289 self.wh_data = self.data[sle.warehouse]
290
Anand Doshi0dc79f42015-04-06 12:59:34 +0530291 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 +0530292 # validate negative stock for serialized items, fifo valuation
Nabin Hait902e8602013-01-08 18:29:24 +0530293 # or when negative stock is not allowed for moving average
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530294 if not self.validate_negative_stock(sle):
Nabin Haita77b8c92020-12-21 14:45:50 +0530295 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530296 return
Nabin Haitb96c0142014-10-07 11:25:04 +0530297
Nabin Haita77b8c92020-12-21 14:45:50 +0530298 # Get dynamic incoming/outgoing rate
299 self.get_dynamic_incoming_outgoing_rate(sle)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530300
Anand Doshi1b531862013-01-10 19:29:51 +0530301 if sle.serial_no:
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530302 self.get_serialized_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530303 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530304 if sle.voucher_type == "Stock Reconciliation":
Nabin Haita77b8c92020-12-21 14:45:50 +0530305 self.wh_data.qty_after_transaction = sle.qty_after_transaction
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530306
Nabin Haita77b8c92020-12-21 14:45:50 +0530307 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 +0530308 else:
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530309 if sle.voucher_type=="Stock Reconciliation" and not sle.batch_no:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530310 # assert
Nabin Haita77b8c92020-12-21 14:45:50 +0530311 self.wh_data.valuation_rate = sle.valuation_rate
312 self.wh_data.qty_after_transaction = sle.qty_after_transaction
313 self.wh_data.stock_queue = [[self.wh_data.qty_after_transaction, self.wh_data.valuation_rate]]
314 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 +0530315 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530316 if self.valuation_method == "Moving Average":
317 self.get_moving_average_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530318 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
319 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 +0530320 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530321 self.get_fifo_values(sle)
Nabin Haita77b8c92020-12-21 14:45:50 +0530322 self.wh_data.qty_after_transaction += flt(sle.actual_qty)
323 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 +0530324
Rushabh Mehta54047782013-12-26 11:07:46 +0530325 # rounding as per precision
Nabin Haita77b8c92020-12-21 14:45:50 +0530326 self.wh_data.stock_value = flt(self.wh_data.stock_value, self.precision)
327 stock_value_difference = self.wh_data.stock_value - self.wh_data.prev_stock_value
328 self.wh_data.prev_stock_value = self.wh_data.stock_value
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530329
Nabin Hait902e8602013-01-08 18:29:24 +0530330 # update current sle
Nabin Haita77b8c92020-12-21 14:45:50 +0530331 sle.qty_after_transaction = self.wh_data.qty_after_transaction
332 sle.valuation_rate = self.wh_data.valuation_rate
333 sle.stock_value = self.wh_data.stock_value
334 sle.stock_queue = json.dumps(self.wh_data.stock_queue)
Rushabh Mehta2e0e7112015-02-18 11:38:05 +0530335 sle.stock_value_difference = stock_value_difference
Rushabh Mehta8bb6e532015-02-18 20:22:59 +0530336 sle.doctype="Stock Ledger Entry"
337 frappe.get_doc(sle).db_update()
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530338
Nabin Haita77b8c92020-12-21 14:45:50 +0530339 self.update_outgoing_rate_on_transaction(sle)
340
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530341 def validate_negative_stock(self, sle):
342 """
343 validate negative stock for entries current datetime onwards
344 will not consider cancelled entries
345 """
Nabin Haita77b8c92020-12-21 14:45:50 +0530346 diff = self.wh_data.qty_after_transaction + flt(sle.actual_qty)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530347
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530348 if diff < 0 and abs(diff) > 0.0001:
349 # negative stock!
350 exc = sle.copy().update({"diff": diff})
Nabin Haita77b8c92020-12-21 14:45:50 +0530351 self.exceptions.setdefault(sle.warehouse, []).append(exc)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530352 return False
Nabin Hait902e8602013-01-08 18:29:24 +0530353 else:
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530354 return True
355
Nabin Haita77b8c92020-12-21 14:45:50 +0530356 def get_dynamic_incoming_outgoing_rate(self, sle):
357 # Get updated incoming/outgoing rate from transaction
358 if sle.recalculate_rate:
359 rate = self.get_incoming_outgoing_rate_from_transaction(sle)
360
361 if flt(sle.actual_qty) >= 0:
362 sle.incoming_rate = rate
363 else:
364 sle.outgoing_rate = rate
365
366 def get_incoming_outgoing_rate_from_transaction(self, sle):
367 rate = 0
368 # Material Transfer, Repack, Manufacturing
369 if sle.voucher_type == "Stock Entry":
370 rate = frappe.db.get_value("Stock Entry Detail", sle.voucher_detail_no, "valuation_rate")
371 # Sales and Purchase Return
372 elif sle.voucher_type in ("Purchase Receipt", "Purchase Invoice", "Delivery Note", "Sales Invoice"):
373 if frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_return"):
374 from erpnext.controllers.sales_and_purchase_return import get_rate_for_return # don't move this import to top
375 rate = get_rate_for_return(sle.voucher_type, sle.voucher_no, sle.item_code, voucher_detail_no=sle.voucher_detail_no)
376 else:
377 if sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
Deepesh Gargb4be2922021-01-28 13:09:56 +0530378 rate_field = "valuation_rate"
Nabin Haita77b8c92020-12-21 14:45:50 +0530379 else:
380 rate_field = "incoming_rate"
381
382 # check in item table
383 item_code, incoming_rate = frappe.db.get_value(sle.voucher_type + " Item",
384 sle.voucher_detail_no, ["item_code", rate_field])
385
386 if item_code == sle.item_code:
387 rate = incoming_rate
388 else:
389 if sle.voucher_type in ("Delivery Note", "Sales Invoice"):
390 ref_doctype = "Packed Item"
391 else:
392 ref_doctype = "Purchase Receipt Item Supplied"
Deepesh Gargb4be2922021-01-28 13:09:56 +0530393
Nabin Haita77b8c92020-12-21 14:45:50 +0530394 rate = frappe.db.get_value(ref_doctype, {"parent_detail_docname": sle.voucher_detail_no,
395 "item_code": sle.item_code}, rate_field)
396
397 return rate
398
399 def update_outgoing_rate_on_transaction(self, sle):
400 """
401 Update outgoing rate in Stock Entry, Delivery Note, Sales Invoice and Sales Return
402 In case of Stock Entry, also calculate FG Item rate and total incoming/outgoing amount
403 """
404 if sle.actual_qty and sle.voucher_detail_no:
405 outgoing_rate = abs(flt(sle.stock_value_difference)) / abs(sle.actual_qty)
406
407 if flt(sle.actual_qty) < 0 and sle.voucher_type == "Stock Entry":
408 self.update_rate_on_stock_entry(sle, outgoing_rate)
409 elif sle.voucher_type in ("Delivery Note", "Sales Invoice"):
410 self.update_rate_on_delivery_and_sales_return(sle, outgoing_rate)
411 elif flt(sle.actual_qty) < 0 and sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
412 self.update_rate_on_purchase_receipt(sle, outgoing_rate)
413
414 def update_rate_on_stock_entry(self, sle, outgoing_rate):
415 frappe.db.set_value("Stock Entry Detail", sle.voucher_detail_no, "basic_rate", outgoing_rate)
416
417 # Update outgoing item's rate, recalculate FG Item's rate and total incoming/outgoing amount
418 stock_entry = frappe.get_doc("Stock Entry", sle.voucher_no)
419 stock_entry.calculate_rate_and_amount(reset_outgoing_rate=False, raise_error_if_no_rate=False)
420 stock_entry.db_update()
421 for d in stock_entry.items:
422 d.db_update()
Deepesh Gargb4be2922021-01-28 13:09:56 +0530423
Nabin Haita77b8c92020-12-21 14:45:50 +0530424 def update_rate_on_delivery_and_sales_return(self, sle, outgoing_rate):
425 # Update item's incoming rate on transaction
426 item_code = frappe.db.get_value(sle.voucher_type + " Item", sle.voucher_detail_no, "item_code")
427 if item_code == sle.item_code:
428 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "incoming_rate", outgoing_rate)
429 else:
430 # packed item
431 frappe.db.set_value("Packed Item",
432 {"parent_detail_docname": sle.voucher_detail_no, "item_code": sle.item_code},
433 "incoming_rate", outgoing_rate)
434
435 def update_rate_on_purchase_receipt(self, sle, outgoing_rate):
436 if frappe.db.exists(sle.voucher_type + " Item", sle.voucher_detail_no):
437 frappe.db.set_value(sle.voucher_type + " Item", sle.voucher_detail_no, "base_net_rate", outgoing_rate)
438 else:
439 frappe.db.set_value("Purchase Receipt Item Supplied", sle.voucher_detail_no, "rate", outgoing_rate)
440
441 # Recalculate subcontracted item's rate in case of subcontracted purchase receipt/invoice
442 if frappe.db.get_value(sle.voucher_type, sle.voucher_no, "is_subcontracted"):
Nabin Haitd46b2362021-02-23 16:38:52 +0530443 doc = frappe.get_doc(sle.voucher_type, sle.voucher_no)
Nabin Haita77b8c92020-12-21 14:45:50 +0530444 doc.update_valuation_rate(reset_outgoing_rate=False)
445 for d in (doc.items + doc.supplied_items):
446 d.db_update()
447
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530448 def get_serialized_values(self, sle):
449 incoming_rate = flt(sle.incoming_rate)
450 actual_qty = flt(sle.actual_qty)
Nabin Hait328c4f92020-01-02 19:00:32 +0530451 serial_nos = cstr(sle.serial_no).split("\n")
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530452
453 if incoming_rate < 0:
454 # wrong incoming rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530455 incoming_rate = self.wh_data.valuation_rate
Rushabh Mehta538607e2016-06-12 11:03:00 +0530456
Nabin Hait2620bf42016-02-29 11:30:27 +0530457 stock_value_change = 0
458 if incoming_rate:
459 stock_value_change = actual_qty * incoming_rate
460 elif actual_qty < 0:
461 # In case of delivery/stock issue, get average purchase rate
462 # of serial nos of current entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530463 if not sle.is_cancelled:
464 outgoing_value = self.get_incoming_value_for_serial_nos(sle, serial_nos)
465 stock_value_change = -1 * outgoing_value
466 else:
467 stock_value_change = actual_qty * sle.outgoing_rate
Rushabh Mehta2a21bc92015-02-25 15:08:42 +0530468
Nabin Haita77b8c92020-12-21 14:45:50 +0530469 new_stock_qty = self.wh_data.qty_after_transaction + actual_qty
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530470
Nabin Hait2620bf42016-02-29 11:30:27 +0530471 if new_stock_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530472 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + stock_value_change
rohitwaghchaure0fe6ced2018-07-27 10:33:30 +0530473 if new_stock_value >= 0:
Nabin Hait2620bf42016-02-29 11:30:27 +0530474 # calculate new valuation rate only if stock value is positive
475 # else it remains the same as that of previous entry
Nabin Haita77b8c92020-12-21 14:45:50 +0530476 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530477
Nabin Haita77b8c92020-12-21 14:45:50 +0530478 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530479 allow_zero_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
480 if not allow_zero_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530481 self.wh_data.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
rohitwaghchaureb1ac9792017-12-01 16:09:02 +0530482 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
483 currency=erpnext.get_company_currency(sle.company))
484
Nabin Hait328c4f92020-01-02 19:00:32 +0530485 def get_incoming_value_for_serial_nos(self, sle, serial_nos):
486 # get rate from serial nos within same company
487 all_serial_nos = frappe.get_all("Serial No",
488 fields=["purchase_rate", "name", "company"],
489 filters = {'name': ('in', serial_nos)})
490
491 incoming_values = sum([flt(d.purchase_rate) for d in all_serial_nos if d.company==sle.company])
492
493 # Get rate for serial nos which has been transferred to other company
494 invalid_serial_nos = [d.name for d in all_serial_nos if d.company!=sle.company]
495 for serial_no in invalid_serial_nos:
496 incoming_rate = frappe.db.sql("""
497 select incoming_rate
498 from `tabStock Ledger Entry`
499 where
500 company = %s
501 and actual_qty > 0
502 and (serial_no = %s
503 or serial_no like %s
504 or serial_no like %s
505 or serial_no like %s
506 )
507 order by posting_date desc
508 limit 1
509 """, (sle.company, serial_no, serial_no+'\n%', '%\n'+serial_no, '%\n'+serial_no+'\n%'))
510
511 incoming_values += flt(incoming_rate[0][0]) if incoming_rate else 0
512
513 return incoming_values
514
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530515 def get_moving_average_values(self, sle):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530516 actual_qty = flt(sle.actual_qty)
Nabin Haita77b8c92020-12-21 14:45:50 +0530517 new_stock_qty = flt(self.wh_data.qty_after_transaction) + actual_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530518 if new_stock_qty >= 0:
519 if actual_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530520 if flt(self.wh_data.qty_after_transaction) <= 0:
521 self.wh_data.valuation_rate = sle.incoming_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530522 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530523 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530524 (actual_qty * sle.incoming_rate)
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530525
Nabin Haita77b8c92020-12-21 14:45:50 +0530526 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530527
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530528 elif sle.outgoing_rate:
529 if new_stock_qty:
Nabin Haita77b8c92020-12-21 14:45:50 +0530530 new_stock_value = (self.wh_data.qty_after_transaction * self.wh_data.valuation_rate) + \
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530531 (actual_qty * sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530532
Nabin Haita77b8c92020-12-21 14:45:50 +0530533 self.wh_data.valuation_rate = new_stock_value / new_stock_qty
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530534 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530535 self.wh_data.valuation_rate = sle.outgoing_rate
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530536 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530537 if flt(self.wh_data.qty_after_transaction) >= 0 and sle.outgoing_rate:
538 self.wh_data.valuation_rate = sle.outgoing_rate
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530539
Nabin Haita77b8c92020-12-21 14:45:50 +0530540 if not self.wh_data.valuation_rate and actual_qty > 0:
541 self.wh_data.valuation_rate = sle.incoming_rate
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530542
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530543 # Get valuation rate from previous SLE or Item master, if item does not have the
Javier Wong9b11d9b2017-04-14 18:24:04 +0800544 # allow zero valuration rate flag set
Nabin Haita77b8c92020-12-21 14:45:50 +0530545 if not self.wh_data.valuation_rate and sle.voucher_detail_no:
Javier Wong9b11d9b2017-04-14 18:24:04 +0800546 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
547 if not allow_zero_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530548 self.wh_data.valuation_rate = get_valuation_rate(sle.item_code, sle.warehouse,
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530549 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
550 currency=erpnext.get_company_currency(sle.company))
551
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530552 def get_fifo_values(self, sle):
553 incoming_rate = flt(sle.incoming_rate)
554 actual_qty = flt(sle.actual_qty)
Nabin Haitada485f2015-07-17 15:09:56 +0530555 outgoing_rate = flt(sle.outgoing_rate)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530556
557 if actual_qty > 0:
Nabin Haita77b8c92020-12-21 14:45:50 +0530558 if not self.wh_data.stock_queue:
559 self.wh_data.stock_queue.append([0, 0])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530560
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530561 # last row has the same rate, just updated the qty
Nabin Haita77b8c92020-12-21 14:45:50 +0530562 if self.wh_data.stock_queue[-1][1]==incoming_rate:
563 self.wh_data.stock_queue[-1][0] += actual_qty
Nabin Hait4d742162014-10-09 19:25:03 +0530564 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530565 if self.wh_data.stock_queue[-1][0] > 0:
566 self.wh_data.stock_queue.append([actual_qty, incoming_rate])
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530567 else:
Nabin Haita77b8c92020-12-21 14:45:50 +0530568 qty = self.wh_data.stock_queue[-1][0] + actual_qty
569 self.wh_data.stock_queue[-1] = [qty, incoming_rate]
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530570 else:
571 qty_to_pop = abs(actual_qty)
572 while qty_to_pop:
Nabin Haita77b8c92020-12-21 14:45:50 +0530573 if not self.wh_data.stock_queue:
Nabin Haita0b967f2017-01-18 18:35:58 +0530574 # Get valuation rate from last sle if exists or from valuation rate field in item master
Javier Wong9b11d9b2017-04-14 18:24:04 +0800575 allow_zero_valuation_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
576 if not allow_zero_valuation_rate:
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530577 _rate = get_valuation_rate(sle.item_code, sle.warehouse,
578 sle.voucher_type, sle.voucher_no, self.allow_zero_rate,
579 currency=erpnext.get_company_currency(sle.company))
Nabin Hait0a6aaf42017-02-07 01:23:26 +0530580 else:
581 _rate = 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530582
Nabin Haita77b8c92020-12-21 14:45:50 +0530583 self.wh_data.stock_queue.append([0, _rate])
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530584
Nabin Haitada485f2015-07-17 15:09:56 +0530585 index = None
586 if outgoing_rate > 0:
587 # Find the entry where rate matched with outgoing rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530588 for i, v in enumerate(self.wh_data.stock_queue):
Nabin Haitada485f2015-07-17 15:09:56 +0530589 if v[1] == outgoing_rate:
590 index = i
591 break
Rushabh Mehta14a908b2015-10-15 12:28:20 +0530592
Nabin Haitada485f2015-07-17 15:09:56 +0530593 # If no entry found with outgoing rate, collapse stack
594 if index == None:
Nabin Haita77b8c92020-12-21 14:45:50 +0530595 new_stock_value = sum((d[0]*d[1] for d in self.wh_data.stock_queue)) - qty_to_pop*outgoing_rate
596 new_stock_qty = sum((d[0] for d in self.wh_data.stock_queue)) - qty_to_pop
597 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 +0530598 break
599 else:
600 index = 0
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530601
Nabin Haitada485f2015-07-17 15:09:56 +0530602 # select first batch or the batch with same rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530603 batch = self.wh_data.stock_queue[index]
Nabin Hait8142cd22015-08-05 18:57:26 +0530604 if qty_to_pop >= batch[0]:
605 # consume current batch
606 qty_to_pop = qty_to_pop - batch[0]
Nabin Haita77b8c92020-12-21 14:45:50 +0530607 self.wh_data.stock_queue.pop(index)
608 if not self.wh_data.stock_queue and qty_to_pop:
Nabin Hait8142cd22015-08-05 18:57:26 +0530609 # stock finished, qty still remains to be withdrawn
610 # negative stock, keep in as a negative batch
Nabin Haita77b8c92020-12-21 14:45:50 +0530611 self.wh_data.stock_queue.append([-qty_to_pop, outgoing_rate or batch[1]])
Nabin Hait8142cd22015-08-05 18:57:26 +0530612 break
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530613
Nabin Hait8142cd22015-08-05 18:57:26 +0530614 else:
615 # qty found in current batch
616 # consume it and exit
617 batch[0] = batch[0] - qty_to_pop
618 qty_to_pop = 0
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530619
Nabin Haita77b8c92020-12-21 14:45:50 +0530620 stock_value = sum((flt(batch[0]) * flt(batch[1]) for batch in self.wh_data.stock_queue))
621 stock_qty = sum((flt(batch[0]) for batch in self.wh_data.stock_queue))
Nabin Hait902e8602013-01-08 18:29:24 +0530622
Nabin Hait6dfc78b2016-06-24 12:28:55 +0530623 if stock_qty:
Nabin Haita77b8c92020-12-21 14:45:50 +0530624 self.wh_data.valuation_rate = stock_value / flt(stock_qty)
Rushabh Mehtacca33b22016-07-08 18:24:46 +0530625
Nabin Haita77b8c92020-12-21 14:45:50 +0530626 if not self.wh_data.stock_queue:
627 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 +0530628
Javier Wong9b11d9b2017-04-14 18:24:04 +0800629 def check_if_allow_zero_valuation_rate(self, voucher_type, voucher_detail_no):
deepeshgarg007f9c0ef32019-07-30 18:49:19 +0530630 ref_item_dt = ""
631
632 if voucher_type == "Stock Entry":
633 ref_item_dt = voucher_type + " Detail"
634 elif voucher_type in ["Purchase Invoice", "Sales Invoice", "Delivery Note", "Purchase Receipt"]:
635 ref_item_dt = voucher_type + " Item"
636
637 if ref_item_dt:
638 return frappe.db.get_value(ref_item_dt, voucher_detail_no, "allow_zero_valuation_rate")
639 else:
640 return 0
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530641
Nabin Haita77b8c92020-12-21 14:45:50 +0530642 def get_sle_before_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530643 """get previous stock ledger entry before current time-bucket"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530644 sle = get_stock_ledger_entries(args, "<", "desc", "limit 1", for_update=False)
645 sle = sle[0] if sle else frappe._dict()
646 return sle
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530647
Nabin Haita77b8c92020-12-21 14:45:50 +0530648 def get_sle_after_datetime(self, args):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530649 """get Stock Ledger Entries after a particular datetime, for reposting"""
Nabin Haita77b8c92020-12-21 14:45:50 +0530650 return get_stock_ledger_entries(args, ">", "asc", for_update=True, check_serial_no=False)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530651
652 def raise_exceptions(self):
Nabin Haita77b8c92020-12-21 14:45:50 +0530653 msg_list = []
654 for warehouse, exceptions in iteritems(self.exceptions):
655 deficiency = min(e["diff"] for e in exceptions)
Rushabh Mehta538607e2016-06-12 11:03:00 +0530656
Nabin Haita77b8c92020-12-21 14:45:50 +0530657 if ((exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]) in
658 frappe.local.flags.currently_saving):
Nabin Hait3edefb12016-07-20 16:13:18 +0530659
Nabin Haita77b8c92020-12-21 14:45:50 +0530660 msg = _("{0} units of {1} needed in {2} to complete this transaction.").format(
Nabin Hait243d59b2021-02-02 16:55:13 +0530661 abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]),
Nabin Haita77b8c92020-12-21 14:45:50 +0530662 frappe.get_desk_link('Warehouse', warehouse))
663 else:
664 msg = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
Nabin Hait243d59b2021-02-02 16:55:13 +0530665 abs(deficiency), frappe.get_desk_link('Item', exceptions[0]["item_code"]),
Nabin Haita77b8c92020-12-21 14:45:50 +0530666 frappe.get_desk_link('Warehouse', warehouse),
667 exceptions[0]["posting_date"], exceptions[0]["posting_time"],
668 frappe.get_desk_link(exceptions[0]["voucher_type"], exceptions[0]["voucher_no"]))
Rushabh Mehta538607e2016-06-12 11:03:00 +0530669
Nabin Haita77b8c92020-12-21 14:45:50 +0530670 if msg:
671 msg_list.append(msg)
672
673 if msg_list:
674 message = "\n\n".join(msg_list)
675 if self.verbose:
676 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
677 else:
678 raise NegativeStockError(message)
Deepesh Gargb4be2922021-01-28 13:09:56 +0530679
Nabin Haita77b8c92020-12-21 14:45:50 +0530680 def update_bin(self):
681 # update bin for each warehouse
682 for warehouse, data in iteritems(self.data):
683 bin_doc = get_bin(self.item_code, warehouse)
Nabin Haita77b8c92020-12-21 14:45:50 +0530684 bin_doc.update({
685 "valuation_rate": data.valuation_rate,
686 "actual_qty": data.qty_after_transaction,
687 "stock_value": data.stock_value
688 })
689 bin_doc.flags.via_stock_ledger_entry = True
690 bin_doc.save(ignore_permissions=True)
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530691
Anand Doshi4dc7caa2013-01-11 11:44:49 +0530692def get_previous_sle(args, for_update=False):
Anand Doshi1b531862013-01-10 19:29:51 +0530693 """
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530694 get the last sle on or before the current time-bucket,
Anand Doshi1b531862013-01-10 19:29:51 +0530695 to get actual qty before transaction, this function
696 is called from various transaction like stock entry, reco etc
Nabin Haitdc82d4f2014-04-07 12:02:57 +0530697
Anand Doshi1b531862013-01-10 19:29:51 +0530698 args = {
699 "item_code": "ABC",
700 "warehouse": "XYZ",
701 "posting_date": "2012-12-12",
702 "posting_time": "12:00",
703 "sle": "name of reference Stock Ledger Entry"
704 }
705 """
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530706 args["name"] = args.get("sle", None) or ""
707 sle = get_stock_ledger_entries(args, "<=", "desc", "limit 1", for_update=for_update)
Pratik Vyas16371b72013-09-18 18:31:03 +0530708 return sle and sle[0] or {}
Nabin Haitfb6e4342014-10-15 11:34:40 +0530709
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530710def get_stock_ledger_entries(previous_sle, operator=None,
711 order="desc", limit=None, for_update=False, debug=False, check_serial_no=True):
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530712 """get stock ledger entries filtered by specific posting datetime conditions"""
Nabin Haitb9ce1042018-02-01 14:58:50 +0530713 conditions = " and timestamp(posting_date, posting_time) {0} timestamp(%(posting_date)s, %(posting_time)s)".format(operator)
714 if previous_sle.get("warehouse"):
715 conditions += " and warehouse = %(warehouse)s"
716 elif previous_sle.get("warehouse_condition"):
717 conditions += " and " + previous_sle.get("warehouse_condition")
718
Rohit Waghchaure66aa37f2019-05-24 16:53:51 +0530719 if check_serial_no and previous_sle.get("serial_no"):
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530720 conditions += " and serial_no like {}".format(frappe.db.escape('%{0}%'.format(previous_sle.get("serial_no"))))
721
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530722 if not previous_sle.get("posting_date"):
723 previous_sle["posting_date"] = "1900-01-01"
724 if not previous_sle.get("posting_time"):
725 previous_sle["posting_time"] = "00:00"
726
727 if operator in (">", "<=") and previous_sle.get("name"):
728 conditions += " and name!=%(name)s"
729
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530730 return frappe.db.sql("""
731 select *, timestamp(posting_date, posting_time) as "timestamp"
732 from `tabStock Ledger Entry`
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530733 where item_code = %%(item_code)s
Nabin Haita77b8c92020-12-21 14:45:50 +0530734 and is_cancelled = 0
Nabin Haitb9ce1042018-02-01 14:58:50 +0530735 %(conditions)s
Aditya Hase0c164242019-01-07 22:07:13 +0530736 order by timestamp(posting_date, posting_time) %(order)s, creation %(order)s
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530737 %(limit)s %(for_update)s""" % {
738 "conditions": conditions,
739 "limit": limit or "",
740 "for_update": for_update and "for update" or "",
741 "order": order
Rushabh Mehta50dc4e92015-02-19 20:05:45 +0530742 }, previous_sle, as_dict=1, debug=debug)
Rushabh Mehtadf9e80c2015-02-17 19:55:17 +0530743
Nabin Haita77b8c92020-12-21 14:45:50 +0530744def get_sle_by_voucher_detail_no(voucher_detail_no, excluded_sle=None):
745 return frappe.db.get_value('Stock Ledger Entry',
746 {'voucher_detail_no': voucher_detail_no, 'name': ['!=', excluded_sle]},
747 ['item_code', 'warehouse', 'posting_date', 'posting_time', 'timestamp(posting_date, posting_time) as timestamp'],
748 as_dict=1)
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530749
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530750def get_valuation_rate(item_code, warehouse, voucher_type, voucher_no,
Nabin Hait7ba092e2018-02-01 10:51:27 +0530751 allow_zero_rate=False, currency=None, company=None, raise_error_if_no_rate=True):
Nabin Haita0b967f2017-01-18 18:35:58 +0530752 # Get valuation rate from last sle for the same item and warehouse
Rohit Waghchaurea5f40942017-06-16 15:21:36 +0530753 if not company:
754 company = erpnext.get_default_company()
755
Nabin Haitfb6e4342014-10-15 11:34:40 +0530756 last_valuation_rate = frappe.db.sql("""select valuation_rate
757 from `tabStock Ledger Entry`
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530758 where
759 item_code = %s
760 AND warehouse = %s
761 AND valuation_rate >= 0
762 AND NOT (voucher_no = %s AND voucher_type = %s)
763 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 +0530764
765 if not last_valuation_rate:
Nabin Haita0b967f2017-01-18 18:35:58 +0530766 # Get valuation rate from last sle for the item against any warehouse
Nabin Haitfb6e4342014-10-15 11:34:40 +0530767 last_valuation_rate = frappe.db.sql("""select valuation_rate
768 from `tabStock Ledger Entry`
Mangesh-Khairnar0df51342019-08-19 10:04:52 +0530769 where
770 item_code = %s
771 AND valuation_rate > 0
772 AND NOT(voucher_no = %s AND voucher_type = %s)
773 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 +0530774
Nabin Haita645f362018-03-01 10:31:24 +0530775 if last_valuation_rate:
Nabin Haita77b8c92020-12-21 14:45:50 +0530776 return flt(last_valuation_rate[0][0])
Nabin Haita645f362018-03-01 10:31:24 +0530777
778 # If negative stock allowed, and item delivered without any incoming entry,
779 # system does not found any SLE, then take valuation rate from Item
780 valuation_rate = frappe.db.get_value("Item", item_code, "valuation_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530781
782 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530783 # try Item Standard rate
784 valuation_rate = frappe.db.get_value("Item", item_code, "standard_rate")
Nabin Haitfb6e4342014-10-15 11:34:40 +0530785
Rushabh Mehtaaedaac62017-05-04 09:35:19 +0530786 if not valuation_rate:
Nabin Haita645f362018-03-01 10:31:24 +0530787 # try in price list
788 valuation_rate = frappe.db.get_value('Item Price',
789 dict(item_code=item_code, buying=1, currency=currency),
790 'price_list_rate')
Rushabh Mehtacc8b2b22017-03-31 12:44:29 +0530791
Nabin Hait7ba092e2018-02-01 10:51:27 +0530792 if not allow_zero_rate and not valuation_rate and raise_error_if_no_rate \
Rohit Waghchauree9ff1912017-06-19 12:54:59 +0530793 and cint(erpnext.is_perpetual_inventory_enabled(company)):
Neil Trini Lasrado193c8912017-03-28 17:39:34 +0530794 frappe.local.message_log = []
Marica97715f22020-05-11 20:45:37 +0530795 form_link = frappe.utils.get_link_to_form("Item", item_code)
796
797 message = _("Valuation Rate for the Item {0}, is required to do accounting entries for {1} {2}.").format(form_link, voucher_type, voucher_no)
798 message += "<br><br>" + _(" Here are the options to proceed:")
799 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>"
800 solutions += "<li>" + _("If not, you can Cancel / Submit this entry ") + _("{0}").format(frappe.bold("after")) + _(" performing either one below:") + "</li>"
801 sub_solutions = "<ul><li>" + _("Create an incoming stock transaction for the Item.") + "</li>"
802 sub_solutions += "<li>" + _("Mention Valuation Rate in the Item master.") + "</li></ul>"
803 msg = message + solutions + sub_solutions + "</li>"
804
805 frappe.throw(msg=msg, title=_("Valuation Rate Missing"))
Nabin Haitfb6e4342014-10-15 11:34:40 +0530806
807 return valuation_rate
Nabin Haita77b8c92020-12-21 14:45:50 +0530808
Nabin Hait186a0452021-02-18 14:14:21 +0530809def update_qty_in_future_sle(args, allow_negative_stock=None):
810 frappe.db.sql("""
811 update `tabStock Ledger Entry`
812 set qty_after_transaction = qty_after_transaction + {qty}
813 where
814 item_code = %(item_code)s
815 and warehouse = %(warehouse)s
816 and voucher_no != %(voucher_no)s
817 and is_cancelled = 0
818 and (timestamp(posting_date, posting_time) > timestamp(%(posting_date)s, %(posting_time)s)
819 or (
820 timestamp(posting_date, posting_time) = timestamp(%(posting_date)s, %(posting_time)s)
821 and creation > %(creation)s
822 )
823 )
824 """.format(qty=args.actual_qty), args)
825
826 validate_negative_qty_in_future_sle(args, allow_negative_stock)
827
Nabin Haita77b8c92020-12-21 14:45:50 +0530828def validate_negative_qty_in_future_sle(args, allow_negative_stock=None):
829 allow_negative_stock = allow_negative_stock \
830 or cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
831
832 if args.actual_qty < 0 and not allow_negative_stock:
833 sle = get_future_sle_with_negative_qty(args)
834 if sle:
835 message = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
836 abs(sle[0]["qty_after_transaction"]),
837 frappe.get_desk_link('Item', args.item_code),
838 frappe.get_desk_link('Warehouse', args.warehouse),
839 sle[0]["posting_date"], sle[0]["posting_time"],
840 frappe.get_desk_link(sle[0]["voucher_type"], sle[0]["voucher_no"]))
Deepesh Gargb4be2922021-01-28 13:09:56 +0530841
Nabin Haita77b8c92020-12-21 14:45:50 +0530842 frappe.throw(message, NegativeStockError, title='Insufficient Stock')
843
844def get_future_sle_with_negative_qty(args):
845 return frappe.db.sql("""
846 select
847 qty_after_transaction, posting_date, posting_time,
848 voucher_type, voucher_no
849 from `tabStock Ledger Entry`
Deepesh Gargb4be2922021-01-28 13:09:56 +0530850 where
Nabin Haita77b8c92020-12-21 14:45:50 +0530851 item_code = %(item_code)s
852 and warehouse = %(warehouse)s
853 and voucher_no != %(voucher_no)s
854 and timestamp(posting_date, posting_time) >= timestamp(%(posting_date)s, %(posting_time)s)
855 and is_cancelled = 0
Nabin Hait186a0452021-02-18 14:14:21 +0530856 and qty_after_transaction < 0
Nabin Hait243d59b2021-02-02 16:55:13 +0530857 order by timestamp(posting_date, posting_time) asc
Nabin Haita77b8c92020-12-21 14:45:50 +0530858 limit 1
Nabin Hait186a0452021-02-18 14:14:21 +0530859 """, args, as_dict=1)