blob: 9ff8314f477ccb112bf92c4c35dec2fca7b4d4c6 [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 Hait73d04b12013-08-05 12:19:38 +053046def get_latest_stock_balance(warehouse, item):
Nabin Hait0dd7be12013-08-02 11:45:43 +053047 return webnotes.conn.sql("""
Nabin Hait73d04b12013-08-05 12:19:38 +053048 SELECT sum(stock_value)
Nabin Hait0dd7be12013-08-02 11:45:43 +053049 FROM tabBin
50 where warehouse in (%s)
51 """ % ', '.join(['%s']*len(warehouse_list)), warehouse_list)[0][0]
52
Nabin Hait9d0f6362013-01-07 18:51:11 +053053def validate_end_of_life(item_code, end_of_life=None, verbose=1):
54 if not end_of_life:
55 end_of_life = webnotes.conn.get_value("Item", item_code, "end_of_life")
56
57 from webnotes.utils import getdate, now_datetime, formatdate
Anand Doshiad6180e2013-06-17 11:57:04 +053058 if end_of_life and getdate(end_of_life) <= now_datetime().date():
Nabin Hait9d0f6362013-01-07 18:51:11 +053059 msg = (_("Item") + " %(item_code)s: " + _("reached its end of life on") + \
60 " %(date)s. " + _("Please check") + ": %(end_of_life_label)s " + \
61 "in Item master") % {
62 "item_code": item_code,
63 "date": formatdate(end_of_life),
Anand Doshia43b29e2013-02-20 15:55:10 +053064 "end_of_life_label": webnotes.get_doctype("Item").get_label("end_of_life")
Nabin Hait9d0f6362013-01-07 18:51:11 +053065 }
66
67 _msgprint(msg, verbose)
68
69def validate_is_stock_item(item_code, is_stock_item=None, verbose=1):
70 if not is_stock_item:
71 is_stock_item = webnotes.conn.get_value("Item", item_code, "is_stock_item")
72
73 if is_stock_item != "Yes":
74 msg = (_("Item") + " %(item_code)s: " + _("is not a Stock Item")) % {
75 "item_code": item_code,
76 }
77
78 _msgprint(msg, verbose)
79
80def validate_cancelled_item(item_code, docstatus=None, verbose=1):
81 if docstatus is None:
82 docstatus = webnotes.conn.get_value("Item", item_code, "docstatus")
83
84 if docstatus == 2:
85 msg = (_("Item") + " %(item_code)s: " + _("is a cancelled Item")) % {
86 "item_code": item_code,
87 }
88
89 _msgprint(msg, verbose)
90
91def _msgprint(msg, verbose):
92 if verbose:
93 msgprint(msg, raise_exception=True)
94 else:
95 raise webnotes.ValidationError, msg
96
Nabin Hait9d0f6362013-01-07 18:51:11 +053097def get_incoming_rate(args):
98 """Get Incoming Rate based on valuation method"""
Anand Doshi1b531862013-01-10 19:29:51 +053099 from stock.stock_ledger import get_previous_sle
Nabin Hait9d0f6362013-01-07 18:51:11 +0530100
101 in_rate = 0
102 if args.get("serial_no"):
103 in_rate = get_avg_purchase_rate(args.get("serial_no"))
104 elif args.get("bom_no"):
105 result = webnotes.conn.sql("""select ifnull(total_cost, 0) / ifnull(quantity, 1)
106 from `tabBOM` where name = %s and docstatus=1 and is_active=1""", args.get("bom_no"))
107 in_rate = result and flt(result[0][0]) or 0
108 else:
109 valuation_method = get_valuation_method(args.get("item_code"))
110 previous_sle = get_previous_sle(args)
111 if valuation_method == 'FIFO':
Nabin Hait831207f2013-01-16 14:15:48 +0530112 if not previous_sle:
113 return 0.0
114 previous_stock_queue = json.loads(previous_sle.get('stock_queue', '[]'))
115 in_rate = previous_stock_queue and \
Nabin Hait6b1f21d2013-01-16 17:17:17 +0530116 get_fifo_rate(previous_stock_queue, args.get("qty") or 0) or 0
Nabin Hait9d0f6362013-01-07 18:51:11 +0530117 elif valuation_method == 'Moving Average':
118 in_rate = previous_sle.get('valuation_rate') or 0
119 return in_rate
120
121def get_avg_purchase_rate(serial_nos):
122 """get average value of serial numbers"""
123
124 serial_nos = get_valid_serial_nos(serial_nos)
125 return flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0)) from `tabSerial No`
126 where name in (%s)""" % ", ".join(["%s"] * len(serial_nos)),
127 tuple(serial_nos))[0][0])
128
129def get_valuation_method(item_code):
130 """get valuation method from item or default"""
131 val_method = webnotes.conn.get_value('Item', item_code, 'valuation_method')
132 if not val_method:
Rushabh Mehta5117d9c2013-02-19 15:27:31 +0530133 val_method = get_global_default('valuation_method') or "FIFO"
Nabin Hait9d0f6362013-01-07 18:51:11 +0530134 return val_method
135
Nabin Hait831207f2013-01-16 14:15:48 +0530136def get_fifo_rate(previous_stock_queue, qty):
137 """get FIFO (average) Rate from Queue"""
138 if qty >= 0:
139 total = sum(f[0] for f in previous_stock_queue)
140 return total and sum(f[0] * f[1] for f in previous_stock_queue) / flt(total) or 0.0
141 else:
142 outgoing_cost = 0
143 qty_to_pop = abs(qty)
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530144 while qty_to_pop and previous_stock_queue:
Nabin Hait831207f2013-01-16 14:15:48 +0530145 batch = previous_stock_queue[0]
146 if 0 < batch[0] <= qty_to_pop:
147 # if batch qty > 0
148 # not enough or exactly same qty in current batch, clear batch
149 outgoing_cost += flt(batch[0]) * flt(batch[1])
150 qty_to_pop -= batch[0]
151 previous_stock_queue.pop(0)
152 else:
153 # all from current batch
154 outgoing_cost += flt(qty_to_pop) * flt(batch[1])
155 batch[0] -= qty_to_pop
156 qty_to_pop = 0
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530157 # if queue gets blank and qty_to_pop remaining, get average rate of full queue
158 return outgoing_cost / abs(qty) - qty_to_pop
Nabin Hait9d0f6362013-01-07 18:51:11 +0530159
160def get_valid_serial_nos(sr_nos, qty=0, item_code=''):
161 """split serial nos, validate and return list of valid serial nos"""
162 # TODO: remove duplicates in client side
163 serial_nos = cstr(sr_nos).strip().replace(',', '\n').split('\n')
164
165 valid_serial_nos = []
166 for val in serial_nos:
167 if val:
168 val = val.strip()
169 if val in valid_serial_nos:
170 msgprint("You have entered duplicate serial no: '%s'" % val, raise_exception=1)
171 else:
172 valid_serial_nos.append(val)
173
174 if qty and len(valid_serial_nos) != abs(qty):
175 msgprint("Please enter serial nos for "
176 + cstr(abs(qty)) + " quantity against item code: " + item_code,
177 raise_exception=1)
178
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530179 return valid_serial_nos
180
Nabin Haitdc95c152013-02-07 12:08:38 +0530181def get_warehouse_list(doctype, txt, searchfield, start, page_len, filters):
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530182 """used in search queries"""
183 wlist = []
184 for w in webnotes.conn.sql_list("""select name from tabWarehouse
185 where name like '%%%s%%'""" % txt):
186 if webnotes.session.user=="Administrator":
187 wlist.append([w])
188 else:
189 warehouse_users = webnotes.conn.sql_list("""select user from `tabWarehouse User`
190 where parent=%s""", w)
191 if not warehouse_users:
192 wlist.append([w])
193 elif webnotes.session.user in warehouse_users:
194 wlist.append([w])
195 return wlist
Nabin Haita72c5122013-03-06 18:50:53 +0530196
Nabin Hait8c7234f2013-03-11 16:32:33 +0530197def get_buying_amount(item_code, warehouse, qty, voucher_type, voucher_no, voucher_detail_no,
Nabin Haitc3afb252013-03-19 12:01:24 +0530198 stock_ledger_entries, item_sales_bom=None):
199 if item_sales_bom and item_sales_bom.get(item_code):
Nabin Haita72c5122013-03-06 18:50:53 +0530200 # sales bom item
201 buying_amount = 0.0
202 for bom_item in item_sales_bom[item_code]:
Anand Doshi96b189c2013-03-26 18:43:10 +0530203 if bom_item.get("parent_detail_docname")==voucher_detail_no:
Anand Doshi8c454202013-03-28 16:40:30 +0530204 buying_amount += _get_buying_amount(voucher_type, voucher_no, voucher_detail_no,
Anand Doshi96b189c2013-03-26 18:43:10 +0530205 bom_item.item_code, bom_item.warehouse or warehouse,
206 bom_item.total_qty or (bom_item.qty * qty), stock_ledger_entries)
Nabin Haita72c5122013-03-06 18:50:53 +0530207 return buying_amount
208 else:
209 # doesn't have sales bom
Nabin Hait8c7234f2013-03-11 16:32:33 +0530210 return _get_buying_amount(voucher_type, voucher_no, voucher_detail_no,
211 item_code, warehouse, qty, stock_ledger_entries)
Nabin Haita72c5122013-03-06 18:50:53 +0530212
Nabin Hait8c7234f2013-03-11 16:32:33 +0530213def _get_buying_amount(voucher_type, voucher_no, item_row, item_code, warehouse, qty,
214 stock_ledger_entries):
Anand Doshi96b189c2013-03-26 18:43:10 +0530215 relevant_stock_ledger_entries = [sle for sle in stock_ledger_entries
216 if sle.item_code == item_code and sle.warehouse == warehouse]
217
218 for i, sle in enumerate(relevant_stock_ledger_entries):
Nabin Hait0cfbc5f2013-03-12 11:34:56 +0530219 if sle.voucher_type == voucher_type and sle.voucher_no == voucher_no and \
Anand Doshi8c454202013-03-28 16:40:30 +0530220 sle.voucher_detail_no == item_row:
Anand Doshi96b189c2013-03-26 18:43:10 +0530221 previous_stock_value = len(relevant_stock_ledger_entries) > i+1 and \
222 flt(relevant_stock_ledger_entries[i+1].stock_value) or 0.0
223
Nabin Haitc3afb252013-03-19 12:01:24 +0530224 buying_amount = previous_stock_value - flt(sle.stock_value)
Anand Doshi6d8d3b42013-03-21 18:45:02 +0530225
Nabin Haitc3afb252013-03-19 12:01:24 +0530226 return buying_amount
Nabin Hait62d06292013-05-22 16:19:10 +0530227 return 0.0
228
229
230def reorder_item():
231 """ Reorder item if stock reaches reorder level"""
232 if not hasattr(webnotes, "auto_indent"):
Rushabh Mehta7a93d5d2013-06-24 18:18:46 +0530233 webnotes.auto_indent = webnotes.conn.get_value('Stock Settings', None, 'auto_indent')
Nabin Hait62d06292013-05-22 16:19:10 +0530234
235 if webnotes.auto_indent:
236 material_requests = {}
237 bin_list = webnotes.conn.sql("""select item_code, warehouse, projected_qty
Anand Doshiad6180e2013-06-17 11:57:04 +0530238 from tabBin where ifnull(item_code, '') != '' and ifnull(warehouse, '') != ''
239 and exists (select name from `tabItem`
240 where `tabItem`.name = `tabBin`.item_code and
241 is_stock_item='Yes' and (is_purchase_item='Yes' or is_sub_contracted_item='Yes') and
242 (ifnull(end_of_life, '')='') or end_of_life > now())""",
Nabin Hait62d06292013-05-22 16:19:10 +0530243 as_dict=True)
244 for bin in bin_list:
245 #check if re-order is required
246 item_reorder = webnotes.conn.get("Item Reorder",
247 {"parent": bin.item_code, "warehouse": bin.warehouse})
248 if item_reorder:
249 reorder_level = item_reorder.warehouse_reorder_level
250 reorder_qty = item_reorder.warehouse_reorder_qty
251 material_request_type = item_reorder.material_request_type or "Purchase"
252 else:
253 reorder_level, reorder_qty = webnotes.conn.get_value("Item", bin.item_code,
254 ["re_order_level", "re_order_qty"])
255 material_request_type = "Purchase"
256
Anand Doshiad6180e2013-06-17 11:57:04 +0530257 if flt(reorder_level) and flt(bin.projected_qty) < flt(reorder_level):
Nabin Hait62d06292013-05-22 16:19:10 +0530258 if flt(reorder_level) - flt(bin.projected_qty) > flt(reorder_qty):
259 reorder_qty = flt(reorder_level) - flt(bin.projected_qty)
260
261 company = webnotes.conn.get_value("Warehouse", bin.warehouse, "company") or \
262 webnotes.defaults.get_defaults()["company"] or \
263 webnotes.conn.sql("""select name from tabCompany limit 1""")[0][0]
264
265 material_requests.setdefault(material_request_type, webnotes._dict()).setdefault(
266 company, []).append(webnotes._dict({
267 "item_code": bin.item_code,
268 "warehouse": bin.warehouse,
269 "reorder_qty": reorder_qty
270 })
271 )
272
273 create_material_request(material_requests)
274
275def create_material_request(material_requests):
276 """ Create indent on reaching reorder level """
277 mr_list = []
278 defaults = webnotes.defaults.get_defaults()
Anand Doshiad6180e2013-06-17 11:57:04 +0530279 exceptions_list = []
Nabin Hait62d06292013-05-22 16:19:10 +0530280 for request_type in material_requests:
281 for company in material_requests[request_type]:
Anand Doshiad6180e2013-06-17 11:57:04 +0530282 try:
283 items = material_requests[request_type][company]
284 if not items:
285 continue
Anand Doshi6f6e91c2013-07-22 11:28:34 +0530286
Nabin Hait62d06292013-05-22 16:19:10 +0530287 mr = [{
288 "doctype": "Material Request",
289 "company": company,
290 "fiscal_year": defaults.fiscal_year,
291 "transaction_date": nowdate(),
292 "material_request_type": request_type,
293 "remark": _("This is an auto generated Material Request.") + \
294 _("""It was raised because the (actual + ordered + indented - reserved)
295 quantity reaches re-order level when the following record was created""")
296 }]
297
Anand Doshiad6180e2013-06-17 11:57:04 +0530298 for d in items:
299 item = webnotes.doc("Item", d.item_code)
300 mr.append({
301 "doctype": "Material Request Item",
302 "parenttype": "Material Request",
303 "parentfield": "indent_details",
304 "item_code": d.item_code,
305 "schedule_date": add_days(nowdate(),cint(item.lead_time_days)),
306 "uom": item.stock_uom,
307 "warehouse": d.warehouse,
308 "item_name": item.item_name,
309 "description": item.description,
310 "item_group": item.item_group,
311 "qty": d.reorder_qty,
312 "brand": item.brand,
313 })
Nabin Hait62d06292013-05-22 16:19:10 +0530314
Anand Doshiad6180e2013-06-17 11:57:04 +0530315 mr_bean = webnotes.bean(mr)
316 mr_bean.insert()
317 mr_bean.submit()
318 mr_list.append(mr_bean)
Anand Doshi6f6e91c2013-07-22 11:28:34 +0530319
Anand Doshiad6180e2013-06-17 11:57:04 +0530320 except:
321 if webnotes.message_log:
322 exceptions_list.append([] + webnotes.message_log)
323 webnotes.message_log = []
324 else:
325 exceptions_list.append(webnotes.getTraceback())
Nabin Hait62d06292013-05-22 16:19:10 +0530326
327 if mr_list:
328 if not hasattr(webnotes, "reorder_email_notify"):
Rushabh Mehta7a93d5d2013-06-24 18:18:46 +0530329 webnotes.reorder_email_notify = webnotes.conn.get_value('Stock Settings', None,
Nabin Hait62d06292013-05-22 16:19:10 +0530330 'reorder_email_notify')
331
332 if(webnotes.reorder_email_notify):
333 send_email_notification(mr_list)
Anand Doshiad6180e2013-06-17 11:57:04 +0530334
335 if exceptions_list:
336 notify_errors(exceptions_list)
Nabin Hait62d06292013-05-22 16:19:10 +0530337
338def send_email_notification(mr_list):
339 """ Notify user about auto creation of indent"""
340
Nabin Hait62d06292013-05-22 16:19:10 +0530341 email_list = webnotes.conn.sql_list("""select distinct r.parent
342 from tabUserRole r, tabProfile p
343 where p.name = r.parent and p.enabled = 1 and p.docstatus < 2
344 and r.role in ('Purchase Manager','Material Manager')
345 and p.name not in ('Administrator', 'All', 'Guest')""")
346
347 msg="""<h3>Following Material Requests has been raised automatically \
348 based on item reorder level:</h3>"""
349 for mr in mr_list:
350 msg += "<p><b><u>" + mr.doc.name + """</u></b></p><table class='table table-bordered'><tr>
351 <th>Item Code</th><th>Warehouse</th><th>Qty</th><th>UOM</th></tr>"""
352 for item in mr.doclist.get({"parentfield": "indent_details"}):
353 msg += "<tr><td>" + item.item_code + "</td><td>" + item.warehouse + "</td><td>" + \
354 cstr(item.qty) + "</td><td>" + cstr(item.uom) + "</td></tr>"
355 msg += "</table>"
356
Anand Doshiad6180e2013-06-17 11:57:04 +0530357 sendmail(email_list, subject='Auto Material Request Generation Notification', msg = msg)
358
359def notify_errors(exceptions_list):
360 subject = "[Important] [ERPNext] Error(s) while creating Material Requests based on Re-order Levels"
361 msg = """Dear System Manager,
362
363 An error occured for certain Items while creating Material Requests based on Re-order level.
364
365 Please rectify these issues:
366 ---
367
368 %s
369
370 ---
371 Regards,
372 Administrator""" % ("\n\n".join(["\n".join(msg) for msg in exceptions_list]),)
373
374 from webnotes.profile import get_system_managers
375 sendmail(get_system_managers(), subject=subject, msg=msg)