blob: f04b66323696a320ab1627f38a2ddfb6e90e281f [file] [log] [blame]
Rushabh Mehtae67d1fb2013-08-05 14:59:54 +05301# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
2# License: GNU General Public License v3. See license.txt
Nabin Hait9d0f6362013-01-07 18:51:11 +05303
4import webnotes
5from webnotes import msgprint, _
6import json
Nabin Hait62d06292013-05-22 16:19:10 +05307from webnotes.utils import flt, cstr, nowdate, add_days, cint
Rushabh Mehta5117d9c2013-02-19 15:27:31 +05308from webnotes.defaults import get_global_default
Anand Doshiad6180e2013-06-17 11:57:04 +05309from webnotes.utils.email_lib import sendmail
Nabin Hait9d0f6362013-01-07 18:51:11 +053010
Rushabh Mehtaa65253b2013-08-27 10:32:56 +053011class UserNotAllowedForWarehouse(webnotes.ValidationError): pass
12
Nabin Hait9d0f6362013-01-07 18:51:11 +053013def validate_end_of_life(item_code, end_of_life=None, verbose=1):
14 if not end_of_life:
15 end_of_life = webnotes.conn.get_value("Item", item_code, "end_of_life")
16
17 from webnotes.utils import getdate, now_datetime, formatdate
Anand Doshiad6180e2013-06-17 11:57:04 +053018 if end_of_life and getdate(end_of_life) <= now_datetime().date():
Nabin Hait9d0f6362013-01-07 18:51:11 +053019 msg = (_("Item") + " %(item_code)s: " + _("reached its end of life on") + \
20 " %(date)s. " + _("Please check") + ": %(end_of_life_label)s " + \
21 "in Item master") % {
22 "item_code": item_code,
23 "date": formatdate(end_of_life),
Anand Doshia43b29e2013-02-20 15:55:10 +053024 "end_of_life_label": webnotes.get_doctype("Item").get_label("end_of_life")
Nabin Hait9d0f6362013-01-07 18:51:11 +053025 }
26
27 _msgprint(msg, verbose)
28
29def validate_is_stock_item(item_code, is_stock_item=None, verbose=1):
30 if not is_stock_item:
31 is_stock_item = webnotes.conn.get_value("Item", item_code, "is_stock_item")
32
33 if is_stock_item != "Yes":
34 msg = (_("Item") + " %(item_code)s: " + _("is not a Stock Item")) % {
35 "item_code": item_code,
36 }
37
38 _msgprint(msg, verbose)
39
40def validate_cancelled_item(item_code, docstatus=None, verbose=1):
41 if docstatus is None:
42 docstatus = webnotes.conn.get_value("Item", item_code, "docstatus")
43
44 if docstatus == 2:
45 msg = (_("Item") + " %(item_code)s: " + _("is a cancelled Item")) % {
46 "item_code": item_code,
47 }
48
49 _msgprint(msg, verbose)
50
51def _msgprint(msg, verbose):
52 if verbose:
53 msgprint(msg, raise_exception=True)
54 else:
55 raise webnotes.ValidationError, msg
56
Nabin Hait9d0f6362013-01-07 18:51:11 +053057def get_incoming_rate(args):
58 """Get Incoming Rate based on valuation method"""
Anand Doshi1b531862013-01-10 19:29:51 +053059 from stock.stock_ledger import get_previous_sle
Nabin Hait9d0f6362013-01-07 18:51:11 +053060
61 in_rate = 0
62 if args.get("serial_no"):
63 in_rate = get_avg_purchase_rate(args.get("serial_no"))
64 elif args.get("bom_no"):
65 result = webnotes.conn.sql("""select ifnull(total_cost, 0) / ifnull(quantity, 1)
66 from `tabBOM` where name = %s and docstatus=1 and is_active=1""", args.get("bom_no"))
67 in_rate = result and flt(result[0][0]) or 0
68 else:
69 valuation_method = get_valuation_method(args.get("item_code"))
70 previous_sle = get_previous_sle(args)
71 if valuation_method == 'FIFO':
Nabin Hait831207f2013-01-16 14:15:48 +053072 if not previous_sle:
73 return 0.0
Rushabh Mehta4c17f942013-08-12 14:18:09 +053074 previous_stock_queue = json.loads(previous_sle.get('stock_queue', '[]') or '[]')
Nabin Hait831207f2013-01-16 14:15:48 +053075 in_rate = previous_stock_queue and \
Nabin Hait6b1f21d2013-01-16 17:17:17 +053076 get_fifo_rate(previous_stock_queue, args.get("qty") or 0) or 0
Nabin Hait9d0f6362013-01-07 18:51:11 +053077 elif valuation_method == 'Moving Average':
78 in_rate = previous_sle.get('valuation_rate') or 0
79 return in_rate
80
81def get_avg_purchase_rate(serial_nos):
82 """get average value of serial numbers"""
83
84 serial_nos = get_valid_serial_nos(serial_nos)
85 return flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0)) from `tabSerial No`
86 where name in (%s)""" % ", ".join(["%s"] * len(serial_nos)),
87 tuple(serial_nos))[0][0])
88
89def get_valuation_method(item_code):
90 """get valuation method from item or default"""
91 val_method = webnotes.conn.get_value('Item', item_code, 'valuation_method')
92 if not val_method:
Rushabh Mehta5117d9c2013-02-19 15:27:31 +053093 val_method = get_global_default('valuation_method') or "FIFO"
Nabin Hait9d0f6362013-01-07 18:51:11 +053094 return val_method
95
Nabin Hait831207f2013-01-16 14:15:48 +053096def get_fifo_rate(previous_stock_queue, qty):
97 """get FIFO (average) Rate from Queue"""
98 if qty >= 0:
99 total = sum(f[0] for f in previous_stock_queue)
100 return total and sum(f[0] * f[1] for f in previous_stock_queue) / flt(total) or 0.0
101 else:
102 outgoing_cost = 0
103 qty_to_pop = abs(qty)
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530104 while qty_to_pop and previous_stock_queue:
Nabin Hait831207f2013-01-16 14:15:48 +0530105 batch = previous_stock_queue[0]
106 if 0 < batch[0] <= qty_to_pop:
107 # if batch qty > 0
108 # not enough or exactly same qty in current batch, clear batch
109 outgoing_cost += flt(batch[0]) * flt(batch[1])
110 qty_to_pop -= batch[0]
111 previous_stock_queue.pop(0)
112 else:
113 # all from current batch
114 outgoing_cost += flt(qty_to_pop) * flt(batch[1])
115 batch[0] -= qty_to_pop
116 qty_to_pop = 0
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530117 # if queue gets blank and qty_to_pop remaining, get average rate of full queue
118 return outgoing_cost / abs(qty) - qty_to_pop
Nabin Hait9d0f6362013-01-07 18:51:11 +0530119
120def get_valid_serial_nos(sr_nos, qty=0, item_code=''):
121 """split serial nos, validate and return list of valid serial nos"""
122 # TODO: remove duplicates in client side
123 serial_nos = cstr(sr_nos).strip().replace(',', '\n').split('\n')
124
125 valid_serial_nos = []
126 for val in serial_nos:
127 if val:
128 val = val.strip()
129 if val in valid_serial_nos:
130 msgprint("You have entered duplicate serial no: '%s'" % val, raise_exception=1)
131 else:
132 valid_serial_nos.append(val)
133
134 if qty and len(valid_serial_nos) != abs(qty):
135 msgprint("Please enter serial nos for "
136 + cstr(abs(qty)) + " quantity against item code: " + item_code,
137 raise_exception=1)
138
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530139 return valid_serial_nos
140
Nabin Haitdc95c152013-02-07 12:08:38 +0530141def get_warehouse_list(doctype, txt, searchfield, start, page_len, filters):
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530142 """used in search queries"""
143 wlist = []
144 for w in webnotes.conn.sql_list("""select name from tabWarehouse
145 where name like '%%%s%%'""" % txt):
146 if webnotes.session.user=="Administrator":
147 wlist.append([w])
148 else:
149 warehouse_users = webnotes.conn.sql_list("""select user from `tabWarehouse User`
150 where parent=%s""", w)
151 if not warehouse_users:
152 wlist.append([w])
153 elif webnotes.session.user in warehouse_users:
154 wlist.append([w])
155 return wlist
Nabin Haita72c5122013-03-06 18:50:53 +0530156
Rushabh Mehtaa65253b2013-08-27 10:32:56 +0530157def validate_warehouse_user(warehouse):
158 if webnotes.session.user=="Administrator":
159 return
160 warehouse_users = [p[0] for p in webnotes.conn.sql("""select user from `tabWarehouse User`
161 where parent=%s""", warehouse)]
162
163 if warehouse_users and not (webnotes.session.user in warehouse_users):
164 webnotes.throw(_("Not allowed entry in Warehouse") \
165 + ": " + warehouse, UserNotAllowedForWarehouse)
166
Anand Doshi5dd6b1d2013-08-07 19:27:30 +0530167def get_buying_amount(item_code, voucher_type, voucher_no, voucher_detail_no,
Nabin Haitc3afb252013-03-19 12:01:24 +0530168 stock_ledger_entries, item_sales_bom=None):
169 if item_sales_bom and item_sales_bom.get(item_code):
Nabin Haita72c5122013-03-06 18:50:53 +0530170 # sales bom item
171 buying_amount = 0.0
172 for bom_item in item_sales_bom[item_code]:
Anand Doshi96b189c2013-03-26 18:43:10 +0530173 if bom_item.get("parent_detail_docname")==voucher_detail_no:
Anand Doshi5dd6b1d2013-08-07 19:27:30 +0530174 buying_amount += _get_buying_amount(voucher_type, voucher_no, voucher_detail_no, stock_ledger_entries)
Nabin Haita72c5122013-03-06 18:50:53 +0530175 return buying_amount
176 else:
177 # doesn't have sales bom
Anand Doshi5dd6b1d2013-08-07 19:27:30 +0530178 return _get_buying_amount(voucher_type, voucher_no, voucher_detail_no, stock_ledger_entries)
Nabin Haita72c5122013-03-06 18:50:53 +0530179
Anand Doshi5dd6b1d2013-08-07 19:27:30 +0530180def _get_buying_amount(voucher_type, voucher_no, item_row, stock_ledger_entries):
181 # IMP NOTE
182 # stock_ledger_entries should already be filtered by item_code and warehouse and
183 # sorted by posting_date desc, posting_time desc
184 for i, sle in enumerate(stock_ledger_entries):
Nabin Hait0cfbc5f2013-03-12 11:34:56 +0530185 if sle.voucher_type == voucher_type and sle.voucher_no == voucher_no and \
Anand Doshi8c454202013-03-28 16:40:30 +0530186 sle.voucher_detail_no == item_row:
Anand Doshi5dd6b1d2013-08-07 19:27:30 +0530187 previous_stock_value = len(stock_ledger_entries) > i+1 and \
188 flt(stock_ledger_entries[i+1].stock_value) or 0.0
Anand Doshi96b189c2013-03-26 18:43:10 +0530189
Nabin Haitc3afb252013-03-19 12:01:24 +0530190 buying_amount = previous_stock_value - flt(sle.stock_value)
Anand Doshi6d8d3b42013-03-21 18:45:02 +0530191
Nabin Haitc3afb252013-03-19 12:01:24 +0530192 return buying_amount
Nabin Hait62d06292013-05-22 16:19:10 +0530193 return 0.0
194
195
196def reorder_item():
197 """ Reorder item if stock reaches reorder level"""
198 if not hasattr(webnotes, "auto_indent"):
Nabin Haitbf5d44c2013-08-12 16:30:48 +0530199 webnotes.auto_indent = cint(webnotes.conn.get_value('Stock Settings', None, 'auto_indent'))
200
Nabin Hait62d06292013-05-22 16:19:10 +0530201 if webnotes.auto_indent:
202 material_requests = {}
203 bin_list = webnotes.conn.sql("""select item_code, warehouse, projected_qty
Anand Doshiad6180e2013-06-17 11:57:04 +0530204 from tabBin where ifnull(item_code, '') != '' and ifnull(warehouse, '') != ''
205 and exists (select name from `tabItem`
206 where `tabItem`.name = `tabBin`.item_code and
207 is_stock_item='Yes' and (is_purchase_item='Yes' or is_sub_contracted_item='Yes') and
Anand Doshi4d47b002013-08-23 16:54:31 +0530208 (ifnull(end_of_life, '')='' or end_of_life > now()))""", as_dict=True)
Nabin Hait62d06292013-05-22 16:19:10 +0530209 for bin in bin_list:
210 #check if re-order is required
211 item_reorder = webnotes.conn.get("Item Reorder",
212 {"parent": bin.item_code, "warehouse": bin.warehouse})
213 if item_reorder:
214 reorder_level = item_reorder.warehouse_reorder_level
215 reorder_qty = item_reorder.warehouse_reorder_qty
216 material_request_type = item_reorder.material_request_type or "Purchase"
217 else:
218 reorder_level, reorder_qty = webnotes.conn.get_value("Item", bin.item_code,
219 ["re_order_level", "re_order_qty"])
220 material_request_type = "Purchase"
221
Anand Doshiad6180e2013-06-17 11:57:04 +0530222 if flt(reorder_level) and flt(bin.projected_qty) < flt(reorder_level):
Nabin Hait62d06292013-05-22 16:19:10 +0530223 if flt(reorder_level) - flt(bin.projected_qty) > flt(reorder_qty):
224 reorder_qty = flt(reorder_level) - flt(bin.projected_qty)
225
226 company = webnotes.conn.get_value("Warehouse", bin.warehouse, "company") or \
227 webnotes.defaults.get_defaults()["company"] or \
228 webnotes.conn.sql("""select name from tabCompany limit 1""")[0][0]
229
230 material_requests.setdefault(material_request_type, webnotes._dict()).setdefault(
231 company, []).append(webnotes._dict({
232 "item_code": bin.item_code,
233 "warehouse": bin.warehouse,
234 "reorder_qty": reorder_qty
235 })
236 )
237
238 create_material_request(material_requests)
239
240def create_material_request(material_requests):
241 """ Create indent on reaching reorder level """
242 mr_list = []
243 defaults = webnotes.defaults.get_defaults()
Anand Doshiad6180e2013-06-17 11:57:04 +0530244 exceptions_list = []
Nabin Hait62d06292013-05-22 16:19:10 +0530245 for request_type in material_requests:
246 for company in material_requests[request_type]:
Anand Doshiad6180e2013-06-17 11:57:04 +0530247 try:
248 items = material_requests[request_type][company]
249 if not items:
250 continue
Anand Doshi6f6e91c2013-07-22 11:28:34 +0530251
Nabin Hait62d06292013-05-22 16:19:10 +0530252 mr = [{
253 "doctype": "Material Request",
254 "company": company,
255 "fiscal_year": defaults.fiscal_year,
256 "transaction_date": nowdate(),
257 "material_request_type": request_type,
258 "remark": _("This is an auto generated Material Request.") + \
259 _("""It was raised because the (actual + ordered + indented - reserved)
260 quantity reaches re-order level when the following record was created""")
261 }]
262
Anand Doshiad6180e2013-06-17 11:57:04 +0530263 for d in items:
264 item = webnotes.doc("Item", d.item_code)
265 mr.append({
266 "doctype": "Material Request Item",
267 "parenttype": "Material Request",
268 "parentfield": "indent_details",
269 "item_code": d.item_code,
270 "schedule_date": add_days(nowdate(),cint(item.lead_time_days)),
271 "uom": item.stock_uom,
272 "warehouse": d.warehouse,
273 "item_name": item.item_name,
274 "description": item.description,
275 "item_group": item.item_group,
276 "qty": d.reorder_qty,
277 "brand": item.brand,
278 })
Nabin Hait62d06292013-05-22 16:19:10 +0530279
Anand Doshiad6180e2013-06-17 11:57:04 +0530280 mr_bean = webnotes.bean(mr)
281 mr_bean.insert()
282 mr_bean.submit()
283 mr_list.append(mr_bean)
Anand Doshi6f6e91c2013-07-22 11:28:34 +0530284
Anand Doshiad6180e2013-06-17 11:57:04 +0530285 except:
286 if webnotes.message_log:
287 exceptions_list.append([] + webnotes.message_log)
288 webnotes.message_log = []
289 else:
290 exceptions_list.append(webnotes.getTraceback())
Nabin Hait62d06292013-05-22 16:19:10 +0530291
292 if mr_list:
293 if not hasattr(webnotes, "reorder_email_notify"):
Nabin Haitbf5d44c2013-08-12 16:30:48 +0530294 webnotes.reorder_email_notify = cint(webnotes.conn.get_value('Stock Settings', None,
295 'reorder_email_notify'))
Nabin Hait62d06292013-05-22 16:19:10 +0530296
297 if(webnotes.reorder_email_notify):
298 send_email_notification(mr_list)
Anand Doshiad6180e2013-06-17 11:57:04 +0530299
300 if exceptions_list:
301 notify_errors(exceptions_list)
Nabin Hait62d06292013-05-22 16:19:10 +0530302
303def send_email_notification(mr_list):
304 """ Notify user about auto creation of indent"""
305
Nabin Hait62d06292013-05-22 16:19:10 +0530306 email_list = webnotes.conn.sql_list("""select distinct r.parent
307 from tabUserRole r, tabProfile p
308 where p.name = r.parent and p.enabled = 1 and p.docstatus < 2
309 and r.role in ('Purchase Manager','Material Manager')
310 and p.name not in ('Administrator', 'All', 'Guest')""")
311
312 msg="""<h3>Following Material Requests has been raised automatically \
313 based on item reorder level:</h3>"""
314 for mr in mr_list:
315 msg += "<p><b><u>" + mr.doc.name + """</u></b></p><table class='table table-bordered'><tr>
316 <th>Item Code</th><th>Warehouse</th><th>Qty</th><th>UOM</th></tr>"""
317 for item in mr.doclist.get({"parentfield": "indent_details"}):
318 msg += "<tr><td>" + item.item_code + "</td><td>" + item.warehouse + "</td><td>" + \
319 cstr(item.qty) + "</td><td>" + cstr(item.uom) + "</td></tr>"
320 msg += "</table>"
Anand Doshiad6180e2013-06-17 11:57:04 +0530321 sendmail(email_list, subject='Auto Material Request Generation Notification', msg = msg)
322
323def notify_errors(exceptions_list):
324 subject = "[Important] [ERPNext] Error(s) while creating Material Requests based on Re-order Levels"
325 msg = """Dear System Manager,
326
327 An error occured for certain Items while creating Material Requests based on Re-order level.
328
329 Please rectify these issues:
330 ---
331
332 %s
333
334 ---
335 Regards,
336 Administrator""" % ("\n\n".join(["\n".join(msg) for msg in exceptions_list]),)
337
338 from webnotes.profile import get_system_managers
339 sendmail(get_system_managers(), subject=subject, msg=msg)