blob: 7105e79401ce4e6cbf69c9dff08a5412ff9c621b [file] [log] [blame]
Rushabh Mehtaad45e312013-11-20 12:59:58 +05301# Copyright (c) 2013, Web Notes 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
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05304import frappe
5from frappe import msgprint, _
Nabin Hait9d0f6362013-01-07 18:51:11 +05306import json
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05307from frappe.utils import flt, cstr, nowdate, add_days, cint
8from frappe.defaults import get_global_default
9from frappe.utils.email_lib import sendmail
Nabin Hait9d0f6362013-01-07 18:51:11 +053010
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053011class InvalidWarehouseCompany(frappe.ValidationError): pass
Nabin Hait0dd7be12013-08-02 11:45:43 +053012
Nabin Hait625da792013-09-25 10:32:51 +053013def get_stock_balance_on(warehouse, posting_date=None):
Nabin Hait0dd7be12013-08-02 11:45:43 +053014 if not posting_date: posting_date = nowdate()
15
Anand Doshie9baaa62014-02-26 12:35:33 +053016 stock_ledger_entries = frappe.db.sql("""
Nabin Hait0dd7be12013-08-02 11:45:43 +053017 SELECT
Nabin Hait625da792013-09-25 10:32:51 +053018 item_code, stock_value
Nabin Hait0dd7be12013-08-02 11:45:43 +053019 FROM
20 `tabStock Ledger Entry`
21 WHERE
Nabin Hait625da792013-09-25 10:32:51 +053022 warehouse=%s AND posting_date <= %s
Nabin Hait0dd7be12013-08-02 11:45:43 +053023 ORDER BY timestamp(posting_date, posting_time) DESC, name DESC
Nabin Hait625da792013-09-25 10:32:51 +053024 """, (warehouse, posting_date), as_dict=1)
Nabin Hait0dd7be12013-08-02 11:45:43 +053025
26 sle_map = {}
27 for sle in stock_ledger_entries:
Nabin Hait625da792013-09-25 10:32:51 +053028 sle_map.setdefault(sle.item_code, flt(sle.stock_value))
Nabin Hait0dd7be12013-08-02 11:45:43 +053029
Nabin Hait625da792013-09-25 10:32:51 +053030 return sum(sle_map.values())
Nabin Hait0dd7be12013-08-02 11:45:43 +053031
Nabin Hait47dc3182013-08-06 15:58:16 +053032def get_latest_stock_balance():
33 bin_map = {}
Anand Doshie9baaa62014-02-26 12:35:33 +053034 for d in frappe.db.sql("""SELECT item_code, warehouse, stock_value as stock_value
Nabin Hait47dc3182013-08-06 15:58:16 +053035 FROM tabBin""", as_dict=1):
Nabin Hait469ee712013-08-07 12:33:37 +053036 bin_map.setdefault(d.warehouse, {}).setdefault(d.item_code, flt(d.stock_value))
Nabin Hait47dc3182013-08-06 15:58:16 +053037
38 return bin_map
Nabin Hait74c281c2013-08-19 16:17:18 +053039
40def get_bin(item_code, warehouse):
Anand Doshie9baaa62014-02-26 12:35:33 +053041 bin = frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse})
Nabin Hait74c281c2013-08-19 16:17:18 +053042 if not bin:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053043 bin_wrapper = frappe.bean([{
Nabin Hait74c281c2013-08-19 16:17:18 +053044 "doctype": "Bin",
45 "item_code": item_code,
46 "warehouse": warehouse,
47 }])
48 bin_wrapper.ignore_permissions = 1
49 bin_wrapper.insert()
50 bin_obj = bin_wrapper.make_controller()
51 else:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +053052 from frappe.model.code import get_obj
Nabin Hait74c281c2013-08-19 16:17:18 +053053 bin_obj = get_obj('Bin', bin)
54 return bin_obj
55
56def update_bin(args):
Anand Doshie9baaa62014-02-26 12:35:33 +053057 is_stock_item = frappe.db.get_value('Item', args.get("item_code"), 'is_stock_item')
Nabin Hait74c281c2013-08-19 16:17:18 +053058 if is_stock_item == 'Yes':
59 bin = get_bin(args.get("item_code"), args.get("warehouse"))
60 bin.update_stock(args)
61 return bin
62 else:
63 msgprint("[Stock Update] Ignored %s since it is not a stock item"
64 % args.get("item_code"))
Nabin Hait0dd7be12013-08-02 11:45:43 +053065
Nabin Hait9d0f6362013-01-07 18:51:11 +053066def get_incoming_rate(args):
67 """Get Incoming Rate based on valuation method"""
Rushabh Mehta1f847992013-12-12 19:12:19 +053068 from erpnext.stock.stock_ledger import get_previous_sle
Nabin Hait9d0f6362013-01-07 18:51:11 +053069
70 in_rate = 0
71 if args.get("serial_no"):
72 in_rate = get_avg_purchase_rate(args.get("serial_no"))
73 elif args.get("bom_no"):
Anand Doshie9baaa62014-02-26 12:35:33 +053074 result = frappe.db.sql("""select ifnull(total_cost, 0) / ifnull(quantity, 1)
Nabin Hait9d0f6362013-01-07 18:51:11 +053075 from `tabBOM` where name = %s and docstatus=1 and is_active=1""", args.get("bom_no"))
76 in_rate = result and flt(result[0][0]) or 0
77 else:
78 valuation_method = get_valuation_method(args.get("item_code"))
79 previous_sle = get_previous_sle(args)
80 if valuation_method == 'FIFO':
Nabin Hait831207f2013-01-16 14:15:48 +053081 if not previous_sle:
82 return 0.0
Rushabh Mehta4c17f942013-08-12 14:18:09 +053083 previous_stock_queue = json.loads(previous_sle.get('stock_queue', '[]') or '[]')
Nabin Hait831207f2013-01-16 14:15:48 +053084 in_rate = previous_stock_queue and \
Nabin Hait6b1f21d2013-01-16 17:17:17 +053085 get_fifo_rate(previous_stock_queue, args.get("qty") or 0) or 0
Nabin Hait9d0f6362013-01-07 18:51:11 +053086 elif valuation_method == 'Moving Average':
87 in_rate = previous_sle.get('valuation_rate') or 0
88 return in_rate
89
90def get_avg_purchase_rate(serial_nos):
91 """get average value of serial numbers"""
92
93 serial_nos = get_valid_serial_nos(serial_nos)
Anand Doshie9baaa62014-02-26 12:35:33 +053094 return flt(frappe.db.sql("""select avg(ifnull(purchase_rate, 0)) from `tabSerial No`
Nabin Hait9d0f6362013-01-07 18:51:11 +053095 where name in (%s)""" % ", ".join(["%s"] * len(serial_nos)),
96 tuple(serial_nos))[0][0])
97
98def get_valuation_method(item_code):
99 """get valuation method from item or default"""
Anand Doshie9baaa62014-02-26 12:35:33 +0530100 val_method = frappe.db.get_value('Item', item_code, 'valuation_method')
Nabin Hait9d0f6362013-01-07 18:51:11 +0530101 if not val_method:
Rushabh Mehta5117d9c2013-02-19 15:27:31 +0530102 val_method = get_global_default('valuation_method') or "FIFO"
Nabin Hait9d0f6362013-01-07 18:51:11 +0530103 return val_method
104
Nabin Hait831207f2013-01-16 14:15:48 +0530105def get_fifo_rate(previous_stock_queue, qty):
106 """get FIFO (average) Rate from Queue"""
107 if qty >= 0:
108 total = sum(f[0] for f in previous_stock_queue)
109 return total and sum(f[0] * f[1] for f in previous_stock_queue) / flt(total) or 0.0
110 else:
111 outgoing_cost = 0
112 qty_to_pop = abs(qty)
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530113 while qty_to_pop and previous_stock_queue:
Nabin Hait831207f2013-01-16 14:15:48 +0530114 batch = previous_stock_queue[0]
115 if 0 < batch[0] <= qty_to_pop:
116 # if batch qty > 0
117 # not enough or exactly same qty in current batch, clear batch
118 outgoing_cost += flt(batch[0]) * flt(batch[1])
119 qty_to_pop -= batch[0]
120 previous_stock_queue.pop(0)
121 else:
122 # all from current batch
123 outgoing_cost += flt(qty_to_pop) * flt(batch[1])
124 batch[0] -= qty_to_pop
125 qty_to_pop = 0
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530126 # if queue gets blank and qty_to_pop remaining, get average rate of full queue
127 return outgoing_cost / abs(qty) - qty_to_pop
Nabin Hait9d0f6362013-01-07 18:51:11 +0530128
129def get_valid_serial_nos(sr_nos, qty=0, item_code=''):
130 """split serial nos, validate and return list of valid serial nos"""
131 # TODO: remove duplicates in client side
132 serial_nos = cstr(sr_nos).strip().replace(',', '\n').split('\n')
133
134 valid_serial_nos = []
135 for val in serial_nos:
136 if val:
137 val = val.strip()
138 if val in valid_serial_nos:
139 msgprint("You have entered duplicate serial no: '%s'" % val, raise_exception=1)
140 else:
141 valid_serial_nos.append(val)
142
143 if qty and len(valid_serial_nos) != abs(qty):
144 msgprint("Please enter serial nos for "
145 + cstr(abs(qty)) + " quantity against item code: " + item_code,
146 raise_exception=1)
147
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530148 return valid_serial_nos
Nabin Haita72c5122013-03-06 18:50:53 +0530149
Anand Doshi373680b2013-10-10 16:04:40 +0530150def validate_warehouse_company(warehouse, company):
Anand Doshie9baaa62014-02-26 12:35:33 +0530151 warehouse_company = frappe.db.get_value("Warehouse", warehouse, "company")
Anand Doshi373680b2013-10-10 16:04:40 +0530152 if warehouse_company and warehouse_company != company:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530153 frappe.msgprint(_("Warehouse does not belong to company.") + " (" + \
Anand Doshi373680b2013-10-10 16:04:40 +0530154 warehouse + ", " + company +")", raise_exception=InvalidWarehouseCompany)
Rushabh Mehtaa65253b2013-08-27 10:32:56 +0530155
Nabin Hait94c90bd2013-08-30 22:48:19 +0530156def get_sales_bom_buying_amount(item_code, warehouse, voucher_type, voucher_no, voucher_detail_no,
157 stock_ledger_entries, item_sales_bom):
158 # sales bom item
159 buying_amount = 0.0
160 for bom_item in item_sales_bom[item_code]:
161 if bom_item.get("parent_detail_docname")==voucher_detail_no:
162 buying_amount += get_buying_amount(voucher_type, voucher_no, voucher_detail_no,
163 stock_ledger_entries.get((bom_item.item_code, warehouse), []))
164
165 return buying_amount
Nabin Haita72c5122013-03-06 18:50:53 +0530166
Nabin Hait94c90bd2013-08-30 22:48:19 +0530167def get_buying_amount(voucher_type, voucher_no, item_row, stock_ledger_entries):
Anand Doshi5dd6b1d2013-08-07 19:27:30 +0530168 # IMP NOTE
169 # stock_ledger_entries should already be filtered by item_code and warehouse and
170 # sorted by posting_date desc, posting_time desc
171 for i, sle in enumerate(stock_ledger_entries):
Nabin Hait0cfbc5f2013-03-12 11:34:56 +0530172 if sle.voucher_type == voucher_type and sle.voucher_no == voucher_no and \
Anand Doshi8c454202013-03-28 16:40:30 +0530173 sle.voucher_detail_no == item_row:
Anand Doshi5dd6b1d2013-08-07 19:27:30 +0530174 previous_stock_value = len(stock_ledger_entries) > i+1 and \
175 flt(stock_ledger_entries[i+1].stock_value) or 0.0
Nabin Haitc3afb252013-03-19 12:01:24 +0530176 buying_amount = previous_stock_value - flt(sle.stock_value)
Anand Doshi6d8d3b42013-03-21 18:45:02 +0530177
Nabin Haitc3afb252013-03-19 12:01:24 +0530178 return buying_amount
Nabin Hait62d06292013-05-22 16:19:10 +0530179 return 0.0
180
181
182def reorder_item():
183 """ Reorder item if stock reaches reorder level"""
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530184 if getattr(frappe.local, "auto_indent", None) is None:
Anand Doshie9baaa62014-02-26 12:35:33 +0530185 frappe.local.auto_indent = cint(frappe.db.get_value('Stock Settings', None, 'auto_indent'))
Nabin Haitbf5d44c2013-08-12 16:30:48 +0530186
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530187 if frappe.local.auto_indent:
Nabin Hait62d06292013-05-22 16:19:10 +0530188 material_requests = {}
Anand Doshie9baaa62014-02-26 12:35:33 +0530189 bin_list = frappe.db.sql("""select item_code, warehouse, projected_qty
Anand Doshiad6180e2013-06-17 11:57:04 +0530190 from tabBin where ifnull(item_code, '') != '' and ifnull(warehouse, '') != ''
191 and exists (select name from `tabItem`
192 where `tabItem`.name = `tabBin`.item_code and
193 is_stock_item='Yes' and (is_purchase_item='Yes' or is_sub_contracted_item='Yes') and
Anand Doshi4d47b002013-08-23 16:54:31 +0530194 (ifnull(end_of_life, '')='' or end_of_life > now()))""", as_dict=True)
Nabin Hait62d06292013-05-22 16:19:10 +0530195 for bin in bin_list:
196 #check if re-order is required
Anand Doshie9baaa62014-02-26 12:35:33 +0530197 item_reorder = frappe.db.get("Item Reorder",
Nabin Hait62d06292013-05-22 16:19:10 +0530198 {"parent": bin.item_code, "warehouse": bin.warehouse})
199 if item_reorder:
200 reorder_level = item_reorder.warehouse_reorder_level
201 reorder_qty = item_reorder.warehouse_reorder_qty
202 material_request_type = item_reorder.material_request_type or "Purchase"
203 else:
Anand Doshie9baaa62014-02-26 12:35:33 +0530204 reorder_level, reorder_qty = frappe.db.get_value("Item", bin.item_code,
Nabin Hait62d06292013-05-22 16:19:10 +0530205 ["re_order_level", "re_order_qty"])
206 material_request_type = "Purchase"
207
Anand Doshiad6180e2013-06-17 11:57:04 +0530208 if flt(reorder_level) and flt(bin.projected_qty) < flt(reorder_level):
Nabin Hait62d06292013-05-22 16:19:10 +0530209 if flt(reorder_level) - flt(bin.projected_qty) > flt(reorder_qty):
210 reorder_qty = flt(reorder_level) - flt(bin.projected_qty)
211
Anand Doshie9baaa62014-02-26 12:35:33 +0530212 company = frappe.db.get_value("Warehouse", bin.warehouse, "company") or \
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530213 frappe.defaults.get_defaults()["company"] or \
Anand Doshie9baaa62014-02-26 12:35:33 +0530214 frappe.db.sql("""select name from tabCompany limit 1""")[0][0]
Nabin Hait62d06292013-05-22 16:19:10 +0530215
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530216 material_requests.setdefault(material_request_type, frappe._dict()).setdefault(
217 company, []).append(frappe._dict({
Nabin Hait62d06292013-05-22 16:19:10 +0530218 "item_code": bin.item_code,
219 "warehouse": bin.warehouse,
220 "reorder_qty": reorder_qty
221 })
222 )
Anand Doshi4a67d362013-11-13 14:53:09 +0530223
Nabin Hait62d06292013-05-22 16:19:10 +0530224 create_material_request(material_requests)
225
226def create_material_request(material_requests):
227 """ Create indent on reaching reorder level """
228 mr_list = []
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530229 defaults = frappe.defaults.get_defaults()
Anand Doshiad6180e2013-06-17 11:57:04 +0530230 exceptions_list = []
Rushabh Mehta1f847992013-12-12 19:12:19 +0530231 from erpnext.accounts.utils import get_fiscal_year
Akhilesh Darjeeb0a1b3a2013-11-26 14:45:27 +0530232 current_fiscal_year = get_fiscal_year(nowdate())[0] or defaults.fiscal_year
Nabin Hait62d06292013-05-22 16:19:10 +0530233 for request_type in material_requests:
234 for company in material_requests[request_type]:
Anand Doshiad6180e2013-06-17 11:57:04 +0530235 try:
236 items = material_requests[request_type][company]
237 if not items:
238 continue
Anand Doshi6f6e91c2013-07-22 11:28:34 +0530239
Nabin Hait62d06292013-05-22 16:19:10 +0530240 mr = [{
241 "doctype": "Material Request",
242 "company": company,
Akhilesh Darjeeb0a1b3a2013-11-26 14:45:27 +0530243 "fiscal_year": current_fiscal_year,
Nabin Hait62d06292013-05-22 16:19:10 +0530244 "transaction_date": nowdate(),
Anand Doshi4a67d362013-11-13 14:53:09 +0530245 "material_request_type": request_type
Nabin Hait62d06292013-05-22 16:19:10 +0530246 }]
247
Anand Doshiad6180e2013-06-17 11:57:04 +0530248 for d in items:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530249 item = frappe.doc("Item", d.item_code)
Anand Doshiad6180e2013-06-17 11:57:04 +0530250 mr.append({
251 "doctype": "Material Request Item",
252 "parenttype": "Material Request",
253 "parentfield": "indent_details",
254 "item_code": d.item_code,
255 "schedule_date": add_days(nowdate(),cint(item.lead_time_days)),
256 "uom": item.stock_uom,
257 "warehouse": d.warehouse,
258 "item_name": item.item_name,
259 "description": item.description,
260 "item_group": item.item_group,
261 "qty": d.reorder_qty,
262 "brand": item.brand,
263 })
Nabin Hait62d06292013-05-22 16:19:10 +0530264
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530265 mr_bean = frappe.bean(mr)
Anand Doshiad6180e2013-06-17 11:57:04 +0530266 mr_bean.insert()
267 mr_bean.submit()
268 mr_list.append(mr_bean)
Anand Doshi6f6e91c2013-07-22 11:28:34 +0530269
Anand Doshiad6180e2013-06-17 11:57:04 +0530270 except:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530271 if frappe.local.message_log:
272 exceptions_list.append([] + frappe.local.message_log)
273 frappe.local.message_log = []
Anand Doshiad6180e2013-06-17 11:57:04 +0530274 else:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530275 exceptions_list.append(frappe.get_traceback())
Nabin Hait62d06292013-05-22 16:19:10 +0530276
277 if mr_list:
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530278 if getattr(frappe.local, "reorder_email_notify", None) is None:
Anand Doshie9baaa62014-02-26 12:35:33 +0530279 frappe.local.reorder_email_notify = cint(frappe.db.get_value('Stock Settings', None,
Nabin Haitbf5d44c2013-08-12 16:30:48 +0530280 'reorder_email_notify'))
Nabin Hait62d06292013-05-22 16:19:10 +0530281
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530282 if(frappe.local.reorder_email_notify):
Nabin Hait62d06292013-05-22 16:19:10 +0530283 send_email_notification(mr_list)
Anand Doshiad6180e2013-06-17 11:57:04 +0530284
285 if exceptions_list:
286 notify_errors(exceptions_list)
Nabin Hait62d06292013-05-22 16:19:10 +0530287
288def send_email_notification(mr_list):
289 """ Notify user about auto creation of indent"""
290
Anand Doshie9baaa62014-02-26 12:35:33 +0530291 email_list = frappe.db.sql_list("""select distinct r.parent
Nabin Hait62d06292013-05-22 16:19:10 +0530292 from tabUserRole r, tabProfile p
293 where p.name = r.parent and p.enabled = 1 and p.docstatus < 2
294 and r.role in ('Purchase Manager','Material Manager')
295 and p.name not in ('Administrator', 'All', 'Guest')""")
296
297 msg="""<h3>Following Material Requests has been raised automatically \
298 based on item reorder level:</h3>"""
299 for mr in mr_list:
300 msg += "<p><b><u>" + mr.doc.name + """</u></b></p><table class='table table-bordered'><tr>
301 <th>Item Code</th><th>Warehouse</th><th>Qty</th><th>UOM</th></tr>"""
302 for item in mr.doclist.get({"parentfield": "indent_details"}):
303 msg += "<tr><td>" + item.item_code + "</td><td>" + item.warehouse + "</td><td>" + \
304 cstr(item.qty) + "</td><td>" + cstr(item.uom) + "</td></tr>"
305 msg += "</table>"
Anand Doshiad6180e2013-06-17 11:57:04 +0530306 sendmail(email_list, subject='Auto Material Request Generation Notification', msg = msg)
307
308def notify_errors(exceptions_list):
309 subject = "[Important] [ERPNext] Error(s) while creating Material Requests based on Re-order Levels"
310 msg = """Dear System Manager,
311
312 An error occured for certain Items while creating Material Requests based on Re-order level.
313
314 Please rectify these issues:
315 ---
316
317 %s
318
319 ---
320 Regards,
321 Administrator""" % ("\n\n".join(["\n".join(msg) for msg in exceptions_list]),)
322
Rushabh Mehta793ba6b2014-02-14 15:47:51 +0530323 from frappe.profile import get_system_managers
Anand Doshiad6180e2013-06-17 11:57:04 +0530324 sendmail(get_system_managers(), subject=subject, msg=msg)