blob: 7d73f77847e0fec8a76c28138c4380118d46e9b8 [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
Sachin Mane19a5a5d2018-06-21 13:01:48 +053014def get_stock_value_from_bin (warehouse=None, item_code=None):
15
16 values = {}
17 conditions = ""
18 if warehouse:
19 conditions += """ and warehouse in (
20 select w2.name from `tabWarehouse` w1
21 join `tabWarehouse` w2 on
22 w1.name = %(warehouse)s
23 and w2.lft between w1.lft and w1.rgt
24 ) """
25
26 values['warehouse'] = warehouse
27
28 if item_code:
29 conditions += " and item_code = %(item_code)s"
30
31
32 values['item_code'] = item_code
33
34 query = "select sum(stock_value) from `tabBin` where 1 = 1" + conditions
35
36 stock_value = frappe.db.sql(query, values)
37
38 return stock_value;
39
Rushabh Mehtaf8509872014-10-08 12:03:19 +053040def get_stock_value_on(warehouse=None, posting_date=None, item_code=None):
Nabin Hait0dd7be12013-08-02 11:45:43 +053041 if not posting_date: posting_date = nowdate()
Anand Doshi2ce39cf2014-04-07 18:51:58 +053042
Rushabh Mehtaf8509872014-10-08 12:03:19 +053043 values, condition = [posting_date], ""
44
45 if warehouse:
Sachin Mane19a5a5d2018-06-21 13:01:48 +053046
Saurabh4d029492016-06-23 12:44:06 +053047 lft, rgt, is_group = frappe.db.get_value("Warehouse", warehouse, ["lft", "rgt", "is_group"])
Sachin Mane19a5a5d2018-06-21 13:01:48 +053048
Saurabh93d68ac2016-06-26 22:50:11 +053049 if is_group:
Saurabh4d029492016-06-23 12:44:06 +053050 values.extend([lft, rgt])
Saurabh554f6f72016-06-06 14:22:37 +053051 condition += "and exists (\
52 select name from `tabWarehouse` wh where wh.name = sle.warehouse\
53 and wh.lft >= %s and wh.rgt <= %s)"
Sachin Mane19a5a5d2018-06-21 13:01:48 +053054
Saurabh554f6f72016-06-06 14:22:37 +053055 else:
56 values.append(warehouse)
57 condition += " AND warehouse = %s"
Rushabh Mehtaf8509872014-10-08 12:03:19 +053058
59 if item_code:
60 values.append(item_code)
61 condition.append(" AND item_code = %s")
62
Anand Doshie9baaa62014-02-26 12:35:33 +053063 stock_ledger_entries = frappe.db.sql("""
Saurabh554f6f72016-06-06 14:22:37 +053064 SELECT item_code, stock_value, name, warehouse
65 FROM `tabStock Ledger Entry` sle
Rushabh Mehtaf8509872014-10-08 12:03:19 +053066 WHERE posting_date <= %s {0}
Nabin Hait0dd7be12013-08-02 11:45:43 +053067 ORDER BY timestamp(posting_date, posting_time) DESC, name DESC
Rushabh Mehtaf8509872014-10-08 12:03:19 +053068 """.format(condition), values, as_dict=1)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053069
Nabin Hait0dd7be12013-08-02 11:45:43 +053070 sle_map = {}
71 for sle in stock_ledger_entries:
Achilles Rasquinhab4de7e32018-03-09 12:35:47 +053072 if not (sle.item_code, sle.warehouse) in sle_map:
Nabin Hait949a9202017-07-05 13:55:41 +053073 sle_map[(sle.item_code, sle.warehouse)] = flt(sle.stock_value)
Sachin Mane19a5a5d2018-06-21 13:01:48 +053074
Nabin Hait625da792013-09-25 10:32:51 +053075 return sum(sle_map.values())
Anand Doshi2ce39cf2014-04-07 18:51:58 +053076
nick98226f48d4b2017-01-09 12:12:36 +053077@frappe.whitelist()
Rushabh Mehta2712e362015-02-17 12:50:20 +053078def get_stock_balance(item_code, warehouse, posting_date=None, posting_time=None, with_valuation_rate=False):
79 """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
88 last_entry = get_previous_sle({
89 "item_code": item_code,
90 "warehouse":warehouse,
91 "posting_date": posting_date,
92 "posting_time": posting_time })
Rushabh Mehtaf8509872014-10-08 12:03:19 +053093
Rushabh Mehta2712e362015-02-17 12:50:20 +053094 if with_valuation_rate:
Rushabh Mehtadc93e0a2015-02-20 15:11:56 +053095 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 +053096 else:
nick9822cc699a92017-06-20 17:13:29 +053097 return last_entry.qty_after_transaction if last_entry else 0.0
Rushabh Mehtaf8509872014-10-08 12:03:19 +053098
Nabin Hait949a9202017-07-05 13:55:41 +053099@frappe.whitelist()
100def get_latest_stock_qty(item_code, warehouse=None):
101 values, condition = [item_code], ""
102 if warehouse:
103 lft, rgt, is_group = frappe.db.get_value("Warehouse", warehouse, ["lft", "rgt", "is_group"])
Sachin Mane19a5a5d2018-06-21 13:01:48 +0530104
Nabin Hait949a9202017-07-05 13:55:41 +0530105 if is_group:
106 values.extend([lft, rgt])
107 condition += "and exists (\
108 select name from `tabWarehouse` wh where wh.name = tabBin.warehouse\
109 and wh.lft >= %s and wh.rgt <= %s)"
Sachin Mane19a5a5d2018-06-21 13:01:48 +0530110
Nabin Hait949a9202017-07-05 13:55:41 +0530111 else:
112 values.append(warehouse)
113 condition += " AND warehouse = %s"
Sachin Mane19a5a5d2018-06-21 13:01:48 +0530114
Nabin Hait949a9202017-07-05 13:55:41 +0530115 actual_qty = frappe.db.sql("""select sum(actual_qty) from tabBin
116 where item_code=%s {0}""".format(condition), values)[0][0]
117
118 return actual_qty
119
120
Nabin Hait47dc3182013-08-06 15:58:16 +0530121def get_latest_stock_balance():
122 bin_map = {}
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530123 for d in frappe.db.sql("""SELECT item_code, warehouse, stock_value as stock_value
Nabin Hait47dc3182013-08-06 15:58:16 +0530124 FROM tabBin""", as_dict=1):
Nabin Hait469ee712013-08-07 12:33:37 +0530125 bin_map.setdefault(d.warehouse, {}).setdefault(d.item_code, flt(d.stock_value))
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530126
Nabin Hait47dc3182013-08-06 15:58:16 +0530127 return bin_map
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530128
Nabin Hait74c281c2013-08-19 16:17:18 +0530129def get_bin(item_code, warehouse):
Anand Doshie9baaa62014-02-26 12:35:33 +0530130 bin = frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse})
Nabin Hait74c281c2013-08-19 16:17:18 +0530131 if not bin:
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530132 bin_obj = frappe.get_doc({
Nabin Hait74c281c2013-08-19 16:17:18 +0530133 "doctype": "Bin",
134 "item_code": item_code,
135 "warehouse": warehouse,
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530136 })
Anand Doshi6dfd4302015-02-10 14:41:27 +0530137 bin_obj.flags.ignore_permissions = 1
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530138 bin_obj.insert()
Nabin Hait74c281c2013-08-19 16:17:18 +0530139 else:
Rushabh Mehtaa504f062014-04-04 12:16:26 +0530140 bin_obj = frappe.get_doc('Bin', bin)
Anand Doshi6dfd4302015-02-10 14:41:27 +0530141 bin_obj.flags.ignore_permissions = True
Nabin Hait74c281c2013-08-19 16:17:18 +0530142 return bin_obj
143
Nabin Hait54c865e2015-03-27 15:38:31 +0530144def update_bin(args, allow_negative_stock=False, via_landed_cost_voucher=False):
Anand Doshie9baaa62014-02-26 12:35:33 +0530145 is_stock_item = frappe.db.get_value('Item', args.get("item_code"), 'is_stock_item')
Rushabh Mehta1e8025b2015-07-24 15:16:25 +0530146 if is_stock_item:
Nabin Hait74c281c2013-08-19 16:17:18 +0530147 bin = get_bin(args.get("item_code"), args.get("warehouse"))
Nabin Hait54c865e2015-03-27 15:38:31 +0530148 bin.update_stock(args, allow_negative_stock, via_landed_cost_voucher)
Nabin Hait74c281c2013-08-19 16:17:18 +0530149 return bin
150 else:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530151 frappe.msgprint(_("Item {0} ignored since it is not a stock item").format(args.get("item_code")))
Nabin Hait0dd7be12013-08-02 11:45:43 +0530152
Nabin Hait5eefff12015-12-07 10:44:56 +0530153@frappe.whitelist()
Nabin Hait7ba092e2018-02-01 10:51:27 +0530154def get_incoming_rate(args, raise_error_if_no_rate=True):
Nabin Hait9d0f6362013-01-07 18:51:11 +0530155 """Get Incoming Rate based on valuation method"""
rohitwaghchaurece8adec2017-12-15 12:13:50 +0530156 from erpnext.stock.stock_ledger import get_previous_sle, get_valuation_rate
Achilles Rasquinha56b2e122018-02-13 14:42:40 +0530157 if isinstance(args, string_types):
Nabin Hait41c8cf62015-12-08 14:50:24 +0530158 args = json.loads(args)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530159
Nabin Hait9d0f6362013-01-07 18:51:11 +0530160 in_rate = 0
Anand Doshi40a8ae22014-08-29 16:28:31 +0530161 if (args.get("serial_no") or "").strip():
Nabin Hait9d0f6362013-01-07 18:51:11 +0530162 in_rate = get_avg_purchase_rate(args.get("serial_no"))
Nabin Hait9d0f6362013-01-07 18:51:11 +0530163 else:
164 valuation_method = get_valuation_method(args.get("item_code"))
165 previous_sle = get_previous_sle(args)
166 if valuation_method == 'FIFO':
rohitwaghchaurece8adec2017-12-15 12:13:50 +0530167 if previous_sle:
168 previous_stock_queue = json.loads(previous_sle.get('stock_queue', '[]') or '[]')
169 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 +0530170 elif valuation_method == 'Moving Average':
171 in_rate = previous_sle.get('valuation_rate') or 0
Anand Doshi094610d2014-04-16 19:56:53 +0530172
rohitwaghchaurece8adec2017-12-15 12:13:50 +0530173 if not in_rate:
174 voucher_no = args.get('voucher_no') or args.get('name')
rohitwaghchaurece8adec2017-12-15 12:13:50 +0530175 in_rate = get_valuation_rate(args.get('item_code'), args.get('warehouse'),
176 args.get('voucher_type'), voucher_no, args.get('allow_zero_valuation'),
Nabin Hait7ba092e2018-02-01 10:51:27 +0530177 currency=erpnext.get_company_currency(args.get('company')), company=args.get('company'),
178 raise_error_if_no_rate=True)
rohitwaghchaurece8adec2017-12-15 12:13:50 +0530179
Nabin Hait9d0f6362013-01-07 18:51:11 +0530180 return in_rate
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530181
Nabin Hait9d0f6362013-01-07 18:51:11 +0530182def get_avg_purchase_rate(serial_nos):
183 """get average value of serial numbers"""
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530184
Nabin Hait9d0f6362013-01-07 18:51:11 +0530185 serial_nos = get_valid_serial_nos(serial_nos)
Anand Doshi602e8252015-11-16 19:05:46 +0530186 return flt(frappe.db.sql("""select avg(purchase_rate) from `tabSerial No`
Nabin Hait9d0f6362013-01-07 18:51:11 +0530187 where name in (%s)""" % ", ".join(["%s"] * len(serial_nos)),
188 tuple(serial_nos))[0][0])
189
190def get_valuation_method(item_code):
191 """get valuation method from item or default"""
Anand Doshie9baaa62014-02-26 12:35:33 +0530192 val_method = frappe.db.get_value('Item', item_code, 'valuation_method')
Nabin Hait9d0f6362013-01-07 18:51:11 +0530193 if not val_method:
Nabin Hait4d742162014-10-09 19:25:03 +0530194 val_method = frappe.db.get_value("Stock Settings", None, "valuation_method") or "FIFO"
Nabin Hait9d0f6362013-01-07 18:51:11 +0530195 return val_method
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530196
Nabin Hait831207f2013-01-16 14:15:48 +0530197def get_fifo_rate(previous_stock_queue, qty):
198 """get FIFO (average) Rate from Queue"""
199 if qty >= 0:
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530200 total = sum(f[0] for f in previous_stock_queue)
Nabin Hait38265ef2014-10-21 20:23:39 +0530201 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 +0530202 else:
Nabin Hait227db762014-05-08 19:06:01 +0530203 available_qty_for_outgoing, outgoing_cost = 0, 0
Nabin Hait831207f2013-01-16 14:15:48 +0530204 qty_to_pop = abs(qty)
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530205 while qty_to_pop and previous_stock_queue:
Nabin Hait831207f2013-01-16 14:15:48 +0530206 batch = previous_stock_queue[0]
Nabin Hait8142cd22015-08-05 18:57:26 +0530207 if 0 < batch[0] <= qty_to_pop:
208 # if batch qty > 0
209 # not enough or exactly same qty in current batch, clear batch
210 available_qty_for_outgoing += flt(batch[0])
211 outgoing_cost += flt(batch[0]) * flt(batch[1])
212 qty_to_pop -= batch[0]
213 previous_stock_queue.pop(0)
214 else:
215 # all from current batch
216 available_qty_for_outgoing += flt(qty_to_pop)
217 outgoing_cost += flt(qty_to_pop) * flt(batch[1])
218 batch[0] -= qty_to_pop
219 qty_to_pop = 0
Anand Doshi094610d2014-04-16 19:56:53 +0530220
Nabin Hait227db762014-05-08 19:06:01 +0530221 return outgoing_cost / available_qty_for_outgoing
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530222
Nabin Hait9d0f6362013-01-07 18:51:11 +0530223def get_valid_serial_nos(sr_nos, qty=0, item_code=''):
224 """split serial nos, validate and return list of valid serial nos"""
225 # TODO: remove duplicates in client side
226 serial_nos = cstr(sr_nos).strip().replace(',', '\n').split('\n')
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530227
Nabin Hait9d0f6362013-01-07 18:51:11 +0530228 valid_serial_nos = []
229 for val in serial_nos:
230 if val:
231 val = val.strip()
232 if val in valid_serial_nos:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530233 frappe.throw(_("Serial number {0} entered more than once").format(val))
Nabin Hait9d0f6362013-01-07 18:51:11 +0530234 else:
235 valid_serial_nos.append(val)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530236
Nabin Hait9d0f6362013-01-07 18:51:11 +0530237 if qty and len(valid_serial_nos) != abs(qty):
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530238 frappe.throw(_("{0} valid serial nos for Item {1}").format(abs(qty), item_code))
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530239
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530240 return valid_serial_nos
Nabin Haita72c5122013-03-06 18:50:53 +0530241
Anand Doshi373680b2013-10-10 16:04:40 +0530242def validate_warehouse_company(warehouse, company):
Anand Doshie9baaa62014-02-26 12:35:33 +0530243 warehouse_company = frappe.db.get_value("Warehouse", warehouse, "company")
Anand Doshi373680b2013-10-10 16:04:40 +0530244 if warehouse_company and warehouse_company != company:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530245 frappe.throw(_("Warehouse {0} does not belong to company {1}").format(warehouse, company),
246 InvalidWarehouseCompany)
Saurabh3d6aecd2016-06-20 17:25:45 +0530247
Saurabh4d029492016-06-23 12:44:06 +0530248def is_group_warehouse(warehouse):
Saurabh93d68ac2016-06-26 22:50:11 +0530249 if frappe.db.get_value("Warehouse", warehouse, "is_group"):
Saurabh4d029492016-06-23 12:44:06 +0530250 frappe.throw(_("Group node warehouse is not allowed to select for transactions"))