blob: 11e758fce32831cdcd7b9e00ac4cfa807a698453 [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
rohitwaghchaurece8adec2017-12-15 12:13:50 +05305import frappe, erpnext
Rushabh Mehta9f0d6252014-04-14 19:20:45 +05306from frappe import _
Nabin Hait9d0f6362013-01-07 18:51:11 +05307import json
Rushabh Mehtaf8509872014-10-08 12:03:19 +05308from frappe.utils import flt, cstr, nowdate, nowtime
Nabin Hait9d0f6362013-01-07 18:51:11 +05309
Achilles Rasquinha56b2e122018-02-13 14:42:40 +053010from six import string_types
11
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053012class InvalidWarehouseCompany(frappe.ValidationError): pass
Anand Doshi2ce39cf2014-04-07 18:51:58 +053013
Shreya Shahe0a47ae2018-08-28 13:46:22 +053014def get_stock_value_from_bin(warehouse=None, item_code=None):
Sachin Mane19a5a5d2018-06-21 13:01:48 +053015 values = {}
16 conditions = ""
17 if warehouse:
rohitwaghchauref1fab872019-09-05 14:47:43 +053018 conditions += """ and `tabBin`.warehouse in (
Sachin Mane19a5a5d2018-06-21 13:01:48 +053019 select w2.name from `tabWarehouse` w1
20 join `tabWarehouse` w2 on
21 w1.name = %(warehouse)s
22 and w2.lft between w1.lft and w1.rgt
23 ) """
24
25 values['warehouse'] = warehouse
26
27 if item_code:
rohitwaghchauref1fab872019-09-05 14:47:43 +053028 conditions += " and `tabBin`.item_code = %(item_code)s"
Sachin Mane19a5a5d2018-06-21 13:01:48 +053029
Sachin Mane19a5a5d2018-06-21 13:01:48 +053030 values['item_code'] = item_code
31
rohitwaghchauref1fab872019-09-05 14:47:43 +053032 query = """select sum(stock_value) from `tabBin`, `tabItem` where 1 = 1
33 and `tabItem`.name = `tabBin`.item_code and ifnull(`tabItem`.disabled, 0) = 0 %s""" % conditions
Sachin Mane19a5a5d2018-06-21 13:01:48 +053034
35 stock_value = frappe.db.sql(query, values)
36
Shreya Shahe0a47ae2018-08-28 13:46:22 +053037 return stock_value
Sachin Mane19a5a5d2018-06-21 13:01:48 +053038
Rushabh Mehtaf8509872014-10-08 12:03:19 +053039def get_stock_value_on(warehouse=None, posting_date=None, item_code=None):
Nabin Hait0dd7be12013-08-02 11:45:43 +053040 if not posting_date: posting_date = nowdate()
Anand Doshi2ce39cf2014-04-07 18:51:58 +053041
Rushabh Mehtaf8509872014-10-08 12:03:19 +053042 values, condition = [posting_date], ""
43
44 if warehouse:
Sachin Mane19a5a5d2018-06-21 13:01:48 +053045
Saurabh4d029492016-06-23 12:44:06 +053046 lft, rgt, is_group = frappe.db.get_value("Warehouse", warehouse, ["lft", "rgt", "is_group"])
Sachin Mane19a5a5d2018-06-21 13:01:48 +053047
Saurabh93d68ac2016-06-26 22:50:11 +053048 if is_group:
Saurabh4d029492016-06-23 12:44:06 +053049 values.extend([lft, rgt])
Saurabh554f6f72016-06-06 14:22:37 +053050 condition += "and exists (\
51 select name from `tabWarehouse` wh where wh.name = sle.warehouse\
52 and wh.lft >= %s and wh.rgt <= %s)"
Sachin Mane19a5a5d2018-06-21 13:01:48 +053053
Saurabh554f6f72016-06-06 14:22:37 +053054 else:
55 values.append(warehouse)
56 condition += " AND warehouse = %s"
Rushabh Mehtaf8509872014-10-08 12:03:19 +053057
58 if item_code:
59 values.append(item_code)
itusedyetnew8aafbd22019-03-20 11:10:41 +053060 condition += " AND item_code = %s"
Rushabh Mehtaf8509872014-10-08 12:03:19 +053061
Anand Doshie9baaa62014-02-26 12:35:33 +053062 stock_ledger_entries = frappe.db.sql("""
Saurabh554f6f72016-06-06 14:22:37 +053063 SELECT item_code, stock_value, name, warehouse
64 FROM `tabStock Ledger Entry` sle
Rushabh Mehtaf8509872014-10-08 12:03:19 +053065 WHERE posting_date <= %s {0}
Aditya Hase0c164242019-01-07 22:07:13 +053066 ORDER BY timestamp(posting_date, posting_time) DESC, creation DESC
Rushabh Mehtaf8509872014-10-08 12:03:19 +053067 """.format(condition), values, as_dict=1)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053068
Nabin Hait0dd7be12013-08-02 11:45:43 +053069 sle_map = {}
70 for sle in stock_ledger_entries:
Achilles Rasquinhab4de7e32018-03-09 12:35:47 +053071 if not (sle.item_code, sle.warehouse) in sle_map:
Nabin Hait949a9202017-07-05 13:55:41 +053072 sle_map[(sle.item_code, sle.warehouse)] = flt(sle.stock_value)
Sachin Mane19a5a5d2018-06-21 13:01:48 +053073
Nabin Hait625da792013-09-25 10:32:51 +053074 return sum(sle_map.values())
Anand Doshi2ce39cf2014-04-07 18:51:58 +053075
nick98226f48d4b2017-01-09 12:12:36 +053076@frappe.whitelist()
Rohit Waghchaure560f8222020-04-06 15:02:43 +053077def get_stock_balance(item_code, warehouse, posting_date=None, posting_time=None,
78 with_valuation_rate=False, with_serial_no=False):
Rushabh Mehta2712e362015-02-17 12:50:20 +053079 """Returns stock balance quantity at given warehouse on given posting date or current date.
80
81 If `with_valuation_rate` is True, will return tuple (qty, rate)"""
Rushabh Mehtadc93e0a2015-02-20 15:11:56 +053082
83 from erpnext.stock.stock_ledger import get_previous_sle
84
Rushabh Mehtaf8509872014-10-08 12:03:19 +053085 if not posting_date: posting_date = nowdate()
86 if not posting_time: posting_time = nowtime()
Rushabh Mehtadc93e0a2015-02-20 15:11:56 +053087
Rohit Waghchaure560f8222020-04-06 15:02:43 +053088 args = {
Rushabh Mehtadc93e0a2015-02-20 15:11:56 +053089 "item_code": item_code,
90 "warehouse":warehouse,
91 "posting_date": posting_date,
Rohit Waghchaure560f8222020-04-06 15:02:43 +053092 "posting_time": posting_time
93 }
94
95 last_entry = get_previous_sle(args)
Rushabh Mehtaf8509872014-10-08 12:03:19 +053096
Rushabh Mehta2712e362015-02-17 12:50:20 +053097 if with_valuation_rate:
Rohit Waghchaure560f8222020-04-06 15:02:43 +053098 if with_serial_no:
99 serial_nos = last_entry.get("serial_no")
100
101 if (serial_nos and
102 len(get_serial_nos_data(serial_nos)) < last_entry.qty_after_transaction):
103 serial_nos = get_serial_nos_data_after_transactions(args)
104
105 return ((last_entry.qty_after_transaction, last_entry.valuation_rate, serial_nos)
106 if last_entry else (0.0, 0.0, 0.0))
107 else:
108 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 +0530109 else:
nick9822cc699a92017-06-20 17:13:29 +0530110 return last_entry.qty_after_transaction if last_entry else 0.0
Rushabh Mehtaf8509872014-10-08 12:03:19 +0530111
Rohit Waghchaure560f8222020-04-06 15:02:43 +0530112def get_serial_nos_data_after_transactions(args):
113 serial_nos = []
114 data = frappe.db.sql(""" SELECT serial_no, actual_qty
115 FROM `tabStock Ledger Entry`
116 WHERE
117 item_code = %(item_code)s and warehouse = %(warehouse)s
118 and timestamp(posting_date, posting_time) < timestamp(%(posting_date)s, %(posting_time)s)
119 order by posting_date, posting_time asc """, args, as_dict=1)
120
121 for d in data:
122 if d.actual_qty > 0:
123 serial_nos.extend(get_serial_nos_data(d.serial_no))
124 else:
125 serial_nos = list(set(serial_nos) - set(get_serial_nos_data(d.serial_no)))
126
127 return '\n'.join(serial_nos)
128
129def get_serial_nos_data(serial_nos):
130 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
131 return get_serial_nos(serial_nos)
132
Nabin Hait949a9202017-07-05 13:55:41 +0530133@frappe.whitelist()
134def get_latest_stock_qty(item_code, warehouse=None):
135 values, condition = [item_code], ""
136 if warehouse:
137 lft, rgt, is_group = frappe.db.get_value("Warehouse", warehouse, ["lft", "rgt", "is_group"])
Sachin Mane19a5a5d2018-06-21 13:01:48 +0530138
Nabin Hait949a9202017-07-05 13:55:41 +0530139 if is_group:
140 values.extend([lft, rgt])
141 condition += "and exists (\
142 select name from `tabWarehouse` wh where wh.name = tabBin.warehouse\
143 and wh.lft >= %s and wh.rgt <= %s)"
Sachin Mane19a5a5d2018-06-21 13:01:48 +0530144
Nabin Hait949a9202017-07-05 13:55:41 +0530145 else:
146 values.append(warehouse)
147 condition += " AND warehouse = %s"
Sachin Mane19a5a5d2018-06-21 13:01:48 +0530148
Nabin Hait949a9202017-07-05 13:55:41 +0530149 actual_qty = frappe.db.sql("""select sum(actual_qty) from tabBin
150 where item_code=%s {0}""".format(condition), values)[0][0]
151
152 return actual_qty
153
154
Nabin Hait47dc3182013-08-06 15:58:16 +0530155def get_latest_stock_balance():
156 bin_map = {}
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530157 for d in frappe.db.sql("""SELECT item_code, warehouse, stock_value as stock_value
Nabin Hait47dc3182013-08-06 15:58:16 +0530158 FROM tabBin""", as_dict=1):
Nabin Hait469ee712013-08-07 12:33:37 +0530159 bin_map.setdefault(d.warehouse, {}).setdefault(d.item_code, flt(d.stock_value))
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530160
Nabin Hait47dc3182013-08-06 15:58:16 +0530161 return bin_map
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530162
Nabin Hait74c281c2013-08-19 16:17:18 +0530163def get_bin(item_code, warehouse):
Anand Doshie9baaa62014-02-26 12:35:33 +0530164 bin = frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse})
Nabin Hait74c281c2013-08-19 16:17:18 +0530165 if not bin:
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530166 bin_obj = frappe.get_doc({
Nabin Hait74c281c2013-08-19 16:17:18 +0530167 "doctype": "Bin",
168 "item_code": item_code,
169 "warehouse": warehouse,
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530170 })
Anand Doshi6dfd4302015-02-10 14:41:27 +0530171 bin_obj.flags.ignore_permissions = 1
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530172 bin_obj.insert()
Nabin Hait74c281c2013-08-19 16:17:18 +0530173 else:
rohitwaghchaureb5a670c2020-02-27 18:18:10 +0530174 bin_obj = frappe.get_cached_doc('Bin', bin)
Anand Doshi6dfd4302015-02-10 14:41:27 +0530175 bin_obj.flags.ignore_permissions = True
Nabin Hait74c281c2013-08-19 16:17:18 +0530176 return bin_obj
177
Nabin Hait54c865e2015-03-27 15:38:31 +0530178def update_bin(args, allow_negative_stock=False, via_landed_cost_voucher=False):
Anand Doshie9baaa62014-02-26 12:35:33 +0530179 is_stock_item = frappe.db.get_value('Item', args.get("item_code"), 'is_stock_item')
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530180 if is_stock_item:
Nabin Hait74c281c2013-08-19 16:17:18 +0530181 bin = get_bin(args.get("item_code"), args.get("warehouse"))
Nabin Hait54c865e2015-03-27 15:38:31 +0530182 bin.update_stock(args, allow_negative_stock, via_landed_cost_voucher)
Nabin Hait74c281c2013-08-19 16:17:18 +0530183 return bin
184 else:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530185 frappe.msgprint(_("Item {0} ignored since it is not a stock item").format(args.get("item_code")))
Nabin Hait0dd7be12013-08-02 11:45:43 +0530186
Nabin Hait5eefff12015-12-07 10:44:56 +0530187@frappe.whitelist()
Nabin Hait7ba092e2018-02-01 10:51:27 +0530188def get_incoming_rate(args, raise_error_if_no_rate=True):
Nabin Hait9d0f6362013-01-07 18:51:11 +0530189 """Get Incoming Rate based on valuation method"""
rohitwaghchaurece8adec2017-12-15 12:13:50 +0530190 from erpnext.stock.stock_ledger import get_previous_sle, get_valuation_rate
Achilles Rasquinha56b2e122018-02-13 14:42:40 +0530191 if isinstance(args, string_types):
Nabin Hait41c8cf62015-12-08 14:50:24 +0530192 args = json.loads(args)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530193
Nabin Hait9d0f6362013-01-07 18:51:11 +0530194 in_rate = 0
Anand Doshi40a8ae22014-08-29 16:28:31 +0530195 if (args.get("serial_no") or "").strip():
Nabin Hait9d0f6362013-01-07 18:51:11 +0530196 in_rate = get_avg_purchase_rate(args.get("serial_no"))
Nabin Hait9d0f6362013-01-07 18:51:11 +0530197 else:
198 valuation_method = get_valuation_method(args.get("item_code"))
199 previous_sle = get_previous_sle(args)
200 if valuation_method == 'FIFO':
rohitwaghchaurece8adec2017-12-15 12:13:50 +0530201 if previous_sle:
202 previous_stock_queue = json.loads(previous_sle.get('stock_queue', '[]') or '[]')
203 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 +0530204 elif valuation_method == 'Moving Average':
205 in_rate = previous_sle.get('valuation_rate') or 0
Anand Doshi094610d2014-04-16 19:56:53 +0530206
rohitwaghchaurece8adec2017-12-15 12:13:50 +0530207 if not in_rate:
208 voucher_no = args.get('voucher_no') or args.get('name')
rohitwaghchaurece8adec2017-12-15 12:13:50 +0530209 in_rate = get_valuation_rate(args.get('item_code'), args.get('warehouse'),
210 args.get('voucher_type'), voucher_no, args.get('allow_zero_valuation'),
Nabin Hait7ba092e2018-02-01 10:51:27 +0530211 currency=erpnext.get_company_currency(args.get('company')), company=args.get('company'),
Rohit Waghchaure87c4b062019-06-01 14:22:46 +0530212 raise_error_if_no_rate=raise_error_if_no_rate)
rohitwaghchaurece8adec2017-12-15 12:13:50 +0530213
Nabin Hait9d0f6362013-01-07 18:51:11 +0530214 return in_rate
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530215
Nabin Hait9d0f6362013-01-07 18:51:11 +0530216def get_avg_purchase_rate(serial_nos):
217 """get average value of serial numbers"""
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530218
Nabin Hait9d0f6362013-01-07 18:51:11 +0530219 serial_nos = get_valid_serial_nos(serial_nos)
Anand Doshi602e8252015-11-16 19:05:46 +0530220 return flt(frappe.db.sql("""select avg(purchase_rate) from `tabSerial No`
Nabin Hait9d0f6362013-01-07 18:51:11 +0530221 where name in (%s)""" % ", ".join(["%s"] * len(serial_nos)),
222 tuple(serial_nos))[0][0])
223
224def get_valuation_method(item_code):
225 """get valuation method from item or default"""
Anand Doshie9baaa62014-02-26 12:35:33 +0530226 val_method = frappe.db.get_value('Item', item_code, 'valuation_method')
Nabin Hait9d0f6362013-01-07 18:51:11 +0530227 if not val_method:
Nabin Hait4d742162014-10-09 19:25:03 +0530228 val_method = frappe.db.get_value("Stock Settings", None, "valuation_method") or "FIFO"
Nabin Hait9d0f6362013-01-07 18:51:11 +0530229 return val_method
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530230
Nabin Hait831207f2013-01-16 14:15:48 +0530231def get_fifo_rate(previous_stock_queue, qty):
232 """get FIFO (average) Rate from Queue"""
marination6f7e9d22020-06-03 17:13:58 +0530233 if flt(qty) >= 0:
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530234 total = sum(f[0] for f in previous_stock_queue)
Nabin Hait38265ef2014-10-21 20:23:39 +0530235 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 +0530236 else:
Nabin Hait227db762014-05-08 19:06:01 +0530237 available_qty_for_outgoing, outgoing_cost = 0, 0
marination6f7e9d22020-06-03 17:13:58 +0530238 qty_to_pop = abs(flt(qty))
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530239 while qty_to_pop and previous_stock_queue:
Nabin Hait831207f2013-01-16 14:15:48 +0530240 batch = previous_stock_queue[0]
Nabin Hait8142cd22015-08-05 18:57:26 +0530241 if 0 < batch[0] <= qty_to_pop:
242 # if batch qty > 0
243 # not enough or exactly same qty in current batch, clear batch
244 available_qty_for_outgoing += flt(batch[0])
245 outgoing_cost += flt(batch[0]) * flt(batch[1])
246 qty_to_pop -= batch[0]
247 previous_stock_queue.pop(0)
248 else:
249 # all from current batch
250 available_qty_for_outgoing += flt(qty_to_pop)
251 outgoing_cost += flt(qty_to_pop) * flt(batch[1])
252 batch[0] -= qty_to_pop
253 qty_to_pop = 0
Anand Doshi094610d2014-04-16 19:56:53 +0530254
Nabin Hait227db762014-05-08 19:06:01 +0530255 return outgoing_cost / available_qty_for_outgoing
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530256
Nabin Hait9d0f6362013-01-07 18:51:11 +0530257def get_valid_serial_nos(sr_nos, qty=0, item_code=''):
258 """split serial nos, validate and return list of valid serial nos"""
259 # TODO: remove duplicates in client side
260 serial_nos = cstr(sr_nos).strip().replace(',', '\n').split('\n')
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530261
Nabin Hait9d0f6362013-01-07 18:51:11 +0530262 valid_serial_nos = []
263 for val in serial_nos:
264 if val:
265 val = val.strip()
266 if val in valid_serial_nos:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530267 frappe.throw(_("Serial number {0} entered more than once").format(val))
Nabin Hait9d0f6362013-01-07 18:51:11 +0530268 else:
269 valid_serial_nos.append(val)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530270
Nabin Hait9d0f6362013-01-07 18:51:11 +0530271 if qty and len(valid_serial_nos) != abs(qty):
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530272 frappe.throw(_("{0} valid serial nos for Item {1}").format(abs(qty), item_code))
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530273
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530274 return valid_serial_nos
Nabin Haita72c5122013-03-06 18:50:53 +0530275
Anand Doshi373680b2013-10-10 16:04:40 +0530276def validate_warehouse_company(warehouse, company):
Anand Doshie9baaa62014-02-26 12:35:33 +0530277 warehouse_company = frappe.db.get_value("Warehouse", warehouse, "company")
Anand Doshi373680b2013-10-10 16:04:40 +0530278 if warehouse_company and warehouse_company != company:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530279 frappe.throw(_("Warehouse {0} does not belong to company {1}").format(warehouse, company),
280 InvalidWarehouseCompany)
Saurabh3d6aecd2016-06-20 17:25:45 +0530281
Saurabh4d029492016-06-23 12:44:06 +0530282def is_group_warehouse(warehouse):
Saurabh93d68ac2016-06-26 22:50:11 +0530283 if frappe.db.get_value("Warehouse", warehouse, "is_group"):
Saurabh4d029492016-06-23 12:44:06 +0530284 frappe.throw(_("Group node warehouse is not allowed to select for transactions"))
Saifb4cf72c2018-10-18 17:29:47 +0500285
286def update_included_uom_in_report(columns, result, include_uom, conversion_factors):
287 if not include_uom or not conversion_factors:
288 return
289
290 convertible_cols = {}
rohitwaghchaureed1cc182019-09-30 15:15:52 +0530291
292 is_dict_obj = False
293 if isinstance(result[0], dict):
294 is_dict_obj = True
295
296 convertible_columns = {}
297 for idx, d in enumerate(columns):
298 key = d.get("fieldname") if is_dict_obj else idx
299 if d.get("convertible"):
300 convertible_columns.setdefault(key, d.get("convertible"))
301
302 # Add new column to show qty/rate as per the selected UOM
303 columns.insert(idx+1, {
304 'label': "{0} (per {1})".format(d.get("label"), include_uom),
305 'fieldname': "{0}_{1}".format(d.get("fieldname"), frappe.scrub(include_uom)),
306 'fieldtype': 'Currency' if d.get("convertible") == 'rate' else 'Float'
307 })
Saifb4cf72c2018-10-18 17:29:47 +0500308
rohitwaghchaure001ee5e2019-11-11 17:43:48 +0530309 update_dict_values = []
Saifb4cf72c2018-10-18 17:29:47 +0500310 for row_idx, row in enumerate(result):
rohitwaghchaureed1cc182019-09-30 15:15:52 +0530311 data = row.items() if is_dict_obj else enumerate(row)
312 for key, value in data:
313 if not key in convertible_columns or not conversion_factors[row_idx]:
314 continue
Saifb4cf72c2018-10-18 17:29:47 +0500315
rohitwaghchaureed1cc182019-09-30 15:15:52 +0530316 if convertible_columns.get(key) == 'rate':
317 new_value = flt(value) * conversion_factors[row_idx]
318 else:
319 new_value = flt(value) / conversion_factors[row_idx]
320
321 if not is_dict_obj:
322 row.insert(key+1, new_value)
323 else:
324 new_key = "{0}_{1}".format(key, frappe.scrub(include_uom))
rohitwaghchaure001ee5e2019-11-11 17:43:48 +0530325 update_dict_values.append([row, new_key, new_value])
326
327 for data in update_dict_values:
328 row, key, value = data
329 row[key] = value
Rohit Waghchaure05d3bcb2019-04-28 18:39:18 +0530330
Rohit Waghchaurecf55c9c2019-11-14 18:22:20 +0530331def get_available_serial_nos(args):
332 return frappe.db.sql(""" SELECT name from `tabSerial No`
333 WHERE item_code = %(item_code)s and warehouse = %(warehouse)s
334 and timestamp(purchase_date, purchase_time) <= timestamp(%(posting_date)s, %(posting_time)s)
335 """, args, as_dict=1)
Suraj Shettybc001d22019-09-16 19:57:04 +0530336
337def add_additional_uom_columns(columns, result, include_uom, conversion_factors):
338 if not include_uom or not conversion_factors:
339 return
340
341 convertible_column_map = {}
342 for col_idx in list(reversed(range(0, len(columns)))):
343 col = columns[col_idx]
344 if isinstance(col, dict) and col.get('convertible') in ['rate', 'qty']:
345 next_col = col_idx + 1
346 columns.insert(next_col, col.copy())
347 columns[next_col]['fieldname'] += '_alt'
348 convertible_column_map[col.get('fieldname')] = frappe._dict({
349 'converted_col': columns[next_col]['fieldname'],
350 'for_type': col.get('convertible')
351 })
352 if col.get('convertible') == 'rate':
353 columns[next_col]['label'] += ' (per {})'.format(include_uom)
354 else:
355 columns[next_col]['label'] += ' ({})'.format(include_uom)
356
357 for row_idx, row in enumerate(result):
358 for convertible_col, data in convertible_column_map.items():
359 conversion_factor = conversion_factors[row.get('item_code')] or 1
360 for_type = data.for_type
361 value_before_conversion = row.get(convertible_col)
362 if for_type == 'rate':
363 row[data.converted_col] = flt(value_before_conversion) * conversion_factor
364 else:
365 row[data.converted_col] = flt(value_before_conversion) / conversion_factor
366
Deepesh Garg2a9c5ba2020-04-30 10:38:58 +0530367 result[row_idx] = row
368
369def get_incoming_outgoing_rate_for_cancel(item_code, voucher_type, voucher_no, voucher_detail_no):
370 outgoing_rate = frappe.db.sql("""SELECT abs(stock_value_difference / actual_qty)
371 FROM `tabStock Ledger Entry`
372 WHERE voucher_type = %s and voucher_no = %s
373 and item_code = %s and voucher_detail_no = %s
374 ORDER BY CREATION DESC limit 1""",
375 (voucher_type, voucher_no, item_code, voucher_detail_no))
376
377 outgoing_rate = outgoing_rate[0][0] if outgoing_rate else 0.0
378
379 return outgoing_rate