blob: aeb06e987f8aa0e3e12076f2760c70a613dabfde [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
Anand Doshid57e7932015-02-24 12:24:53 +05304from __future__ import unicode_literals
Nabin Hait9d0f6362013-01-07 18:51:11 +05305
Chillar Anand915b3432021-09-02 16:44:59 +05306import json
7
8import frappe
9from frappe import _
10from frappe.utils import cstr, flt, get_link_to_form, nowdate, nowtime
Achilles Rasquinha56b2e122018-02-13 14:42:40 +053011from six import string_types
12
Chillar Anand915b3432021-09-02 16:44:59 +053013import erpnext
14
15
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053016class InvalidWarehouseCompany(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
Rushabh Mehtaf8509872014-10-08 12:03:19 +053090 if not posting_date: posting_date = nowdate()
91 if not posting_time: 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:
104 serial_nos = last_entry.get("serial_no")
105
106 if (serial_nos and
107 len(get_serial_nos_data(serial_nos)) < last_entry.qty_after_transaction):
108 serial_nos = get_serial_nos_data_after_transactions(args)
109
110 return ((last_entry.qty_after_transaction, last_entry.valuation_rate, serial_nos)
111 if last_entry else (0.0, 0.0, 0.0))
112 else:
113 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 +0530114 else:
nick9822cc699a92017-06-20 17:13:29 +0530115 return last_entry.qty_after_transaction if last_entry else 0.0
Rushabh Mehtaf8509872014-10-08 12:03:19 +0530116
Rohit Waghchaure560f8222020-04-06 15:02:43 +0530117def get_serial_nos_data_after_transactions(args):
118 serial_nos = []
119 data = frappe.db.sql(""" SELECT serial_no, actual_qty
120 FROM `tabStock Ledger Entry`
121 WHERE
122 item_code = %(item_code)s and warehouse = %(warehouse)s
123 and timestamp(posting_date, posting_time) < timestamp(%(posting_date)s, %(posting_time)s)
124 order by posting_date, posting_time asc """, args, as_dict=1)
125
126 for d in data:
127 if d.actual_qty > 0:
128 serial_nos.extend(get_serial_nos_data(d.serial_no))
129 else:
130 serial_nos = list(set(serial_nos) - set(get_serial_nos_data(d.serial_no)))
131
132 return '\n'.join(serial_nos)
133
134def get_serial_nos_data(serial_nos):
135 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
136 return get_serial_nos(serial_nos)
137
Nabin Hait949a9202017-07-05 13:55:41 +0530138@frappe.whitelist()
139def get_latest_stock_qty(item_code, warehouse=None):
140 values, condition = [item_code], ""
141 if warehouse:
142 lft, rgt, is_group = frappe.db.get_value("Warehouse", warehouse, ["lft", "rgt", "is_group"])
Sachin Mane19a5a5d2018-06-21 13:01:48 +0530143
Nabin Hait949a9202017-07-05 13:55:41 +0530144 if is_group:
145 values.extend([lft, rgt])
146 condition += "and exists (\
147 select name from `tabWarehouse` wh where wh.name = tabBin.warehouse\
148 and wh.lft >= %s and wh.rgt <= %s)"
Sachin Mane19a5a5d2018-06-21 13:01:48 +0530149
Nabin Hait949a9202017-07-05 13:55:41 +0530150 else:
151 values.append(warehouse)
152 condition += " AND warehouse = %s"
Sachin Mane19a5a5d2018-06-21 13:01:48 +0530153
Nabin Hait949a9202017-07-05 13:55:41 +0530154 actual_qty = frappe.db.sql("""select sum(actual_qty) from tabBin
155 where item_code=%s {0}""".format(condition), values)[0][0]
156
157 return actual_qty
158
159
Nabin Hait47dc3182013-08-06 15:58:16 +0530160def get_latest_stock_balance():
161 bin_map = {}
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530162 for d in frappe.db.sql("""SELECT item_code, warehouse, stock_value as stock_value
Nabin Hait47dc3182013-08-06 15:58:16 +0530163 FROM tabBin""", as_dict=1):
Nabin Hait469ee712013-08-07 12:33:37 +0530164 bin_map.setdefault(d.warehouse, {}).setdefault(d.item_code, flt(d.stock_value))
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530165
Nabin Hait47dc3182013-08-06 15:58:16 +0530166 return bin_map
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530167
Nabin Hait74c281c2013-08-19 16:17:18 +0530168def get_bin(item_code, warehouse):
Anand Doshie9baaa62014-02-26 12:35:33 +0530169 bin = frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse})
Nabin Hait74c281c2013-08-19 16:17:18 +0530170 if not bin:
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530171 bin_obj = frappe.get_doc({
Nabin Hait74c281c2013-08-19 16:17:18 +0530172 "doctype": "Bin",
173 "item_code": item_code,
174 "warehouse": warehouse,
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530175 })
Anand Doshi6dfd4302015-02-10 14:41:27 +0530176 bin_obj.flags.ignore_permissions = 1
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530177 bin_obj.insert()
Nabin Hait74c281c2013-08-19 16:17:18 +0530178 else:
rohitwaghchaure00ea3362021-05-01 13:53:39 +0530179 bin_obj = frappe.get_doc('Bin', bin, for_update=True)
Anand Doshi6dfd4302015-02-10 14:41:27 +0530180 bin_obj.flags.ignore_permissions = True
Nabin Hait74c281c2013-08-19 16:17:18 +0530181 return bin_obj
182
Nabin Hait54c865e2015-03-27 15:38:31 +0530183def update_bin(args, allow_negative_stock=False, via_landed_cost_voucher=False):
Rohit Waghchaure4d81d452021-06-15 10:21:44 +0530184 is_stock_item = frappe.get_cached_value('Item', args.get("item_code"), 'is_stock_item')
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530185 if is_stock_item:
Nabin Hait74c281c2013-08-19 16:17:18 +0530186 bin = get_bin(args.get("item_code"), args.get("warehouse"))
Nabin Hait54c865e2015-03-27 15:38:31 +0530187 bin.update_stock(args, allow_negative_stock, via_landed_cost_voucher)
Nabin Hait74c281c2013-08-19 16:17:18 +0530188 return bin
189 else:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530190 frappe.msgprint(_("Item {0} ignored since it is not a stock item").format(args.get("item_code")))
Nabin Hait0dd7be12013-08-02 11:45:43 +0530191
Nabin Hait5eefff12015-12-07 10:44:56 +0530192@frappe.whitelist()
Nabin Hait7ba092e2018-02-01 10:51:27 +0530193def get_incoming_rate(args, raise_error_if_no_rate=True):
Nabin Hait9d0f6362013-01-07 18:51:11 +0530194 """Get Incoming Rate based on valuation method"""
rohitwaghchaurece8adec2017-12-15 12:13:50 +0530195 from erpnext.stock.stock_ledger import get_previous_sle, get_valuation_rate
Achilles Rasquinha56b2e122018-02-13 14:42:40 +0530196 if isinstance(args, string_types):
Nabin Hait41c8cf62015-12-08 14:50:24 +0530197 args = json.loads(args)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530198
Nabin Hait9d0f6362013-01-07 18:51:11 +0530199 in_rate = 0
Anand Doshi40a8ae22014-08-29 16:28:31 +0530200 if (args.get("serial_no") or "").strip():
Nabin Hait9d0f6362013-01-07 18:51:11 +0530201 in_rate = get_avg_purchase_rate(args.get("serial_no"))
Nabin Hait9d0f6362013-01-07 18:51:11 +0530202 else:
203 valuation_method = get_valuation_method(args.get("item_code"))
204 previous_sle = get_previous_sle(args)
205 if valuation_method == 'FIFO':
rohitwaghchaurece8adec2017-12-15 12:13:50 +0530206 if previous_sle:
207 previous_stock_queue = json.loads(previous_sle.get('stock_queue', '[]') or '[]')
208 in_rate = get_fifo_rate(previous_stock_queue, args.get("qty") or 0) if previous_stock_queue else 0
Nabin Hait9d0f6362013-01-07 18:51:11 +0530209 elif valuation_method == 'Moving Average':
210 in_rate = previous_sle.get('valuation_rate') or 0
Anand Doshi094610d2014-04-16 19:56:53 +0530211
rohitwaghchaurece8adec2017-12-15 12:13:50 +0530212 if not in_rate:
213 voucher_no = args.get('voucher_no') or args.get('name')
rohitwaghchaurece8adec2017-12-15 12:13:50 +0530214 in_rate = get_valuation_rate(args.get('item_code'), args.get('warehouse'),
215 args.get('voucher_type'), voucher_no, args.get('allow_zero_valuation'),
Nabin Hait7ba092e2018-02-01 10:51:27 +0530216 currency=erpnext.get_company_currency(args.get('company')), company=args.get('company'),
Rohit Waghchaure87c4b062019-06-01 14:22:46 +0530217 raise_error_if_no_rate=raise_error_if_no_rate)
rohitwaghchaurece8adec2017-12-15 12:13:50 +0530218
Nabin Haita77b8c92020-12-21 14:45:50 +0530219 return flt(in_rate)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530220
Nabin Hait9d0f6362013-01-07 18:51:11 +0530221def get_avg_purchase_rate(serial_nos):
222 """get average value of serial numbers"""
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530223
Nabin Hait9d0f6362013-01-07 18:51:11 +0530224 serial_nos = get_valid_serial_nos(serial_nos)
Anand Doshi602e8252015-11-16 19:05:46 +0530225 return flt(frappe.db.sql("""select avg(purchase_rate) from `tabSerial No`
Nabin Hait9d0f6362013-01-07 18:51:11 +0530226 where name in (%s)""" % ", ".join(["%s"] * len(serial_nos)),
227 tuple(serial_nos))[0][0])
228
229def get_valuation_method(item_code):
230 """get valuation method from item or default"""
Ankush91527152021-08-11 11:17:50 +0530231 val_method = frappe.db.get_value('Item', item_code, 'valuation_method', cache=True)
Nabin Hait9d0f6362013-01-07 18:51:11 +0530232 if not val_method:
Nabin Hait4d742162014-10-09 19:25:03 +0530233 val_method = frappe.db.get_value("Stock Settings", None, "valuation_method") or "FIFO"
Nabin Hait9d0f6362013-01-07 18:51:11 +0530234 return val_method
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530235
Nabin Hait831207f2013-01-16 14:15:48 +0530236def get_fifo_rate(previous_stock_queue, qty):
237 """get FIFO (average) Rate from Queue"""
marination6f7e9d22020-06-03 17:13:58 +0530238 if flt(qty) >= 0:
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530239 total = sum(f[0] for f in previous_stock_queue)
Nabin Hait38265ef2014-10-21 20:23:39 +0530240 return sum(flt(f[0]) * flt(f[1]) for f in previous_stock_queue) / flt(total) if total else 0.0
Nabin Hait831207f2013-01-16 14:15:48 +0530241 else:
Nabin Hait227db762014-05-08 19:06:01 +0530242 available_qty_for_outgoing, outgoing_cost = 0, 0
marination6f7e9d22020-06-03 17:13:58 +0530243 qty_to_pop = abs(flt(qty))
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530244 while qty_to_pop and previous_stock_queue:
Nabin Hait831207f2013-01-16 14:15:48 +0530245 batch = previous_stock_queue[0]
Nabin Hait8142cd22015-08-05 18:57:26 +0530246 if 0 < batch[0] <= qty_to_pop:
247 # if batch qty > 0
248 # not enough or exactly same qty in current batch, clear batch
249 available_qty_for_outgoing += flt(batch[0])
250 outgoing_cost += flt(batch[0]) * flt(batch[1])
251 qty_to_pop -= batch[0]
252 previous_stock_queue.pop(0)
253 else:
254 # all from current batch
255 available_qty_for_outgoing += flt(qty_to_pop)
256 outgoing_cost += flt(qty_to_pop) * flt(batch[1])
257 batch[0] -= qty_to_pop
258 qty_to_pop = 0
Anand Doshi094610d2014-04-16 19:56:53 +0530259
Nabin Hait227db762014-05-08 19:06:01 +0530260 return outgoing_cost / available_qty_for_outgoing
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530261
Nabin Hait9d0f6362013-01-07 18:51:11 +0530262def get_valid_serial_nos(sr_nos, qty=0, item_code=''):
263 """split serial nos, validate and return list of valid serial nos"""
264 # TODO: remove duplicates in client side
265 serial_nos = cstr(sr_nos).strip().replace(',', '\n').split('\n')
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530266
Nabin Hait9d0f6362013-01-07 18:51:11 +0530267 valid_serial_nos = []
268 for val in serial_nos:
269 if val:
270 val = val.strip()
271 if val in valid_serial_nos:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530272 frappe.throw(_("Serial number {0} entered more than once").format(val))
Nabin Hait9d0f6362013-01-07 18:51:11 +0530273 else:
274 valid_serial_nos.append(val)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530275
Nabin Hait9d0f6362013-01-07 18:51:11 +0530276 if qty and len(valid_serial_nos) != abs(qty):
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530277 frappe.throw(_("{0} valid serial nos for Item {1}").format(abs(qty), item_code))
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530278
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530279 return valid_serial_nos
Nabin Haita72c5122013-03-06 18:50:53 +0530280
Anand Doshi373680b2013-10-10 16:04:40 +0530281def validate_warehouse_company(warehouse, company):
Ankush91527152021-08-11 11:17:50 +0530282 warehouse_company = frappe.db.get_value("Warehouse", warehouse, "company", cache=True)
Anand Doshi373680b2013-10-10 16:04:40 +0530283 if warehouse_company and warehouse_company != company:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530284 frappe.throw(_("Warehouse {0} does not belong to company {1}").format(warehouse, company),
285 InvalidWarehouseCompany)
Saurabh3d6aecd2016-06-20 17:25:45 +0530286
Saurabh4d029492016-06-23 12:44:06 +0530287def is_group_warehouse(warehouse):
Ankush91527152021-08-11 11:17:50 +0530288 if frappe.db.get_value("Warehouse", warehouse, "is_group", cache=True):
Saurabh4d029492016-06-23 12:44:06 +0530289 frappe.throw(_("Group node warehouse is not allowed to select for transactions"))
Saifb4cf72c2018-10-18 17:29:47 +0500290
Jannat Patel30c88732021-02-11 11:46:48 +0530291def validate_disabled_warehouse(warehouse):
Ankush91527152021-08-11 11:17:50 +0530292 if frappe.db.get_value("Warehouse", warehouse, "disabled", cache=True):
Jannat Patel30c88732021-02-11 11:46:48 +0530293 frappe.throw(_("Disabled Warehouse {0} cannot be used for this transaction.").format(get_link_to_form('Warehouse', warehouse)))
294
Saifb4cf72c2018-10-18 17:29:47 +0500295def update_included_uom_in_report(columns, result, include_uom, conversion_factors):
296 if not include_uom or not conversion_factors:
297 return
298
299 convertible_cols = {}
rohitwaghchaureed1cc182019-09-30 15:15:52 +0530300 is_dict_obj = False
301 if isinstance(result[0], dict):
302 is_dict_obj = True
303
304 convertible_columns = {}
305 for idx, d in enumerate(columns):
306 key = d.get("fieldname") if is_dict_obj else idx
307 if d.get("convertible"):
308 convertible_columns.setdefault(key, d.get("convertible"))
309
310 # Add new column to show qty/rate as per the selected UOM
311 columns.insert(idx+1, {
312 'label': "{0} (per {1})".format(d.get("label"), include_uom),
313 'fieldname': "{0}_{1}".format(d.get("fieldname"), frappe.scrub(include_uom)),
314 'fieldtype': 'Currency' if d.get("convertible") == 'rate' else 'Float'
315 })
Saifb4cf72c2018-10-18 17:29:47 +0500316
rohitwaghchaure001ee5e2019-11-11 17:43:48 +0530317 update_dict_values = []
Saifb4cf72c2018-10-18 17:29:47 +0500318 for row_idx, row in enumerate(result):
rohitwaghchaureed1cc182019-09-30 15:15:52 +0530319 data = row.items() if is_dict_obj else enumerate(row)
320 for key, value in data:
Noah Jacobd8668f72021-07-15 18:32:15 +0530321 if key not in convertible_columns:
rohitwaghchaureed1cc182019-09-30 15:15:52 +0530322 continue
Noah Jacobd8668f72021-07-15 18:32:15 +0530323 # If no conversion factor for the UOM, defaults to 1
324 if not conversion_factors[row_idx]:
325 conversion_factors[row_idx] = 1
Saifb4cf72c2018-10-18 17:29:47 +0500326
rohitwaghchaureed1cc182019-09-30 15:15:52 +0530327 if convertible_columns.get(key) == 'rate':
Noah Jacobd8668f72021-07-15 18:32:15 +0530328 new_value = flt(value) * conversion_factors[row_idx]
rohitwaghchaureed1cc182019-09-30 15:15:52 +0530329 else:
Noah Jacobd8668f72021-07-15 18:32:15 +0530330 new_value = flt(value) / conversion_factors[row_idx]
rohitwaghchaureed1cc182019-09-30 15:15:52 +0530331
332 if not is_dict_obj:
333 row.insert(key+1, new_value)
334 else:
335 new_key = "{0}_{1}".format(key, frappe.scrub(include_uom))
rohitwaghchaure001ee5e2019-11-11 17:43:48 +0530336 update_dict_values.append([row, new_key, new_value])
337
338 for data in update_dict_values:
339 row, key, value = data
340 row[key] = value
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530341
Rohit Waghchaurecf55c9c2019-11-14 18:22:20 +0530342def get_available_serial_nos(args):
343 return frappe.db.sql(""" SELECT name from `tabSerial No`
344 WHERE item_code = %(item_code)s and warehouse = %(warehouse)s
345 and timestamp(purchase_date, purchase_time) <= timestamp(%(posting_date)s, %(posting_time)s)
346 """, args, as_dict=1)
Suraj Shettybc001d22019-09-16 19:57:04 +0530347
348def add_additional_uom_columns(columns, result, include_uom, conversion_factors):
349 if not include_uom or not conversion_factors:
350 return
351
352 convertible_column_map = {}
353 for col_idx in list(reversed(range(0, len(columns)))):
354 col = columns[col_idx]
355 if isinstance(col, dict) and col.get('convertible') in ['rate', 'qty']:
356 next_col = col_idx + 1
357 columns.insert(next_col, col.copy())
358 columns[next_col]['fieldname'] += '_alt'
359 convertible_column_map[col.get('fieldname')] = frappe._dict({
360 'converted_col': columns[next_col]['fieldname'],
361 'for_type': col.get('convertible')
362 })
363 if col.get('convertible') == 'rate':
364 columns[next_col]['label'] += ' (per {})'.format(include_uom)
365 else:
366 columns[next_col]['label'] += ' ({})'.format(include_uom)
367
368 for row_idx, row in enumerate(result):
369 for convertible_col, data in convertible_column_map.items():
370 conversion_factor = conversion_factors[row.get('item_code')] or 1
371 for_type = data.for_type
372 value_before_conversion = row.get(convertible_col)
373 if for_type == 'rate':
374 row[data.converted_col] = flt(value_before_conversion) * conversion_factor
375 else:
376 row[data.converted_col] = flt(value_before_conversion) / conversion_factor
377
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530378 result[row_idx] = row
379
380def get_incoming_outgoing_rate_for_cancel(item_code, voucher_type, voucher_no, voucher_detail_no):
381 outgoing_rate = frappe.db.sql("""SELECT abs(stock_value_difference / actual_qty)
382 FROM `tabStock Ledger Entry`
383 WHERE voucher_type = %s and voucher_no = %s
384 and item_code = %s and voucher_detail_no = %s
385 ORDER BY CREATION DESC limit 1""",
386 (voucher_type, voucher_no, item_code, voucher_detail_no))
387
388 outgoing_rate = outgoing_rate[0][0] if outgoing_rate else 0.0
389
Nabin Haita77b8c92020-12-21 14:45:50 +0530390 return outgoing_rate
391
392def is_reposting_item_valuation_in_progress():
393 reposting_in_progress = frappe.db.exists("Repost Item Valuation",
394 {'docstatus': 1, 'status': ['in', ['Queued','In Progress']]})
395 if reposting_in_progress:
Noah Jacobd8668f72021-07-15 18:32:15 +0530396 frappe.msgprint(_("Item valuation reposting in progress. Report might show incorrect item valuation."), alert=1)