2015-03-03 09:25:30 +00:00
|
|
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
|
2013-08-05 09:29:54 +00:00
|
|
|
# License: GNU General Public License v3. See license.txt
|
2013-01-07 13:21:11 +00:00
|
|
|
|
2015-02-24 06:54:53 +00:00
|
|
|
from __future__ import unicode_literals
|
2017-12-15 06:43:50 +00:00
|
|
|
import frappe, erpnext
|
2014-04-14 13:50:45 +00:00
|
|
|
from frappe import _
|
2013-01-07 13:21:11 +00:00
|
|
|
import json
|
2014-10-08 06:33:19 +00:00
|
|
|
from frappe.utils import flt, cstr, nowdate, nowtime
|
2013-01-07 13:21:11 +00:00
|
|
|
|
2018-02-13 09:12:40 +00:00
|
|
|
from six import string_types
|
|
|
|
|
2014-02-14 10:17:51 +00:00
|
|
|
class InvalidWarehouseCompany(frappe.ValidationError): pass
|
2014-04-07 13:21:58 +00:00
|
|
|
|
2018-08-28 08:16:22 +00:00
|
|
|
def get_stock_value_from_bin(warehouse=None, item_code=None):
|
2018-06-21 07:31:48 +00:00
|
|
|
values = {}
|
|
|
|
conditions = ""
|
|
|
|
if warehouse:
|
2019-09-05 09:17:43 +00:00
|
|
|
conditions += """ and `tabBin`.warehouse in (
|
2018-06-21 07:31:48 +00:00
|
|
|
select w2.name from `tabWarehouse` w1
|
|
|
|
join `tabWarehouse` w2 on
|
|
|
|
w1.name = %(warehouse)s
|
|
|
|
and w2.lft between w1.lft and w1.rgt
|
|
|
|
) """
|
|
|
|
|
|
|
|
values['warehouse'] = warehouse
|
|
|
|
|
|
|
|
if item_code:
|
2019-09-05 09:17:43 +00:00
|
|
|
conditions += " and `tabBin`.item_code = %(item_code)s"
|
2018-06-21 07:31:48 +00:00
|
|
|
|
|
|
|
values['item_code'] = item_code
|
|
|
|
|
2019-09-05 09:17:43 +00:00
|
|
|
query = """select sum(stock_value) from `tabBin`, `tabItem` where 1 = 1
|
|
|
|
and `tabItem`.name = `tabBin`.item_code and ifnull(`tabItem`.disabled, 0) = 0 %s""" % conditions
|
2018-06-21 07:31:48 +00:00
|
|
|
|
|
|
|
stock_value = frappe.db.sql(query, values)
|
|
|
|
|
2018-08-28 08:16:22 +00:00
|
|
|
return stock_value
|
2018-06-21 07:31:48 +00:00
|
|
|
|
2014-10-08 06:33:19 +00:00
|
|
|
def get_stock_value_on(warehouse=None, posting_date=None, item_code=None):
|
2013-08-02 06:15:43 +00:00
|
|
|
if not posting_date: posting_date = nowdate()
|
2014-04-07 13:21:58 +00:00
|
|
|
|
2014-10-08 06:33:19 +00:00
|
|
|
values, condition = [posting_date], ""
|
|
|
|
|
|
|
|
if warehouse:
|
2018-06-21 07:31:48 +00:00
|
|
|
|
2016-06-23 07:14:06 +00:00
|
|
|
lft, rgt, is_group = frappe.db.get_value("Warehouse", warehouse, ["lft", "rgt", "is_group"])
|
2018-06-21 07:31:48 +00:00
|
|
|
|
2016-06-26 17:20:11 +00:00
|
|
|
if is_group:
|
2016-06-23 07:14:06 +00:00
|
|
|
values.extend([lft, rgt])
|
2016-06-06 08:52:37 +00:00
|
|
|
condition += "and exists (\
|
|
|
|
select name from `tabWarehouse` wh where wh.name = sle.warehouse\
|
|
|
|
and wh.lft >= %s and wh.rgt <= %s)"
|
2018-06-21 07:31:48 +00:00
|
|
|
|
2016-06-06 08:52:37 +00:00
|
|
|
else:
|
|
|
|
values.append(warehouse)
|
|
|
|
condition += " AND warehouse = %s"
|
2014-10-08 06:33:19 +00:00
|
|
|
|
|
|
|
if item_code:
|
|
|
|
values.append(item_code)
|
2019-03-20 05:40:41 +00:00
|
|
|
condition += " AND item_code = %s"
|
2014-10-08 06:33:19 +00:00
|
|
|
|
2014-02-26 07:05:33 +00:00
|
|
|
stock_ledger_entries = frappe.db.sql("""
|
2016-06-06 08:52:37 +00:00
|
|
|
SELECT item_code, stock_value, name, warehouse
|
|
|
|
FROM `tabStock Ledger Entry` sle
|
2014-10-08 06:33:19 +00:00
|
|
|
WHERE posting_date <= %s {0}
|
2019-01-07 16:37:13 +00:00
|
|
|
ORDER BY timestamp(posting_date, posting_time) DESC, creation DESC
|
2014-10-08 06:33:19 +00:00
|
|
|
""".format(condition), values, as_dict=1)
|
2014-04-07 13:21:58 +00:00
|
|
|
|
2013-08-02 06:15:43 +00:00
|
|
|
sle_map = {}
|
|
|
|
for sle in stock_ledger_entries:
|
2018-03-09 07:05:47 +00:00
|
|
|
if not (sle.item_code, sle.warehouse) in sle_map:
|
2017-07-05 08:25:41 +00:00
|
|
|
sle_map[(sle.item_code, sle.warehouse)] = flt(sle.stock_value)
|
2018-06-21 07:31:48 +00:00
|
|
|
|
2013-09-25 05:02:51 +00:00
|
|
|
return sum(sle_map.values())
|
2014-04-07 13:21:58 +00:00
|
|
|
|
2017-01-09 06:42:36 +00:00
|
|
|
@frappe.whitelist()
|
2015-02-17 07:20:20 +00:00
|
|
|
def get_stock_balance(item_code, warehouse, posting_date=None, posting_time=None, with_valuation_rate=False):
|
|
|
|
"""Returns stock balance quantity at given warehouse on given posting date or current date.
|
|
|
|
|
|
|
|
If `with_valuation_rate` is True, will return tuple (qty, rate)"""
|
2015-02-20 09:41:56 +00:00
|
|
|
|
|
|
|
from erpnext.stock.stock_ledger import get_previous_sle
|
|
|
|
|
2014-10-08 06:33:19 +00:00
|
|
|
if not posting_date: posting_date = nowdate()
|
|
|
|
if not posting_time: posting_time = nowtime()
|
2015-02-20 09:41:56 +00:00
|
|
|
|
|
|
|
last_entry = get_previous_sle({
|
|
|
|
"item_code": item_code,
|
|
|
|
"warehouse":warehouse,
|
|
|
|
"posting_date": posting_date,
|
|
|
|
"posting_time": posting_time })
|
2014-10-08 06:33:19 +00:00
|
|
|
|
2015-02-17 07:20:20 +00:00
|
|
|
if with_valuation_rate:
|
2015-02-20 09:41:56 +00:00
|
|
|
return (last_entry.qty_after_transaction, last_entry.valuation_rate) if last_entry else (0.0, 0.0)
|
2014-10-08 06:33:19 +00:00
|
|
|
else:
|
2017-06-20 11:43:29 +00:00
|
|
|
return last_entry.qty_after_transaction if last_entry else 0.0
|
2014-10-08 06:33:19 +00:00
|
|
|
|
2017-07-05 08:25:41 +00:00
|
|
|
@frappe.whitelist()
|
|
|
|
def get_latest_stock_qty(item_code, warehouse=None):
|
|
|
|
values, condition = [item_code], ""
|
|
|
|
if warehouse:
|
|
|
|
lft, rgt, is_group = frappe.db.get_value("Warehouse", warehouse, ["lft", "rgt", "is_group"])
|
2018-06-21 07:31:48 +00:00
|
|
|
|
2017-07-05 08:25:41 +00:00
|
|
|
if is_group:
|
|
|
|
values.extend([lft, rgt])
|
|
|
|
condition += "and exists (\
|
|
|
|
select name from `tabWarehouse` wh where wh.name = tabBin.warehouse\
|
|
|
|
and wh.lft >= %s and wh.rgt <= %s)"
|
2018-06-21 07:31:48 +00:00
|
|
|
|
2017-07-05 08:25:41 +00:00
|
|
|
else:
|
|
|
|
values.append(warehouse)
|
|
|
|
condition += " AND warehouse = %s"
|
2018-06-21 07:31:48 +00:00
|
|
|
|
2017-07-05 08:25:41 +00:00
|
|
|
actual_qty = frappe.db.sql("""select sum(actual_qty) from tabBin
|
|
|
|
where item_code=%s {0}""".format(condition), values)[0][0]
|
|
|
|
|
|
|
|
return actual_qty
|
|
|
|
|
|
|
|
|
2013-08-06 10:28:16 +00:00
|
|
|
def get_latest_stock_balance():
|
|
|
|
bin_map = {}
|
2014-04-07 13:21:58 +00:00
|
|
|
for d in frappe.db.sql("""SELECT item_code, warehouse, stock_value as stock_value
|
2013-08-06 10:28:16 +00:00
|
|
|
FROM tabBin""", as_dict=1):
|
2013-08-07 07:03:37 +00:00
|
|
|
bin_map.setdefault(d.warehouse, {}).setdefault(d.item_code, flt(d.stock_value))
|
2014-04-07 13:21:58 +00:00
|
|
|
|
2013-08-06 10:28:16 +00:00
|
|
|
return bin_map
|
2014-04-07 13:21:58 +00:00
|
|
|
|
2013-08-19 10:47:18 +00:00
|
|
|
def get_bin(item_code, warehouse):
|
2014-02-26 07:05:33 +00:00
|
|
|
bin = frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse})
|
2013-08-19 10:47:18 +00:00
|
|
|
if not bin:
|
2014-04-04 06:46:26 +00:00
|
|
|
bin_obj = frappe.get_doc({
|
2013-08-19 10:47:18 +00:00
|
|
|
"doctype": "Bin",
|
|
|
|
"item_code": item_code,
|
|
|
|
"warehouse": warehouse,
|
2014-04-04 06:46:26 +00:00
|
|
|
})
|
2015-02-10 09:11:27 +00:00
|
|
|
bin_obj.flags.ignore_permissions = 1
|
2014-04-04 06:46:26 +00:00
|
|
|
bin_obj.insert()
|
2013-08-19 10:47:18 +00:00
|
|
|
else:
|
2014-04-04 06:46:26 +00:00
|
|
|
bin_obj = frappe.get_doc('Bin', bin)
|
2015-02-10 09:11:27 +00:00
|
|
|
bin_obj.flags.ignore_permissions = True
|
2013-08-19 10:47:18 +00:00
|
|
|
return bin_obj
|
|
|
|
|
2015-03-27 10:08:31 +00:00
|
|
|
def update_bin(args, allow_negative_stock=False, via_landed_cost_voucher=False):
|
2014-02-26 07:05:33 +00:00
|
|
|
is_stock_item = frappe.db.get_value('Item', args.get("item_code"), 'is_stock_item')
|
2015-07-24 09:46:25 +00:00
|
|
|
if is_stock_item:
|
2013-08-19 10:47:18 +00:00
|
|
|
bin = get_bin(args.get("item_code"), args.get("warehouse"))
|
2015-03-27 10:08:31 +00:00
|
|
|
bin.update_stock(args, allow_negative_stock, via_landed_cost_voucher)
|
2013-08-19 10:47:18 +00:00
|
|
|
return bin
|
|
|
|
else:
|
2014-04-14 13:50:45 +00:00
|
|
|
frappe.msgprint(_("Item {0} ignored since it is not a stock item").format(args.get("item_code")))
|
2013-08-02 06:15:43 +00:00
|
|
|
|
2015-12-07 05:14:56 +00:00
|
|
|
@frappe.whitelist()
|
2018-02-01 05:21:27 +00:00
|
|
|
def get_incoming_rate(args, raise_error_if_no_rate=True):
|
2013-01-07 13:21:11 +00:00
|
|
|
"""Get Incoming Rate based on valuation method"""
|
2017-12-15 06:43:50 +00:00
|
|
|
from erpnext.stock.stock_ledger import get_previous_sle, get_valuation_rate
|
2018-02-13 09:12:40 +00:00
|
|
|
if isinstance(args, string_types):
|
2015-12-08 09:20:24 +00:00
|
|
|
args = json.loads(args)
|
2014-04-07 13:21:58 +00:00
|
|
|
|
2013-01-07 13:21:11 +00:00
|
|
|
in_rate = 0
|
2014-08-29 10:58:31 +00:00
|
|
|
if (args.get("serial_no") or "").strip():
|
2013-01-07 13:21:11 +00:00
|
|
|
in_rate = get_avg_purchase_rate(args.get("serial_no"))
|
|
|
|
else:
|
|
|
|
valuation_method = get_valuation_method(args.get("item_code"))
|
|
|
|
previous_sle = get_previous_sle(args)
|
|
|
|
if valuation_method == 'FIFO':
|
2017-12-15 06:43:50 +00:00
|
|
|
if previous_sle:
|
|
|
|
previous_stock_queue = json.loads(previous_sle.get('stock_queue', '[]') or '[]')
|
|
|
|
in_rate = get_fifo_rate(previous_stock_queue, args.get("qty") or 0) if previous_stock_queue else 0
|
2013-01-07 13:21:11 +00:00
|
|
|
elif valuation_method == 'Moving Average':
|
|
|
|
in_rate = previous_sle.get('valuation_rate') or 0
|
2014-04-16 14:26:53 +00:00
|
|
|
|
2017-12-15 06:43:50 +00:00
|
|
|
if not in_rate:
|
|
|
|
voucher_no = args.get('voucher_no') or args.get('name')
|
|
|
|
in_rate = get_valuation_rate(args.get('item_code'), args.get('warehouse'),
|
|
|
|
args.get('voucher_type'), voucher_no, args.get('allow_zero_valuation'),
|
2018-02-01 05:21:27 +00:00
|
|
|
currency=erpnext.get_company_currency(args.get('company')), company=args.get('company'),
|
2019-06-01 08:52:46 +00:00
|
|
|
raise_error_if_no_rate=raise_error_if_no_rate)
|
2017-12-15 06:43:50 +00:00
|
|
|
|
2013-01-07 13:21:11 +00:00
|
|
|
return in_rate
|
2014-04-07 13:21:58 +00:00
|
|
|
|
2013-01-07 13:21:11 +00:00
|
|
|
def get_avg_purchase_rate(serial_nos):
|
|
|
|
"""get average value of serial numbers"""
|
2014-04-07 13:21:58 +00:00
|
|
|
|
2013-01-07 13:21:11 +00:00
|
|
|
serial_nos = get_valid_serial_nos(serial_nos)
|
2015-11-16 13:35:46 +00:00
|
|
|
return flt(frappe.db.sql("""select avg(purchase_rate) from `tabSerial No`
|
2013-01-07 13:21:11 +00:00
|
|
|
where name in (%s)""" % ", ".join(["%s"] * len(serial_nos)),
|
|
|
|
tuple(serial_nos))[0][0])
|
|
|
|
|
|
|
|
def get_valuation_method(item_code):
|
|
|
|
"""get valuation method from item or default"""
|
2014-02-26 07:05:33 +00:00
|
|
|
val_method = frappe.db.get_value('Item', item_code, 'valuation_method')
|
2013-01-07 13:21:11 +00:00
|
|
|
if not val_method:
|
2014-10-09 13:55:03 +00:00
|
|
|
val_method = frappe.db.get_value("Stock Settings", None, "valuation_method") or "FIFO"
|
2013-01-07 13:21:11 +00:00
|
|
|
return val_method
|
2014-04-07 13:21:58 +00:00
|
|
|
|
2013-01-16 08:45:48 +00:00
|
|
|
def get_fifo_rate(previous_stock_queue, qty):
|
|
|
|
"""get FIFO (average) Rate from Queue"""
|
|
|
|
if qty >= 0:
|
2014-04-07 13:21:58 +00:00
|
|
|
total = sum(f[0] for f in previous_stock_queue)
|
2014-10-21 14:53:39 +00:00
|
|
|
return sum(flt(f[0]) * flt(f[1]) for f in previous_stock_queue) / flt(total) if total else 0.0
|
2013-01-16 08:45:48 +00:00
|
|
|
else:
|
2014-05-08 13:36:01 +00:00
|
|
|
available_qty_for_outgoing, outgoing_cost = 0, 0
|
2013-01-16 08:45:48 +00:00
|
|
|
qty_to_pop = abs(qty)
|
2013-01-17 06:52:59 +00:00
|
|
|
while qty_to_pop and previous_stock_queue:
|
2013-01-16 08:45:48 +00:00
|
|
|
batch = previous_stock_queue[0]
|
2015-08-05 13:27:26 +00:00
|
|
|
if 0 < batch[0] <= qty_to_pop:
|
|
|
|
# if batch qty > 0
|
|
|
|
# not enough or exactly same qty in current batch, clear batch
|
|
|
|
available_qty_for_outgoing += flt(batch[0])
|
|
|
|
outgoing_cost += flt(batch[0]) * flt(batch[1])
|
|
|
|
qty_to_pop -= batch[0]
|
|
|
|
previous_stock_queue.pop(0)
|
|
|
|
else:
|
|
|
|
# all from current batch
|
|
|
|
available_qty_for_outgoing += flt(qty_to_pop)
|
|
|
|
outgoing_cost += flt(qty_to_pop) * flt(batch[1])
|
|
|
|
batch[0] -= qty_to_pop
|
|
|
|
qty_to_pop = 0
|
2014-04-16 14:26:53 +00:00
|
|
|
|
2014-05-08 13:36:01 +00:00
|
|
|
return outgoing_cost / available_qty_for_outgoing
|
2014-04-07 13:21:58 +00:00
|
|
|
|
2013-01-07 13:21:11 +00:00
|
|
|
def get_valid_serial_nos(sr_nos, qty=0, item_code=''):
|
|
|
|
"""split serial nos, validate and return list of valid serial nos"""
|
|
|
|
# TODO: remove duplicates in client side
|
|
|
|
serial_nos = cstr(sr_nos).strip().replace(',', '\n').split('\n')
|
2014-04-07 13:21:58 +00:00
|
|
|
|
2013-01-07 13:21:11 +00:00
|
|
|
valid_serial_nos = []
|
|
|
|
for val in serial_nos:
|
|
|
|
if val:
|
|
|
|
val = val.strip()
|
|
|
|
if val in valid_serial_nos:
|
2014-04-14 13:50:45 +00:00
|
|
|
frappe.throw(_("Serial number {0} entered more than once").format(val))
|
2013-01-07 13:21:11 +00:00
|
|
|
else:
|
|
|
|
valid_serial_nos.append(val)
|
2014-04-07 13:21:58 +00:00
|
|
|
|
2013-01-07 13:21:11 +00:00
|
|
|
if qty and len(valid_serial_nos) != abs(qty):
|
2014-04-14 13:50:45 +00:00
|
|
|
frappe.throw(_("{0} valid serial nos for Item {1}").format(abs(qty), item_code))
|
2014-04-07 13:21:58 +00:00
|
|
|
|
2013-02-04 08:26:50 +00:00
|
|
|
return valid_serial_nos
|
2013-03-06 13:20:53 +00:00
|
|
|
|
2013-10-10 10:34:40 +00:00
|
|
|
def validate_warehouse_company(warehouse, company):
|
2014-02-26 07:05:33 +00:00
|
|
|
warehouse_company = frappe.db.get_value("Warehouse", warehouse, "company")
|
2013-10-10 10:34:40 +00:00
|
|
|
if warehouse_company and warehouse_company != company:
|
2014-04-14 13:50:45 +00:00
|
|
|
frappe.throw(_("Warehouse {0} does not belong to company {1}").format(warehouse, company),
|
|
|
|
InvalidWarehouseCompany)
|
2016-06-20 11:55:45 +00:00
|
|
|
|
2016-06-23 07:14:06 +00:00
|
|
|
def is_group_warehouse(warehouse):
|
2016-06-26 17:20:11 +00:00
|
|
|
if frappe.db.get_value("Warehouse", warehouse, "is_group"):
|
2016-06-23 07:14:06 +00:00
|
|
|
frappe.throw(_("Group node warehouse is not allowed to select for transactions"))
|
2018-10-18 12:29:47 +00:00
|
|
|
|
|
|
|
def update_included_uom_in_report(columns, result, include_uom, conversion_factors):
|
|
|
|
if not include_uom or not conversion_factors:
|
|
|
|
return
|
|
|
|
|
|
|
|
convertible_cols = {}
|
|
|
|
for col_idx in reversed(range(0, len(columns))):
|
|
|
|
col = columns[col_idx]
|
|
|
|
if isinstance(col, dict) and col.get("convertible") in ['rate', 'qty']:
|
|
|
|
convertible_cols[col_idx] = col['convertible']
|
|
|
|
columns.insert(col_idx+1, col.copy())
|
|
|
|
columns[col_idx+1]['fieldname'] += "_alt"
|
|
|
|
if convertible_cols[col_idx] == 'rate':
|
|
|
|
columns[col_idx+1]['label'] += " (per {})".format(include_uom)
|
|
|
|
else:
|
|
|
|
columns[col_idx+1]['label'] += " ({})".format(include_uom)
|
|
|
|
|
|
|
|
for row_idx, row in enumerate(result):
|
|
|
|
new_row = []
|
|
|
|
for col_idx, d in enumerate(row):
|
|
|
|
new_row.append(d)
|
|
|
|
if col_idx in convertible_cols:
|
|
|
|
if conversion_factors[row_idx]:
|
|
|
|
if convertible_cols[col_idx] == 'rate':
|
|
|
|
new_row.append(flt(d) * conversion_factors[row_idx])
|
|
|
|
else:
|
|
|
|
new_row.append(flt(d) / conversion_factors[row_idx])
|
|
|
|
else:
|
|
|
|
new_row.append(None)
|
|
|
|
|
|
|
|
result[row_idx] = new_row
|
2019-04-28 13:09:18 +00:00
|
|
|
|
|
|
|
def get_available_serial_nos(item_code, warehouse):
|
|
|
|
return frappe.get_all("Serial No", filters = {'item_code': item_code,
|
|
|
|
'warehouse': warehouse, 'delivery_document_no': ''}) or []
|