blob: d53d271e1c15b7833e8e8de8ee05b4c3b2c87c7a [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
11def validate_end_of_life(item_code, end_of_life=None, verbose=1):
12 if not end_of_life:
13 end_of_life = webnotes.conn.get_value("Item", item_code, "end_of_life")
14
15 from webnotes.utils import getdate, now_datetime, formatdate
Anand Doshiad6180e2013-06-17 11:57:04 +053016 if end_of_life and getdate(end_of_life) <= now_datetime().date():
Nabin Hait9d0f6362013-01-07 18:51:11 +053017 msg = (_("Item") + " %(item_code)s: " + _("reached its end of life on") + \
18 " %(date)s. " + _("Please check") + ": %(end_of_life_label)s " + \
19 "in Item master") % {
20 "item_code": item_code,
21 "date": formatdate(end_of_life),
Anand Doshia43b29e2013-02-20 15:55:10 +053022 "end_of_life_label": webnotes.get_doctype("Item").get_label("end_of_life")
Nabin Hait9d0f6362013-01-07 18:51:11 +053023 }
24
25 _msgprint(msg, verbose)
26
27def validate_is_stock_item(item_code, is_stock_item=None, verbose=1):
28 if not is_stock_item:
29 is_stock_item = webnotes.conn.get_value("Item", item_code, "is_stock_item")
30
31 if is_stock_item != "Yes":
32 msg = (_("Item") + " %(item_code)s: " + _("is not a Stock Item")) % {
33 "item_code": item_code,
34 }
35
36 _msgprint(msg, verbose)
37
38def validate_cancelled_item(item_code, docstatus=None, verbose=1):
39 if docstatus is None:
40 docstatus = webnotes.conn.get_value("Item", item_code, "docstatus")
41
42 if docstatus == 2:
43 msg = (_("Item") + " %(item_code)s: " + _("is a cancelled Item")) % {
44 "item_code": item_code,
45 }
46
47 _msgprint(msg, verbose)
48
49def _msgprint(msg, verbose):
50 if verbose:
51 msgprint(msg, raise_exception=True)
52 else:
53 raise webnotes.ValidationError, msg
54
Nabin Hait9d0f6362013-01-07 18:51:11 +053055def get_incoming_rate(args):
56 """Get Incoming Rate based on valuation method"""
Anand Doshi1b531862013-01-10 19:29:51 +053057 from stock.stock_ledger import get_previous_sle
Nabin Hait9d0f6362013-01-07 18:51:11 +053058
59 in_rate = 0
60 if args.get("serial_no"):
61 in_rate = get_avg_purchase_rate(args.get("serial_no"))
62 elif args.get("bom_no"):
63 result = webnotes.conn.sql("""select ifnull(total_cost, 0) / ifnull(quantity, 1)
64 from `tabBOM` where name = %s and docstatus=1 and is_active=1""", args.get("bom_no"))
65 in_rate = result and flt(result[0][0]) or 0
66 else:
67 valuation_method = get_valuation_method(args.get("item_code"))
68 previous_sle = get_previous_sle(args)
69 if valuation_method == 'FIFO':
Nabin Hait831207f2013-01-16 14:15:48 +053070 if not previous_sle:
71 return 0.0
72 previous_stock_queue = json.loads(previous_sle.get('stock_queue', '[]'))
73 in_rate = previous_stock_queue and \
Nabin Hait6b1f21d2013-01-16 17:17:17 +053074 get_fifo_rate(previous_stock_queue, args.get("qty") or 0) or 0
Nabin Hait9d0f6362013-01-07 18:51:11 +053075 elif valuation_method == 'Moving Average':
76 in_rate = previous_sle.get('valuation_rate') or 0
77 return in_rate
78
79def get_avg_purchase_rate(serial_nos):
80 """get average value of serial numbers"""
81
82 serial_nos = get_valid_serial_nos(serial_nos)
83 return flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0)) from `tabSerial No`
84 where name in (%s)""" % ", ".join(["%s"] * len(serial_nos)),
85 tuple(serial_nos))[0][0])
86
87def get_valuation_method(item_code):
88 """get valuation method from item or default"""
89 val_method = webnotes.conn.get_value('Item', item_code, 'valuation_method')
90 if not val_method:
Rushabh Mehta5117d9c2013-02-19 15:27:31 +053091 val_method = get_global_default('valuation_method') or "FIFO"
Nabin Hait9d0f6362013-01-07 18:51:11 +053092 return val_method
93
Nabin Hait831207f2013-01-16 14:15:48 +053094def get_fifo_rate(previous_stock_queue, qty):
95 """get FIFO (average) Rate from Queue"""
96 if qty >= 0:
97 total = sum(f[0] for f in previous_stock_queue)
98 return total and sum(f[0] * f[1] for f in previous_stock_queue) / flt(total) or 0.0
99 else:
100 outgoing_cost = 0
101 qty_to_pop = abs(qty)
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530102 while qty_to_pop and previous_stock_queue:
Nabin Hait831207f2013-01-16 14:15:48 +0530103 batch = previous_stock_queue[0]
104 if 0 < batch[0] <= qty_to_pop:
105 # if batch qty > 0
106 # not enough or exactly same qty in current batch, clear batch
107 outgoing_cost += flt(batch[0]) * flt(batch[1])
108 qty_to_pop -= batch[0]
109 previous_stock_queue.pop(0)
110 else:
111 # all from current batch
112 outgoing_cost += flt(qty_to_pop) * flt(batch[1])
113 batch[0] -= qty_to_pop
114 qty_to_pop = 0
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530115 # if queue gets blank and qty_to_pop remaining, get average rate of full queue
116 return outgoing_cost / abs(qty) - qty_to_pop
Nabin Hait9d0f6362013-01-07 18:51:11 +0530117
118def get_valid_serial_nos(sr_nos, qty=0, item_code=''):
119 """split serial nos, validate and return list of valid serial nos"""
120 # TODO: remove duplicates in client side
121 serial_nos = cstr(sr_nos).strip().replace(',', '\n').split('\n')
122
123 valid_serial_nos = []
124 for val in serial_nos:
125 if val:
126 val = val.strip()
127 if val in valid_serial_nos:
128 msgprint("You have entered duplicate serial no: '%s'" % val, raise_exception=1)
129 else:
130 valid_serial_nos.append(val)
131
132 if qty and len(valid_serial_nos) != abs(qty):
133 msgprint("Please enter serial nos for "
134 + cstr(abs(qty)) + " quantity against item code: " + item_code,
135 raise_exception=1)
136
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530137 return valid_serial_nos
138
Nabin Haitdc95c152013-02-07 12:08:38 +0530139def get_warehouse_list(doctype, txt, searchfield, start, page_len, filters):
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530140 """used in search queries"""
141 wlist = []
142 for w in webnotes.conn.sql_list("""select name from tabWarehouse
143 where name like '%%%s%%'""" % txt):
144 if webnotes.session.user=="Administrator":
145 wlist.append([w])
146 else:
147 warehouse_users = webnotes.conn.sql_list("""select user from `tabWarehouse User`
148 where parent=%s""", w)
149 if not warehouse_users:
150 wlist.append([w])
151 elif webnotes.session.user in warehouse_users:
152 wlist.append([w])
153 return wlist
Nabin Haita72c5122013-03-06 18:50:53 +0530154
Nabin Hait8c7234f2013-03-11 16:32:33 +0530155def get_buying_amount(item_code, warehouse, qty, voucher_type, voucher_no, voucher_detail_no,
Nabin Haitc3afb252013-03-19 12:01:24 +0530156 stock_ledger_entries, item_sales_bom=None):
157 if item_sales_bom and item_sales_bom.get(item_code):
Nabin Haita72c5122013-03-06 18:50:53 +0530158 # sales bom item
159 buying_amount = 0.0
160 for bom_item in item_sales_bom[item_code]:
Anand Doshi96b189c2013-03-26 18:43:10 +0530161 if bom_item.get("parent_detail_docname")==voucher_detail_no:
Anand Doshi8c454202013-03-28 16:40:30 +0530162 buying_amount += _get_buying_amount(voucher_type, voucher_no, voucher_detail_no,
Anand Doshi96b189c2013-03-26 18:43:10 +0530163 bom_item.item_code, bom_item.warehouse or warehouse,
164 bom_item.total_qty or (bom_item.qty * qty), stock_ledger_entries)
Nabin Haita72c5122013-03-06 18:50:53 +0530165 return buying_amount
166 else:
167 # doesn't have sales bom
Nabin Hait8c7234f2013-03-11 16:32:33 +0530168 return _get_buying_amount(voucher_type, voucher_no, voucher_detail_no,
169 item_code, warehouse, qty, stock_ledger_entries)
Nabin Haita72c5122013-03-06 18:50:53 +0530170
Nabin Hait8c7234f2013-03-11 16:32:33 +0530171def _get_buying_amount(voucher_type, voucher_no, item_row, item_code, warehouse, qty,
172 stock_ledger_entries):
Anand Doshi96b189c2013-03-26 18:43:10 +0530173 relevant_stock_ledger_entries = [sle for sle in stock_ledger_entries
174 if sle.item_code == item_code and sle.warehouse == warehouse]
175
176 for i, sle in enumerate(relevant_stock_ledger_entries):
Nabin Hait0cfbc5f2013-03-12 11:34:56 +0530177 if sle.voucher_type == voucher_type and sle.voucher_no == voucher_no and \
Anand Doshi8c454202013-03-28 16:40:30 +0530178 sle.voucher_detail_no == item_row:
Anand Doshi96b189c2013-03-26 18:43:10 +0530179 previous_stock_value = len(relevant_stock_ledger_entries) > i+1 and \
180 flt(relevant_stock_ledger_entries[i+1].stock_value) or 0.0
181
Nabin Haitc3afb252013-03-19 12:01:24 +0530182 buying_amount = previous_stock_value - flt(sle.stock_value)
Anand Doshi6d8d3b42013-03-21 18:45:02 +0530183
Nabin Haitc3afb252013-03-19 12:01:24 +0530184 return buying_amount
Nabin Hait62d06292013-05-22 16:19:10 +0530185 return 0.0
186
187
188def reorder_item():
189 """ Reorder item if stock reaches reorder level"""
190 if not hasattr(webnotes, "auto_indent"):
Rushabh Mehta7a93d5d2013-06-24 18:18:46 +0530191 webnotes.auto_indent = webnotes.conn.get_value('Stock Settings', None, 'auto_indent')
Nabin Hait62d06292013-05-22 16:19:10 +0530192
193 if webnotes.auto_indent:
194 material_requests = {}
195 bin_list = webnotes.conn.sql("""select item_code, warehouse, projected_qty
Anand Doshiad6180e2013-06-17 11:57:04 +0530196 from tabBin where ifnull(item_code, '') != '' and ifnull(warehouse, '') != ''
197 and exists (select name from `tabItem`
198 where `tabItem`.name = `tabBin`.item_code and
199 is_stock_item='Yes' and (is_purchase_item='Yes' or is_sub_contracted_item='Yes') and
200 (ifnull(end_of_life, '')='') or end_of_life > now())""",
Nabin Hait62d06292013-05-22 16:19:10 +0530201 as_dict=True)
202 for bin in bin_list:
203 #check if re-order is required
204 item_reorder = webnotes.conn.get("Item Reorder",
205 {"parent": bin.item_code, "warehouse": bin.warehouse})
206 if item_reorder:
207 reorder_level = item_reorder.warehouse_reorder_level
208 reorder_qty = item_reorder.warehouse_reorder_qty
209 material_request_type = item_reorder.material_request_type or "Purchase"
210 else:
211 reorder_level, reorder_qty = webnotes.conn.get_value("Item", bin.item_code,
212 ["re_order_level", "re_order_qty"])
213 material_request_type = "Purchase"
214
Anand Doshiad6180e2013-06-17 11:57:04 +0530215 if flt(reorder_level) and flt(bin.projected_qty) < flt(reorder_level):
Nabin Hait62d06292013-05-22 16:19:10 +0530216 if flt(reorder_level) - flt(bin.projected_qty) > flt(reorder_qty):
217 reorder_qty = flt(reorder_level) - flt(bin.projected_qty)
218
219 company = webnotes.conn.get_value("Warehouse", bin.warehouse, "company") or \
220 webnotes.defaults.get_defaults()["company"] or \
221 webnotes.conn.sql("""select name from tabCompany limit 1""")[0][0]
222
223 material_requests.setdefault(material_request_type, webnotes._dict()).setdefault(
224 company, []).append(webnotes._dict({
225 "item_code": bin.item_code,
226 "warehouse": bin.warehouse,
227 "reorder_qty": reorder_qty
228 })
229 )
230
231 create_material_request(material_requests)
232
233def create_material_request(material_requests):
234 """ Create indent on reaching reorder level """
235 mr_list = []
236 defaults = webnotes.defaults.get_defaults()
Anand Doshiad6180e2013-06-17 11:57:04 +0530237 exceptions_list = []
Nabin Hait62d06292013-05-22 16:19:10 +0530238 for request_type in material_requests:
239 for company in material_requests[request_type]:
Anand Doshiad6180e2013-06-17 11:57:04 +0530240 try:
241 items = material_requests[request_type][company]
242 if not items:
243 continue
Anand Doshi6f6e91c2013-07-22 11:28:34 +0530244
Nabin Hait62d06292013-05-22 16:19:10 +0530245 mr = [{
246 "doctype": "Material Request",
247 "company": company,
248 "fiscal_year": defaults.fiscal_year,
249 "transaction_date": nowdate(),
250 "material_request_type": request_type,
251 "remark": _("This is an auto generated Material Request.") + \
252 _("""It was raised because the (actual + ordered + indented - reserved)
253 quantity reaches re-order level when the following record was created""")
254 }]
255
Anand Doshiad6180e2013-06-17 11:57:04 +0530256 for d in items:
257 item = webnotes.doc("Item", d.item_code)
258 mr.append({
259 "doctype": "Material Request Item",
260 "parenttype": "Material Request",
261 "parentfield": "indent_details",
262 "item_code": d.item_code,
263 "schedule_date": add_days(nowdate(),cint(item.lead_time_days)),
264 "uom": item.stock_uom,
265 "warehouse": d.warehouse,
266 "item_name": item.item_name,
267 "description": item.description,
268 "item_group": item.item_group,
269 "qty": d.reorder_qty,
270 "brand": item.brand,
271 })
Nabin Hait62d06292013-05-22 16:19:10 +0530272
Anand Doshiad6180e2013-06-17 11:57:04 +0530273 mr_bean = webnotes.bean(mr)
274 mr_bean.insert()
275 mr_bean.submit()
276 mr_list.append(mr_bean)
Anand Doshi6f6e91c2013-07-22 11:28:34 +0530277
Anand Doshiad6180e2013-06-17 11:57:04 +0530278 except:
279 if webnotes.message_log:
280 exceptions_list.append([] + webnotes.message_log)
281 webnotes.message_log = []
282 else:
283 exceptions_list.append(webnotes.getTraceback())
Nabin Hait62d06292013-05-22 16:19:10 +0530284
285 if mr_list:
286 if not hasattr(webnotes, "reorder_email_notify"):
Rushabh Mehta7a93d5d2013-06-24 18:18:46 +0530287 webnotes.reorder_email_notify = webnotes.conn.get_value('Stock Settings', None,
Nabin Hait62d06292013-05-22 16:19:10 +0530288 'reorder_email_notify')
289
290 if(webnotes.reorder_email_notify):
291 send_email_notification(mr_list)
Anand Doshiad6180e2013-06-17 11:57:04 +0530292
293 if exceptions_list:
294 notify_errors(exceptions_list)
Nabin Hait62d06292013-05-22 16:19:10 +0530295
296def send_email_notification(mr_list):
297 """ Notify user about auto creation of indent"""
298
Nabin Hait62d06292013-05-22 16:19:10 +0530299 email_list = webnotes.conn.sql_list("""select distinct r.parent
300 from tabUserRole r, tabProfile p
301 where p.name = r.parent and p.enabled = 1 and p.docstatus < 2
302 and r.role in ('Purchase Manager','Material Manager')
303 and p.name not in ('Administrator', 'All', 'Guest')""")
304
305 msg="""<h3>Following Material Requests has been raised automatically \
306 based on item reorder level:</h3>"""
307 for mr in mr_list:
308 msg += "<p><b><u>" + mr.doc.name + """</u></b></p><table class='table table-bordered'><tr>
309 <th>Item Code</th><th>Warehouse</th><th>Qty</th><th>UOM</th></tr>"""
310 for item in mr.doclist.get({"parentfield": "indent_details"}):
311 msg += "<tr><td>" + item.item_code + "</td><td>" + item.warehouse + "</td><td>" + \
312 cstr(item.qty) + "</td><td>" + cstr(item.uom) + "</td></tr>"
313 msg += "</table>"
314
Anand Doshiad6180e2013-06-17 11:57:04 +0530315 sendmail(email_list, subject='Auto Material Request Generation Notification', msg = msg)
316
317def notify_errors(exceptions_list):
318 subject = "[Important] [ERPNext] Error(s) while creating Material Requests based on Re-order Levels"
319 msg = """Dear System Manager,
320
321 An error occured for certain Items while creating Material Requests based on Re-order level.
322
323 Please rectify these issues:
324 ---
325
326 %s
327
328 ---
329 Regards,
330 Administrator""" % ("\n\n".join(["\n".join(msg) for msg in exceptions_list]),)
331
332 from webnotes.profile import get_system_managers
333 sendmail(get_system_managers(), subject=subject, msg=msg)