Anand Doshi | 885e074 | 2015-03-03 14:55:30 +0530 | [diff] [blame] | 1 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors |
Rushabh Mehta | e67d1fb | 2013-08-05 14:59:54 +0530 | [diff] [blame] | 2 | # License: GNU General Public License v3. See license.txt |
Nabin Hait | 9d0f636 | 2013-01-07 18:51:11 +0530 | [diff] [blame] | 3 | |
Nabin Hait | 9d0f636 | 2013-01-07 18:51:11 +0530 | [diff] [blame] | 4 | |
Chillar Anand | 915b343 | 2021-09-02 16:44:59 +0530 | [diff] [blame] | 5 | import json |
| 6 | |
| 7 | import frappe |
| 8 | from frappe import _ |
| 9 | from frappe.utils import cstr, flt, get_link_to_form, nowdate, nowtime |
Achilles Rasquinha | 56b2e12 | 2018-02-13 14:42:40 +0530 | [diff] [blame] | 10 | |
Chillar Anand | 915b343 | 2021-09-02 16:44:59 +0530 | [diff] [blame] | 11 | import erpnext |
Ankush Menat | 61c5ad4 | 2022-01-15 18:06:50 +0530 | [diff] [blame] | 12 | from erpnext.stock.valuation import FIFOValuation, LIFOValuation |
Chillar Anand | 915b343 | 2021-09-02 16:44:59 +0530 | [diff] [blame] | 13 | |
| 14 | |
Rushabh Mehta | 793ba6b | 2014-02-14 15:47:51 +0530 | [diff] [blame] | 15 | class InvalidWarehouseCompany(frappe.ValidationError): pass |
Ankush Menat | 75bc404 | 2021-12-10 12:39:38 +0530 | [diff] [blame] | 16 | class PendingRepostingError(frappe.ValidationError): pass |
Anand Doshi | 2ce39cf | 2014-04-07 18:51:58 +0530 | [diff] [blame] | 17 | |
Shreya Shah | e0a47ae | 2018-08-28 13:46:22 +0530 | [diff] [blame] | 18 | def get_stock_value_from_bin(warehouse=None, item_code=None): |
Sachin Mane | 19a5a5d | 2018-06-21 13:01:48 +0530 | [diff] [blame] | 19 | values = {} |
| 20 | conditions = "" |
| 21 | if warehouse: |
rohitwaghchaure | f1fab87 | 2019-09-05 14:47:43 +0530 | [diff] [blame] | 22 | conditions += """ and `tabBin`.warehouse in ( |
Sachin Mane | 19a5a5d | 2018-06-21 13:01:48 +0530 | [diff] [blame] | 23 | 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: |
rohitwaghchaure | f1fab87 | 2019-09-05 14:47:43 +0530 | [diff] [blame] | 32 | conditions += " and `tabBin`.item_code = %(item_code)s" |
Sachin Mane | 19a5a5d | 2018-06-21 13:01:48 +0530 | [diff] [blame] | 33 | |
Sachin Mane | 19a5a5d | 2018-06-21 13:01:48 +0530 | [diff] [blame] | 34 | values['item_code'] = item_code |
| 35 | |
rohitwaghchaure | f1fab87 | 2019-09-05 14:47:43 +0530 | [diff] [blame] | 36 | 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 Mane | 19a5a5d | 2018-06-21 13:01:48 +0530 | [diff] [blame] | 38 | |
| 39 | stock_value = frappe.db.sql(query, values) |
| 40 | |
Shreya Shah | e0a47ae | 2018-08-28 13:46:22 +0530 | [diff] [blame] | 41 | return stock_value |
Sachin Mane | 19a5a5d | 2018-06-21 13:01:48 +0530 | [diff] [blame] | 42 | |
Rushabh Mehta | f850987 | 2014-10-08 12:03:19 +0530 | [diff] [blame] | 43 | def get_stock_value_on(warehouse=None, posting_date=None, item_code=None): |
Nabin Hait | 0dd7be1 | 2013-08-02 11:45:43 +0530 | [diff] [blame] | 44 | if not posting_date: posting_date = nowdate() |
Anand Doshi | 2ce39cf | 2014-04-07 18:51:58 +0530 | [diff] [blame] | 45 | |
Rushabh Mehta | f850987 | 2014-10-08 12:03:19 +0530 | [diff] [blame] | 46 | values, condition = [posting_date], "" |
| 47 | |
| 48 | if warehouse: |
Sachin Mane | 19a5a5d | 2018-06-21 13:01:48 +0530 | [diff] [blame] | 49 | |
Saurabh | 4d02949 | 2016-06-23 12:44:06 +0530 | [diff] [blame] | 50 | lft, rgt, is_group = frappe.db.get_value("Warehouse", warehouse, ["lft", "rgt", "is_group"]) |
Sachin Mane | 19a5a5d | 2018-06-21 13:01:48 +0530 | [diff] [blame] | 51 | |
Saurabh | 93d68ac | 2016-06-26 22:50:11 +0530 | [diff] [blame] | 52 | if is_group: |
Saurabh | 4d02949 | 2016-06-23 12:44:06 +0530 | [diff] [blame] | 53 | values.extend([lft, rgt]) |
Saurabh | 554f6f7 | 2016-06-06 14:22:37 +0530 | [diff] [blame] | 54 | condition += "and exists (\ |
| 55 | select name from `tabWarehouse` wh where wh.name = sle.warehouse\ |
| 56 | and wh.lft >= %s and wh.rgt <= %s)" |
Sachin Mane | 19a5a5d | 2018-06-21 13:01:48 +0530 | [diff] [blame] | 57 | |
Saurabh | 554f6f7 | 2016-06-06 14:22:37 +0530 | [diff] [blame] | 58 | else: |
| 59 | values.append(warehouse) |
| 60 | condition += " AND warehouse = %s" |
Rushabh Mehta | f850987 | 2014-10-08 12:03:19 +0530 | [diff] [blame] | 61 | |
| 62 | if item_code: |
| 63 | values.append(item_code) |
itusedyetnew | 8aafbd2 | 2019-03-20 11:10:41 +0530 | [diff] [blame] | 64 | condition += " AND item_code = %s" |
Rushabh Mehta | f850987 | 2014-10-08 12:03:19 +0530 | [diff] [blame] | 65 | |
Anand Doshi | e9baaa6 | 2014-02-26 12:35:33 +0530 | [diff] [blame] | 66 | stock_ledger_entries = frappe.db.sql(""" |
Saurabh | 554f6f7 | 2016-06-06 14:22:37 +0530 | [diff] [blame] | 67 | SELECT item_code, stock_value, name, warehouse |
| 68 | FROM `tabStock Ledger Entry` sle |
Rushabh Mehta | f850987 | 2014-10-08 12:03:19 +0530 | [diff] [blame] | 69 | WHERE posting_date <= %s {0} |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 70 | and is_cancelled = 0 |
Aditya Hase | 0c16424 | 2019-01-07 22:07:13 +0530 | [diff] [blame] | 71 | ORDER BY timestamp(posting_date, posting_time) DESC, creation DESC |
Rushabh Mehta | f850987 | 2014-10-08 12:03:19 +0530 | [diff] [blame] | 72 | """.format(condition), values, as_dict=1) |
Anand Doshi | 2ce39cf | 2014-04-07 18:51:58 +0530 | [diff] [blame] | 73 | |
Nabin Hait | 0dd7be1 | 2013-08-02 11:45:43 +0530 | [diff] [blame] | 74 | sle_map = {} |
| 75 | for sle in stock_ledger_entries: |
Achilles Rasquinha | b4de7e3 | 2018-03-09 12:35:47 +0530 | [diff] [blame] | 76 | if not (sle.item_code, sle.warehouse) in sle_map: |
Nabin Hait | 949a920 | 2017-07-05 13:55:41 +0530 | [diff] [blame] | 77 | sle_map[(sle.item_code, sle.warehouse)] = flt(sle.stock_value) |
Sachin Mane | 19a5a5d | 2018-06-21 13:01:48 +0530 | [diff] [blame] | 78 | |
Nabin Hait | 625da79 | 2013-09-25 10:32:51 +0530 | [diff] [blame] | 79 | return sum(sle_map.values()) |
Anand Doshi | 2ce39cf | 2014-04-07 18:51:58 +0530 | [diff] [blame] | 80 | |
nick9822 | 6f48d4b | 2017-01-09 12:12:36 +0530 | [diff] [blame] | 81 | @frappe.whitelist() |
Rohit Waghchaure | 560f822 | 2020-04-06 15:02:43 +0530 | [diff] [blame] | 82 | def get_stock_balance(item_code, warehouse, posting_date=None, posting_time=None, |
| 83 | with_valuation_rate=False, with_serial_no=False): |
Rushabh Mehta | 2712e36 | 2015-02-17 12:50:20 +0530 | [diff] [blame] | 84 | """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 Mehta | dc93e0a | 2015-02-20 15:11:56 +0530 | [diff] [blame] | 87 | |
| 88 | from erpnext.stock.stock_ledger import get_previous_sle |
| 89 | |
rohitwaghchaure | f02e6b4 | 2022-01-03 14:28:34 +0530 | [diff] [blame] | 90 | if posting_date is None: posting_date = nowdate() |
| 91 | if posting_time is None: posting_time = nowtime() |
Rushabh Mehta | dc93e0a | 2015-02-20 15:11:56 +0530 | [diff] [blame] | 92 | |
Rohit Waghchaure | 560f822 | 2020-04-06 15:02:43 +0530 | [diff] [blame] | 93 | args = { |
Rushabh Mehta | dc93e0a | 2015-02-20 15:11:56 +0530 | [diff] [blame] | 94 | "item_code": item_code, |
| 95 | "warehouse":warehouse, |
| 96 | "posting_date": posting_date, |
Rohit Waghchaure | 560f822 | 2020-04-06 15:02:43 +0530 | [diff] [blame] | 97 | "posting_time": posting_time |
| 98 | } |
| 99 | |
| 100 | last_entry = get_previous_sle(args) |
Rushabh Mehta | f850987 | 2014-10-08 12:03:19 +0530 | [diff] [blame] | 101 | |
Rushabh Mehta | 2712e36 | 2015-02-17 12:50:20 +0530 | [diff] [blame] | 102 | if with_valuation_rate: |
Rohit Waghchaure | 560f822 | 2020-04-06 15:02:43 +0530 | [diff] [blame] | 103 | if with_serial_no: |
Ankush Menat | 2aa019a | 2021-10-29 14:32:13 +0530 | [diff] [blame] | 104 | serial_nos = get_serial_nos_data_after_transactions(args) |
Rohit Waghchaure | 560f822 | 2020-04-06 15:02:43 +0530 | [diff] [blame] | 105 | |
| 106 | return ((last_entry.qty_after_transaction, last_entry.valuation_rate, serial_nos) |
Ankush Menat | 33c4a0b | 2022-01-21 14:04:09 +0530 | [diff] [blame] | 107 | if last_entry else (0.0, 0.0, None)) |
Rohit Waghchaure | 560f822 | 2020-04-06 15:02:43 +0530 | [diff] [blame] | 108 | else: |
| 109 | return (last_entry.qty_after_transaction, last_entry.valuation_rate) if last_entry else (0.0, 0.0) |
Rushabh Mehta | f850987 | 2014-10-08 12:03:19 +0530 | [diff] [blame] | 110 | else: |
nick9822 | cc699a9 | 2017-06-20 17:13:29 +0530 | [diff] [blame] | 111 | return last_entry.qty_after_transaction if last_entry else 0.0 |
Rushabh Mehta | f850987 | 2014-10-08 12:03:19 +0530 | [diff] [blame] | 112 | |
Rohit Waghchaure | 560f822 | 2020-04-06 15:02:43 +0530 | [diff] [blame] | 113 | def get_serial_nos_data_after_transactions(args): |
Noah Jacob | deb6b38 | 2021-10-21 17:17:11 +0530 | [diff] [blame] | 114 | from pypika import CustomFunction |
| 115 | |
Ankush Menat | f4b60a4 | 2021-10-29 14:56:54 +0530 | [diff] [blame] | 116 | serial_nos = set() |
Noah Jacob | deb6b38 | 2021-10-21 17:17:11 +0530 | [diff] [blame] | 117 | args = frappe._dict(args) |
| 118 | sle = frappe.qb.DocType('Stock Ledger Entry') |
| 119 | Timestamp = CustomFunction('timestamp', ['date', 'time']) |
| 120 | |
Ankush Menat | f4b60a4 | 2021-10-29 14:56:54 +0530 | [diff] [blame] | 121 | stock_ledger_entries = frappe.qb.from_( |
Noah Jacob | deb6b38 | 2021-10-21 17:17:11 +0530 | [diff] [blame] | 122 | 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 Menat | ff9cfe0 | 2021-10-29 16:30:12 +0530 | [diff] [blame] | 131 | sle.posting_date, sle.posting_time, sle.creation |
Noah Jacob | deb6b38 | 2021-10-21 17:17:11 +0530 | [diff] [blame] | 132 | ).run(as_dict=1) |
Rohit Waghchaure | 560f822 | 2020-04-06 15:02:43 +0530 | [diff] [blame] | 133 | |
Ankush Menat | f4b60a4 | 2021-10-29 14:56:54 +0530 | [diff] [blame] | 134 | 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 Waghchaure | 560f822 | 2020-04-06 15:02:43 +0530 | [diff] [blame] | 138 | else: |
Ankush Menat | f4b60a4 | 2021-10-29 14:56:54 +0530 | [diff] [blame] | 139 | serial_nos.difference_update(changed_serial_no) |
Rohit Waghchaure | 560f822 | 2020-04-06 15:02:43 +0530 | [diff] [blame] | 140 | |
| 141 | return '\n'.join(serial_nos) |
| 142 | |
| 143 | def 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 Hait | 949a920 | 2017-07-05 13:55:41 +0530 | [diff] [blame] | 147 | @frappe.whitelist() |
| 148 | def 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 Mane | 19a5a5d | 2018-06-21 13:01:48 +0530 | [diff] [blame] | 152 | |
Nabin Hait | 949a920 | 2017-07-05 13:55:41 +0530 | [diff] [blame] | 153 | 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 Mane | 19a5a5d | 2018-06-21 13:01:48 +0530 | [diff] [blame] | 158 | |
Nabin Hait | 949a920 | 2017-07-05 13:55:41 +0530 | [diff] [blame] | 159 | else: |
| 160 | values.append(warehouse) |
| 161 | condition += " AND warehouse = %s" |
Sachin Mane | 19a5a5d | 2018-06-21 13:01:48 +0530 | [diff] [blame] | 162 | |
Nabin Hait | 949a920 | 2017-07-05 13:55:41 +0530 | [diff] [blame] | 163 | 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 Hait | 47dc318 | 2013-08-06 15:58:16 +0530 | [diff] [blame] | 169 | def get_latest_stock_balance(): |
| 170 | bin_map = {} |
Anand Doshi | 2ce39cf | 2014-04-07 18:51:58 +0530 | [diff] [blame] | 171 | for d in frappe.db.sql("""SELECT item_code, warehouse, stock_value as stock_value |
Nabin Hait | 47dc318 | 2013-08-06 15:58:16 +0530 | [diff] [blame] | 172 | FROM tabBin""", as_dict=1): |
Nabin Hait | 469ee71 | 2013-08-07 12:33:37 +0530 | [diff] [blame] | 173 | bin_map.setdefault(d.warehouse, {}).setdefault(d.item_code, flt(d.stock_value)) |
Anand Doshi | 2ce39cf | 2014-04-07 18:51:58 +0530 | [diff] [blame] | 174 | |
Nabin Hait | 47dc318 | 2013-08-06 15:58:16 +0530 | [diff] [blame] | 175 | return bin_map |
Anand Doshi | 2ce39cf | 2014-04-07 18:51:58 +0530 | [diff] [blame] | 176 | |
Nabin Hait | 74c281c | 2013-08-19 16:17:18 +0530 | [diff] [blame] | 177 | def get_bin(item_code, warehouse): |
Anand Doshi | e9baaa6 | 2014-02-26 12:35:33 +0530 | [diff] [blame] | 178 | bin = frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse}) |
Nabin Hait | 74c281c | 2013-08-19 16:17:18 +0530 | [diff] [blame] | 179 | if not bin: |
Ankush Menat | 08810db | 2022-01-30 16:25:42 +0530 | [diff] [blame] | 180 | bin_obj = _create_bin(item_code, warehouse) |
Nabin Hait | 74c281c | 2013-08-19 16:17:18 +0530 | [diff] [blame] | 181 | else: |
rohitwaghchaure | 00ea336 | 2021-05-01 13:53:39 +0530 | [diff] [blame] | 182 | bin_obj = frappe.get_doc('Bin', bin, for_update=True) |
Anand Doshi | 6dfd430 | 2015-02-10 14:41:27 +0530 | [diff] [blame] | 183 | bin_obj.flags.ignore_permissions = True |
Nabin Hait | 74c281c | 2013-08-19 16:17:18 +0530 | [diff] [blame] | 184 | return bin_obj |
| 185 | |
Ankush Menat | 97060c4 | 2021-12-03 11:50:38 +0530 | [diff] [blame] | 186 | def get_or_make_bin(item_code: str , warehouse: str) -> str: |
Deepesh Garg | 6f107da | 2021-10-12 20:15:55 +0530 | [diff] [blame] | 187 | bin_record = frappe.db.get_value('Bin', {'item_code': item_code, 'warehouse': warehouse}) |
| 188 | |
| 189 | if not bin_record: |
Ankush Menat | 08810db | 2022-01-30 16:25:42 +0530 | [diff] [blame] | 190 | bin_obj = _create_bin(item_code, warehouse) |
| 191 | bin_record = bin_obj.name |
| 192 | return bin_record |
| 193 | |
| 194 | def _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 Garg | 6f107da | 2021-10-12 20:15:55 +0530 | [diff] [blame] | 201 | bin_obj.flags.ignore_permissions = 1 |
| 202 | bin_obj.insert() |
Ankush Menat | 08810db | 2022-01-30 16:25:42 +0530 | [diff] [blame] | 203 | 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 Garg | 6f107da | 2021-10-12 20:15:55 +0530 | [diff] [blame] | 206 | |
Ankush Menat | 08810db | 2022-01-30 16:25:42 +0530 | [diff] [blame] | 207 | return bin_obj |
Deepesh Garg | 6f107da | 2021-10-12 20:15:55 +0530 | [diff] [blame] | 208 | |
Nabin Hait | 5eefff1 | 2015-12-07 10:44:56 +0530 | [diff] [blame] | 209 | @frappe.whitelist() |
Nabin Hait | 7ba092e | 2018-02-01 10:51:27 +0530 | [diff] [blame] | 210 | def get_incoming_rate(args, raise_error_if_no_rate=True): |
Nabin Hait | 9d0f636 | 2013-01-07 18:51:11 +0530 | [diff] [blame] | 211 | """Get Incoming Rate based on valuation method""" |
Ankush Menat | ab92652 | 2022-02-19 15:37:03 +0530 | [diff] [blame] | 212 | from erpnext.stock.stock_ledger import ( |
| 213 | get_batch_incoming_rate, |
| 214 | get_previous_sle, |
| 215 | get_valuation_rate, |
| 216 | ) |
Ankush Menat | 8fe5feb | 2021-11-04 19:48:32 +0530 | [diff] [blame] | 217 | if isinstance(args, str): |
Nabin Hait | 41c8cf6 | 2015-12-08 14:50:24 +0530 | [diff] [blame] | 218 | args = json.loads(args) |
Anand Doshi | 2ce39cf | 2014-04-07 18:51:58 +0530 | [diff] [blame] | 219 | |
Ankush Menat | ab92652 | 2022-02-19 15:37:03 +0530 | [diff] [blame] | 220 | voucher_no = args.get('voucher_no') or args.get('name') |
| 221 | |
| 222 | in_rate = None |
Anand Doshi | 40a8ae2 | 2014-08-29 16:28:31 +0530 | [diff] [blame] | 223 | if (args.get("serial_no") or "").strip(): |
Nabin Hait | 9d0f636 | 2013-01-07 18:51:11 +0530 | [diff] [blame] | 224 | in_rate = get_avg_purchase_rate(args.get("serial_no")) |
Ankush Menat | ab92652 | 2022-02-19 15:37:03 +0530 | [diff] [blame] | 225 | elif args.get("batch_no") and \ |
| 226 | frappe.db.get_value("Batch", args.get("batch_no"), "use_batchwise_valuation", cache=True): |
| 227 | in_rate = get_batch_incoming_rate( |
| 228 | item_code=args.get('item_code'), |
| 229 | warehouse=args.get('warehouse'), |
| 230 | batch_no=args.get("batch_no"), |
| 231 | posting_date=args.get("posting_date"), |
| 232 | posting_time=args.get("posting_time"), |
| 233 | ) |
Nabin Hait | 9d0f636 | 2013-01-07 18:51:11 +0530 | [diff] [blame] | 234 | else: |
| 235 | valuation_method = get_valuation_method(args.get("item_code")) |
| 236 | previous_sle = get_previous_sle(args) |
Ankush Menat | 61c5ad4 | 2022-01-15 18:06:50 +0530 | [diff] [blame] | 237 | if valuation_method in ('FIFO', 'LIFO'): |
rohitwaghchaure | ce8adec | 2017-12-15 12:13:50 +0530 | [diff] [blame] | 238 | if previous_sle: |
| 239 | previous_stock_queue = json.loads(previous_sle.get('stock_queue', '[]') or '[]') |
Ankush Menat | 61c5ad4 | 2022-01-15 18:06:50 +0530 | [diff] [blame] | 240 | in_rate = _get_fifo_lifo_rate(previous_stock_queue, args.get("qty") or 0, valuation_method) if previous_stock_queue else 0 |
Nabin Hait | 9d0f636 | 2013-01-07 18:51:11 +0530 | [diff] [blame] | 241 | elif valuation_method == 'Moving Average': |
| 242 | in_rate = previous_sle.get('valuation_rate') or 0 |
Anand Doshi | 094610d | 2014-04-16 19:56:53 +0530 | [diff] [blame] | 243 | |
Ankush Menat | ab92652 | 2022-02-19 15:37:03 +0530 | [diff] [blame] | 244 | if in_rate is None: |
rohitwaghchaure | ce8adec | 2017-12-15 12:13:50 +0530 | [diff] [blame] | 245 | in_rate = get_valuation_rate(args.get('item_code'), args.get('warehouse'), |
| 246 | args.get('voucher_type'), voucher_no, args.get('allow_zero_valuation'), |
Nabin Hait | 7ba092e | 2018-02-01 10:51:27 +0530 | [diff] [blame] | 247 | currency=erpnext.get_company_currency(args.get('company')), company=args.get('company'), |
Ankush Menat | 342d09a | 2022-02-19 14:28:51 +0530 | [diff] [blame] | 248 | raise_error_if_no_rate=raise_error_if_no_rate, batch_no=args.get("batch_no")) |
rohitwaghchaure | ce8adec | 2017-12-15 12:13:50 +0530 | [diff] [blame] | 249 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 250 | return flt(in_rate) |
Anand Doshi | 2ce39cf | 2014-04-07 18:51:58 +0530 | [diff] [blame] | 251 | |
Nabin Hait | 9d0f636 | 2013-01-07 18:51:11 +0530 | [diff] [blame] | 252 | def get_avg_purchase_rate(serial_nos): |
| 253 | """get average value of serial numbers""" |
Anand Doshi | 2ce39cf | 2014-04-07 18:51:58 +0530 | [diff] [blame] | 254 | |
Nabin Hait | 9d0f636 | 2013-01-07 18:51:11 +0530 | [diff] [blame] | 255 | serial_nos = get_valid_serial_nos(serial_nos) |
Anand Doshi | 602e825 | 2015-11-16 19:05:46 +0530 | [diff] [blame] | 256 | return flt(frappe.db.sql("""select avg(purchase_rate) from `tabSerial No` |
Nabin Hait | 9d0f636 | 2013-01-07 18:51:11 +0530 | [diff] [blame] | 257 | where name in (%s)""" % ", ".join(["%s"] * len(serial_nos)), |
| 258 | tuple(serial_nos))[0][0]) |
| 259 | |
| 260 | def get_valuation_method(item_code): |
| 261 | """get valuation method from item or default""" |
Ankush | 9152715 | 2021-08-11 11:17:50 +0530 | [diff] [blame] | 262 | val_method = frappe.db.get_value('Item', item_code, 'valuation_method', cache=True) |
Nabin Hait | 9d0f636 | 2013-01-07 18:51:11 +0530 | [diff] [blame] | 263 | if not val_method: |
Ankush Menat | f38690f | 2022-02-20 12:58:53 +0530 | [diff] [blame] | 264 | val_method = frappe.db.get_value("Stock Settings", None, "valuation_method", cache=True) or "FIFO" |
Nabin Hait | 9d0f636 | 2013-01-07 18:51:11 +0530 | [diff] [blame] | 265 | return val_method |
Anand Doshi | 2ce39cf | 2014-04-07 18:51:58 +0530 | [diff] [blame] | 266 | |
Nabin Hait | 831207f | 2013-01-16 14:15:48 +0530 | [diff] [blame] | 267 | def get_fifo_rate(previous_stock_queue, qty): |
| 268 | """get FIFO (average) Rate from Queue""" |
Ankush Menat | 61c5ad4 | 2022-01-15 18:06:50 +0530 | [diff] [blame] | 269 | return _get_fifo_lifo_rate(previous_stock_queue, qty, "FIFO") |
Anand Doshi | 094610d | 2014-04-16 19:56:53 +0530 | [diff] [blame] | 270 | |
Ankush Menat | 61c5ad4 | 2022-01-15 18:06:50 +0530 | [diff] [blame] | 271 | def get_lifo_rate(previous_stock_queue, qty): |
| 272 | """get LIFO (average) Rate from Queue""" |
| 273 | return _get_fifo_lifo_rate(previous_stock_queue, qty, "LIFO") |
| 274 | |
| 275 | |
| 276 | def _get_fifo_lifo_rate(previous_stock_queue, qty, method): |
| 277 | ValuationKlass = LIFOValuation if method == "LIFO" else FIFOValuation |
| 278 | |
| 279 | stock_queue = ValuationKlass(previous_stock_queue) |
| 280 | if flt(qty) >= 0: |
| 281 | total_qty, total_value = stock_queue.get_total_stock_and_value() |
| 282 | return total_value / total_qty if total_qty else 0.0 |
| 283 | else: |
| 284 | popped_bins = stock_queue.remove_stock(abs(flt(qty))) |
| 285 | |
| 286 | total_qty, total_value = ValuationKlass(popped_bins).get_total_stock_and_value() |
| 287 | return total_value / total_qty if total_qty else 0.0 |
Anand Doshi | 2ce39cf | 2014-04-07 18:51:58 +0530 | [diff] [blame] | 288 | |
Nabin Hait | 9d0f636 | 2013-01-07 18:51:11 +0530 | [diff] [blame] | 289 | def get_valid_serial_nos(sr_nos, qty=0, item_code=''): |
| 290 | """split serial nos, validate and return list of valid serial nos""" |
| 291 | # TODO: remove duplicates in client side |
| 292 | serial_nos = cstr(sr_nos).strip().replace(',', '\n').split('\n') |
Anand Doshi | 2ce39cf | 2014-04-07 18:51:58 +0530 | [diff] [blame] | 293 | |
Nabin Hait | 9d0f636 | 2013-01-07 18:51:11 +0530 | [diff] [blame] | 294 | valid_serial_nos = [] |
| 295 | for val in serial_nos: |
| 296 | if val: |
| 297 | val = val.strip() |
| 298 | if val in valid_serial_nos: |
Rushabh Mehta | 9f0d625 | 2014-04-14 19:20:45 +0530 | [diff] [blame] | 299 | frappe.throw(_("Serial number {0} entered more than once").format(val)) |
Nabin Hait | 9d0f636 | 2013-01-07 18:51:11 +0530 | [diff] [blame] | 300 | else: |
| 301 | valid_serial_nos.append(val) |
Anand Doshi | 2ce39cf | 2014-04-07 18:51:58 +0530 | [diff] [blame] | 302 | |
Nabin Hait | 9d0f636 | 2013-01-07 18:51:11 +0530 | [diff] [blame] | 303 | if qty and len(valid_serial_nos) != abs(qty): |
Rushabh Mehta | 9f0d625 | 2014-04-14 19:20:45 +0530 | [diff] [blame] | 304 | frappe.throw(_("{0} valid serial nos for Item {1}").format(abs(qty), item_code)) |
Anand Doshi | 2ce39cf | 2014-04-07 18:51:58 +0530 | [diff] [blame] | 305 | |
Rushabh Mehta | 0dbe898 | 2013-02-04 13:56:50 +0530 | [diff] [blame] | 306 | return valid_serial_nos |
Nabin Hait | a72c512 | 2013-03-06 18:50:53 +0530 | [diff] [blame] | 307 | |
Anand Doshi | 373680b | 2013-10-10 16:04:40 +0530 | [diff] [blame] | 308 | def validate_warehouse_company(warehouse, company): |
Ankush | 9152715 | 2021-08-11 11:17:50 +0530 | [diff] [blame] | 309 | warehouse_company = frappe.db.get_value("Warehouse", warehouse, "company", cache=True) |
Anand Doshi | 373680b | 2013-10-10 16:04:40 +0530 | [diff] [blame] | 310 | if warehouse_company and warehouse_company != company: |
Rushabh Mehta | 9f0d625 | 2014-04-14 19:20:45 +0530 | [diff] [blame] | 311 | frappe.throw(_("Warehouse {0} does not belong to company {1}").format(warehouse, company), |
| 312 | InvalidWarehouseCompany) |
Saurabh | 3d6aecd | 2016-06-20 17:25:45 +0530 | [diff] [blame] | 313 | |
Saurabh | 4d02949 | 2016-06-23 12:44:06 +0530 | [diff] [blame] | 314 | def is_group_warehouse(warehouse): |
Ankush | 9152715 | 2021-08-11 11:17:50 +0530 | [diff] [blame] | 315 | if frappe.db.get_value("Warehouse", warehouse, "is_group", cache=True): |
Saurabh | 4d02949 | 2016-06-23 12:44:06 +0530 | [diff] [blame] | 316 | frappe.throw(_("Group node warehouse is not allowed to select for transactions")) |
Saif | b4cf72c | 2018-10-18 17:29:47 +0500 | [diff] [blame] | 317 | |
Jannat Patel | 30c8873 | 2021-02-11 11:46:48 +0530 | [diff] [blame] | 318 | def validate_disabled_warehouse(warehouse): |
Ankush | 9152715 | 2021-08-11 11:17:50 +0530 | [diff] [blame] | 319 | if frappe.db.get_value("Warehouse", warehouse, "disabled", cache=True): |
Jannat Patel | 30c8873 | 2021-02-11 11:46:48 +0530 | [diff] [blame] | 320 | frappe.throw(_("Disabled Warehouse {0} cannot be used for this transaction.").format(get_link_to_form('Warehouse', warehouse))) |
| 321 | |
Saif | b4cf72c | 2018-10-18 17:29:47 +0500 | [diff] [blame] | 322 | def update_included_uom_in_report(columns, result, include_uom, conversion_factors): |
| 323 | if not include_uom or not conversion_factors: |
| 324 | return |
| 325 | |
| 326 | convertible_cols = {} |
rohitwaghchaure | ed1cc18 | 2019-09-30 15:15:52 +0530 | [diff] [blame] | 327 | is_dict_obj = False |
| 328 | if isinstance(result[0], dict): |
| 329 | is_dict_obj = True |
| 330 | |
| 331 | convertible_columns = {} |
| 332 | for idx, d in enumerate(columns): |
| 333 | key = d.get("fieldname") if is_dict_obj else idx |
| 334 | if d.get("convertible"): |
| 335 | convertible_columns.setdefault(key, d.get("convertible")) |
| 336 | |
| 337 | # Add new column to show qty/rate as per the selected UOM |
| 338 | columns.insert(idx+1, { |
| 339 | 'label': "{0} (per {1})".format(d.get("label"), include_uom), |
| 340 | 'fieldname': "{0}_{1}".format(d.get("fieldname"), frappe.scrub(include_uom)), |
| 341 | 'fieldtype': 'Currency' if d.get("convertible") == 'rate' else 'Float' |
| 342 | }) |
Saif | b4cf72c | 2018-10-18 17:29:47 +0500 | [diff] [blame] | 343 | |
rohitwaghchaure | 001ee5e | 2019-11-11 17:43:48 +0530 | [diff] [blame] | 344 | update_dict_values = [] |
Saif | b4cf72c | 2018-10-18 17:29:47 +0500 | [diff] [blame] | 345 | for row_idx, row in enumerate(result): |
rohitwaghchaure | ed1cc18 | 2019-09-30 15:15:52 +0530 | [diff] [blame] | 346 | data = row.items() if is_dict_obj else enumerate(row) |
| 347 | for key, value in data: |
Noah Jacob | d8668f7 | 2021-07-15 18:32:15 +0530 | [diff] [blame] | 348 | if key not in convertible_columns: |
rohitwaghchaure | ed1cc18 | 2019-09-30 15:15:52 +0530 | [diff] [blame] | 349 | continue |
Noah Jacob | d8668f7 | 2021-07-15 18:32:15 +0530 | [diff] [blame] | 350 | # If no conversion factor for the UOM, defaults to 1 |
| 351 | if not conversion_factors[row_idx]: |
| 352 | conversion_factors[row_idx] = 1 |
Saif | b4cf72c | 2018-10-18 17:29:47 +0500 | [diff] [blame] | 353 | |
rohitwaghchaure | ed1cc18 | 2019-09-30 15:15:52 +0530 | [diff] [blame] | 354 | if convertible_columns.get(key) == 'rate': |
Noah Jacob | d8668f7 | 2021-07-15 18:32:15 +0530 | [diff] [blame] | 355 | new_value = flt(value) * conversion_factors[row_idx] |
rohitwaghchaure | ed1cc18 | 2019-09-30 15:15:52 +0530 | [diff] [blame] | 356 | else: |
Noah Jacob | d8668f7 | 2021-07-15 18:32:15 +0530 | [diff] [blame] | 357 | new_value = flt(value) / conversion_factors[row_idx] |
rohitwaghchaure | ed1cc18 | 2019-09-30 15:15:52 +0530 | [diff] [blame] | 358 | |
| 359 | if not is_dict_obj: |
| 360 | row.insert(key+1, new_value) |
| 361 | else: |
| 362 | new_key = "{0}_{1}".format(key, frappe.scrub(include_uom)) |
rohitwaghchaure | 001ee5e | 2019-11-11 17:43:48 +0530 | [diff] [blame] | 363 | update_dict_values.append([row, new_key, new_value]) |
| 364 | |
| 365 | for data in update_dict_values: |
| 366 | row, key, value = data |
| 367 | row[key] = value |
Rohit Waghchaure | 05d3bcb | 2019-04-28 18:39:18 +0530 | [diff] [blame] | 368 | |
Rohit Waghchaure | cf55c9c | 2019-11-14 18:22:20 +0530 | [diff] [blame] | 369 | def get_available_serial_nos(args): |
| 370 | return frappe.db.sql(""" SELECT name from `tabSerial No` |
| 371 | WHERE item_code = %(item_code)s and warehouse = %(warehouse)s |
| 372 | and timestamp(purchase_date, purchase_time) <= timestamp(%(posting_date)s, %(posting_time)s) |
| 373 | """, args, as_dict=1) |
Suraj Shetty | bc001d2 | 2019-09-16 19:57:04 +0530 | [diff] [blame] | 374 | |
| 375 | def add_additional_uom_columns(columns, result, include_uom, conversion_factors): |
| 376 | if not include_uom or not conversion_factors: |
| 377 | return |
| 378 | |
| 379 | convertible_column_map = {} |
| 380 | for col_idx in list(reversed(range(0, len(columns)))): |
| 381 | col = columns[col_idx] |
| 382 | if isinstance(col, dict) and col.get('convertible') in ['rate', 'qty']: |
| 383 | next_col = col_idx + 1 |
| 384 | columns.insert(next_col, col.copy()) |
| 385 | columns[next_col]['fieldname'] += '_alt' |
| 386 | convertible_column_map[col.get('fieldname')] = frappe._dict({ |
| 387 | 'converted_col': columns[next_col]['fieldname'], |
| 388 | 'for_type': col.get('convertible') |
| 389 | }) |
| 390 | if col.get('convertible') == 'rate': |
| 391 | columns[next_col]['label'] += ' (per {})'.format(include_uom) |
| 392 | else: |
| 393 | columns[next_col]['label'] += ' ({})'.format(include_uom) |
| 394 | |
| 395 | for row_idx, row in enumerate(result): |
| 396 | for convertible_col, data in convertible_column_map.items(): |
| 397 | conversion_factor = conversion_factors[row.get('item_code')] or 1 |
| 398 | for_type = data.for_type |
| 399 | value_before_conversion = row.get(convertible_col) |
| 400 | if for_type == 'rate': |
| 401 | row[data.converted_col] = flt(value_before_conversion) * conversion_factor |
| 402 | else: |
| 403 | row[data.converted_col] = flt(value_before_conversion) / conversion_factor |
| 404 | |
Deepesh Garg | 2a9c5ba | 2020-04-30 10:38:58 +0530 | [diff] [blame] | 405 | result[row_idx] = row |
| 406 | |
| 407 | def get_incoming_outgoing_rate_for_cancel(item_code, voucher_type, voucher_no, voucher_detail_no): |
| 408 | outgoing_rate = frappe.db.sql("""SELECT abs(stock_value_difference / actual_qty) |
| 409 | FROM `tabStock Ledger Entry` |
| 410 | WHERE voucher_type = %s and voucher_no = %s |
| 411 | and item_code = %s and voucher_detail_no = %s |
| 412 | ORDER BY CREATION DESC limit 1""", |
| 413 | (voucher_type, voucher_no, item_code, voucher_detail_no)) |
| 414 | |
| 415 | outgoing_rate = outgoing_rate[0][0] if outgoing_rate else 0.0 |
| 416 | |
Nabin Hait | a77b8c9 | 2020-12-21 14:45:50 +0530 | [diff] [blame] | 417 | return outgoing_rate |
| 418 | |
| 419 | def is_reposting_item_valuation_in_progress(): |
| 420 | reposting_in_progress = frappe.db.exists("Repost Item Valuation", |
| 421 | {'docstatus': 1, 'status': ['in', ['Queued','In Progress']]}) |
| 422 | if reposting_in_progress: |
Noah Jacob | d8668f7 | 2021-07-15 18:32:15 +0530 | [diff] [blame] | 423 | frappe.msgprint(_("Item valuation reposting in progress. Report might show incorrect item valuation."), alert=1) |
Ankush Menat | d37541d | 2021-12-10 12:04:10 +0530 | [diff] [blame] | 424 | |
| 425 | def check_pending_reposting(posting_date: str, throw_error: bool = True) -> bool: |
| 426 | """Check if there are pending reposting job till the specified posting date.""" |
| 427 | |
| 428 | filters = { |
| 429 | "docstatus": 1, |
| 430 | "status": ["in", ["Queued","In Progress", "Failed"]], |
| 431 | "posting_date": ["<=", posting_date], |
| 432 | } |
| 433 | |
| 434 | reposting_pending = frappe.db.exists("Repost Item Valuation", filters) |
| 435 | if reposting_pending and throw_error: |
| 436 | msg = _("Stock/Accounts can not be frozen as processing of backdated entries is going on. Please try again later.") |
| 437 | frappe.msgprint(msg, |
Ankush Menat | 75bc404 | 2021-12-10 12:39:38 +0530 | [diff] [blame] | 438 | raise_exception=PendingRepostingError, |
Ankush Menat | d37541d | 2021-12-10 12:04:10 +0530 | [diff] [blame] | 439 | title="Stock Reposting Ongoing", |
| 440 | indicator="red", |
| 441 | primary_action={ |
| 442 | "label": _("Show pending entries"), |
| 443 | "client_action": "erpnext.route_to_pending_reposts", |
| 444 | "args": filters, |
| 445 | } |
| 446 | ) |
| 447 | |
| 448 | return bool(reposting_pending) |