blob: c75c737fc5a2562a22f2b66b96902a61b13edd1a [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
6
7import frappe
8from frappe import _
9from frappe.utils import cstr, flt, get_link_to_form, nowdate, nowtime
Achilles Rasquinha56b2e122018-02-13 14:42:40 +053010
Chillar Anand915b3432021-09-02 16:44:59 +053011import erpnext
Ankush Menat61c5ad42022-01-15 18:06:50 +053012from erpnext.stock.valuation import FIFOValuation, LIFOValuation
Chillar Anand915b3432021-09-02 16:44:59 +053013
14
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053015class InvalidWarehouseCompany(frappe.ValidationError): pass
Ankush Menat75bc4042021-12-10 12:39:38 +053016class PendingRepostingError(frappe.ValidationError): pass
Anand Doshi2ce39cf2014-04-07 18:51:58 +053017
Shreya Shahe0a47ae2018-08-28 13:46:22 +053018def get_stock_value_from_bin(warehouse=None, item_code=None):
Sachin Mane19a5a5d2018-06-21 13:01:48 +053019 values = {}
20 conditions = ""
21 if warehouse:
rohitwaghchauref1fab872019-09-05 14:47:43 +053022 conditions += """ and `tabBin`.warehouse in (
Sachin Mane19a5a5d2018-06-21 13:01:48 +053023 select w2.name from `tabWarehouse` w1
24 join `tabWarehouse` w2 on
25 w1.name = %(warehouse)s
26 and w2.lft between w1.lft and w1.rgt
27 ) """
28
29 values['warehouse'] = warehouse
30
31 if item_code:
rohitwaghchauref1fab872019-09-05 14:47:43 +053032 conditions += " and `tabBin`.item_code = %(item_code)s"
Sachin Mane19a5a5d2018-06-21 13:01:48 +053033
Sachin Mane19a5a5d2018-06-21 13:01:48 +053034 values['item_code'] = item_code
35
rohitwaghchauref1fab872019-09-05 14:47:43 +053036 query = """select sum(stock_value) from `tabBin`, `tabItem` where 1 = 1
37 and `tabItem`.name = `tabBin`.item_code and ifnull(`tabItem`.disabled, 0) = 0 %s""" % conditions
Sachin Mane19a5a5d2018-06-21 13:01:48 +053038
39 stock_value = frappe.db.sql(query, values)
40
Shreya Shahe0a47ae2018-08-28 13:46:22 +053041 return stock_value
Sachin Mane19a5a5d2018-06-21 13:01:48 +053042
Rushabh Mehtaf8509872014-10-08 12:03:19 +053043def get_stock_value_on(warehouse=None, posting_date=None, item_code=None):
Nabin Hait0dd7be12013-08-02 11:45:43 +053044 if not posting_date: posting_date = nowdate()
Anand Doshi2ce39cf2014-04-07 18:51:58 +053045
Rushabh Mehtaf8509872014-10-08 12:03:19 +053046 values, condition = [posting_date], ""
47
48 if warehouse:
Sachin Mane19a5a5d2018-06-21 13:01:48 +053049
Saurabh4d029492016-06-23 12:44:06 +053050 lft, rgt, is_group = frappe.db.get_value("Warehouse", warehouse, ["lft", "rgt", "is_group"])
Sachin Mane19a5a5d2018-06-21 13:01:48 +053051
Saurabh93d68ac2016-06-26 22:50:11 +053052 if is_group:
Saurabh4d029492016-06-23 12:44:06 +053053 values.extend([lft, rgt])
Saurabh554f6f72016-06-06 14:22:37 +053054 condition += "and exists (\
55 select name from `tabWarehouse` wh where wh.name = sle.warehouse\
56 and wh.lft >= %s and wh.rgt <= %s)"
Sachin Mane19a5a5d2018-06-21 13:01:48 +053057
Saurabh554f6f72016-06-06 14:22:37 +053058 else:
59 values.append(warehouse)
60 condition += " AND warehouse = %s"
Rushabh Mehtaf8509872014-10-08 12:03:19 +053061
62 if item_code:
63 values.append(item_code)
itusedyetnew8aafbd22019-03-20 11:10:41 +053064 condition += " AND item_code = %s"
Rushabh Mehtaf8509872014-10-08 12:03:19 +053065
Anand Doshie9baaa62014-02-26 12:35:33 +053066 stock_ledger_entries = frappe.db.sql("""
Saurabh554f6f72016-06-06 14:22:37 +053067 SELECT item_code, stock_value, name, warehouse
68 FROM `tabStock Ledger Entry` sle
Rushabh Mehtaf8509872014-10-08 12:03:19 +053069 WHERE posting_date <= %s {0}
Nabin Haita77b8c92020-12-21 14:45:50 +053070 and is_cancelled = 0
Aditya Hase0c164242019-01-07 22:07:13 +053071 ORDER BY timestamp(posting_date, posting_time) DESC, creation DESC
Rushabh Mehtaf8509872014-10-08 12:03:19 +053072 """.format(condition), values, as_dict=1)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053073
Nabin Hait0dd7be12013-08-02 11:45:43 +053074 sle_map = {}
75 for sle in stock_ledger_entries:
Achilles Rasquinhab4de7e32018-03-09 12:35:47 +053076 if not (sle.item_code, sle.warehouse) in sle_map:
Nabin Hait949a9202017-07-05 13:55:41 +053077 sle_map[(sle.item_code, sle.warehouse)] = flt(sle.stock_value)
Sachin Mane19a5a5d2018-06-21 13:01:48 +053078
Nabin Hait625da792013-09-25 10:32:51 +053079 return sum(sle_map.values())
Anand Doshi2ce39cf2014-04-07 18:51:58 +053080
nick98226f48d4b2017-01-09 12:12:36 +053081@frappe.whitelist()
Rohit Waghchaure560f8222020-04-06 15:02:43 +053082def get_stock_balance(item_code, warehouse, posting_date=None, posting_time=None,
83 with_valuation_rate=False, with_serial_no=False):
Rushabh Mehta2712e362015-02-17 12:50:20 +053084 """Returns stock balance quantity at given warehouse on given posting date or current date.
85
86 If `with_valuation_rate` is True, will return tuple (qty, rate)"""
Rushabh Mehtadc93e0a2015-02-20 15:11:56 +053087
88 from erpnext.stock.stock_ledger import get_previous_sle
89
rohitwaghchauref02e6b42022-01-03 14:28:34 +053090 if posting_date is None: posting_date = nowdate()
91 if posting_time is None: posting_time = nowtime()
Rushabh Mehtadc93e0a2015-02-20 15:11:56 +053092
Rohit Waghchaure560f8222020-04-06 15:02:43 +053093 args = {
Rushabh Mehtadc93e0a2015-02-20 15:11:56 +053094 "item_code": item_code,
95 "warehouse":warehouse,
96 "posting_date": posting_date,
Rohit Waghchaure560f8222020-04-06 15:02:43 +053097 "posting_time": posting_time
98 }
99
100 last_entry = get_previous_sle(args)
Rushabh Mehtaf8509872014-10-08 12:03:19 +0530101
Rushabh Mehta2712e362015-02-17 12:50:20 +0530102 if with_valuation_rate:
Rohit Waghchaure560f8222020-04-06 15:02:43 +0530103 if with_serial_no:
Ankush Menat2aa019a2021-10-29 14:32:13 +0530104 serial_nos = get_serial_nos_data_after_transactions(args)
Rohit Waghchaure560f8222020-04-06 15:02:43 +0530105
106 return ((last_entry.qty_after_transaction, last_entry.valuation_rate, serial_nos)
Ankush Menat33c4a0b2022-01-21 14:04:09 +0530107 if last_entry else (0.0, 0.0, None))
Rohit Waghchaure560f8222020-04-06 15:02:43 +0530108 else:
109 return (last_entry.qty_after_transaction, last_entry.valuation_rate) if last_entry else (0.0, 0.0)
Rushabh Mehtaf8509872014-10-08 12:03:19 +0530110 else:
nick9822cc699a92017-06-20 17:13:29 +0530111 return last_entry.qty_after_transaction if last_entry else 0.0
Rushabh Mehtaf8509872014-10-08 12:03:19 +0530112
Rohit Waghchaure560f8222020-04-06 15:02:43 +0530113def get_serial_nos_data_after_transactions(args):
Noah Jacobdeb6b382021-10-21 17:17:11 +0530114 from pypika import CustomFunction
115
Ankush Menatf4b60a42021-10-29 14:56:54 +0530116 serial_nos = set()
Noah Jacobdeb6b382021-10-21 17:17:11 +0530117 args = frappe._dict(args)
118 sle = frappe.qb.DocType('Stock Ledger Entry')
119 Timestamp = CustomFunction('timestamp', ['date', 'time'])
120
Ankush Menatf4b60a42021-10-29 14:56:54 +0530121 stock_ledger_entries = frappe.qb.from_(
Noah Jacobdeb6b382021-10-21 17:17:11 +0530122 sle
123 ).select(
124 'serial_no','actual_qty'
125 ).where(
126 (sle.item_code == args.item_code)
127 & (sle.warehouse == args.warehouse)
128 & (Timestamp(sle.posting_date, sle.posting_time) < Timestamp(args.posting_date, args.posting_time))
129 & (sle.is_cancelled == 0)
130 ).orderby(
Ankush Menatff9cfe02021-10-29 16:30:12 +0530131 sle.posting_date, sle.posting_time, sle.creation
Noah Jacobdeb6b382021-10-21 17:17:11 +0530132 ).run(as_dict=1)
Rohit Waghchaure560f8222020-04-06 15:02:43 +0530133
Ankush Menatf4b60a42021-10-29 14:56:54 +0530134 for stock_ledger_entry in stock_ledger_entries:
135 changed_serial_no = get_serial_nos_data(stock_ledger_entry.serial_no)
136 if stock_ledger_entry.actual_qty > 0:
137 serial_nos.update(changed_serial_no)
Rohit Waghchaure560f8222020-04-06 15:02:43 +0530138 else:
Ankush Menatf4b60a42021-10-29 14:56:54 +0530139 serial_nos.difference_update(changed_serial_no)
Rohit Waghchaure560f8222020-04-06 15:02:43 +0530140
141 return '\n'.join(serial_nos)
142
143def get_serial_nos_data(serial_nos):
144 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
145 return get_serial_nos(serial_nos)
146
Nabin Hait949a9202017-07-05 13:55:41 +0530147@frappe.whitelist()
148def get_latest_stock_qty(item_code, warehouse=None):
149 values, condition = [item_code], ""
150 if warehouse:
151 lft, rgt, is_group = frappe.db.get_value("Warehouse", warehouse, ["lft", "rgt", "is_group"])
Sachin Mane19a5a5d2018-06-21 13:01:48 +0530152
Nabin Hait949a9202017-07-05 13:55:41 +0530153 if is_group:
154 values.extend([lft, rgt])
155 condition += "and exists (\
156 select name from `tabWarehouse` wh where wh.name = tabBin.warehouse\
157 and wh.lft >= %s and wh.rgt <= %s)"
Sachin Mane19a5a5d2018-06-21 13:01:48 +0530158
Nabin Hait949a9202017-07-05 13:55:41 +0530159 else:
160 values.append(warehouse)
161 condition += " AND warehouse = %s"
Sachin Mane19a5a5d2018-06-21 13:01:48 +0530162
Nabin Hait949a9202017-07-05 13:55:41 +0530163 actual_qty = frappe.db.sql("""select sum(actual_qty) from tabBin
164 where item_code=%s {0}""".format(condition), values)[0][0]
165
166 return actual_qty
167
168
Nabin Hait47dc3182013-08-06 15:58:16 +0530169def get_latest_stock_balance():
170 bin_map = {}
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530171 for d in frappe.db.sql("""SELECT item_code, warehouse, stock_value as stock_value
Nabin Hait47dc3182013-08-06 15:58:16 +0530172 FROM tabBin""", as_dict=1):
Nabin Hait469ee712013-08-07 12:33:37 +0530173 bin_map.setdefault(d.warehouse, {}).setdefault(d.item_code, flt(d.stock_value))
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530174
Nabin Hait47dc3182013-08-06 15:58:16 +0530175 return bin_map
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530176
Nabin Hait74c281c2013-08-19 16:17:18 +0530177def get_bin(item_code, warehouse):
Anand Doshie9baaa62014-02-26 12:35:33 +0530178 bin = frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse})
Nabin Hait74c281c2013-08-19 16:17:18 +0530179 if not bin:
Ankush Menat08810db2022-01-30 16:25:42 +0530180 bin_obj = _create_bin(item_code, warehouse)
Nabin Hait74c281c2013-08-19 16:17:18 +0530181 else:
rohitwaghchaure00ea3362021-05-01 13:53:39 +0530182 bin_obj = frappe.get_doc('Bin', bin, for_update=True)
Anand Doshi6dfd4302015-02-10 14:41:27 +0530183 bin_obj.flags.ignore_permissions = True
Nabin Hait74c281c2013-08-19 16:17:18 +0530184 return bin_obj
185
Ankush Menat97060c42021-12-03 11:50:38 +0530186def get_or_make_bin(item_code: str , warehouse: str) -> str:
Deepesh Garg6f107da2021-10-12 20:15:55 +0530187 bin_record = frappe.db.get_value('Bin', {'item_code': item_code, 'warehouse': warehouse})
188
189 if not bin_record:
Ankush Menat08810db2022-01-30 16:25:42 +0530190 bin_obj = _create_bin(item_code, warehouse)
191 bin_record = bin_obj.name
192 return bin_record
193
194def _create_bin(item_code, warehouse):
195 """Create a bin and take care of concurrent inserts."""
196
197 bin_creation_savepoint = "create_bin"
198 try:
199 frappe.db.savepoint(bin_creation_savepoint)
200 bin_obj = frappe.get_doc(doctype="Bin", item_code=item_code, warehouse=warehouse)
Deepesh Garg6f107da2021-10-12 20:15:55 +0530201 bin_obj.flags.ignore_permissions = 1
202 bin_obj.insert()
Ankush Menat08810db2022-01-30 16:25:42 +0530203 except frappe.UniqueValidationError:
204 frappe.db.rollback(save_point=bin_creation_savepoint) # preserve transaction in postgres
205 bin_obj = frappe.get_last_doc("Bin", {"item_code": item_code, "warehouse": warehouse})
Deepesh Garg6f107da2021-10-12 20:15:55 +0530206
Ankush Menat08810db2022-01-30 16:25:42 +0530207 return bin_obj
Deepesh Garg6f107da2021-10-12 20:15:55 +0530208
Nabin Hait54c865e2015-03-27 15:38:31 +0530209def update_bin(args, allow_negative_stock=False, via_landed_cost_voucher=False):
Ankush Menatcef84c22021-12-03 12:18:59 +0530210 """WARNING: This function is deprecated. Inline this function instead of using it."""
Deepesh Garg6f107da2021-10-12 20:15:55 +0530211 from erpnext.stock.doctype.bin.bin import update_stock
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530212 is_stock_item = frappe.get_cached_value('Item', args.get("item_code"), 'is_stock_item')
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530213 if is_stock_item:
Ankush Menat97060c42021-12-03 11:50:38 +0530214 bin_name = get_or_make_bin(args.get("item_code"), args.get("warehouse"))
215 update_stock(bin_name, args, allow_negative_stock, via_landed_cost_voucher)
Nabin Hait74c281c2013-08-19 16:17:18 +0530216 else:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530217 frappe.msgprint(_("Item {0} ignored since it is not a stock item").format(args.get("item_code")))
Nabin Hait0dd7be12013-08-02 11:45:43 +0530218
Nabin Hait5eefff12015-12-07 10:44:56 +0530219@frappe.whitelist()
Nabin Hait7ba092e2018-02-01 10:51:27 +0530220def get_incoming_rate(args, raise_error_if_no_rate=True):
Nabin Hait9d0f6362013-01-07 18:51:11 +0530221 """Get Incoming Rate based on valuation method"""
rohitwaghchaurece8adec2017-12-15 12:13:50 +0530222 from erpnext.stock.stock_ledger import get_previous_sle, get_valuation_rate
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530223 if isinstance(args, str):
Nabin Hait41c8cf62015-12-08 14:50:24 +0530224 args = json.loads(args)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530225
Nabin Hait9d0f6362013-01-07 18:51:11 +0530226 in_rate = 0
Anand Doshi40a8ae22014-08-29 16:28:31 +0530227 if (args.get("serial_no") or "").strip():
Nabin Hait9d0f6362013-01-07 18:51:11 +0530228 in_rate = get_avg_purchase_rate(args.get("serial_no"))
Nabin Hait9d0f6362013-01-07 18:51:11 +0530229 else:
230 valuation_method = get_valuation_method(args.get("item_code"))
231 previous_sle = get_previous_sle(args)
Ankush Menat61c5ad42022-01-15 18:06:50 +0530232 if valuation_method in ('FIFO', 'LIFO'):
rohitwaghchaurece8adec2017-12-15 12:13:50 +0530233 if previous_sle:
234 previous_stock_queue = json.loads(previous_sle.get('stock_queue', '[]') or '[]')
Ankush Menat61c5ad42022-01-15 18:06:50 +0530235 in_rate = _get_fifo_lifo_rate(previous_stock_queue, args.get("qty") or 0, valuation_method) if previous_stock_queue else 0
Nabin Hait9d0f6362013-01-07 18:51:11 +0530236 elif valuation_method == 'Moving Average':
237 in_rate = previous_sle.get('valuation_rate') or 0
Anand Doshi094610d2014-04-16 19:56:53 +0530238
rohitwaghchaurece8adec2017-12-15 12:13:50 +0530239 if not in_rate:
240 voucher_no = args.get('voucher_no') or args.get('name')
rohitwaghchaurece8adec2017-12-15 12:13:50 +0530241 in_rate = get_valuation_rate(args.get('item_code'), args.get('warehouse'),
242 args.get('voucher_type'), voucher_no, args.get('allow_zero_valuation'),
Nabin Hait7ba092e2018-02-01 10:51:27 +0530243 currency=erpnext.get_company_currency(args.get('company')), company=args.get('company'),
Rohit Waghchaure87c4b062019-06-01 14:22:46 +0530244 raise_error_if_no_rate=raise_error_if_no_rate)
rohitwaghchaurece8adec2017-12-15 12:13:50 +0530245
Nabin Haita77b8c92020-12-21 14:45:50 +0530246 return flt(in_rate)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530247
Nabin Hait9d0f6362013-01-07 18:51:11 +0530248def get_avg_purchase_rate(serial_nos):
249 """get average value of serial numbers"""
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530250
Nabin Hait9d0f6362013-01-07 18:51:11 +0530251 serial_nos = get_valid_serial_nos(serial_nos)
Anand Doshi602e8252015-11-16 19:05:46 +0530252 return flt(frappe.db.sql("""select avg(purchase_rate) from `tabSerial No`
Nabin Hait9d0f6362013-01-07 18:51:11 +0530253 where name in (%s)""" % ", ".join(["%s"] * len(serial_nos)),
254 tuple(serial_nos))[0][0])
255
256def get_valuation_method(item_code):
257 """get valuation method from item or default"""
Ankush91527152021-08-11 11:17:50 +0530258 val_method = frappe.db.get_value('Item', item_code, 'valuation_method', cache=True)
Nabin Hait9d0f6362013-01-07 18:51:11 +0530259 if not val_method:
Nabin Hait4d742162014-10-09 19:25:03 +0530260 val_method = frappe.db.get_value("Stock Settings", None, "valuation_method") or "FIFO"
Nabin Hait9d0f6362013-01-07 18:51:11 +0530261 return val_method
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530262
Nabin Hait831207f2013-01-16 14:15:48 +0530263def get_fifo_rate(previous_stock_queue, qty):
264 """get FIFO (average) Rate from Queue"""
Ankush Menat61c5ad42022-01-15 18:06:50 +0530265 return _get_fifo_lifo_rate(previous_stock_queue, qty, "FIFO")
Anand Doshi094610d2014-04-16 19:56:53 +0530266
Ankush Menat61c5ad42022-01-15 18:06:50 +0530267def get_lifo_rate(previous_stock_queue, qty):
268 """get LIFO (average) Rate from Queue"""
269 return _get_fifo_lifo_rate(previous_stock_queue, qty, "LIFO")
270
271
272def _get_fifo_lifo_rate(previous_stock_queue, qty, method):
273 ValuationKlass = LIFOValuation if method == "LIFO" else FIFOValuation
274
275 stock_queue = ValuationKlass(previous_stock_queue)
276 if flt(qty) >= 0:
277 total_qty, total_value = stock_queue.get_total_stock_and_value()
278 return total_value / total_qty if total_qty else 0.0
279 else:
280 popped_bins = stock_queue.remove_stock(abs(flt(qty)))
281
282 total_qty, total_value = ValuationKlass(popped_bins).get_total_stock_and_value()
283 return total_value / total_qty if total_qty else 0.0
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530284
Nabin Hait9d0f6362013-01-07 18:51:11 +0530285def get_valid_serial_nos(sr_nos, qty=0, item_code=''):
286 """split serial nos, validate and return list of valid serial nos"""
287 # TODO: remove duplicates in client side
288 serial_nos = cstr(sr_nos).strip().replace(',', '\n').split('\n')
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530289
Nabin Hait9d0f6362013-01-07 18:51:11 +0530290 valid_serial_nos = []
291 for val in serial_nos:
292 if val:
293 val = val.strip()
294 if val in valid_serial_nos:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530295 frappe.throw(_("Serial number {0} entered more than once").format(val))
Nabin Hait9d0f6362013-01-07 18:51:11 +0530296 else:
297 valid_serial_nos.append(val)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530298
Nabin Hait9d0f6362013-01-07 18:51:11 +0530299 if qty and len(valid_serial_nos) != abs(qty):
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530300 frappe.throw(_("{0} valid serial nos for Item {1}").format(abs(qty), item_code))
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530301
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530302 return valid_serial_nos
Nabin Haita72c5122013-03-06 18:50:53 +0530303
Anand Doshi373680b2013-10-10 16:04:40 +0530304def validate_warehouse_company(warehouse, company):
Ankush91527152021-08-11 11:17:50 +0530305 warehouse_company = frappe.db.get_value("Warehouse", warehouse, "company", cache=True)
Anand Doshi373680b2013-10-10 16:04:40 +0530306 if warehouse_company and warehouse_company != company:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530307 frappe.throw(_("Warehouse {0} does not belong to company {1}").format(warehouse, company),
308 InvalidWarehouseCompany)
Saurabh3d6aecd2016-06-20 17:25:45 +0530309
Saurabh4d029492016-06-23 12:44:06 +0530310def is_group_warehouse(warehouse):
Ankush91527152021-08-11 11:17:50 +0530311 if frappe.db.get_value("Warehouse", warehouse, "is_group", cache=True):
Saurabh4d029492016-06-23 12:44:06 +0530312 frappe.throw(_("Group node warehouse is not allowed to select for transactions"))
Saifb4cf72c2018-10-18 17:29:47 +0500313
Jannat Patel30c88732021-02-11 11:46:48 +0530314def validate_disabled_warehouse(warehouse):
Ankush91527152021-08-11 11:17:50 +0530315 if frappe.db.get_value("Warehouse", warehouse, "disabled", cache=True):
Jannat Patel30c88732021-02-11 11:46:48 +0530316 frappe.throw(_("Disabled Warehouse {0} cannot be used for this transaction.").format(get_link_to_form('Warehouse', warehouse)))
317
Saifb4cf72c2018-10-18 17:29:47 +0500318def update_included_uom_in_report(columns, result, include_uom, conversion_factors):
319 if not include_uom or not conversion_factors:
320 return
321
322 convertible_cols = {}
rohitwaghchaureed1cc182019-09-30 15:15:52 +0530323 is_dict_obj = False
324 if isinstance(result[0], dict):
325 is_dict_obj = True
326
327 convertible_columns = {}
328 for idx, d in enumerate(columns):
329 key = d.get("fieldname") if is_dict_obj else idx
330 if d.get("convertible"):
331 convertible_columns.setdefault(key, d.get("convertible"))
332
333 # Add new column to show qty/rate as per the selected UOM
334 columns.insert(idx+1, {
335 'label': "{0} (per {1})".format(d.get("label"), include_uom),
336 'fieldname': "{0}_{1}".format(d.get("fieldname"), frappe.scrub(include_uom)),
337 'fieldtype': 'Currency' if d.get("convertible") == 'rate' else 'Float'
338 })
Saifb4cf72c2018-10-18 17:29:47 +0500339
rohitwaghchaure001ee5e2019-11-11 17:43:48 +0530340 update_dict_values = []
Saifb4cf72c2018-10-18 17:29:47 +0500341 for row_idx, row in enumerate(result):
rohitwaghchaureed1cc182019-09-30 15:15:52 +0530342 data = row.items() if is_dict_obj else enumerate(row)
343 for key, value in data:
Noah Jacobd8668f72021-07-15 18:32:15 +0530344 if key not in convertible_columns:
rohitwaghchaureed1cc182019-09-30 15:15:52 +0530345 continue
Noah Jacobd8668f72021-07-15 18:32:15 +0530346 # If no conversion factor for the UOM, defaults to 1
347 if not conversion_factors[row_idx]:
348 conversion_factors[row_idx] = 1
Saifb4cf72c2018-10-18 17:29:47 +0500349
rohitwaghchaureed1cc182019-09-30 15:15:52 +0530350 if convertible_columns.get(key) == 'rate':
Noah Jacobd8668f72021-07-15 18:32:15 +0530351 new_value = flt(value) * conversion_factors[row_idx]
rohitwaghchaureed1cc182019-09-30 15:15:52 +0530352 else:
Noah Jacobd8668f72021-07-15 18:32:15 +0530353 new_value = flt(value) / conversion_factors[row_idx]
rohitwaghchaureed1cc182019-09-30 15:15:52 +0530354
355 if not is_dict_obj:
356 row.insert(key+1, new_value)
357 else:
358 new_key = "{0}_{1}".format(key, frappe.scrub(include_uom))
rohitwaghchaure001ee5e2019-11-11 17:43:48 +0530359 update_dict_values.append([row, new_key, new_value])
360
361 for data in update_dict_values:
362 row, key, value = data
363 row[key] = value
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530364
Rohit Waghchaurecf55c9c2019-11-14 18:22:20 +0530365def get_available_serial_nos(args):
366 return frappe.db.sql(""" SELECT name from `tabSerial No`
367 WHERE item_code = %(item_code)s and warehouse = %(warehouse)s
368 and timestamp(purchase_date, purchase_time) <= timestamp(%(posting_date)s, %(posting_time)s)
369 """, args, as_dict=1)
Suraj Shettybc001d22019-09-16 19:57:04 +0530370
371def add_additional_uom_columns(columns, result, include_uom, conversion_factors):
372 if not include_uom or not conversion_factors:
373 return
374
375 convertible_column_map = {}
376 for col_idx in list(reversed(range(0, len(columns)))):
377 col = columns[col_idx]
378 if isinstance(col, dict) and col.get('convertible') in ['rate', 'qty']:
379 next_col = col_idx + 1
380 columns.insert(next_col, col.copy())
381 columns[next_col]['fieldname'] += '_alt'
382 convertible_column_map[col.get('fieldname')] = frappe._dict({
383 'converted_col': columns[next_col]['fieldname'],
384 'for_type': col.get('convertible')
385 })
386 if col.get('convertible') == 'rate':
387 columns[next_col]['label'] += ' (per {})'.format(include_uom)
388 else:
389 columns[next_col]['label'] += ' ({})'.format(include_uom)
390
391 for row_idx, row in enumerate(result):
392 for convertible_col, data in convertible_column_map.items():
393 conversion_factor = conversion_factors[row.get('item_code')] or 1
394 for_type = data.for_type
395 value_before_conversion = row.get(convertible_col)
396 if for_type == 'rate':
397 row[data.converted_col] = flt(value_before_conversion) * conversion_factor
398 else:
399 row[data.converted_col] = flt(value_before_conversion) / conversion_factor
400
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530401 result[row_idx] = row
402
403def get_incoming_outgoing_rate_for_cancel(item_code, voucher_type, voucher_no, voucher_detail_no):
404 outgoing_rate = frappe.db.sql("""SELECT abs(stock_value_difference / actual_qty)
405 FROM `tabStock Ledger Entry`
406 WHERE voucher_type = %s and voucher_no = %s
407 and item_code = %s and voucher_detail_no = %s
408 ORDER BY CREATION DESC limit 1""",
409 (voucher_type, voucher_no, item_code, voucher_detail_no))
410
411 outgoing_rate = outgoing_rate[0][0] if outgoing_rate else 0.0
412
Nabin Haita77b8c92020-12-21 14:45:50 +0530413 return outgoing_rate
414
415def is_reposting_item_valuation_in_progress():
416 reposting_in_progress = frappe.db.exists("Repost Item Valuation",
417 {'docstatus': 1, 'status': ['in', ['Queued','In Progress']]})
418 if reposting_in_progress:
Noah Jacobd8668f72021-07-15 18:32:15 +0530419 frappe.msgprint(_("Item valuation reposting in progress. Report might show incorrect item valuation."), alert=1)
Ankush Menatd37541d2021-12-10 12:04:10 +0530420
Noah Jacob20216fa2022-01-21 11:50:13 +0530421
422def calculate_mapped_packed_items_return(return_doc):
423 parent_items = set([item.parent_item for item in return_doc.packed_items])
424 against_doc = frappe.get_doc(return_doc.doctype, return_doc.return_against)
425
426 for original_bundle, returned_bundle in zip(against_doc.items, return_doc.items):
427 if original_bundle.item_code in parent_items:
428 for returned_packed_item, original_packed_item in zip(return_doc.packed_items, against_doc.packed_items):
429 if returned_packed_item.parent_item == original_bundle.item_code:
430 returned_packed_item.parent_detail_docname = returned_bundle.name
431 returned_packed_item.qty = (original_packed_item.qty / original_bundle.qty) * returned_bundle.qty
432
433
Ankush Menatd37541d2021-12-10 12:04:10 +0530434def check_pending_reposting(posting_date: str, throw_error: bool = True) -> bool:
435 """Check if there are pending reposting job till the specified posting date."""
436
437 filters = {
438 "docstatus": 1,
439 "status": ["in", ["Queued","In Progress", "Failed"]],
440 "posting_date": ["<=", posting_date],
441 }
442
443 reposting_pending = frappe.db.exists("Repost Item Valuation", filters)
444 if reposting_pending and throw_error:
445 msg = _("Stock/Accounts can not be frozen as processing of backdated entries is going on. Please try again later.")
446 frappe.msgprint(msg,
Ankush Menat75bc4042021-12-10 12:39:38 +0530447 raise_exception=PendingRepostingError,
Ankush Menatd37541d2021-12-10 12:04:10 +0530448 title="Stock Reposting Ongoing",
449 indicator="red",
450 primary_action={
451 "label": _("Show pending entries"),
452 "client_action": "erpnext.route_to_pending_reposts",
453 "args": filters,
454 }
455 )
456
457 return bool(reposting_pending)