blob: ff341c3daf543787e3aa165f49555fb98905f81a [file] [log] [blame]
Anand Doshi885e0742015-03-03 14:55:30 +05301# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
Rushabh Mehtaf8509872014-10-08 12:03:19 +05302# License: GNU General Public License v3. See license.txt
3
4import frappe
Rushabh Mehta3cdf3542016-02-08 11:52:22 +05305from frappe.utils import flt, nowdate, add_days, cint
Anand Doshi5cf7a0b2015-11-26 15:11:18 +05306from frappe import _
Rushabh Mehtaf8509872014-10-08 12:03:19 +05307
8def reorder_item():
9 """ Reorder item if stock reaches reorder level"""
10 # if initial setup not completed, return
Anand Doshi8860b9d2015-05-28 01:09:21 -040011 if not (frappe.db.a_row_exists("Company") and frappe.db.a_row_exists("Fiscal Year")):
Rushabh Mehtaf8509872014-10-08 12:03:19 +053012 return
13
Nabin Haitfd4bcd82015-05-22 16:55:40 +053014 if cint(frappe.db.get_value('Stock Settings', None, 'auto_indent')):
Rushabh Mehtaf8509872014-10-08 12:03:19 +053015 return _reorder_item()
16
17def _reorder_item():
18 material_requests = {"Purchase": {}, "Transfer": {}}
Anand Doshi7b2b0cd2015-10-15 18:07:51 +053019 warehouse_company = frappe._dict(frappe.db.sql("""select name, company from `tabWarehouse`
20 where disabled=0"""))
Rushabh Mehtaf8509872014-10-08 12:03:19 +053021 default_company = (frappe.defaults.get_defaults().get("company") or
22 frappe.db.sql("""select name from tabCompany limit 1""")[0][0])
23
Anand Doshi7b2b0cd2015-10-15 18:07:51 +053024 items_to_consider = frappe.db.sql_list("""select name from `tabItem` item
25 where is_stock_item=1 and has_variants=0
26 and (is_purchase_item=1 or is_sub_contracted_item=1)
Anand Doshi21e09a22015-10-29 12:21:41 +053027 and disabled=0
Anand Doshi7b2b0cd2015-10-15 18:07:51 +053028 and (end_of_life is null or end_of_life='0000-00-00' or end_of_life > %(today)s)
Rushabh Mehta3cdf3542016-02-08 11:52:22 +053029 and (exists (select name from `tabItem Reorder` ir where ir.parent=item.name)
Anand Doshi7b2b0cd2015-10-15 18:07:51 +053030 or (variant_of is not null and variant_of != ''
Rushabh Mehta3cdf3542016-02-08 11:52:22 +053031 and exists (select name from `tabItem Reorder` ir where ir.parent=item.variant_of))
Anand Doshi7b2b0cd2015-10-15 18:07:51 +053032 )""",
33 {"today": nowdate()})
34
35 if not items_to_consider:
36 return
37
38 item_warehouse_projected_qty = get_item_warehouse_projected_qty(items_to_consider)
39
Rushabh Mehtaf8509872014-10-08 12:03:19 +053040 def add_to_material_request(item_code, warehouse, reorder_level, reorder_qty, material_request_type):
Anand Doshi7b2b0cd2015-10-15 18:07:51 +053041 if warehouse not in warehouse_company:
42 # a disabled warehouse
Rushabh Mehtaf8509872014-10-08 12:03:19 +053043 return
44
45 reorder_level = flt(reorder_level)
46 reorder_qty = flt(reorder_qty)
Anand Doshi7b2b0cd2015-10-15 18:07:51 +053047
48 # projected_qty will be 0 if Bin does not exist
49 projected_qty = flt(item_warehouse_projected_qty.get(item_code, {}).get(warehouse))
Rushabh Mehtaf8509872014-10-08 12:03:19 +053050
Nabin Hait38be62c2016-02-22 16:24:23 +053051 if ((reorder_level and projected_qty <= reorder_level)
52 or (not reorder_level and reorder_qty and projected_qty < 0)):
Rushabh Mehtaf8509872014-10-08 12:03:19 +053053 deficiency = reorder_level - projected_qty
54 if deficiency > reorder_qty:
55 reorder_qty = deficiency
56
57 company = warehouse_company.get(warehouse) or default_company
58
59 material_requests[material_request_type].setdefault(company, []).append({
60 "item_code": item_code,
61 "warehouse": warehouse,
62 "reorder_qty": reorder_qty
63 })
64
Anand Doshi7b2b0cd2015-10-15 18:07:51 +053065 for item_code in items_to_consider:
Rushabh Mehtaf8509872014-10-08 12:03:19 +053066 item = frappe.get_doc("Item", item_code)
67
Nabin Haite7d15362014-12-25 16:01:55 +053068 if item.variant_of and not item.get("reorder_levels"):
Rushabh Mehtaf8509872014-10-08 12:03:19 +053069 item.update_template_tables()
70
Nabin Haite7d15362014-12-25 16:01:55 +053071 if item.get("reorder_levels"):
72 for d in item.get("reorder_levels"):
Rushabh Mehtaf8509872014-10-08 12:03:19 +053073 add_to_material_request(item_code, d.warehouse, d.warehouse_reorder_level,
74 d.warehouse_reorder_qty, d.material_request_type)
75
Rushabh Mehtaf8509872014-10-08 12:03:19 +053076 if material_requests:
77 return create_material_request(material_requests)
78
Anand Doshi7b2b0cd2015-10-15 18:07:51 +053079def get_item_warehouse_projected_qty(items_to_consider):
Rushabh Mehtaf8509872014-10-08 12:03:19 +053080 item_warehouse_projected_qty = {}
81
82 for item_code, warehouse, projected_qty in frappe.db.sql("""select item_code, warehouse, projected_qty
Anand Doshi7b2b0cd2015-10-15 18:07:51 +053083 from tabBin where item_code in ({0})
84 and (warehouse != "" and warehouse is not null)"""\
85 .format(", ".join(["%s"] * len(items_to_consider))), items_to_consider):
Rushabh Mehtaf8509872014-10-08 12:03:19 +053086
87 item_warehouse_projected_qty.setdefault(item_code, {})[warehouse] = flt(projected_qty)
88
89 return item_warehouse_projected_qty
90
91def create_material_request(material_requests):
92 """ Create indent on reaching reorder level """
93 mr_list = []
Rushabh Mehtaf8509872014-10-08 12:03:19 +053094 exceptions_list = []
95
96 def _log_exception():
97 if frappe.local.message_log:
98 exceptions_list.extend(frappe.local.message_log)
99 frappe.local.message_log = []
100 else:
101 exceptions_list.append(frappe.get_traceback())
102
Rushabh Mehtaf8509872014-10-08 12:03:19 +0530103 for request_type in material_requests:
104 for company in material_requests[request_type]:
105 try:
106 items = material_requests[request_type][company]
107 if not items:
108 continue
109
110 mr = frappe.new_doc("Material Request")
111 mr.update({
112 "company": company,
Rushabh Mehtaf8509872014-10-08 12:03:19 +0530113 "transaction_date": nowdate(),
Anand Doshid65a03d2015-11-12 20:35:05 +0530114 "material_request_type": "Material Transfer" if request_type=="Transfer" else request_type
Rushabh Mehtaf8509872014-10-08 12:03:19 +0530115 })
116
117 for d in items:
118 d = frappe._dict(d)
119 item = frappe.get_doc("Item", d.item_code)
Nabin Haite7d15362014-12-25 16:01:55 +0530120 mr.append("items", {
Rushabh Mehtaf8509872014-10-08 12:03:19 +0530121 "doctype": "Material Request Item",
122 "item_code": d.item_code,
123 "schedule_date": add_days(nowdate(),cint(item.lead_time_days)),
124 "uom": item.stock_uom,
125 "warehouse": d.warehouse,
126 "item_name": item.item_name,
127 "description": item.description,
128 "item_group": item.item_group,
129 "qty": d.reorder_qty,
130 "brand": item.brand,
131 })
132
133 mr.insert()
134 mr.submit()
135 mr_list.append(mr)
136
137 except:
138 _log_exception()
139
140 if mr_list:
141 if getattr(frappe.local, "reorder_email_notify", None) is None:
142 frappe.local.reorder_email_notify = cint(frappe.db.get_value('Stock Settings', None,
143 'reorder_email_notify'))
144
145 if(frappe.local.reorder_email_notify):
146 send_email_notification(mr_list)
147
148 if exceptions_list:
149 notify_errors(exceptions_list)
150
151 return mr_list
152
153def send_email_notification(mr_list):
154 """ Notify user about auto creation of indent"""
155
156 email_list = frappe.db.sql_list("""select distinct r.parent
157 from tabUserRole r, tabUser p
158 where p.name = r.parent and p.enabled = 1 and p.docstatus < 2
Rushabh Mehta94157332015-07-13 15:06:12 +0530159 and r.role in ('Purchase Manager','Stock Manager')
Rushabh Mehtaf8509872014-10-08 12:03:19 +0530160 and p.name not in ('Administrator', 'All', 'Guest')""")
161
Anand Doshi5cf7a0b2015-11-26 15:11:18 +0530162 msg = frappe.render_template("templates/emails/reorder_item.html", {
163 "mr_list": mr_list
164 })
165
Anand Doshi8860b9d2015-05-28 01:09:21 -0400166 frappe.sendmail(recipients=email_list,
Anand Doshi5cf7a0b2015-11-26 15:11:18 +0530167 subject=_('Auto Material Requests Generated'), message = msg)
Rushabh Mehtaf8509872014-10-08 12:03:19 +0530168
169def notify_errors(exceptions_list):
170 subject = "[Important] [ERPNext] Auto Reorder Errors"
171 content = """Dear System Manager,
172
173An error occured for certain Items while creating Material Requests based on Re-order level.
174
175Please rectify these issues:
176---
177<pre>
178%s
179</pre>
180---
181Regards,
182Administrator""" % ("\n\n".join(exceptions_list),)
183
184 from frappe.email import sendmail_to_system_managers
185 sendmail_to_system_managers(subject, content)