blob: fd1ece2151b205a79f5a6026df2b7846fa6e2297 [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
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05305import frappe
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
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053010class InvalidWarehouseCompany(frappe.ValidationError): pass
Anand Doshi2ce39cf2014-04-07 18:51:58 +053011
Rushabh Mehtaf8509872014-10-08 12:03:19 +053012def get_stock_value_on(warehouse=None, posting_date=None, item_code=None):
Nabin Hait0dd7be12013-08-02 11:45:43 +053013 if not posting_date: posting_date = nowdate()
Anand Doshi2ce39cf2014-04-07 18:51:58 +053014
Rushabh Mehtaf8509872014-10-08 12:03:19 +053015 values, condition = [posting_date], ""
16
17 if warehouse:
Saurabh554f6f72016-06-06 14:22:37 +053018
Saurabh4d029492016-06-23 12:44:06 +053019 lft, rgt, is_group = frappe.db.get_value("Warehouse", warehouse, ["lft", "rgt", "is_group"])
Saurabh554f6f72016-06-06 14:22:37 +053020
Saurabh93d68ac2016-06-26 22:50:11 +053021 if is_group:
Saurabh4d029492016-06-23 12:44:06 +053022 values.extend([lft, rgt])
Saurabh554f6f72016-06-06 14:22:37 +053023 condition += "and exists (\
24 select name from `tabWarehouse` wh where wh.name = sle.warehouse\
25 and wh.lft >= %s and wh.rgt <= %s)"
26
27 else:
28 values.append(warehouse)
29 condition += " AND warehouse = %s"
Rushabh Mehtaf8509872014-10-08 12:03:19 +053030
31 if item_code:
32 values.append(item_code)
33 condition.append(" AND item_code = %s")
34
Anand Doshie9baaa62014-02-26 12:35:33 +053035 stock_ledger_entries = frappe.db.sql("""
Saurabh554f6f72016-06-06 14:22:37 +053036 SELECT item_code, stock_value, name, warehouse
37 FROM `tabStock Ledger Entry` sle
Rushabh Mehtaf8509872014-10-08 12:03:19 +053038 WHERE posting_date <= %s {0}
Nabin Hait0dd7be12013-08-02 11:45:43 +053039 ORDER BY timestamp(posting_date, posting_time) DESC, name DESC
Rushabh Mehtaf8509872014-10-08 12:03:19 +053040 """.format(condition), values, as_dict=1)
Anand Doshi2ce39cf2014-04-07 18:51:58 +053041
Nabin Hait0dd7be12013-08-02 11:45:43 +053042 sle_map = {}
43 for sle in stock_ledger_entries:
Saurabh554f6f72016-06-06 14:22:37 +053044 sle_map[sle.item_code] = sle_map.get(sle.item_code, 0.0) + flt(sle.stock_value)
45
Nabin Hait625da792013-09-25 10:32:51 +053046 return sum(sle_map.values())
Anand Doshi2ce39cf2014-04-07 18:51:58 +053047
nick98226f48d4b2017-01-09 12:12:36 +053048@frappe.whitelist()
Rushabh Mehta2712e362015-02-17 12:50:20 +053049def get_stock_balance(item_code, warehouse, posting_date=None, posting_time=None, with_valuation_rate=False):
50 """Returns stock balance quantity at given warehouse on given posting date or current date.
51
52 If `with_valuation_rate` is True, will return tuple (qty, rate)"""
Rushabh Mehtadc93e0a2015-02-20 15:11:56 +053053
54 from erpnext.stock.stock_ledger import get_previous_sle
55
Rushabh Mehtaf8509872014-10-08 12:03:19 +053056 if not posting_date: posting_date = nowdate()
57 if not posting_time: posting_time = nowtime()
Rushabh Mehtadc93e0a2015-02-20 15:11:56 +053058
59 last_entry = get_previous_sle({
60 "item_code": item_code,
61 "warehouse":warehouse,
62 "posting_date": posting_date,
63 "posting_time": posting_time })
Rushabh Mehtaf8509872014-10-08 12:03:19 +053064
Rushabh Mehta2712e362015-02-17 12:50:20 +053065 if with_valuation_rate:
Rushabh Mehtadc93e0a2015-02-20 15:11:56 +053066 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 +053067 else:
Rushabh Mehtadc93e0a2015-02-20 15:11:56 +053068 return last_entry.qty_after_transaction or 0.0
Rushabh Mehtaf8509872014-10-08 12:03:19 +053069
Nabin Hait47dc3182013-08-06 15:58:16 +053070def get_latest_stock_balance():
71 bin_map = {}
Anand Doshi2ce39cf2014-04-07 18:51:58 +053072 for d in frappe.db.sql("""SELECT item_code, warehouse, stock_value as stock_value
Nabin Hait47dc3182013-08-06 15:58:16 +053073 FROM tabBin""", as_dict=1):
Nabin Hait469ee712013-08-07 12:33:37 +053074 bin_map.setdefault(d.warehouse, {}).setdefault(d.item_code, flt(d.stock_value))
Anand Doshi2ce39cf2014-04-07 18:51:58 +053075
Nabin Hait47dc3182013-08-06 15:58:16 +053076 return bin_map
Anand Doshi2ce39cf2014-04-07 18:51:58 +053077
Nabin Hait74c281c2013-08-19 16:17:18 +053078def get_bin(item_code, warehouse):
Anand Doshie9baaa62014-02-26 12:35:33 +053079 bin = frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse})
Nabin Hait74c281c2013-08-19 16:17:18 +053080 if not bin:
Rushabh Mehtaa504f062014-04-04 12:16:26 +053081 bin_obj = frappe.get_doc({
Nabin Hait74c281c2013-08-19 16:17:18 +053082 "doctype": "Bin",
83 "item_code": item_code,
84 "warehouse": warehouse,
Rushabh Mehtaa504f062014-04-04 12:16:26 +053085 })
Anand Doshi6dfd4302015-02-10 14:41:27 +053086 bin_obj.flags.ignore_permissions = 1
Rushabh Mehtaa504f062014-04-04 12:16:26 +053087 bin_obj.insert()
Nabin Hait74c281c2013-08-19 16:17:18 +053088 else:
Rushabh Mehtaa504f062014-04-04 12:16:26 +053089 bin_obj = frappe.get_doc('Bin', bin)
Anand Doshi6dfd4302015-02-10 14:41:27 +053090 bin_obj.flags.ignore_permissions = True
Nabin Hait74c281c2013-08-19 16:17:18 +053091 return bin_obj
92
Nabin Hait54c865e2015-03-27 15:38:31 +053093def update_bin(args, allow_negative_stock=False, via_landed_cost_voucher=False):
Anand Doshie9baaa62014-02-26 12:35:33 +053094 is_stock_item = frappe.db.get_value('Item', args.get("item_code"), 'is_stock_item')
Rushabh Mehta1e8025b2015-07-24 15:16:25 +053095 if is_stock_item:
Nabin Hait74c281c2013-08-19 16:17:18 +053096 bin = get_bin(args.get("item_code"), args.get("warehouse"))
Nabin Hait54c865e2015-03-27 15:38:31 +053097 bin.update_stock(args, allow_negative_stock, via_landed_cost_voucher)
Nabin Hait74c281c2013-08-19 16:17:18 +053098 return bin
99 else:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530100 frappe.msgprint(_("Item {0} ignored since it is not a stock item").format(args.get("item_code")))
Nabin Hait0dd7be12013-08-02 11:45:43 +0530101
Nabin Hait5eefff12015-12-07 10:44:56 +0530102@frappe.whitelist()
Nabin Hait9d0f6362013-01-07 18:51:11 +0530103def get_incoming_rate(args):
104 """Get Incoming Rate based on valuation method"""
Rushabh Mehta1f847992013-12-12 19:12:19 +0530105 from erpnext.stock.stock_ledger import get_previous_sle
Nabin Hait41c8cf62015-12-08 14:50:24 +0530106
107 if isinstance(args, basestring):
108 args = json.loads(args)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530109
Nabin Hait9d0f6362013-01-07 18:51:11 +0530110 in_rate = 0
Anand Doshi40a8ae22014-08-29 16:28:31 +0530111 if (args.get("serial_no") or "").strip():
Nabin Hait9d0f6362013-01-07 18:51:11 +0530112 in_rate = get_avg_purchase_rate(args.get("serial_no"))
Nabin Hait9d0f6362013-01-07 18:51:11 +0530113 else:
114 valuation_method = get_valuation_method(args.get("item_code"))
115 previous_sle = get_previous_sle(args)
116 if valuation_method == 'FIFO':
Nabin Hait831207f2013-01-16 14:15:48 +0530117 if not previous_sle:
118 return 0.0
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530119 previous_stock_queue = json.loads(previous_sle.get('stock_queue', '[]') or '[]')
Nabin Hait227db762014-05-08 19:06:01 +0530120 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 +0530121 elif valuation_method == 'Moving Average':
122 in_rate = previous_sle.get('valuation_rate') or 0
Anand Doshi094610d2014-04-16 19:56:53 +0530123
Nabin Hait9d0f6362013-01-07 18:51:11 +0530124 return in_rate
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530125
Nabin Hait9d0f6362013-01-07 18:51:11 +0530126def get_avg_purchase_rate(serial_nos):
127 """get average value of serial numbers"""
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530128
Nabin Hait9d0f6362013-01-07 18:51:11 +0530129 serial_nos = get_valid_serial_nos(serial_nos)
Anand Doshi602e8252015-11-16 19:05:46 +0530130 return flt(frappe.db.sql("""select avg(purchase_rate) from `tabSerial No`
Nabin Hait9d0f6362013-01-07 18:51:11 +0530131 where name in (%s)""" % ", ".join(["%s"] * len(serial_nos)),
132 tuple(serial_nos))[0][0])
133
134def get_valuation_method(item_code):
135 """get valuation method from item or default"""
Anand Doshie9baaa62014-02-26 12:35:33 +0530136 val_method = frappe.db.get_value('Item', item_code, 'valuation_method')
Nabin Hait9d0f6362013-01-07 18:51:11 +0530137 if not val_method:
Nabin Hait4d742162014-10-09 19:25:03 +0530138 val_method = frappe.db.get_value("Stock Settings", None, "valuation_method") or "FIFO"
Nabin Hait9d0f6362013-01-07 18:51:11 +0530139 return val_method
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530140
Nabin Hait831207f2013-01-16 14:15:48 +0530141def get_fifo_rate(previous_stock_queue, qty):
142 """get FIFO (average) Rate from Queue"""
143 if qty >= 0:
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530144 total = sum(f[0] for f in previous_stock_queue)
Nabin Hait38265ef2014-10-21 20:23:39 +0530145 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 +0530146 else:
Nabin Hait227db762014-05-08 19:06:01 +0530147 available_qty_for_outgoing, outgoing_cost = 0, 0
Nabin Hait831207f2013-01-16 14:15:48 +0530148 qty_to_pop = abs(qty)
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530149 while qty_to_pop and previous_stock_queue:
Nabin Hait831207f2013-01-16 14:15:48 +0530150 batch = previous_stock_queue[0]
Nabin Hait8142cd22015-08-05 18:57:26 +0530151 if 0 < batch[0] <= qty_to_pop:
152 # if batch qty > 0
153 # not enough or exactly same qty in current batch, clear batch
154 available_qty_for_outgoing += flt(batch[0])
155 outgoing_cost += flt(batch[0]) * flt(batch[1])
156 qty_to_pop -= batch[0]
157 previous_stock_queue.pop(0)
158 else:
159 # all from current batch
160 available_qty_for_outgoing += flt(qty_to_pop)
161 outgoing_cost += flt(qty_to_pop) * flt(batch[1])
162 batch[0] -= qty_to_pop
163 qty_to_pop = 0
Anand Doshi094610d2014-04-16 19:56:53 +0530164
Nabin Hait227db762014-05-08 19:06:01 +0530165 return outgoing_cost / available_qty_for_outgoing
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530166
Nabin Hait9d0f6362013-01-07 18:51:11 +0530167def get_valid_serial_nos(sr_nos, qty=0, item_code=''):
168 """split serial nos, validate and return list of valid serial nos"""
169 # TODO: remove duplicates in client side
170 serial_nos = cstr(sr_nos).strip().replace(',', '\n').split('\n')
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530171
Nabin Hait9d0f6362013-01-07 18:51:11 +0530172 valid_serial_nos = []
173 for val in serial_nos:
174 if val:
175 val = val.strip()
176 if val in valid_serial_nos:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530177 frappe.throw(_("Serial number {0} entered more than once").format(val))
Nabin Hait9d0f6362013-01-07 18:51:11 +0530178 else:
179 valid_serial_nos.append(val)
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530180
Nabin Hait9d0f6362013-01-07 18:51:11 +0530181 if qty and len(valid_serial_nos) != abs(qty):
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530182 frappe.throw(_("{0} valid serial nos for Item {1}").format(abs(qty), item_code))
Anand Doshi2ce39cf2014-04-07 18:51:58 +0530183
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530184 return valid_serial_nos
Nabin Haita72c5122013-03-06 18:50:53 +0530185
Anand Doshi373680b2013-10-10 16:04:40 +0530186def validate_warehouse_company(warehouse, company):
Anand Doshie9baaa62014-02-26 12:35:33 +0530187 warehouse_company = frappe.db.get_value("Warehouse", warehouse, "company")
Anand Doshi373680b2013-10-10 16:04:40 +0530188 if warehouse_company and warehouse_company != company:
Rushabh Mehta9f0d6252014-04-14 19:20:45 +0530189 frappe.throw(_("Warehouse {0} does not belong to company {1}").format(warehouse, company),
190 InvalidWarehouseCompany)
Saurabh3d6aecd2016-06-20 17:25:45 +0530191
Saurabh4d029492016-06-23 12:44:06 +0530192def is_group_warehouse(warehouse):
Saurabh93d68ac2016-06-26 22:50:11 +0530193 if frappe.db.get_value("Warehouse", warehouse, "is_group"):
Saurabh4d029492016-06-23 12:44:06 +0530194 frappe.throw(_("Group node warehouse is not allowed to select for transactions"))
nick98226f48d4b2017-01-09 12:12:36 +0530195