blob: 5d5c872ccb8e10c90ecd11f8665b6d76ccfa4f49 [file] [log] [blame]
Nabin Hait9d0f6362013-01-07 18:51:11 +05301# ERPNext - web based ERP (http://erpnext.com)
2# Copyright (C) 2012 Web Notes Technologies Pvt Ltd
3#
4# This program is free software: you can redistribute it and/or modify
5# it under the terms of the GNU General Public License as published by
6# the Free Software Foundation, either version 3 of the License, or
7# (at your option) any later version.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License
15# along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17import webnotes
18from webnotes import msgprint, _
19import json
Nabin Hait62d06292013-05-22 16:19:10 +053020from webnotes.utils import flt, cstr, nowdate, add_days, cint
Rushabh Mehta5117d9c2013-02-19 15:27:31 +053021from webnotes.defaults import get_global_default
Anand Doshiad6180e2013-06-17 11:57:04 +053022from webnotes.utils.email_lib import sendmail
Nabin Hait9d0f6362013-01-07 18:51:11 +053023
Nabin Hait0dd7be12013-08-02 11:45:43 +053024
25def get_stock_balance_on(warehouse_list, posting_date=None):
26 if not posting_date: posting_date = nowdate()
27
28 stock_ledger_entries = webnotes.conn.sql("""
29 SELECT
30 item_code, warehouse, stock_value
31 FROM
32 `tabStock Ledger Entry`
33 WHERE
34 warehouse in (%s)
35 AND posting_date <= %s
36 ORDER BY timestamp(posting_date, posting_time) DESC, name DESC
37 """ % (', '.join(['%s']*len(warehouse_list)), '%s'),
38 tuple(warehouse_list + [posting_date]), as_dict=1)
39
40 sle_map = {}
41 for sle in stock_ledger_entries:
42 sle_map.setdefault(sle.warehouse, {}).setdefault(sle.item_code, flt(sle.stock_value))
43
44 return sum([sum(item_dict.values()) for item_dict in sle_map.values()])
45
Nabin Hait47dc3182013-08-06 15:58:16 +053046def get_latest_stock_balance():
47 bin_map = {}
48 for d in webnotes.conn.sql("""SELECT item_code, warehouse, sum(stock_value) as stock_value
49 FROM tabBin""", as_dict=1):
50 bin_map.setdefault(d.warehouse, {}).setdefault(d.item_code, d.stock_value)
51
52 return bin_map
Nabin Hait0dd7be12013-08-02 11:45:43 +053053
Nabin Hait9d0f6362013-01-07 18:51:11 +053054def validate_end_of_life(item_code, end_of_life=None, verbose=1):
55 if not end_of_life:
56 end_of_life = webnotes.conn.get_value("Item", item_code, "end_of_life")
57
58 from webnotes.utils import getdate, now_datetime, formatdate
Anand Doshiad6180e2013-06-17 11:57:04 +053059 if end_of_life and getdate(end_of_life) <= now_datetime().date():
Nabin Hait9d0f6362013-01-07 18:51:11 +053060 msg = (_("Item") + " %(item_code)s: " + _("reached its end of life on") + \
61 " %(date)s. " + _("Please check") + ": %(end_of_life_label)s " + \
62 "in Item master") % {
63 "item_code": item_code,
64 "date": formatdate(end_of_life),
Anand Doshia43b29e2013-02-20 15:55:10 +053065 "end_of_life_label": webnotes.get_doctype("Item").get_label("end_of_life")
Nabin Hait9d0f6362013-01-07 18:51:11 +053066 }
67
68 _msgprint(msg, verbose)
69
70def validate_is_stock_item(item_code, is_stock_item=None, verbose=1):
71 if not is_stock_item:
72 is_stock_item = webnotes.conn.get_value("Item", item_code, "is_stock_item")
73
74 if is_stock_item != "Yes":
75 msg = (_("Item") + " %(item_code)s: " + _("is not a Stock Item")) % {
76 "item_code": item_code,
77 }
78
79 _msgprint(msg, verbose)
80
81def validate_cancelled_item(item_code, docstatus=None, verbose=1):
82 if docstatus is None:
83 docstatus = webnotes.conn.get_value("Item", item_code, "docstatus")
84
85 if docstatus == 2:
86 msg = (_("Item") + " %(item_code)s: " + _("is a cancelled Item")) % {
87 "item_code": item_code,
88 }
89
90 _msgprint(msg, verbose)
91
92def _msgprint(msg, verbose):
93 if verbose:
94 msgprint(msg, raise_exception=True)
95 else:
96 raise webnotes.ValidationError, msg
97
Nabin Hait9d0f6362013-01-07 18:51:11 +053098def get_incoming_rate(args):
99 """Get Incoming Rate based on valuation method"""
Anand Doshi1b531862013-01-10 19:29:51 +0530100 from stock.stock_ledger import get_previous_sle
Nabin Hait9d0f6362013-01-07 18:51:11 +0530101
102 in_rate = 0
103 if args.get("serial_no"):
104 in_rate = get_avg_purchase_rate(args.get("serial_no"))
105 elif args.get("bom_no"):
106 result = webnotes.conn.sql("""select ifnull(total_cost, 0) / ifnull(quantity, 1)
107 from `tabBOM` where name = %s and docstatus=1 and is_active=1""", args.get("bom_no"))
108 in_rate = result and flt(result[0][0]) or 0
109 else:
110 valuation_method = get_valuation_method(args.get("item_code"))
111 previous_sle = get_previous_sle(args)
112 if valuation_method == 'FIFO':
Nabin Hait831207f2013-01-16 14:15:48 +0530113 if not previous_sle:
114 return 0.0
115 previous_stock_queue = json.loads(previous_sle.get('stock_queue', '[]'))
116 in_rate = previous_stock_queue and \
Nabin Hait6b1f21d2013-01-16 17:17:17 +0530117 get_fifo_rate(previous_stock_queue, args.get("qty") or 0) or 0
Nabin Hait9d0f6362013-01-07 18:51:11 +0530118 elif valuation_method == 'Moving Average':
119 in_rate = previous_sle.get('valuation_rate') or 0
120 return in_rate
121
122def get_avg_purchase_rate(serial_nos):
123 """get average value of serial numbers"""
124
125 serial_nos = get_valid_serial_nos(serial_nos)
126 return flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0)) from `tabSerial No`
127 where name in (%s)""" % ", ".join(["%s"] * len(serial_nos)),
128 tuple(serial_nos))[0][0])
129
130def get_valuation_method(item_code):
131 """get valuation method from item or default"""
132 val_method = webnotes.conn.get_value('Item', item_code, 'valuation_method')
133 if not val_method:
Rushabh Mehta5117d9c2013-02-19 15:27:31 +0530134 val_method = get_global_default('valuation_method') or "FIFO"
Nabin Hait9d0f6362013-01-07 18:51:11 +0530135 return val_method
136
Nabin Hait831207f2013-01-16 14:15:48 +0530137def get_fifo_rate(previous_stock_queue, qty):
138 """get FIFO (average) Rate from Queue"""
139 if qty >= 0:
140 total = sum(f[0] for f in previous_stock_queue)
141 return total and sum(f[0] * f[1] for f in previous_stock_queue) / flt(total) or 0.0
142 else:
143 outgoing_cost = 0
144 qty_to_pop = abs(qty)
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530145 while qty_to_pop and previous_stock_queue:
Nabin Hait831207f2013-01-16 14:15:48 +0530146 batch = previous_stock_queue[0]
147 if 0 < batch[0] <= qty_to_pop:
148 # if batch qty > 0
149 # not enough or exactly same qty in current batch, clear batch
150 outgoing_cost += flt(batch[0]) * flt(batch[1])
151 qty_to_pop -= batch[0]
152 previous_stock_queue.pop(0)
153 else:
154 # all from current batch
155 outgoing_cost += flt(qty_to_pop) * flt(batch[1])
156 batch[0] -= qty_to_pop
157 qty_to_pop = 0
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530158 # if queue gets blank and qty_to_pop remaining, get average rate of full queue
159 return outgoing_cost / abs(qty) - qty_to_pop
Nabin Hait9d0f6362013-01-07 18:51:11 +0530160
161def get_valid_serial_nos(sr_nos, qty=0, item_code=''):
162 """split serial nos, validate and return list of valid serial nos"""
163 # TODO: remove duplicates in client side
164 serial_nos = cstr(sr_nos).strip().replace(',', '\n').split('\n')
165
166 valid_serial_nos = []
167 for val in serial_nos:
168 if val:
169 val = val.strip()
170 if val in valid_serial_nos:
171 msgprint("You have entered duplicate serial no: '%s'" % val, raise_exception=1)
172 else:
173 valid_serial_nos.append(val)
174
175 if qty and len(valid_serial_nos) != abs(qty):
176 msgprint("Please enter serial nos for "
177 + cstr(abs(qty)) + " quantity against item code: " + item_code,
178 raise_exception=1)
179
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530180 return valid_serial_nos
181
Nabin Haitdc95c152013-02-07 12:08:38 +0530182def get_warehouse_list(doctype, txt, searchfield, start, page_len, filters):
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530183 """used in search queries"""
184 wlist = []
185 for w in webnotes.conn.sql_list("""select name from tabWarehouse
186 where name like '%%%s%%'""" % txt):
187 if webnotes.session.user=="Administrator":
188 wlist.append([w])
189 else:
190 warehouse_users = webnotes.conn.sql_list("""select user from `tabWarehouse User`
191 where parent=%s""", w)
192 if not warehouse_users:
193 wlist.append([w])
194 elif webnotes.session.user in warehouse_users:
195 wlist.append([w])
196 return wlist
Nabin Haita72c5122013-03-06 18:50:53 +0530197
Nabin Hait8c7234f2013-03-11 16:32:33 +0530198def get_buying_amount(item_code, warehouse, qty, voucher_type, voucher_no, voucher_detail_no,
Nabin Haitc3afb252013-03-19 12:01:24 +0530199 stock_ledger_entries, item_sales_bom=None):
200 if item_sales_bom and item_sales_bom.get(item_code):
Nabin Haita72c5122013-03-06 18:50:53 +0530201 # sales bom item
202 buying_amount = 0.0
203 for bom_item in item_sales_bom[item_code]:
Anand Doshi96b189c2013-03-26 18:43:10 +0530204 if bom_item.get("parent_detail_docname")==voucher_detail_no:
Anand Doshi8c454202013-03-28 16:40:30 +0530205 buying_amount += _get_buying_amount(voucher_type, voucher_no, voucher_detail_no,
Anand Doshi96b189c2013-03-26 18:43:10 +0530206 bom_item.item_code, bom_item.warehouse or warehouse,
207 bom_item.total_qty or (bom_item.qty * qty), stock_ledger_entries)
Nabin Haita72c5122013-03-06 18:50:53 +0530208 return buying_amount
209 else:
210 # doesn't have sales bom
Nabin Hait8c7234f2013-03-11 16:32:33 +0530211 return _get_buying_amount(voucher_type, voucher_no, voucher_detail_no,
212 item_code, warehouse, qty, stock_ledger_entries)
Nabin Haita72c5122013-03-06 18:50:53 +0530213
Nabin Hait8c7234f2013-03-11 16:32:33 +0530214def _get_buying_amount(voucher_type, voucher_no, item_row, item_code, warehouse, qty,
215 stock_ledger_entries):
Anand Doshi96b189c2013-03-26 18:43:10 +0530216 relevant_stock_ledger_entries = [sle for sle in stock_ledger_entries
217 if sle.item_code == item_code and sle.warehouse == warehouse]
218
219 for i, sle in enumerate(relevant_stock_ledger_entries):
Nabin Hait0cfbc5f2013-03-12 11:34:56 +0530220 if sle.voucher_type == voucher_type and sle.voucher_no == voucher_no and \
Anand Doshi8c454202013-03-28 16:40:30 +0530221 sle.voucher_detail_no == item_row:
Anand Doshi96b189c2013-03-26 18:43:10 +0530222 previous_stock_value = len(relevant_stock_ledger_entries) > i+1 and \
223 flt(relevant_stock_ledger_entries[i+1].stock_value) or 0.0
224
Nabin Haitc3afb252013-03-19 12:01:24 +0530225 buying_amount = previous_stock_value - flt(sle.stock_value)
Anand Doshi6d8d3b42013-03-21 18:45:02 +0530226
Nabin Haitc3afb252013-03-19 12:01:24 +0530227 return buying_amount
Nabin Hait62d06292013-05-22 16:19:10 +0530228 return 0.0
229
230
231def reorder_item():
232 """ Reorder item if stock reaches reorder level"""
233 if not hasattr(webnotes, "auto_indent"):
Rushabh Mehta7a93d5d2013-06-24 18:18:46 +0530234 webnotes.auto_indent = webnotes.conn.get_value('Stock Settings', None, 'auto_indent')
Nabin Hait62d06292013-05-22 16:19:10 +0530235
236 if webnotes.auto_indent:
237 material_requests = {}
238 bin_list = webnotes.conn.sql("""select item_code, warehouse, projected_qty
Anand Doshiad6180e2013-06-17 11:57:04 +0530239 from tabBin where ifnull(item_code, '') != '' and ifnull(warehouse, '') != ''
240 and exists (select name from `tabItem`
241 where `tabItem`.name = `tabBin`.item_code and
242 is_stock_item='Yes' and (is_purchase_item='Yes' or is_sub_contracted_item='Yes') and
243 (ifnull(end_of_life, '')='') or end_of_life > now())""",
Nabin Hait62d06292013-05-22 16:19:10 +0530244 as_dict=True)
245 for bin in bin_list:
246 #check if re-order is required
247 item_reorder = webnotes.conn.get("Item Reorder",
248 {"parent": bin.item_code, "warehouse": bin.warehouse})
249 if item_reorder:
250 reorder_level = item_reorder.warehouse_reorder_level
251 reorder_qty = item_reorder.warehouse_reorder_qty
252 material_request_type = item_reorder.material_request_type or "Purchase"
253 else:
254 reorder_level, reorder_qty = webnotes.conn.get_value("Item", bin.item_code,
255 ["re_order_level", "re_order_qty"])
256 material_request_type = "Purchase"
257
Anand Doshiad6180e2013-06-17 11:57:04 +0530258 if flt(reorder_level) and flt(bin.projected_qty) < flt(reorder_level):
Nabin Hait62d06292013-05-22 16:19:10 +0530259 if flt(reorder_level) - flt(bin.projected_qty) > flt(reorder_qty):
260 reorder_qty = flt(reorder_level) - flt(bin.projected_qty)
261
262 company = webnotes.conn.get_value("Warehouse", bin.warehouse, "company") or \
263 webnotes.defaults.get_defaults()["company"] or \
264 webnotes.conn.sql("""select name from tabCompany limit 1""")[0][0]
265
266 material_requests.setdefault(material_request_type, webnotes._dict()).setdefault(
267 company, []).append(webnotes._dict({
268 "item_code": bin.item_code,
269 "warehouse": bin.warehouse,
270 "reorder_qty": reorder_qty
271 })
272 )
273
274 create_material_request(material_requests)
275
276def create_material_request(material_requests):
277 """ Create indent on reaching reorder level """
278 mr_list = []
279 defaults = webnotes.defaults.get_defaults()
Anand Doshiad6180e2013-06-17 11:57:04 +0530280 exceptions_list = []
Nabin Hait62d06292013-05-22 16:19:10 +0530281 for request_type in material_requests:
282 for company in material_requests[request_type]:
Anand Doshiad6180e2013-06-17 11:57:04 +0530283 try:
284 items = material_requests[request_type][company]
285 if not items:
286 continue
Anand Doshi6f6e91c2013-07-22 11:28:34 +0530287
Nabin Hait62d06292013-05-22 16:19:10 +0530288 mr = [{
289 "doctype": "Material Request",
290 "company": company,
291 "fiscal_year": defaults.fiscal_year,
292 "transaction_date": nowdate(),
293 "material_request_type": request_type,
294 "remark": _("This is an auto generated Material Request.") + \
295 _("""It was raised because the (actual + ordered + indented - reserved)
296 quantity reaches re-order level when the following record was created""")
297 }]
298
Anand Doshiad6180e2013-06-17 11:57:04 +0530299 for d in items:
300 item = webnotes.doc("Item", d.item_code)
301 mr.append({
302 "doctype": "Material Request Item",
303 "parenttype": "Material Request",
304 "parentfield": "indent_details",
305 "item_code": d.item_code,
306 "schedule_date": add_days(nowdate(),cint(item.lead_time_days)),
307 "uom": item.stock_uom,
308 "warehouse": d.warehouse,
309 "item_name": item.item_name,
310 "description": item.description,
311 "item_group": item.item_group,
312 "qty": d.reorder_qty,
313 "brand": item.brand,
314 })
Nabin Hait62d06292013-05-22 16:19:10 +0530315
Anand Doshiad6180e2013-06-17 11:57:04 +0530316 mr_bean = webnotes.bean(mr)
317 mr_bean.insert()
318 mr_bean.submit()
319 mr_list.append(mr_bean)
Anand Doshi6f6e91c2013-07-22 11:28:34 +0530320
Anand Doshiad6180e2013-06-17 11:57:04 +0530321 except:
322 if webnotes.message_log:
323 exceptions_list.append([] + webnotes.message_log)
324 webnotes.message_log = []
325 else:
326 exceptions_list.append(webnotes.getTraceback())
Nabin Hait62d06292013-05-22 16:19:10 +0530327
328 if mr_list:
329 if not hasattr(webnotes, "reorder_email_notify"):
Rushabh Mehta7a93d5d2013-06-24 18:18:46 +0530330 webnotes.reorder_email_notify = webnotes.conn.get_value('Stock Settings', None,
Nabin Hait62d06292013-05-22 16:19:10 +0530331 'reorder_email_notify')
332
333 if(webnotes.reorder_email_notify):
334 send_email_notification(mr_list)
Anand Doshiad6180e2013-06-17 11:57:04 +0530335
336 if exceptions_list:
337 notify_errors(exceptions_list)
Nabin Hait62d06292013-05-22 16:19:10 +0530338
339def send_email_notification(mr_list):
340 """ Notify user about auto creation of indent"""
341
Nabin Hait62d06292013-05-22 16:19:10 +0530342 email_list = webnotes.conn.sql_list("""select distinct r.parent
343 from tabUserRole r, tabProfile p
344 where p.name = r.parent and p.enabled = 1 and p.docstatus < 2
345 and r.role in ('Purchase Manager','Material Manager')
346 and p.name not in ('Administrator', 'All', 'Guest')""")
347
348 msg="""<h3>Following Material Requests has been raised automatically \
349 based on item reorder level:</h3>"""
350 for mr in mr_list:
351 msg += "<p><b><u>" + mr.doc.name + """</u></b></p><table class='table table-bordered'><tr>
352 <th>Item Code</th><th>Warehouse</th><th>Qty</th><th>UOM</th></tr>"""
353 for item in mr.doclist.get({"parentfield": "indent_details"}):
354 msg += "<tr><td>" + item.item_code + "</td><td>" + item.warehouse + "</td><td>" + \
355 cstr(item.qty) + "</td><td>" + cstr(item.uom) + "</td></tr>"
356 msg += "</table>"
357
Anand Doshiad6180e2013-06-17 11:57:04 +0530358 sendmail(email_list, subject='Auto Material Request Generation Notification', msg = msg)
359
360def notify_errors(exceptions_list):
361 subject = "[Important] [ERPNext] Error(s) while creating Material Requests based on Re-order Levels"
362 msg = """Dear System Manager,
363
364 An error occured for certain Items while creating Material Requests based on Re-order level.
365
366 Please rectify these issues:
367 ---
368
369 %s
370
371 ---
372 Regards,
373 Administrator""" % ("\n\n".join(["\n".join(msg) for msg in exceptions_list]),)
374
375 from webnotes.profile import get_system_managers
376 sendmail(get_system_managers(), subject=subject, msg=msg)