blob: e4206c3751d728586f04e14a0beeb756c4cc47c2 [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
Nabin Hait0dd7be12013-08-02 11:45:43 +053011
12def get_stock_balance_on(warehouse_list, posting_date=None):
13 if not posting_date: posting_date = nowdate()
14
15 stock_ledger_entries = webnotes.conn.sql("""
16 SELECT
17 item_code, warehouse, stock_value
18 FROM
19 `tabStock Ledger Entry`
20 WHERE
21 warehouse in (%s)
22 AND posting_date <= %s
23 ORDER BY timestamp(posting_date, posting_time) DESC, name DESC
24 """ % (', '.join(['%s']*len(warehouse_list)), '%s'),
25 tuple(warehouse_list + [posting_date]), as_dict=1)
26
27 sle_map = {}
28 for sle in stock_ledger_entries:
29 sle_map.setdefault(sle.warehouse, {}).setdefault(sle.item_code, flt(sle.stock_value))
30
31 return sum([sum(item_dict.values()) for item_dict in sle_map.values()])
32
Nabin Hait47dc3182013-08-06 15:58:16 +053033def get_latest_stock_balance():
34 bin_map = {}
Nabin Hait469ee712013-08-07 12:33:37 +053035 for d in webnotes.conn.sql("""SELECT item_code, warehouse, stock_value as stock_value
Nabin Hait47dc3182013-08-06 15:58:16 +053036 FROM tabBin""", as_dict=1):
Nabin Hait469ee712013-08-07 12:33:37 +053037 bin_map.setdefault(d.warehouse, {}).setdefault(d.item_code, flt(d.stock_value))
Nabin Hait47dc3182013-08-06 15:58:16 +053038
39 return bin_map
Nabin Hait0dd7be12013-08-02 11:45:43 +053040
Nabin Hait9d0f6362013-01-07 18:51:11 +053041def validate_end_of_life(item_code, end_of_life=None, verbose=1):
42 if not end_of_life:
43 end_of_life = webnotes.conn.get_value("Item", item_code, "end_of_life")
44
45 from webnotes.utils import getdate, now_datetime, formatdate
Anand Doshiad6180e2013-06-17 11:57:04 +053046 if end_of_life and getdate(end_of_life) <= now_datetime().date():
Nabin Hait9d0f6362013-01-07 18:51:11 +053047 msg = (_("Item") + " %(item_code)s: " + _("reached its end of life on") + \
48 " %(date)s. " + _("Please check") + ": %(end_of_life_label)s " + \
49 "in Item master") % {
50 "item_code": item_code,
51 "date": formatdate(end_of_life),
Anand Doshia43b29e2013-02-20 15:55:10 +053052 "end_of_life_label": webnotes.get_doctype("Item").get_label("end_of_life")
Nabin Hait9d0f6362013-01-07 18:51:11 +053053 }
54
55 _msgprint(msg, verbose)
56
57def validate_is_stock_item(item_code, is_stock_item=None, verbose=1):
58 if not is_stock_item:
59 is_stock_item = webnotes.conn.get_value("Item", item_code, "is_stock_item")
60
61 if is_stock_item != "Yes":
62 msg = (_("Item") + " %(item_code)s: " + _("is not a Stock Item")) % {
63 "item_code": item_code,
64 }
65
66 _msgprint(msg, verbose)
67
68def validate_cancelled_item(item_code, docstatus=None, verbose=1):
69 if docstatus is None:
70 docstatus = webnotes.conn.get_value("Item", item_code, "docstatus")
71
72 if docstatus == 2:
73 msg = (_("Item") + " %(item_code)s: " + _("is a cancelled Item")) % {
74 "item_code": item_code,
75 }
76
77 _msgprint(msg, verbose)
78
79def _msgprint(msg, verbose):
80 if verbose:
81 msgprint(msg, raise_exception=True)
82 else:
83 raise webnotes.ValidationError, msg
84
Nabin Hait9d0f6362013-01-07 18:51:11 +053085def get_incoming_rate(args):
86 """Get Incoming Rate based on valuation method"""
Anand Doshi1b531862013-01-10 19:29:51 +053087 from stock.stock_ledger import get_previous_sle
Nabin Hait9d0f6362013-01-07 18:51:11 +053088
89 in_rate = 0
90 if args.get("serial_no"):
91 in_rate = get_avg_purchase_rate(args.get("serial_no"))
92 elif args.get("bom_no"):
93 result = webnotes.conn.sql("""select ifnull(total_cost, 0) / ifnull(quantity, 1)
94 from `tabBOM` where name = %s and docstatus=1 and is_active=1""", args.get("bom_no"))
95 in_rate = result and flt(result[0][0]) or 0
96 else:
97 valuation_method = get_valuation_method(args.get("item_code"))
98 previous_sle = get_previous_sle(args)
99 if valuation_method == 'FIFO':
Nabin Hait831207f2013-01-16 14:15:48 +0530100 if not previous_sle:
101 return 0.0
102 previous_stock_queue = json.loads(previous_sle.get('stock_queue', '[]'))
103 in_rate = previous_stock_queue and \
Nabin Hait6b1f21d2013-01-16 17:17:17 +0530104 get_fifo_rate(previous_stock_queue, args.get("qty") or 0) or 0
Nabin Hait9d0f6362013-01-07 18:51:11 +0530105 elif valuation_method == 'Moving Average':
106 in_rate = previous_sle.get('valuation_rate') or 0
107 return in_rate
108
109def get_avg_purchase_rate(serial_nos):
110 """get average value of serial numbers"""
111
112 serial_nos = get_valid_serial_nos(serial_nos)
113 return flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0)) from `tabSerial No`
114 where name in (%s)""" % ", ".join(["%s"] * len(serial_nos)),
115 tuple(serial_nos))[0][0])
116
117def get_valuation_method(item_code):
118 """get valuation method from item or default"""
119 val_method = webnotes.conn.get_value('Item', item_code, 'valuation_method')
120 if not val_method:
Rushabh Mehta5117d9c2013-02-19 15:27:31 +0530121 val_method = get_global_default('valuation_method') or "FIFO"
Nabin Hait9d0f6362013-01-07 18:51:11 +0530122 return val_method
123
Nabin Hait831207f2013-01-16 14:15:48 +0530124def get_fifo_rate(previous_stock_queue, qty):
125 """get FIFO (average) Rate from Queue"""
126 if qty >= 0:
127 total = sum(f[0] for f in previous_stock_queue)
128 return total and sum(f[0] * f[1] for f in previous_stock_queue) / flt(total) or 0.0
129 else:
130 outgoing_cost = 0
131 qty_to_pop = abs(qty)
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530132 while qty_to_pop and previous_stock_queue:
Nabin Hait831207f2013-01-16 14:15:48 +0530133 batch = previous_stock_queue[0]
134 if 0 < batch[0] <= qty_to_pop:
135 # if batch qty > 0
136 # not enough or exactly same qty in current batch, clear batch
137 outgoing_cost += flt(batch[0]) * flt(batch[1])
138 qty_to_pop -= batch[0]
139 previous_stock_queue.pop(0)
140 else:
141 # all from current batch
142 outgoing_cost += flt(qty_to_pop) * flt(batch[1])
143 batch[0] -= qty_to_pop
144 qty_to_pop = 0
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530145 # if queue gets blank and qty_to_pop remaining, get average rate of full queue
146 return outgoing_cost / abs(qty) - qty_to_pop
Nabin Hait9d0f6362013-01-07 18:51:11 +0530147
148def get_valid_serial_nos(sr_nos, qty=0, item_code=''):
149 """split serial nos, validate and return list of valid serial nos"""
150 # TODO: remove duplicates in client side
151 serial_nos = cstr(sr_nos).strip().replace(',', '\n').split('\n')
152
153 valid_serial_nos = []
154 for val in serial_nos:
155 if val:
156 val = val.strip()
157 if val in valid_serial_nos:
158 msgprint("You have entered duplicate serial no: '%s'" % val, raise_exception=1)
159 else:
160 valid_serial_nos.append(val)
161
162 if qty and len(valid_serial_nos) != abs(qty):
163 msgprint("Please enter serial nos for "
164 + cstr(abs(qty)) + " quantity against item code: " + item_code,
165 raise_exception=1)
166
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530167 return valid_serial_nos
168
Nabin Haitdc95c152013-02-07 12:08:38 +0530169def get_warehouse_list(doctype, txt, searchfield, start, page_len, filters):
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530170 """used in search queries"""
171 wlist = []
172 for w in webnotes.conn.sql_list("""select name from tabWarehouse
173 where name like '%%%s%%'""" % txt):
174 if webnotes.session.user=="Administrator":
175 wlist.append([w])
176 else:
177 warehouse_users = webnotes.conn.sql_list("""select user from `tabWarehouse User`
178 where parent=%s""", w)
179 if not warehouse_users:
180 wlist.append([w])
181 elif webnotes.session.user in warehouse_users:
182 wlist.append([w])
183 return wlist
Nabin Haita72c5122013-03-06 18:50:53 +0530184
Nabin Hait8c7234f2013-03-11 16:32:33 +0530185def get_buying_amount(item_code, warehouse, qty, voucher_type, voucher_no, voucher_detail_no,
Nabin Haitc3afb252013-03-19 12:01:24 +0530186 stock_ledger_entries, item_sales_bom=None):
187 if item_sales_bom and item_sales_bom.get(item_code):
Nabin Haita72c5122013-03-06 18:50:53 +0530188 # sales bom item
189 buying_amount = 0.0
190 for bom_item in item_sales_bom[item_code]:
Anand Doshi96b189c2013-03-26 18:43:10 +0530191 if bom_item.get("parent_detail_docname")==voucher_detail_no:
Anand Doshi8c454202013-03-28 16:40:30 +0530192 buying_amount += _get_buying_amount(voucher_type, voucher_no, voucher_detail_no,
Anand Doshi96b189c2013-03-26 18:43:10 +0530193 bom_item.item_code, bom_item.warehouse or warehouse,
194 bom_item.total_qty or (bom_item.qty * qty), stock_ledger_entries)
Nabin Haita72c5122013-03-06 18:50:53 +0530195 return buying_amount
196 else:
197 # doesn't have sales bom
Nabin Hait8c7234f2013-03-11 16:32:33 +0530198 return _get_buying_amount(voucher_type, voucher_no, voucher_detail_no,
199 item_code, warehouse, qty, stock_ledger_entries)
Nabin Haita72c5122013-03-06 18:50:53 +0530200
Nabin Hait8c7234f2013-03-11 16:32:33 +0530201def _get_buying_amount(voucher_type, voucher_no, item_row, item_code, warehouse, qty,
202 stock_ledger_entries):
Anand Doshi96b189c2013-03-26 18:43:10 +0530203 relevant_stock_ledger_entries = [sle for sle in stock_ledger_entries
204 if sle.item_code == item_code and sle.warehouse == warehouse]
205
206 for i, sle in enumerate(relevant_stock_ledger_entries):
Nabin Hait0cfbc5f2013-03-12 11:34:56 +0530207 if sle.voucher_type == voucher_type and sle.voucher_no == voucher_no and \
Anand Doshi8c454202013-03-28 16:40:30 +0530208 sle.voucher_detail_no == item_row:
Anand Doshi96b189c2013-03-26 18:43:10 +0530209 previous_stock_value = len(relevant_stock_ledger_entries) > i+1 and \
210 flt(relevant_stock_ledger_entries[i+1].stock_value) or 0.0
Nabin Haitc3afb252013-03-19 12:01:24 +0530211 buying_amount = previous_stock_value - flt(sle.stock_value)
Anand Doshi6d8d3b42013-03-21 18:45:02 +0530212
Nabin Haitc3afb252013-03-19 12:01:24 +0530213 return buying_amount
Nabin Hait62d06292013-05-22 16:19:10 +0530214 return 0.0
215
216
217def reorder_item():
218 """ Reorder item if stock reaches reorder level"""
219 if not hasattr(webnotes, "auto_indent"):
Rushabh Mehta7a93d5d2013-06-24 18:18:46 +0530220 webnotes.auto_indent = webnotes.conn.get_value('Stock Settings', None, 'auto_indent')
Nabin Hait62d06292013-05-22 16:19:10 +0530221
222 if webnotes.auto_indent:
223 material_requests = {}
224 bin_list = webnotes.conn.sql("""select item_code, warehouse, projected_qty
Anand Doshiad6180e2013-06-17 11:57:04 +0530225 from tabBin where ifnull(item_code, '') != '' and ifnull(warehouse, '') != ''
226 and exists (select name from `tabItem`
227 where `tabItem`.name = `tabBin`.item_code and
228 is_stock_item='Yes' and (is_purchase_item='Yes' or is_sub_contracted_item='Yes') and
229 (ifnull(end_of_life, '')='') or end_of_life > now())""",
Nabin Hait62d06292013-05-22 16:19:10 +0530230 as_dict=True)
231 for bin in bin_list:
232 #check if re-order is required
233 item_reorder = webnotes.conn.get("Item Reorder",
234 {"parent": bin.item_code, "warehouse": bin.warehouse})
235 if item_reorder:
236 reorder_level = item_reorder.warehouse_reorder_level
237 reorder_qty = item_reorder.warehouse_reorder_qty
238 material_request_type = item_reorder.material_request_type or "Purchase"
239 else:
240 reorder_level, reorder_qty = webnotes.conn.get_value("Item", bin.item_code,
241 ["re_order_level", "re_order_qty"])
242 material_request_type = "Purchase"
243
Anand Doshiad6180e2013-06-17 11:57:04 +0530244 if flt(reorder_level) and flt(bin.projected_qty) < flt(reorder_level):
Nabin Hait62d06292013-05-22 16:19:10 +0530245 if flt(reorder_level) - flt(bin.projected_qty) > flt(reorder_qty):
246 reorder_qty = flt(reorder_level) - flt(bin.projected_qty)
247
248 company = webnotes.conn.get_value("Warehouse", bin.warehouse, "company") or \
249 webnotes.defaults.get_defaults()["company"] or \
250 webnotes.conn.sql("""select name from tabCompany limit 1""")[0][0]
251
252 material_requests.setdefault(material_request_type, webnotes._dict()).setdefault(
253 company, []).append(webnotes._dict({
254 "item_code": bin.item_code,
255 "warehouse": bin.warehouse,
256 "reorder_qty": reorder_qty
257 })
258 )
259
260 create_material_request(material_requests)
261
262def create_material_request(material_requests):
263 """ Create indent on reaching reorder level """
264 mr_list = []
265 defaults = webnotes.defaults.get_defaults()
Anand Doshiad6180e2013-06-17 11:57:04 +0530266 exceptions_list = []
Nabin Hait62d06292013-05-22 16:19:10 +0530267 for request_type in material_requests:
268 for company in material_requests[request_type]:
Anand Doshiad6180e2013-06-17 11:57:04 +0530269 try:
270 items = material_requests[request_type][company]
271 if not items:
272 continue
Anand Doshi6f6e91c2013-07-22 11:28:34 +0530273
Nabin Hait62d06292013-05-22 16:19:10 +0530274 mr = [{
275 "doctype": "Material Request",
276 "company": company,
277 "fiscal_year": defaults.fiscal_year,
278 "transaction_date": nowdate(),
279 "material_request_type": request_type,
280 "remark": _("This is an auto generated Material Request.") + \
281 _("""It was raised because the (actual + ordered + indented - reserved)
282 quantity reaches re-order level when the following record was created""")
283 }]
284
Anand Doshiad6180e2013-06-17 11:57:04 +0530285 for d in items:
286 item = webnotes.doc("Item", d.item_code)
287 mr.append({
288 "doctype": "Material Request Item",
289 "parenttype": "Material Request",
290 "parentfield": "indent_details",
291 "item_code": d.item_code,
292 "schedule_date": add_days(nowdate(),cint(item.lead_time_days)),
293 "uom": item.stock_uom,
294 "warehouse": d.warehouse,
295 "item_name": item.item_name,
296 "description": item.description,
297 "item_group": item.item_group,
298 "qty": d.reorder_qty,
299 "brand": item.brand,
300 })
Nabin Hait62d06292013-05-22 16:19:10 +0530301
Anand Doshiad6180e2013-06-17 11:57:04 +0530302 mr_bean = webnotes.bean(mr)
303 mr_bean.insert()
304 mr_bean.submit()
305 mr_list.append(mr_bean)
Anand Doshi6f6e91c2013-07-22 11:28:34 +0530306
Anand Doshiad6180e2013-06-17 11:57:04 +0530307 except:
308 if webnotes.message_log:
309 exceptions_list.append([] + webnotes.message_log)
310 webnotes.message_log = []
311 else:
312 exceptions_list.append(webnotes.getTraceback())
Nabin Hait62d06292013-05-22 16:19:10 +0530313
314 if mr_list:
315 if not hasattr(webnotes, "reorder_email_notify"):
Rushabh Mehta7a93d5d2013-06-24 18:18:46 +0530316 webnotes.reorder_email_notify = webnotes.conn.get_value('Stock Settings', None,
Nabin Hait62d06292013-05-22 16:19:10 +0530317 'reorder_email_notify')
318
319 if(webnotes.reorder_email_notify):
320 send_email_notification(mr_list)
Anand Doshiad6180e2013-06-17 11:57:04 +0530321
322 if exceptions_list:
323 notify_errors(exceptions_list)
Nabin Hait62d06292013-05-22 16:19:10 +0530324
325def send_email_notification(mr_list):
326 """ Notify user about auto creation of indent"""
327
Nabin Hait62d06292013-05-22 16:19:10 +0530328 email_list = webnotes.conn.sql_list("""select distinct r.parent
329 from tabUserRole r, tabProfile p
330 where p.name = r.parent and p.enabled = 1 and p.docstatus < 2
331 and r.role in ('Purchase Manager','Material Manager')
332 and p.name not in ('Administrator', 'All', 'Guest')""")
333
334 msg="""<h3>Following Material Requests has been raised automatically \
335 based on item reorder level:</h3>"""
336 for mr in mr_list:
337 msg += "<p><b><u>" + mr.doc.name + """</u></b></p><table class='table table-bordered'><tr>
338 <th>Item Code</th><th>Warehouse</th><th>Qty</th><th>UOM</th></tr>"""
339 for item in mr.doclist.get({"parentfield": "indent_details"}):
340 msg += "<tr><td>" + item.item_code + "</td><td>" + item.warehouse + "</td><td>" + \
341 cstr(item.qty) + "</td><td>" + cstr(item.uom) + "</td></tr>"
342 msg += "</table>"
343
Anand Doshiad6180e2013-06-17 11:57:04 +0530344 sendmail(email_list, subject='Auto Material Request Generation Notification', msg = msg)
345
346def notify_errors(exceptions_list):
347 subject = "[Important] [ERPNext] Error(s) while creating Material Requests based on Re-order Levels"
348 msg = """Dear System Manager,
349
350 An error occured for certain Items while creating Material Requests based on Re-order level.
351
352 Please rectify these issues:
353 ---
354
355 %s
356
357 ---
358 Regards,
359 Administrator""" % ("\n\n".join(["\n".join(msg) for msg in exceptions_list]),)
360
361 from webnotes.profile import get_system_managers
362 sendmail(get_system_managers(), subject=subject, msg=msg)