2013-11-20 07:29:58 +00:00
|
|
|
# Copyright (c) 2013, Web Notes 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
|
|
|
|
2014-02-14 10:17:51 +00:00
|
|
|
import frappe
|
|
|
|
from frappe import msgprint, _
|
2013-01-07 13:21:11 +00:00
|
|
|
import json
|
2014-02-14 10:17:51 +00:00
|
|
|
from frappe.utils import flt, cstr, nowdate, add_days, cint
|
|
|
|
from frappe.defaults import get_global_default
|
|
|
|
from frappe.utils.email_lib import sendmail
|
2013-01-07 13:21:11 +00:00
|
|
|
|
2014-02-14 10:17:51 +00:00
|
|
|
class InvalidWarehouseCompany(frappe.ValidationError): pass
|
2013-08-02 06:15:43 +00:00
|
|
|
|
2013-09-25 05:02:51 +00:00
|
|
|
def get_stock_balance_on(warehouse, posting_date=None):
|
2013-08-02 06:15:43 +00:00
|
|
|
if not posting_date: posting_date = nowdate()
|
|
|
|
|
2014-02-14 10:17:51 +00:00
|
|
|
stock_ledger_entries = frappe.conn.sql("""
|
2013-08-02 06:15:43 +00:00
|
|
|
SELECT
|
2013-09-25 05:02:51 +00:00
|
|
|
item_code, stock_value
|
2013-08-02 06:15:43 +00:00
|
|
|
FROM
|
|
|
|
`tabStock Ledger Entry`
|
|
|
|
WHERE
|
2013-09-25 05:02:51 +00:00
|
|
|
warehouse=%s AND posting_date <= %s
|
2013-08-02 06:15:43 +00:00
|
|
|
ORDER BY timestamp(posting_date, posting_time) DESC, name DESC
|
2013-09-25 05:02:51 +00:00
|
|
|
""", (warehouse, posting_date), as_dict=1)
|
2013-08-02 06:15:43 +00:00
|
|
|
|
|
|
|
sle_map = {}
|
|
|
|
for sle in stock_ledger_entries:
|
2013-09-25 05:02:51 +00:00
|
|
|
sle_map.setdefault(sle.item_code, flt(sle.stock_value))
|
2013-08-02 06:15:43 +00:00
|
|
|
|
2013-09-25 05:02:51 +00:00
|
|
|
return sum(sle_map.values())
|
2013-08-02 06:15:43 +00:00
|
|
|
|
2013-08-06 10:28:16 +00:00
|
|
|
def get_latest_stock_balance():
|
|
|
|
bin_map = {}
|
2014-02-14 10:17:51 +00:00
|
|
|
for d in frappe.conn.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))
|
2013-08-06 10:28:16 +00:00
|
|
|
|
|
|
|
return bin_map
|
2013-08-19 10:47:18 +00:00
|
|
|
|
|
|
|
def get_bin(item_code, warehouse):
|
2014-02-14 10:17:51 +00:00
|
|
|
bin = frappe.conn.get_value("Bin", {"item_code": item_code, "warehouse": warehouse})
|
2013-08-19 10:47:18 +00:00
|
|
|
if not bin:
|
2014-02-14 10:17:51 +00:00
|
|
|
bin_wrapper = frappe.bean([{
|
2013-08-19 10:47:18 +00:00
|
|
|
"doctype": "Bin",
|
|
|
|
"item_code": item_code,
|
|
|
|
"warehouse": warehouse,
|
|
|
|
}])
|
|
|
|
bin_wrapper.ignore_permissions = 1
|
|
|
|
bin_wrapper.insert()
|
|
|
|
bin_obj = bin_wrapper.make_controller()
|
|
|
|
else:
|
2014-02-14 10:17:51 +00:00
|
|
|
from frappe.model.code import get_obj
|
2013-08-19 10:47:18 +00:00
|
|
|
bin_obj = get_obj('Bin', bin)
|
|
|
|
return bin_obj
|
|
|
|
|
|
|
|
def update_bin(args):
|
2014-02-14 10:17:51 +00:00
|
|
|
is_stock_item = frappe.conn.get_value('Item', args.get("item_code"), 'is_stock_item')
|
2013-08-19 10:47:18 +00:00
|
|
|
if is_stock_item == 'Yes':
|
|
|
|
bin = get_bin(args.get("item_code"), args.get("warehouse"))
|
|
|
|
bin.update_stock(args)
|
|
|
|
return bin
|
|
|
|
else:
|
|
|
|
msgprint("[Stock Update] Ignored %s since it is not a stock item"
|
|
|
|
% args.get("item_code"))
|
2013-08-02 06:15:43 +00:00
|
|
|
|
2013-01-07 13:21:11 +00:00
|
|
|
def get_incoming_rate(args):
|
|
|
|
"""Get Incoming Rate based on valuation method"""
|
2013-12-12 13:42:19 +00:00
|
|
|
from erpnext.stock.stock_ledger import get_previous_sle
|
2013-01-07 13:21:11 +00:00
|
|
|
|
|
|
|
in_rate = 0
|
|
|
|
if args.get("serial_no"):
|
|
|
|
in_rate = get_avg_purchase_rate(args.get("serial_no"))
|
|
|
|
elif args.get("bom_no"):
|
2014-02-14 10:17:51 +00:00
|
|
|
result = frappe.conn.sql("""select ifnull(total_cost, 0) / ifnull(quantity, 1)
|
2013-01-07 13:21:11 +00:00
|
|
|
from `tabBOM` where name = %s and docstatus=1 and is_active=1""", args.get("bom_no"))
|
|
|
|
in_rate = result and flt(result[0][0]) or 0
|
|
|
|
else:
|
|
|
|
valuation_method = get_valuation_method(args.get("item_code"))
|
|
|
|
previous_sle = get_previous_sle(args)
|
|
|
|
if valuation_method == 'FIFO':
|
2013-01-16 08:45:48 +00:00
|
|
|
if not previous_sle:
|
|
|
|
return 0.0
|
2013-08-12 08:48:09 +00:00
|
|
|
previous_stock_queue = json.loads(previous_sle.get('stock_queue', '[]') or '[]')
|
2013-01-16 08:45:48 +00:00
|
|
|
in_rate = previous_stock_queue and \
|
2013-01-16 11:47:17 +00:00
|
|
|
get_fifo_rate(previous_stock_queue, args.get("qty") or 0) or 0
|
2013-01-07 13:21:11 +00:00
|
|
|
elif valuation_method == 'Moving Average':
|
|
|
|
in_rate = previous_sle.get('valuation_rate') or 0
|
|
|
|
return in_rate
|
|
|
|
|
|
|
|
def get_avg_purchase_rate(serial_nos):
|
|
|
|
"""get average value of serial numbers"""
|
|
|
|
|
|
|
|
serial_nos = get_valid_serial_nos(serial_nos)
|
2014-02-14 10:17:51 +00:00
|
|
|
return flt(frappe.conn.sql("""select avg(ifnull(purchase_rate, 0)) 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-14 10:17:51 +00:00
|
|
|
val_method = frappe.conn.get_value('Item', item_code, 'valuation_method')
|
2013-01-07 13:21:11 +00:00
|
|
|
if not val_method:
|
2013-02-19 09:57:31 +00:00
|
|
|
val_method = get_global_default('valuation_method') or "FIFO"
|
2013-01-07 13:21:11 +00:00
|
|
|
return val_method
|
|
|
|
|
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:
|
|
|
|
total = sum(f[0] for f in previous_stock_queue)
|
|
|
|
return total and sum(f[0] * f[1] for f in previous_stock_queue) / flt(total) or 0.0
|
|
|
|
else:
|
|
|
|
outgoing_cost = 0
|
|
|
|
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]
|
|
|
|
if 0 < batch[0] <= qty_to_pop:
|
|
|
|
# if batch qty > 0
|
|
|
|
# not enough or exactly same qty in current batch, clear batch
|
|
|
|
outgoing_cost += flt(batch[0]) * flt(batch[1])
|
|
|
|
qty_to_pop -= batch[0]
|
|
|
|
previous_stock_queue.pop(0)
|
|
|
|
else:
|
|
|
|
# all from current batch
|
|
|
|
outgoing_cost += flt(qty_to_pop) * flt(batch[1])
|
|
|
|
batch[0] -= qty_to_pop
|
|
|
|
qty_to_pop = 0
|
2013-01-17 06:52:59 +00:00
|
|
|
# if queue gets blank and qty_to_pop remaining, get average rate of full queue
|
|
|
|
return outgoing_cost / abs(qty) - qty_to_pop
|
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')
|
|
|
|
|
|
|
|
valid_serial_nos = []
|
|
|
|
for val in serial_nos:
|
|
|
|
if val:
|
|
|
|
val = val.strip()
|
|
|
|
if val in valid_serial_nos:
|
|
|
|
msgprint("You have entered duplicate serial no: '%s'" % val, raise_exception=1)
|
|
|
|
else:
|
|
|
|
valid_serial_nos.append(val)
|
|
|
|
|
|
|
|
if qty and len(valid_serial_nos) != abs(qty):
|
|
|
|
msgprint("Please enter serial nos for "
|
|
|
|
+ cstr(abs(qty)) + " quantity against item code: " + item_code,
|
|
|
|
raise_exception=1)
|
|
|
|
|
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-14 10:17:51 +00:00
|
|
|
warehouse_company = frappe.conn.get_value("Warehouse", warehouse, "company")
|
2013-10-10 10:34:40 +00:00
|
|
|
if warehouse_company and warehouse_company != company:
|
2014-02-14 10:17:51 +00:00
|
|
|
frappe.msgprint(_("Warehouse does not belong to company.") + " (" + \
|
2013-10-10 10:34:40 +00:00
|
|
|
warehouse + ", " + company +")", raise_exception=InvalidWarehouseCompany)
|
2013-08-27 05:02:56 +00:00
|
|
|
|
2013-08-30 17:18:19 +00:00
|
|
|
def get_sales_bom_buying_amount(item_code, warehouse, voucher_type, voucher_no, voucher_detail_no,
|
|
|
|
stock_ledger_entries, item_sales_bom):
|
|
|
|
# sales bom item
|
|
|
|
buying_amount = 0.0
|
|
|
|
for bom_item in item_sales_bom[item_code]:
|
|
|
|
if bom_item.get("parent_detail_docname")==voucher_detail_no:
|
|
|
|
buying_amount += get_buying_amount(voucher_type, voucher_no, voucher_detail_no,
|
|
|
|
stock_ledger_entries.get((bom_item.item_code, warehouse), []))
|
|
|
|
|
|
|
|
return buying_amount
|
2013-03-06 13:20:53 +00:00
|
|
|
|
2013-08-30 17:18:19 +00:00
|
|
|
def get_buying_amount(voucher_type, voucher_no, item_row, stock_ledger_entries):
|
2013-08-07 13:57:30 +00:00
|
|
|
# IMP NOTE
|
|
|
|
# stock_ledger_entries should already be filtered by item_code and warehouse and
|
|
|
|
# sorted by posting_date desc, posting_time desc
|
|
|
|
for i, sle in enumerate(stock_ledger_entries):
|
2013-03-12 06:04:56 +00:00
|
|
|
if sle.voucher_type == voucher_type and sle.voucher_no == voucher_no and \
|
2013-03-28 11:10:30 +00:00
|
|
|
sle.voucher_detail_no == item_row:
|
2013-08-07 13:57:30 +00:00
|
|
|
previous_stock_value = len(stock_ledger_entries) > i+1 and \
|
|
|
|
flt(stock_ledger_entries[i+1].stock_value) or 0.0
|
2013-03-19 06:31:24 +00:00
|
|
|
buying_amount = previous_stock_value - flt(sle.stock_value)
|
2013-03-21 13:15:02 +00:00
|
|
|
|
2013-03-19 06:31:24 +00:00
|
|
|
return buying_amount
|
2013-05-22 10:49:10 +00:00
|
|
|
return 0.0
|
|
|
|
|
|
|
|
|
|
|
|
def reorder_item():
|
|
|
|
""" Reorder item if stock reaches reorder level"""
|
2014-02-14 10:17:51 +00:00
|
|
|
if getattr(frappe.local, "auto_indent", None) is None:
|
|
|
|
frappe.local.auto_indent = cint(frappe.conn.get_value('Stock Settings', None, 'auto_indent'))
|
2013-08-12 11:00:48 +00:00
|
|
|
|
2014-02-14 10:17:51 +00:00
|
|
|
if frappe.local.auto_indent:
|
2013-05-22 10:49:10 +00:00
|
|
|
material_requests = {}
|
2014-02-14 10:17:51 +00:00
|
|
|
bin_list = frappe.conn.sql("""select item_code, warehouse, projected_qty
|
2013-06-17 06:27:04 +00:00
|
|
|
from tabBin where ifnull(item_code, '') != '' and ifnull(warehouse, '') != ''
|
|
|
|
and exists (select name from `tabItem`
|
|
|
|
where `tabItem`.name = `tabBin`.item_code and
|
|
|
|
is_stock_item='Yes' and (is_purchase_item='Yes' or is_sub_contracted_item='Yes') and
|
2013-08-23 11:24:31 +00:00
|
|
|
(ifnull(end_of_life, '')='' or end_of_life > now()))""", as_dict=True)
|
2013-05-22 10:49:10 +00:00
|
|
|
for bin in bin_list:
|
|
|
|
#check if re-order is required
|
2014-02-14 10:17:51 +00:00
|
|
|
item_reorder = frappe.conn.get("Item Reorder",
|
2013-05-22 10:49:10 +00:00
|
|
|
{"parent": bin.item_code, "warehouse": bin.warehouse})
|
|
|
|
if item_reorder:
|
|
|
|
reorder_level = item_reorder.warehouse_reorder_level
|
|
|
|
reorder_qty = item_reorder.warehouse_reorder_qty
|
|
|
|
material_request_type = item_reorder.material_request_type or "Purchase"
|
|
|
|
else:
|
2014-02-14 10:17:51 +00:00
|
|
|
reorder_level, reorder_qty = frappe.conn.get_value("Item", bin.item_code,
|
2013-05-22 10:49:10 +00:00
|
|
|
["re_order_level", "re_order_qty"])
|
|
|
|
material_request_type = "Purchase"
|
|
|
|
|
2013-06-17 06:27:04 +00:00
|
|
|
if flt(reorder_level) and flt(bin.projected_qty) < flt(reorder_level):
|
2013-05-22 10:49:10 +00:00
|
|
|
if flt(reorder_level) - flt(bin.projected_qty) > flt(reorder_qty):
|
|
|
|
reorder_qty = flt(reorder_level) - flt(bin.projected_qty)
|
|
|
|
|
2014-02-14 10:17:51 +00:00
|
|
|
company = frappe.conn.get_value("Warehouse", bin.warehouse, "company") or \
|
|
|
|
frappe.defaults.get_defaults()["company"] or \
|
|
|
|
frappe.conn.sql("""select name from tabCompany limit 1""")[0][0]
|
2013-05-22 10:49:10 +00:00
|
|
|
|
2014-02-14 10:17:51 +00:00
|
|
|
material_requests.setdefault(material_request_type, frappe._dict()).setdefault(
|
|
|
|
company, []).append(frappe._dict({
|
2013-05-22 10:49:10 +00:00
|
|
|
"item_code": bin.item_code,
|
|
|
|
"warehouse": bin.warehouse,
|
|
|
|
"reorder_qty": reorder_qty
|
|
|
|
})
|
|
|
|
)
|
2013-11-13 09:23:09 +00:00
|
|
|
|
2013-05-22 10:49:10 +00:00
|
|
|
create_material_request(material_requests)
|
|
|
|
|
|
|
|
def create_material_request(material_requests):
|
|
|
|
""" Create indent on reaching reorder level """
|
|
|
|
mr_list = []
|
2014-02-14 10:17:51 +00:00
|
|
|
defaults = frappe.defaults.get_defaults()
|
2013-06-17 06:27:04 +00:00
|
|
|
exceptions_list = []
|
2013-12-12 13:42:19 +00:00
|
|
|
from erpnext.accounts.utils import get_fiscal_year
|
2013-11-26 09:15:27 +00:00
|
|
|
current_fiscal_year = get_fiscal_year(nowdate())[0] or defaults.fiscal_year
|
2013-05-22 10:49:10 +00:00
|
|
|
for request_type in material_requests:
|
|
|
|
for company in material_requests[request_type]:
|
2013-06-17 06:27:04 +00:00
|
|
|
try:
|
|
|
|
items = material_requests[request_type][company]
|
|
|
|
if not items:
|
|
|
|
continue
|
2013-07-22 05:58:34 +00:00
|
|
|
|
2013-05-22 10:49:10 +00:00
|
|
|
mr = [{
|
|
|
|
"doctype": "Material Request",
|
|
|
|
"company": company,
|
2013-11-26 09:15:27 +00:00
|
|
|
"fiscal_year": current_fiscal_year,
|
2013-05-22 10:49:10 +00:00
|
|
|
"transaction_date": nowdate(),
|
2013-11-13 09:23:09 +00:00
|
|
|
"material_request_type": request_type
|
2013-05-22 10:49:10 +00:00
|
|
|
}]
|
|
|
|
|
2013-06-17 06:27:04 +00:00
|
|
|
for d in items:
|
2014-02-14 10:17:51 +00:00
|
|
|
item = frappe.doc("Item", d.item_code)
|
2013-06-17 06:27:04 +00:00
|
|
|
mr.append({
|
|
|
|
"doctype": "Material Request Item",
|
|
|
|
"parenttype": "Material Request",
|
|
|
|
"parentfield": "indent_details",
|
|
|
|
"item_code": d.item_code,
|
|
|
|
"schedule_date": add_days(nowdate(),cint(item.lead_time_days)),
|
|
|
|
"uom": item.stock_uom,
|
|
|
|
"warehouse": d.warehouse,
|
|
|
|
"item_name": item.item_name,
|
|
|
|
"description": item.description,
|
|
|
|
"item_group": item.item_group,
|
|
|
|
"qty": d.reorder_qty,
|
|
|
|
"brand": item.brand,
|
|
|
|
})
|
2013-05-22 10:49:10 +00:00
|
|
|
|
2014-02-14 10:17:51 +00:00
|
|
|
mr_bean = frappe.bean(mr)
|
2013-06-17 06:27:04 +00:00
|
|
|
mr_bean.insert()
|
|
|
|
mr_bean.submit()
|
|
|
|
mr_list.append(mr_bean)
|
2013-07-22 05:58:34 +00:00
|
|
|
|
2013-06-17 06:27:04 +00:00
|
|
|
except:
|
2014-02-14 10:17:51 +00:00
|
|
|
if frappe.local.message_log:
|
|
|
|
exceptions_list.append([] + frappe.local.message_log)
|
|
|
|
frappe.local.message_log = []
|
2013-06-17 06:27:04 +00:00
|
|
|
else:
|
2014-02-14 10:17:51 +00:00
|
|
|
exceptions_list.append(frappe.get_traceback())
|
2013-05-22 10:49:10 +00:00
|
|
|
|
|
|
|
if mr_list:
|
2014-02-14 10:17:51 +00:00
|
|
|
if getattr(frappe.local, "reorder_email_notify", None) is None:
|
|
|
|
frappe.local.reorder_email_notify = cint(frappe.conn.get_value('Stock Settings', None,
|
2013-08-12 11:00:48 +00:00
|
|
|
'reorder_email_notify'))
|
2013-05-22 10:49:10 +00:00
|
|
|
|
2014-02-14 10:17:51 +00:00
|
|
|
if(frappe.local.reorder_email_notify):
|
2013-05-22 10:49:10 +00:00
|
|
|
send_email_notification(mr_list)
|
2013-06-17 06:27:04 +00:00
|
|
|
|
|
|
|
if exceptions_list:
|
|
|
|
notify_errors(exceptions_list)
|
2013-05-22 10:49:10 +00:00
|
|
|
|
|
|
|
def send_email_notification(mr_list):
|
|
|
|
""" Notify user about auto creation of indent"""
|
|
|
|
|
2014-02-14 10:17:51 +00:00
|
|
|
email_list = frappe.conn.sql_list("""select distinct r.parent
|
2013-05-22 10:49:10 +00:00
|
|
|
from tabUserRole r, tabProfile p
|
|
|
|
where p.name = r.parent and p.enabled = 1 and p.docstatus < 2
|
|
|
|
and r.role in ('Purchase Manager','Material Manager')
|
|
|
|
and p.name not in ('Administrator', 'All', 'Guest')""")
|
|
|
|
|
|
|
|
msg="""<h3>Following Material Requests has been raised automatically \
|
|
|
|
based on item reorder level:</h3>"""
|
|
|
|
for mr in mr_list:
|
|
|
|
msg += "<p><b><u>" + mr.doc.name + """</u></b></p><table class='table table-bordered'><tr>
|
|
|
|
<th>Item Code</th><th>Warehouse</th><th>Qty</th><th>UOM</th></tr>"""
|
|
|
|
for item in mr.doclist.get({"parentfield": "indent_details"}):
|
|
|
|
msg += "<tr><td>" + item.item_code + "</td><td>" + item.warehouse + "</td><td>" + \
|
|
|
|
cstr(item.qty) + "</td><td>" + cstr(item.uom) + "</td></tr>"
|
|
|
|
msg += "</table>"
|
2013-06-17 06:27:04 +00:00
|
|
|
sendmail(email_list, subject='Auto Material Request Generation Notification', msg = msg)
|
|
|
|
|
|
|
|
def notify_errors(exceptions_list):
|
|
|
|
subject = "[Important] [ERPNext] Error(s) while creating Material Requests based on Re-order Levels"
|
|
|
|
msg = """Dear System Manager,
|
|
|
|
|
|
|
|
An error occured for certain Items while creating Material Requests based on Re-order level.
|
|
|
|
|
|
|
|
Please rectify these issues:
|
|
|
|
---
|
|
|
|
|
|
|
|
%s
|
|
|
|
|
|
|
|
---
|
|
|
|
Regards,
|
|
|
|
Administrator""" % ("\n\n".join(["\n".join(msg) for msg in exceptions_list]),)
|
|
|
|
|
2014-02-14 10:17:51 +00:00
|
|
|
from frappe.profile import get_system_managers
|
2013-06-17 06:27:04 +00:00
|
|
|
sendmail(get_system_managers(), subject=subject, msg=msg)
|