blob: 52471e4c6fd3fbe6db2a05cc9e761d3e83524853 [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
Nabin Hait94c90bd2013-08-30 22:48:19 +0530167def get_sales_bom_buying_amount(item_code, warehouse, voucher_type, voucher_no, voucher_detail_no,
168 stock_ledger_entries, item_sales_bom):
169 # sales bom item
170 buying_amount = 0.0
171 for bom_item in item_sales_bom[item_code]:
172 if bom_item.get("parent_detail_docname")==voucher_detail_no:
173 buying_amount += get_buying_amount(voucher_type, voucher_no, voucher_detail_no,
174 stock_ledger_entries.get((bom_item.item_code, warehouse), []))
175
176 return buying_amount
Nabin Haita72c5122013-03-06 18:50:53 +0530177
Nabin Hait94c90bd2013-08-30 22:48:19 +0530178def get_buying_amount(voucher_type, voucher_no, item_row, stock_ledger_entries):
Anand Doshi5dd6b1d2013-08-07 19:27:30 +0530179 # IMP NOTE
180 # stock_ledger_entries should already be filtered by item_code and warehouse and
181 # sorted by posting_date desc, posting_time desc
182 for i, sle in enumerate(stock_ledger_entries):
Nabin Hait0cfbc5f2013-03-12 11:34:56 +0530183 if sle.voucher_type == voucher_type and sle.voucher_no == voucher_no and \
Anand Doshi8c454202013-03-28 16:40:30 +0530184 sle.voucher_detail_no == item_row:
Anand Doshi5dd6b1d2013-08-07 19:27:30 +0530185 previous_stock_value = len(stock_ledger_entries) > i+1 and \
186 flt(stock_ledger_entries[i+1].stock_value) or 0.0
Anand Doshi96b189c2013-03-26 18:43:10 +0530187
Nabin Haitc3afb252013-03-19 12:01:24 +0530188 buying_amount = previous_stock_value - flt(sle.stock_value)
Anand Doshi6d8d3b42013-03-21 18:45:02 +0530189
Nabin Haitc3afb252013-03-19 12:01:24 +0530190 return buying_amount
Nabin Hait62d06292013-05-22 16:19:10 +0530191 return 0.0
192
193
194def reorder_item():
195 """ Reorder item if stock reaches reorder level"""
196 if not hasattr(webnotes, "auto_indent"):
Nabin Haitbf5d44c2013-08-12 16:30:48 +0530197 webnotes.auto_indent = cint(webnotes.conn.get_value('Stock Settings', None, 'auto_indent'))
198
Nabin Hait62d06292013-05-22 16:19:10 +0530199 if webnotes.auto_indent:
200 material_requests = {}
201 bin_list = webnotes.conn.sql("""select item_code, warehouse, projected_qty
Anand Doshiad6180e2013-06-17 11:57:04 +0530202 from tabBin where ifnull(item_code, '') != '' and ifnull(warehouse, '') != ''
203 and exists (select name from `tabItem`
204 where `tabItem`.name = `tabBin`.item_code and
205 is_stock_item='Yes' and (is_purchase_item='Yes' or is_sub_contracted_item='Yes') and
Anand Doshi4d47b002013-08-23 16:54:31 +0530206 (ifnull(end_of_life, '')='' or end_of_life > now()))""", as_dict=True)
Nabin Hait62d06292013-05-22 16:19:10 +0530207 for bin in bin_list:
208 #check if re-order is required
209 item_reorder = webnotes.conn.get("Item Reorder",
210 {"parent": bin.item_code, "warehouse": bin.warehouse})
211 if item_reorder:
212 reorder_level = item_reorder.warehouse_reorder_level
213 reorder_qty = item_reorder.warehouse_reorder_qty
214 material_request_type = item_reorder.material_request_type or "Purchase"
215 else:
216 reorder_level, reorder_qty = webnotes.conn.get_value("Item", bin.item_code,
217 ["re_order_level", "re_order_qty"])
218 material_request_type = "Purchase"
219
Anand Doshiad6180e2013-06-17 11:57:04 +0530220 if flt(reorder_level) and flt(bin.projected_qty) < flt(reorder_level):
Nabin Hait62d06292013-05-22 16:19:10 +0530221 if flt(reorder_level) - flt(bin.projected_qty) > flt(reorder_qty):
222 reorder_qty = flt(reorder_level) - flt(bin.projected_qty)
223
224 company = webnotes.conn.get_value("Warehouse", bin.warehouse, "company") or \
225 webnotes.defaults.get_defaults()["company"] or \
226 webnotes.conn.sql("""select name from tabCompany limit 1""")[0][0]
227
228 material_requests.setdefault(material_request_type, webnotes._dict()).setdefault(
229 company, []).append(webnotes._dict({
230 "item_code": bin.item_code,
231 "warehouse": bin.warehouse,
232 "reorder_qty": reorder_qty
233 })
234 )
235
236 create_material_request(material_requests)
237
238def create_material_request(material_requests):
239 """ Create indent on reaching reorder level """
240 mr_list = []
241 defaults = webnotes.defaults.get_defaults()
Anand Doshiad6180e2013-06-17 11:57:04 +0530242 exceptions_list = []
Nabin Hait62d06292013-05-22 16:19:10 +0530243 for request_type in material_requests:
244 for company in material_requests[request_type]:
Anand Doshiad6180e2013-06-17 11:57:04 +0530245 try:
246 items = material_requests[request_type][company]
247 if not items:
248 continue
Anand Doshi6f6e91c2013-07-22 11:28:34 +0530249
Nabin Hait62d06292013-05-22 16:19:10 +0530250 mr = [{
251 "doctype": "Material Request",
252 "company": company,
253 "fiscal_year": defaults.fiscal_year,
254 "transaction_date": nowdate(),
255 "material_request_type": request_type,
256 "remark": _("This is an auto generated Material Request.") + \
257 _("""It was raised because the (actual + ordered + indented - reserved)
258 quantity reaches re-order level when the following record was created""")
259 }]
260
Anand Doshiad6180e2013-06-17 11:57:04 +0530261 for d in items:
262 item = webnotes.doc("Item", d.item_code)
263 mr.append({
264 "doctype": "Material Request Item",
265 "parenttype": "Material Request",
266 "parentfield": "indent_details",
267 "item_code": d.item_code,
268 "schedule_date": add_days(nowdate(),cint(item.lead_time_days)),
269 "uom": item.stock_uom,
270 "warehouse": d.warehouse,
271 "item_name": item.item_name,
272 "description": item.description,
273 "item_group": item.item_group,
274 "qty": d.reorder_qty,
275 "brand": item.brand,
276 })
Nabin Hait62d06292013-05-22 16:19:10 +0530277
Anand Doshiad6180e2013-06-17 11:57:04 +0530278 mr_bean = webnotes.bean(mr)
279 mr_bean.insert()
280 mr_bean.submit()
281 mr_list.append(mr_bean)
Anand Doshi6f6e91c2013-07-22 11:28:34 +0530282
Anand Doshiad6180e2013-06-17 11:57:04 +0530283 except:
284 if webnotes.message_log:
285 exceptions_list.append([] + webnotes.message_log)
286 webnotes.message_log = []
287 else:
288 exceptions_list.append(webnotes.getTraceback())
Nabin Hait62d06292013-05-22 16:19:10 +0530289
290 if mr_list:
291 if not hasattr(webnotes, "reorder_email_notify"):
Nabin Haitbf5d44c2013-08-12 16:30:48 +0530292 webnotes.reorder_email_notify = cint(webnotes.conn.get_value('Stock Settings', None,
293 'reorder_email_notify'))
Nabin Hait62d06292013-05-22 16:19:10 +0530294
295 if(webnotes.reorder_email_notify):
296 send_email_notification(mr_list)
Anand Doshiad6180e2013-06-17 11:57:04 +0530297
298 if exceptions_list:
299 notify_errors(exceptions_list)
Nabin Hait62d06292013-05-22 16:19:10 +0530300
301def send_email_notification(mr_list):
302 """ Notify user about auto creation of indent"""
303
Nabin Hait62d06292013-05-22 16:19:10 +0530304 email_list = webnotes.conn.sql_list("""select distinct r.parent
305 from tabUserRole r, tabProfile p
306 where p.name = r.parent and p.enabled = 1 and p.docstatus < 2
307 and r.role in ('Purchase Manager','Material Manager')
308 and p.name not in ('Administrator', 'All', 'Guest')""")
309
310 msg="""<h3>Following Material Requests has been raised automatically \
311 based on item reorder level:</h3>"""
312 for mr in mr_list:
313 msg += "<p><b><u>" + mr.doc.name + """</u></b></p><table class='table table-bordered'><tr>
314 <th>Item Code</th><th>Warehouse</th><th>Qty</th><th>UOM</th></tr>"""
315 for item in mr.doclist.get({"parentfield": "indent_details"}):
316 msg += "<tr><td>" + item.item_code + "</td><td>" + item.warehouse + "</td><td>" + \
317 cstr(item.qty) + "</td><td>" + cstr(item.uom) + "</td></tr>"
318 msg += "</table>"
Anand Doshiad6180e2013-06-17 11:57:04 +0530319 sendmail(email_list, subject='Auto Material Request Generation Notification', msg = msg)
320
321def notify_errors(exceptions_list):
322 subject = "[Important] [ERPNext] Error(s) while creating Material Requests based on Re-order Levels"
323 msg = """Dear System Manager,
324
325 An error occured for certain Items while creating Material Requests based on Re-order level.
326
327 Please rectify these issues:
328 ---
329
330 %s
331
332 ---
333 Regards,
334 Administrator""" % ("\n\n".join(["\n".join(msg) for msg in exceptions_list]),)
335
336 from webnotes.profile import get_system_managers
337 sendmail(get_system_managers(), subject=subject, msg=msg)