blob: 848783b2c6247de6b7223e09a743d6ba30ee12ed [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
Rushabh Mehta4c17f942013-08-12 14:18:09 +053072 previous_stock_queue = json.loads(previous_sle.get('stock_queue', '[]') or '[]')
Nabin Hait831207f2013-01-16 14:15:48 +053073 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
Anand Doshi5dd6b1d2013-08-07 19:27:30 +0530155def get_buying_amount(item_code, 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 Doshi5dd6b1d2013-08-07 19:27:30 +0530162 buying_amount += _get_buying_amount(voucher_type, voucher_no, voucher_detail_no, stock_ledger_entries)
Nabin Haita72c5122013-03-06 18:50:53 +0530163 return buying_amount
164 else:
165 # doesn't have sales bom
Anand Doshi5dd6b1d2013-08-07 19:27:30 +0530166 return _get_buying_amount(voucher_type, voucher_no, voucher_detail_no, stock_ledger_entries)
Nabin Haita72c5122013-03-06 18:50:53 +0530167
Anand Doshi5dd6b1d2013-08-07 19:27:30 +0530168def _get_buying_amount(voucher_type, voucher_no, item_row, stock_ledger_entries):
169 # IMP NOTE
170 # stock_ledger_entries should already be filtered by item_code and warehouse and
171 # sorted by posting_date desc, posting_time desc
172 for i, sle in enumerate(stock_ledger_entries):
Nabin Hait0cfbc5f2013-03-12 11:34:56 +0530173 if sle.voucher_type == voucher_type and sle.voucher_no == voucher_no and \
Anand Doshi8c454202013-03-28 16:40:30 +0530174 sle.voucher_detail_no == item_row:
Anand Doshi5dd6b1d2013-08-07 19:27:30 +0530175 previous_stock_value = len(stock_ledger_entries) > i+1 and \
176 flt(stock_ledger_entries[i+1].stock_value) or 0.0
Anand Doshi96b189c2013-03-26 18:43:10 +0530177
Nabin Haitc3afb252013-03-19 12:01:24 +0530178 buying_amount = previous_stock_value - flt(sle.stock_value)
Anand Doshi6d8d3b42013-03-21 18:45:02 +0530179
Nabin Haitc3afb252013-03-19 12:01:24 +0530180 return buying_amount
Nabin Hait62d06292013-05-22 16:19:10 +0530181 return 0.0
182
183
184def reorder_item():
185 """ Reorder item if stock reaches reorder level"""
186 if not hasattr(webnotes, "auto_indent"):
Nabin Haitbf5d44c2013-08-12 16:30:48 +0530187 webnotes.auto_indent = cint(webnotes.conn.get_value('Stock Settings', None, 'auto_indent'))
188
Nabin Hait62d06292013-05-22 16:19:10 +0530189 if webnotes.auto_indent:
190 material_requests = {}
191 bin_list = webnotes.conn.sql("""select item_code, warehouse, projected_qty
Anand Doshiad6180e2013-06-17 11:57:04 +0530192 from tabBin where ifnull(item_code, '') != '' and ifnull(warehouse, '') != ''
193 and exists (select name from `tabItem`
194 where `tabItem`.name = `tabBin`.item_code and
195 is_stock_item='Yes' and (is_purchase_item='Yes' or is_sub_contracted_item='Yes') and
196 (ifnull(end_of_life, '')='') or end_of_life > now())""",
Nabin Hait62d06292013-05-22 16:19:10 +0530197 as_dict=True)
198 for bin in bin_list:
199 #check if re-order is required
200 item_reorder = webnotes.conn.get("Item Reorder",
201 {"parent": bin.item_code, "warehouse": bin.warehouse})
202 if item_reorder:
203 reorder_level = item_reorder.warehouse_reorder_level
204 reorder_qty = item_reorder.warehouse_reorder_qty
205 material_request_type = item_reorder.material_request_type or "Purchase"
206 else:
207 reorder_level, reorder_qty = webnotes.conn.get_value("Item", bin.item_code,
208 ["re_order_level", "re_order_qty"])
209 material_request_type = "Purchase"
210
Anand Doshiad6180e2013-06-17 11:57:04 +0530211 if flt(reorder_level) and flt(bin.projected_qty) < flt(reorder_level):
Nabin Hait62d06292013-05-22 16:19:10 +0530212 if flt(reorder_level) - flt(bin.projected_qty) > flt(reorder_qty):
213 reorder_qty = flt(reorder_level) - flt(bin.projected_qty)
214
215 company = webnotes.conn.get_value("Warehouse", bin.warehouse, "company") or \
216 webnotes.defaults.get_defaults()["company"] or \
217 webnotes.conn.sql("""select name from tabCompany limit 1""")[0][0]
218
219 material_requests.setdefault(material_request_type, webnotes._dict()).setdefault(
220 company, []).append(webnotes._dict({
221 "item_code": bin.item_code,
222 "warehouse": bin.warehouse,
223 "reorder_qty": reorder_qty
224 })
225 )
226
227 create_material_request(material_requests)
228
229def create_material_request(material_requests):
230 """ Create indent on reaching reorder level """
231 mr_list = []
232 defaults = webnotes.defaults.get_defaults()
Anand Doshiad6180e2013-06-17 11:57:04 +0530233 exceptions_list = []
Nabin Hait62d06292013-05-22 16:19:10 +0530234 for request_type in material_requests:
235 for company in material_requests[request_type]:
Anand Doshiad6180e2013-06-17 11:57:04 +0530236 try:
237 items = material_requests[request_type][company]
238 if not items:
239 continue
Anand Doshi6f6e91c2013-07-22 11:28:34 +0530240
Nabin Hait62d06292013-05-22 16:19:10 +0530241 mr = [{
242 "doctype": "Material Request",
243 "company": company,
244 "fiscal_year": defaults.fiscal_year,
245 "transaction_date": nowdate(),
246 "material_request_type": request_type,
247 "remark": _("This is an auto generated Material Request.") + \
248 _("""It was raised because the (actual + ordered + indented - reserved)
249 quantity reaches re-order level when the following record was created""")
250 }]
251
Anand Doshiad6180e2013-06-17 11:57:04 +0530252 for d in items:
253 item = webnotes.doc("Item", d.item_code)
254 mr.append({
255 "doctype": "Material Request Item",
256 "parenttype": "Material Request",
257 "parentfield": "indent_details",
258 "item_code": d.item_code,
259 "schedule_date": add_days(nowdate(),cint(item.lead_time_days)),
260 "uom": item.stock_uom,
261 "warehouse": d.warehouse,
262 "item_name": item.item_name,
263 "description": item.description,
264 "item_group": item.item_group,
265 "qty": d.reorder_qty,
266 "brand": item.brand,
267 })
Nabin Hait62d06292013-05-22 16:19:10 +0530268
Anand Doshiad6180e2013-06-17 11:57:04 +0530269 mr_bean = webnotes.bean(mr)
270 mr_bean.insert()
271 mr_bean.submit()
272 mr_list.append(mr_bean)
Anand Doshi6f6e91c2013-07-22 11:28:34 +0530273
Anand Doshiad6180e2013-06-17 11:57:04 +0530274 except:
275 if webnotes.message_log:
276 exceptions_list.append([] + webnotes.message_log)
277 webnotes.message_log = []
278 else:
279 exceptions_list.append(webnotes.getTraceback())
Nabin Hait62d06292013-05-22 16:19:10 +0530280
281 if mr_list:
282 if not hasattr(webnotes, "reorder_email_notify"):
Nabin Haitbf5d44c2013-08-12 16:30:48 +0530283 webnotes.reorder_email_notify = cint(webnotes.conn.get_value('Stock Settings', None,
284 'reorder_email_notify'))
Nabin Hait62d06292013-05-22 16:19:10 +0530285
286 if(webnotes.reorder_email_notify):
287 send_email_notification(mr_list)
Anand Doshiad6180e2013-06-17 11:57:04 +0530288
289 if exceptions_list:
290 notify_errors(exceptions_list)
Nabin Hait62d06292013-05-22 16:19:10 +0530291
292def send_email_notification(mr_list):
293 """ Notify user about auto creation of indent"""
294
Nabin Hait62d06292013-05-22 16:19:10 +0530295 email_list = webnotes.conn.sql_list("""select distinct r.parent
296 from tabUserRole r, tabProfile p
297 where p.name = r.parent and p.enabled = 1 and p.docstatus < 2
298 and r.role in ('Purchase Manager','Material Manager')
299 and p.name not in ('Administrator', 'All', 'Guest')""")
300
301 msg="""<h3>Following Material Requests has been raised automatically \
302 based on item reorder level:</h3>"""
303 for mr in mr_list:
304 msg += "<p><b><u>" + mr.doc.name + """</u></b></p><table class='table table-bordered'><tr>
305 <th>Item Code</th><th>Warehouse</th><th>Qty</th><th>UOM</th></tr>"""
306 for item in mr.doclist.get({"parentfield": "indent_details"}):
307 msg += "<tr><td>" + item.item_code + "</td><td>" + item.warehouse + "</td><td>" + \
308 cstr(item.qty) + "</td><td>" + cstr(item.uom) + "</td></tr>"
309 msg += "</table>"
Anand Doshiad6180e2013-06-17 11:57:04 +0530310 sendmail(email_list, subject='Auto Material Request Generation Notification', msg = msg)
311
312def notify_errors(exceptions_list):
313 subject = "[Important] [ERPNext] Error(s) while creating Material Requests based on Re-order Levels"
314 msg = """Dear System Manager,
315
316 An error occured for certain Items while creating Material Requests based on Re-order level.
317
318 Please rectify these issues:
319 ---
320
321 %s
322
323 ---
324 Regards,
325 Administrator""" % ("\n\n".join(["\n".join(msg) for msg in exceptions_list]),)
326
327 from webnotes.profile import get_system_managers
328 sendmail(get_system_managers(), subject=subject, msg=msg)