blob: 82ff5b86dac10049d2fe15e78d327b4603a272d8 [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
Nabin Hait9d0f6362013-01-07 18:51:11 +05303
Nabin Hait9d0f6362013-01-07 18:51:11 +05304
Chillar Anand915b3432021-09-02 16:44:59 +05305import json
Ankush Menat47f27a52022-04-01 15:20:40 +05306from typing import Dict, Optional
Chillar Anand915b3432021-09-02 16:44:59 +05307
8import frappe
9from frappe import _
s-aga-r9a37ac62023-04-21 13:28:14 +053010from frappe.query_builder.functions import CombineDatetime, IfNull, Sum
Rohit Waghchaured80ca522024-02-07 21:56:21 +053011from frappe.utils import cstr, flt, get_link_to_form, get_time, getdate, nowdate, nowtime
Achilles Rasquinha56b2e122018-02-13 14:42:40 +053012
Chillar Anand915b3432021-09-02 16:44:59 +053013import erpnext
Rohit Waghchaure01650122024-02-06 13:31:36 +053014from erpnext.stock.doctype.serial_and_batch_bundle.serial_and_batch_bundle import (
15 get_available_serial_nos,
16)
s-aga-re782a052023-04-25 13:54:36 +053017from erpnext.stock.doctype.warehouse.warehouse import get_child_warehouses
Rohit Waghchaure46704642023-03-23 11:41:20 +053018from erpnext.stock.serial_batch_bundle import BatchNoValuation, SerialNoValuation
Ankush Menat61c5ad42022-01-15 18:06:50 +053019from erpnext.stock.valuation import FIFOValuation, LIFOValuation
Chillar Anand915b3432021-09-02 16:44:59 +053020
Devin Slauenwhiteb88e8502022-10-20 06:26:07 -040021BarcodeScanResult = Dict[str, Optional[str]]
22
Chillar Anand915b3432021-09-02 16:44:59 +053023
Ankush Menat494bd9e2022-03-28 18:52:46 +053024class InvalidWarehouseCompany(frappe.ValidationError):
25 pass
26
27
28class PendingRepostingError(frappe.ValidationError):
29 pass
30
Anand Doshi2ce39cf2014-04-07 18:51:58 +053031
Shreya Shahe0a47ae2018-08-28 13:46:22 +053032def get_stock_value_from_bin(warehouse=None, item_code=None):
Sachin Mane19a5a5d2018-06-21 13:01:48 +053033 values = {}
34 conditions = ""
35 if warehouse:
rohitwaghchauref1fab872019-09-05 14:47:43 +053036 conditions += """ and `tabBin`.warehouse in (
Sachin Mane19a5a5d2018-06-21 13:01:48 +053037 select w2.name from `tabWarehouse` w1
38 join `tabWarehouse` w2 on
39 w1.name = %(warehouse)s
40 and w2.lft between w1.lft and w1.rgt
41 ) """
42
Ankush Menat494bd9e2022-03-28 18:52:46 +053043 values["warehouse"] = warehouse
Sachin Mane19a5a5d2018-06-21 13:01:48 +053044
45 if item_code:
rohitwaghchauref1fab872019-09-05 14:47:43 +053046 conditions += " and `tabBin`.item_code = %(item_code)s"
Sachin Mane19a5a5d2018-06-21 13:01:48 +053047
Ankush Menat494bd9e2022-03-28 18:52:46 +053048 values["item_code"] = item_code
Sachin Mane19a5a5d2018-06-21 13:01:48 +053049
Ankush Menat494bd9e2022-03-28 18:52:46 +053050 query = (
51 """select sum(stock_value) from `tabBin`, `tabItem` where 1 = 1
52 and `tabItem`.name = `tabBin`.item_code and ifnull(`tabItem`.disabled, 0) = 0 %s"""
53 % conditions
54 )
Sachin Mane19a5a5d2018-06-21 13:01:48 +053055
56 stock_value = frappe.db.sql(query, values)
57
Shreya Shahe0a47ae2018-08-28 13:46:22 +053058 return stock_value
Sachin Mane19a5a5d2018-06-21 13:01:48 +053059
Ankush Menat494bd9e2022-03-28 18:52:46 +053060
s-aga-re782a052023-04-25 13:54:36 +053061def get_stock_value_on(
62 warehouses: list | str = None, posting_date: str = None, item_code: str = None
63) -> float:
Ankush Menat494bd9e2022-03-28 18:52:46 +053064 if not posting_date:
65 posting_date = nowdate()
Anand Doshi2ce39cf2014-04-07 18:51:58 +053066
s-aga-re43bc382023-04-19 12:05:17 +053067 sle = frappe.qb.DocType("Stock Ledger Entry")
68 query = (
69 frappe.qb.from_(sle)
s-aga-r9a37ac62023-04-21 13:28:14 +053070 .select(IfNull(Sum(sle.stock_value_difference), 0))
s-aga-re43bc382023-04-19 12:05:17 +053071 .where((sle.posting_date <= posting_date) & (sle.is_cancelled == 0))
72 .orderby(CombineDatetime(sle.posting_date, sle.posting_time), order=frappe.qb.desc)
73 .orderby(sle.creation, order=frappe.qb.desc)
Ankush Menat494bd9e2022-03-28 18:52:46 +053074 )
Anand Doshi2ce39cf2014-04-07 18:51:58 +053075
s-aga-re782a052023-04-25 13:54:36 +053076 if warehouses:
77 if isinstance(warehouses, str):
78 warehouses = [warehouses]
Sachin Mane19a5a5d2018-06-21 13:01:48 +053079
s-aga-re782a052023-04-25 13:54:36 +053080 warehouses = set(warehouses)
81 for wh in list(warehouses):
82 if frappe.db.get_value("Warehouse", wh, "is_group"):
83 warehouses.update(get_child_warehouses(wh))
84
85 query = query.where(sle.warehouse.isin(warehouses))
Nabin Hait9d0f6362013-01-07 18:51:11 +053086
87 if item_code:
s-aga-re43bc382023-04-19 12:05:17 +053088 query = query.where(sle.item_code == item_code)
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053089
s-aga-r9a37ac62023-04-21 13:28:14 +053090 return query.run(as_list=True)[0][0]
Anand Doshi2ce39cf2014-04-07 18:51:58 +053091
Ankush Menat494bd9e2022-03-28 18:52:46 +053092
nick98226f48d4b2017-01-09 12:12:36 +053093@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +053094def get_stock_balance(
95 item_code,
96 warehouse,
97 posting_date=None,
98 posting_time=None,
99 with_valuation_rate=False,
100 with_serial_no=False,
mergify[bot]27a1e3b2023-10-16 19:15:18 +0530101 inventory_dimensions_dict=None,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530102):
Rushabh Mehta2712e362015-02-17 12:50:20 +0530103 """Returns stock balance quantity at given warehouse on given posting date or current date.
104
105 If `with_valuation_rate` is True, will return tuple (qty, rate)"""
Rushabh Mehtadc93e0a2015-02-20 15:11:56 +0530106
107 from erpnext.stock.stock_ledger import get_previous_sle
108
Ankush Menat494bd9e2022-03-28 18:52:46 +0530109 if posting_date is None:
110 posting_date = nowdate()
111 if posting_time is None:
112 posting_time = nowtime()
Rushabh Mehtadc93e0a2015-02-20 15:11:56 +0530113
Rohit Waghchaure560f8222020-04-06 15:02:43 +0530114 args = {
Rushabh Mehtadc93e0a2015-02-20 15:11:56 +0530115 "item_code": item_code,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530116 "warehouse": warehouse,
Rushabh Mehtadc93e0a2015-02-20 15:11:56 +0530117 "posting_date": posting_date,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530118 "posting_time": posting_time,
Rohit Waghchaure560f8222020-04-06 15:02:43 +0530119 }
120
mergify[bot]27a1e3b2023-10-16 19:15:18 +0530121 extra_cond = ""
122 if inventory_dimensions_dict:
123 for field, value in inventory_dimensions_dict.items():
124 args[field] = value
125 extra_cond += f" and {field} = %({field})s"
126
127 last_entry = get_previous_sle(args, extra_cond=extra_cond)
Rushabh Mehtaf8509872014-10-08 12:03:19 +0530128
Rushabh Mehta2712e362015-02-17 12:50:20 +0530129 if with_valuation_rate:
Rohit Waghchaure560f8222020-04-06 15:02:43 +0530130 if with_serial_no:
Rohit Waghchaure01650122024-02-06 13:31:36 +0530131 serial_no_details = get_available_serial_nos(
132 frappe._dict(
133 {
134 "item_code": item_code,
135 "warehouse": warehouse,
136 "posting_date": posting_date,
137 "posting_time": posting_time,
138 "ignore_warehouse": 1,
139 }
140 )
141 )
142
143 serial_nos = ""
144 if serial_no_details:
145 serial_nos = "\n".join(d.serial_no for d in serial_no_details)
Rohit Waghchaure560f8222020-04-06 15:02:43 +0530146
Ankush Menat494bd9e2022-03-28 18:52:46 +0530147 return (
148 (last_entry.qty_after_transaction, last_entry.valuation_rate, serial_nos)
149 if last_entry
150 else (0.0, 0.0, None)
151 )
Rohit Waghchaure560f8222020-04-06 15:02:43 +0530152 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530153 return (
154 (last_entry.qty_after_transaction, last_entry.valuation_rate) if last_entry else (0.0, 0.0)
155 )
Rushabh Mehtaf8509872014-10-08 12:03:19 +0530156 else:
nick9822cc699a92017-06-20 17:13:29 +0530157 return last_entry.qty_after_transaction if last_entry else 0.0
Rushabh Mehtaf8509872014-10-08 12:03:19 +0530158
Ankush Menat494bd9e2022-03-28 18:52:46 +0530159
Rohit Waghchaure560f8222020-04-06 15:02:43 +0530160def get_serial_nos_data(serial_nos):
161 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
Ankush Menat494bd9e2022-03-28 18:52:46 +0530162
Rohit Waghchaure560f8222020-04-06 15:02:43 +0530163 return get_serial_nos(serial_nos)
164
Ankush Menat494bd9e2022-03-28 18:52:46 +0530165
Nabin Hait949a9202017-07-05 13:55:41 +0530166@frappe.whitelist()
167def get_latest_stock_qty(item_code, warehouse=None):
168 values, condition = [item_code], ""
169 if warehouse:
170 lft, rgt, is_group = frappe.db.get_value("Warehouse", warehouse, ["lft", "rgt", "is_group"])
Sachin Mane19a5a5d2018-06-21 13:01:48 +0530171
Nabin Hait949a9202017-07-05 13:55:41 +0530172 if is_group:
173 values.extend([lft, rgt])
174 condition += "and exists (\
175 select name from `tabWarehouse` wh where wh.name = tabBin.warehouse\
176 and wh.lft >= %s and wh.rgt <= %s)"
Sachin Mane19a5a5d2018-06-21 13:01:48 +0530177
Nabin Hait949a9202017-07-05 13:55:41 +0530178 else:
179 values.append(warehouse)
180 condition += " AND warehouse = %s"
Sachin Mane19a5a5d2018-06-21 13:01:48 +0530181
Ankush Menat494bd9e2022-03-28 18:52:46 +0530182 actual_qty = frappe.db.sql(
183 """select sum(actual_qty) from tabBin
184 where item_code=%s {0}""".format(
185 condition
186 ),
187 values,
188 )[0][0]
Nabin Hait949a9202017-07-05 13:55:41 +0530189
190 return actual_qty
191
192
Nabin Hait47dc3182013-08-06 15:58:16 +0530193def get_latest_stock_balance():
194 bin_map = {}
Ankush Menat494bd9e2022-03-28 18:52:46 +0530195 for d in frappe.db.sql(
196 """SELECT item_code, warehouse, stock_value as stock_value
197 FROM tabBin""",
198 as_dict=1,
199 ):
200 bin_map.setdefault(d.warehouse, {}).setdefault(d.item_code, flt(d.stock_value))
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530201
Nabin Hait47dc3182013-08-06 15:58:16 +0530202 return bin_map
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530203
Ankush Menat494bd9e2022-03-28 18:52:46 +0530204
Nabin Hait74c281c2013-08-19 16:17:18 +0530205def get_bin(item_code, warehouse):
Anand Doshie9baaa62014-02-26 12:35:33 +0530206 bin = frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse})
Nabin Hait74c281c2013-08-19 16:17:18 +0530207 if not bin:
Ankush Menat08810db2022-01-30 16:25:42 +0530208 bin_obj = _create_bin(item_code, warehouse)
Nabin Hait74c281c2013-08-19 16:17:18 +0530209 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530210 bin_obj = frappe.get_doc("Bin", bin, for_update=True)
Anand Doshi6dfd4302015-02-10 14:41:27 +0530211 bin_obj.flags.ignore_permissions = True
Nabin Hait74c281c2013-08-19 16:17:18 +0530212 return bin_obj
213
Ankush Menat494bd9e2022-03-28 18:52:46 +0530214
215def get_or_make_bin(item_code: str, warehouse: str) -> str:
Rohit Waghchaure9e5e2de2023-05-25 23:41:56 +0530216 bin_record = frappe.get_cached_value("Bin", {"item_code": item_code, "warehouse": warehouse})
Deepesh Garg6f107da2021-10-12 20:15:55 +0530217
218 if not bin_record:
Ankush Menat08810db2022-01-30 16:25:42 +0530219 bin_obj = _create_bin(item_code, warehouse)
220 bin_record = bin_obj.name
221 return bin_record
222
Ankush Menat494bd9e2022-03-28 18:52:46 +0530223
Ankush Menat08810db2022-01-30 16:25:42 +0530224def _create_bin(item_code, warehouse):
225 """Create a bin and take care of concurrent inserts."""
226
227 bin_creation_savepoint = "create_bin"
228 try:
229 frappe.db.savepoint(bin_creation_savepoint)
230 bin_obj = frappe.get_doc(doctype="Bin", item_code=item_code, warehouse=warehouse)
Deepesh Garg6f107da2021-10-12 20:15:55 +0530231 bin_obj.flags.ignore_permissions = 1
232 bin_obj.insert()
Ankush Menat08810db2022-01-30 16:25:42 +0530233 except frappe.UniqueValidationError:
234 frappe.db.rollback(save_point=bin_creation_savepoint) # preserve transaction in postgres
235 bin_obj = frappe.get_last_doc("Bin", {"item_code": item_code, "warehouse": warehouse})
Deepesh Garg6f107da2021-10-12 20:15:55 +0530236
Ankush Menat08810db2022-01-30 16:25:42 +0530237 return bin_obj
Deepesh Garg6f107da2021-10-12 20:15:55 +0530238
Ankush Menat494bd9e2022-03-28 18:52:46 +0530239
Nabin Hait5eefff12015-12-07 10:44:56 +0530240@frappe.whitelist()
Nabin Hait7ba092e2018-02-01 10:51:27 +0530241def get_incoming_rate(args, raise_error_if_no_rate=True):
Nabin Hait9d0f6362013-01-07 18:51:11 +0530242 """Get Incoming Rate based on valuation method"""
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530243 from erpnext.stock.stock_ledger import get_previous_sle, get_valuation_rate
Ankush Menat494bd9e2022-03-28 18:52:46 +0530244
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530245 if isinstance(args, str):
Nabin Hait41c8cf62015-12-08 14:50:24 +0530246 args = json.loads(args)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530247
Ankush Menatab926522022-02-19 15:37:03 +0530248 in_rate = None
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530249
250 item_details = frappe.get_cached_value(
251 "Item", args.get("item_code"), ["has_serial_no", "has_batch_no"], as_dict=1
252 )
253
Rohit Waghchaure674bd3e2023-03-17 16:42:59 +0530254 if isinstance(args, dict):
255 args = frappe._dict(args)
256
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530257 if item_details and item_details.has_serial_no and args.get("serial_and_batch_bundle"):
Rohit Waghchaure674bd3e2023-03-17 16:42:59 +0530258 args.actual_qty = args.qty
Rohit Waghchaure46704642023-03-23 11:41:20 +0530259 sn_obj = SerialNoValuation(
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530260 sle=args,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530261 warehouse=args.get("warehouse"),
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530262 item_code=args.get("item_code"),
Ankush Menatab926522022-02-19 15:37:03 +0530263 )
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530264
265 in_rate = sn_obj.get_incoming_rate()
266
Rohit Waghchaured3ceb072023-03-31 09:03:54 +0530267 elif item_details and item_details.has_batch_no and args.get("serial_and_batch_bundle"):
Rohit Waghchaure674bd3e2023-03-17 16:42:59 +0530268 args.actual_qty = args.qty
Rohit Waghchaure46704642023-03-23 11:41:20 +0530269 batch_obj = BatchNoValuation(
Rohit Waghchauree6143ab2023-03-13 14:51:43 +0530270 sle=args,
271 warehouse=args.get("warehouse"),
272 item_code=args.get("item_code"),
273 )
274
275 in_rate = batch_obj.get_incoming_rate()
276
rohitwaghchaure67d828d2024-01-27 12:00:06 +0530277 elif (args.get("serial_no") or "").strip() and not args.get("serial_and_batch_bundle"):
278 in_rate = get_avg_purchase_rate(args.get("serial_no"))
279 elif (
280 args.get("batch_no")
281 and frappe.db.get_value("Batch", args.get("batch_no"), "use_batchwise_valuation", cache=True)
282 and not args.get("serial_and_batch_bundle")
283 ):
284 in_rate = get_batch_incoming_rate(
285 item_code=args.get("item_code"),
286 warehouse=args.get("warehouse"),
287 batch_no=args.get("batch_no"),
288 posting_date=args.get("posting_date"),
289 posting_time=args.get("posting_time"),
290 )
291
Nabin Hait9d0f6362013-01-07 18:51:11 +0530292 else:
293 valuation_method = get_valuation_method(args.get("item_code"))
294 previous_sle = get_previous_sle(args)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530295 if valuation_method in ("FIFO", "LIFO"):
rohitwaghchaurece8adec2017-12-15 12:13:50 +0530296 if previous_sle:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530297 previous_stock_queue = json.loads(previous_sle.get("stock_queue", "[]") or "[]")
298 in_rate = (
299 _get_fifo_lifo_rate(previous_stock_queue, args.get("qty") or 0, valuation_method)
300 if previous_stock_queue
Hossein Yousefian1d162ff2023-04-16 11:03:16 +0330301 else None
Ankush Menat494bd9e2022-03-28 18:52:46 +0530302 )
303 elif valuation_method == "Moving Average":
Hossein Yousefian1d162ff2023-04-16 11:03:16 +0330304 in_rate = previous_sle.get("valuation_rate")
Anand Doshi094610d2014-04-16 19:56:53 +0530305
Ankush Menatab926522022-02-19 15:37:03 +0530306 if in_rate is None:
Hossein Yousefian13d4f852023-04-18 14:50:09 +0330307 voucher_no = args.get("voucher_no") or args.get("name")
Ankush Menat494bd9e2022-03-28 18:52:46 +0530308 in_rate = get_valuation_rate(
309 args.get("item_code"),
310 args.get("warehouse"),
311 args.get("voucher_type"),
312 voucher_no,
313 args.get("allow_zero_valuation"),
314 currency=erpnext.get_company_currency(args.get("company")),
315 company=args.get("company"),
316 raise_error_if_no_rate=raise_error_if_no_rate,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530317 )
rohitwaghchaurece8adec2017-12-15 12:13:50 +0530318
Nabin Haita77b8c92020-12-21 14:45:50 +0530319 return flt(in_rate)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530320
Ankush Menat494bd9e2022-03-28 18:52:46 +0530321
rohitwaghchaure67d828d2024-01-27 12:00:06 +0530322def get_batch_incoming_rate(
323 item_code, warehouse, batch_no, posting_date, posting_time, creation=None
324):
325
326 sle = frappe.qb.DocType("Stock Ledger Entry")
327
328 timestamp_condition = CombineDatetime(sle.posting_date, sle.posting_time) < CombineDatetime(
329 posting_date, posting_time
330 )
331 if creation:
332 timestamp_condition |= (
333 CombineDatetime(sle.posting_date, sle.posting_time)
334 == CombineDatetime(posting_date, posting_time)
335 ) & (sle.creation < creation)
336
337 batch_details = (
338 frappe.qb.from_(sle)
339 .select(Sum(sle.stock_value_difference).as_("batch_value"), Sum(sle.actual_qty).as_("batch_qty"))
340 .where(
341 (sle.item_code == item_code)
342 & (sle.warehouse == warehouse)
343 & (sle.batch_no == batch_no)
344 & (sle.serial_and_batch_bundle.isnull())
345 & (sle.is_cancelled == 0)
346 )
347 .where(timestamp_condition)
348 ).run(as_dict=True)
349
350 if batch_details and batch_details[0].batch_qty:
351 return batch_details[0].batch_value / batch_details[0].batch_qty
352
353
Nabin Hait9d0f6362013-01-07 18:51:11 +0530354def get_avg_purchase_rate(serial_nos):
355 """get average value of serial numbers"""
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530356
Nabin Hait9d0f6362013-01-07 18:51:11 +0530357 serial_nos = get_valid_serial_nos(serial_nos)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530358 return flt(
359 frappe.db.sql(
360 """select avg(purchase_rate) from `tabSerial No`
361 where name in (%s)"""
362 % ", ".join(["%s"] * len(serial_nos)),
363 tuple(serial_nos),
364 )[0][0]
365 )
366
Nabin Hait9d0f6362013-01-07 18:51:11 +0530367
368def get_valuation_method(item_code):
369 """get valuation method from item or default"""
Ankush Menat494bd9e2022-03-28 18:52:46 +0530370 val_method = frappe.db.get_value("Item", item_code, "valuation_method", cache=True)
Nabin Hait9d0f6362013-01-07 18:51:11 +0530371 if not val_method:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530372 val_method = (
Ankush Menatbb18ae82024-01-09 21:56:47 +0530373 frappe.db.get_single_value("Stock Settings", "valuation_method", cache=True) or "FIFO"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530374 )
Nabin Hait9d0f6362013-01-07 18:51:11 +0530375 return val_method
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530376
Ankush Menat494bd9e2022-03-28 18:52:46 +0530377
Nabin Hait831207f2013-01-16 14:15:48 +0530378def get_fifo_rate(previous_stock_queue, qty):
379 """get FIFO (average) Rate from Queue"""
Ankush Menat61c5ad42022-01-15 18:06:50 +0530380 return _get_fifo_lifo_rate(previous_stock_queue, qty, "FIFO")
Anand Doshi094610d2014-04-16 19:56:53 +0530381
Ankush Menat494bd9e2022-03-28 18:52:46 +0530382
Ankush Menat61c5ad42022-01-15 18:06:50 +0530383def get_lifo_rate(previous_stock_queue, qty):
384 """get LIFO (average) Rate from Queue"""
385 return _get_fifo_lifo_rate(previous_stock_queue, qty, "LIFO")
386
387
388def _get_fifo_lifo_rate(previous_stock_queue, qty, method):
389 ValuationKlass = LIFOValuation if method == "LIFO" else FIFOValuation
390
391 stock_queue = ValuationKlass(previous_stock_queue)
392 if flt(qty) >= 0:
393 total_qty, total_value = stock_queue.get_total_stock_and_value()
394 return total_value / total_qty if total_qty else 0.0
395 else:
396 popped_bins = stock_queue.remove_stock(abs(flt(qty)))
397
398 total_qty, total_value = ValuationKlass(popped_bins).get_total_stock_and_value()
399 return total_value / total_qty if total_qty else 0.0
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530400
Ankush Menat494bd9e2022-03-28 18:52:46 +0530401
402def get_valid_serial_nos(sr_nos, qty=0, item_code=""):
Nabin Hait9d0f6362013-01-07 18:51:11 +0530403 """split serial nos, validate and return list of valid serial nos"""
404 # TODO: remove duplicates in client side
Ankush Menat494bd9e2022-03-28 18:52:46 +0530405 serial_nos = cstr(sr_nos).strip().replace(",", "\n").split("\n")
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530406
Nabin Hait9d0f6362013-01-07 18:51:11 +0530407 valid_serial_nos = []
408 for val in serial_nos:
409 if val:
410 val = val.strip()
411 if val in valid_serial_nos:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530412 frappe.throw(_("Serial number {0} entered more than once").format(val))
Nabin Hait9d0f6362013-01-07 18:51:11 +0530413 else:
414 valid_serial_nos.append(val)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530415
Nabin Hait9d0f6362013-01-07 18:51:11 +0530416 if qty and len(valid_serial_nos) != abs(qty):
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530417 frappe.throw(_("{0} valid serial nos for Item {1}").format(abs(qty), item_code))
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530418
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530419 return valid_serial_nos
Nabin Haita72c5122013-03-06 18:50:53 +0530420
Ankush Menat494bd9e2022-03-28 18:52:46 +0530421
Anand Doshi373680b2013-10-10 16:04:40 +0530422def validate_warehouse_company(warehouse, company):
Ankush91527152021-08-11 11:17:50 +0530423 warehouse_company = frappe.db.get_value("Warehouse", warehouse, "company", cache=True)
Anand Doshi373680b2013-10-10 16:04:40 +0530424 if warehouse_company and warehouse_company != company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530425 frappe.throw(
426 _("Warehouse {0} does not belong to company {1}").format(warehouse, company),
427 InvalidWarehouseCompany,
428 )
429
Saurabh3d6aecd2016-06-20 17:25:45 +0530430
Saurabh4d029492016-06-23 12:44:06 +0530431def is_group_warehouse(warehouse):
Ankush91527152021-08-11 11:17:50 +0530432 if frappe.db.get_value("Warehouse", warehouse, "is_group", cache=True):
Saurabh4d029492016-06-23 12:44:06 +0530433 frappe.throw(_("Group node warehouse is not allowed to select for transactions"))
Saifb4cf72c2018-10-18 17:29:47 +0500434
Ankush Menat494bd9e2022-03-28 18:52:46 +0530435
Jannat Patel30c88732021-02-11 11:46:48 +0530436def validate_disabled_warehouse(warehouse):
Ankush91527152021-08-11 11:17:50 +0530437 if frappe.db.get_value("Warehouse", warehouse, "disabled", cache=True):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530438 frappe.throw(
439 _("Disabled Warehouse {0} cannot be used for this transaction.").format(
440 get_link_to_form("Warehouse", warehouse)
441 )
442 )
443
Jannat Patel30c88732021-02-11 11:46:48 +0530444
Saifb4cf72c2018-10-18 17:29:47 +0500445def update_included_uom_in_report(columns, result, include_uom, conversion_factors):
446 if not include_uom or not conversion_factors:
447 return
448
449 convertible_cols = {}
rohitwaghchaureed1cc182019-09-30 15:15:52 +0530450 is_dict_obj = False
451 if isinstance(result[0], dict):
452 is_dict_obj = True
453
454 convertible_columns = {}
455 for idx, d in enumerate(columns):
456 key = d.get("fieldname") if is_dict_obj else idx
457 if d.get("convertible"):
458 convertible_columns.setdefault(key, d.get("convertible"))
459
460 # Add new column to show qty/rate as per the selected UOM
Ankush Menat494bd9e2022-03-28 18:52:46 +0530461 columns.insert(
462 idx + 1,
463 {
464 "label": "{0} (per {1})".format(d.get("label"), include_uom),
465 "fieldname": "{0}_{1}".format(d.get("fieldname"), frappe.scrub(include_uom)),
466 "fieldtype": "Currency" if d.get("convertible") == "rate" else "Float",
467 },
468 )
Saifb4cf72c2018-10-18 17:29:47 +0500469
rohitwaghchaure001ee5e2019-11-11 17:43:48 +0530470 update_dict_values = []
Saifb4cf72c2018-10-18 17:29:47 +0500471 for row_idx, row in enumerate(result):
rohitwaghchaureed1cc182019-09-30 15:15:52 +0530472 data = row.items() if is_dict_obj else enumerate(row)
473 for key, value in data:
Noah Jacobd8668f72021-07-15 18:32:15 +0530474 if key not in convertible_columns:
rohitwaghchaureed1cc182019-09-30 15:15:52 +0530475 continue
Noah Jacobd8668f72021-07-15 18:32:15 +0530476 # If no conversion factor for the UOM, defaults to 1
477 if not conversion_factors[row_idx]:
478 conversion_factors[row_idx] = 1
Saifb4cf72c2018-10-18 17:29:47 +0500479
Ankush Menat494bd9e2022-03-28 18:52:46 +0530480 if convertible_columns.get(key) == "rate":
Noah Jacobd8668f72021-07-15 18:32:15 +0530481 new_value = flt(value) * conversion_factors[row_idx]
rohitwaghchaureed1cc182019-09-30 15:15:52 +0530482 else:
Noah Jacobd8668f72021-07-15 18:32:15 +0530483 new_value = flt(value) / conversion_factors[row_idx]
rohitwaghchaureed1cc182019-09-30 15:15:52 +0530484
485 if not is_dict_obj:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530486 row.insert(key + 1, new_value)
rohitwaghchaureed1cc182019-09-30 15:15:52 +0530487 else:
488 new_key = "{0}_{1}".format(key, frappe.scrub(include_uom))
rohitwaghchaure001ee5e2019-11-11 17:43:48 +0530489 update_dict_values.append([row, new_key, new_value])
490
491 for data in update_dict_values:
492 row, key, value = data
493 row[key] = value
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530494
Ankush Menat494bd9e2022-03-28 18:52:46 +0530495
Suraj Shettybc001d22019-09-16 19:57:04 +0530496def add_additional_uom_columns(columns, result, include_uom, conversion_factors):
497 if not include_uom or not conversion_factors:
498 return
499
500 convertible_column_map = {}
501 for col_idx in list(reversed(range(0, len(columns)))):
502 col = columns[col_idx]
Ankush Menat494bd9e2022-03-28 18:52:46 +0530503 if isinstance(col, dict) and col.get("convertible") in ["rate", "qty"]:
Suraj Shettybc001d22019-09-16 19:57:04 +0530504 next_col = col_idx + 1
505 columns.insert(next_col, col.copy())
Ankush Menat494bd9e2022-03-28 18:52:46 +0530506 columns[next_col]["fieldname"] += "_alt"
507 convertible_column_map[col.get("fieldname")] = frappe._dict(
508 {"converted_col": columns[next_col]["fieldname"], "for_type": col.get("convertible")}
509 )
510 if col.get("convertible") == "rate":
511 columns[next_col]["label"] += " (per {})".format(include_uom)
Suraj Shettybc001d22019-09-16 19:57:04 +0530512 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530513 columns[next_col]["label"] += " ({})".format(include_uom)
Suraj Shettybc001d22019-09-16 19:57:04 +0530514
515 for row_idx, row in enumerate(result):
516 for convertible_col, data in convertible_column_map.items():
Rohit Waghchaurea627d2a2023-06-20 15:55:18 +0530517 conversion_factor = conversion_factors.get(row.get("item_code")) or 1.0
Suraj Shettybc001d22019-09-16 19:57:04 +0530518 for_type = data.for_type
519 value_before_conversion = row.get(convertible_col)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530520 if for_type == "rate":
Suraj Shettybc001d22019-09-16 19:57:04 +0530521 row[data.converted_col] = flt(value_before_conversion) * conversion_factor
522 else:
523 row[data.converted_col] = flt(value_before_conversion) / conversion_factor
524
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530525 result[row_idx] = row
526
Ankush Menat494bd9e2022-03-28 18:52:46 +0530527
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530528def get_incoming_outgoing_rate_for_cancel(item_code, voucher_type, voucher_no, voucher_detail_no):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530529 outgoing_rate = frappe.db.sql(
Conorea28ed12022-06-17 10:47:48 -0500530 """SELECT CASE WHEN actual_qty = 0 THEN 0 ELSE abs(stock_value_difference / actual_qty) END
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530531 FROM `tabStock Ledger Entry`
532 WHERE voucher_type = %s and voucher_no = %s
533 and item_code = %s and voucher_detail_no = %s
534 ORDER BY CREATION DESC limit 1""",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530535 (voucher_type, voucher_no, item_code, voucher_detail_no),
536 )
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530537
538 outgoing_rate = outgoing_rate[0][0] if outgoing_rate else 0.0
539
Nabin Haita77b8c92020-12-21 14:45:50 +0530540 return outgoing_rate
541
Ankush Menat494bd9e2022-03-28 18:52:46 +0530542
Nabin Haita77b8c92020-12-21 14:45:50 +0530543def is_reposting_item_valuation_in_progress():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530544 reposting_in_progress = frappe.db.exists(
545 "Repost Item Valuation", {"docstatus": 1, "status": ["in", ["Queued", "In Progress"]]}
546 )
Nabin Haita77b8c92020-12-21 14:45:50 +0530547 if reposting_in_progress:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530548 frappe.msgprint(
549 _("Item valuation reposting in progress. Report might show incorrect item valuation."), alert=1
550 )
551
Ankush Menatd37541d2021-12-10 12:04:10 +0530552
553def check_pending_reposting(posting_date: str, throw_error: bool = True) -> bool:
554 """Check if there are pending reposting job till the specified posting date."""
555
556 filters = {
557 "docstatus": 1,
Ankush Menatb12fe0f2022-03-29 13:54:26 +0530558 "status": ["in", ["Queued", "In Progress"]],
Ankush Menatd37541d2021-12-10 12:04:10 +0530559 "posting_date": ["<=", posting_date],
560 }
561
Ankush Menat494bd9e2022-03-28 18:52:46 +0530562 reposting_pending = frappe.db.exists("Repost Item Valuation", filters)
Ankush Menatd37541d2021-12-10 12:04:10 +0530563 if reposting_pending and throw_error:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530564 msg = _(
565 "Stock/Accounts can not be frozen as processing of backdated entries is going on. Please try again later."
566 )
567 frappe.msgprint(
568 msg,
569 raise_exception=PendingRepostingError,
570 title="Stock Reposting Ongoing",
571 indicator="red",
572 primary_action={
573 "label": _("Show pending entries"),
574 "client_action": "erpnext.route_to_pending_reposts",
575 "args": filters,
576 },
577 )
Ankush Menatd37541d2021-12-10 12:04:10 +0530578
579 return bool(reposting_pending)
Ankush Menat47f27a52022-04-01 15:20:40 +0530580
581
582@frappe.whitelist()
Devin Slauenwhiteb88e8502022-10-20 06:26:07 -0400583def scan_barcode(search_value: str) -> BarcodeScanResult:
584 def set_cache(data: BarcodeScanResult):
585 frappe.cache().set_value(f"erpnext:barcode_scan:{search_value}", data, expires_in_sec=120)
586
587 def get_cache() -> Optional[BarcodeScanResult]:
588 if data := frappe.cache().get_value(f"erpnext:barcode_scan:{search_value}"):
589 return data
590
591 if scan_data := get_cache():
592 return scan_data
Ankush Menat47f27a52022-04-01 15:20:40 +0530593
594 # search barcode no
595 barcode_data = frappe.db.get_value(
596 "Item Barcode",
597 {"barcode": search_value},
Ankush Menat3974fbb2022-06-01 16:43:56 +0530598 ["barcode", "parent as item_code", "uom"],
Ankush Menat47f27a52022-04-01 15:20:40 +0530599 as_dict=True,
600 )
601 if barcode_data:
Devin Slauenwhiteb88e8502022-10-20 06:26:07 -0400602 _update_item_info(barcode_data)
603 set_cache(barcode_data)
604 return barcode_data
Ankush Menat47f27a52022-04-01 15:20:40 +0530605
606 # search serial no
607 serial_no_data = frappe.db.get_value(
608 "Serial No",
609 search_value,
610 ["name as serial_no", "item_code", "batch_no"],
611 as_dict=True,
612 )
613 if serial_no_data:
Devin Slauenwhiteb88e8502022-10-20 06:26:07 -0400614 _update_item_info(serial_no_data)
615 set_cache(serial_no_data)
616 return serial_no_data
Ankush Menat47f27a52022-04-01 15:20:40 +0530617
618 # search batch no
619 batch_no_data = frappe.db.get_value(
620 "Batch",
621 search_value,
622 ["name as batch_no", "item as item_code"],
623 as_dict=True,
624 )
625 if batch_no_data:
rohitwaghchauref09e2132024-01-04 14:58:02 +0530626 if frappe.get_cached_value("Item", batch_no_data.item_code, "has_serial_no"):
627 frappe.throw(
628 _(
629 "Batch No {0} is linked with Item {1} which has serial no. Please scan serial no instead."
630 ).format(search_value, batch_no_data.item_code)
631 )
632
Devin Slauenwhiteb88e8502022-10-20 06:26:07 -0400633 _update_item_info(batch_no_data)
634 set_cache(batch_no_data)
Ankush Menat11207c42022-10-20 16:17:57 +0530635 return batch_no_data
Ankush Menat47f27a52022-04-01 15:20:40 +0530636
637 return {}
638
639
640def _update_item_info(scan_result: Dict[str, Optional[str]]) -> Dict[str, Optional[str]]:
641 if item_code := scan_result.get("item_code"):
642 if item_info := frappe.get_cached_value(
643 "Item",
644 item_code,
645 ["has_batch_no", "has_serial_no"],
646 as_dict=True,
647 ):
648 scan_result.update(item_info)
649 return scan_result
Rohit Waghchaured80ca522024-02-07 21:56:21 +0530650
651
652def get_combine_datetime(posting_date, posting_time):
653 import datetime
654
655 if isinstance(posting_date, str):
656 posting_date = getdate(posting_date)
657
658 if isinstance(posting_time, str):
659 posting_time = get_time(posting_time)
660
661 if isinstance(posting_time, datetime.timedelta):
662 posting_time = (datetime.datetime.min + posting_time).time()
663
664 return datetime.datetime.combine(posting_date, posting_time)