blob: 5e7e53bb0146ed039636804a7e485704e347c555 [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
Nabin Hait9d0f6362013-01-07 18:51:11 +053022
23def validate_end_of_life(item_code, end_of_life=None, verbose=1):
24 if not end_of_life:
25 end_of_life = webnotes.conn.get_value("Item", item_code, "end_of_life")
26
27 from webnotes.utils import getdate, now_datetime, formatdate
28 if end_of_life and getdate(end_of_life) > now_datetime().date():
29 msg = (_("Item") + " %(item_code)s: " + _("reached its end of life on") + \
30 " %(date)s. " + _("Please check") + ": %(end_of_life_label)s " + \
31 "in Item master") % {
32 "item_code": item_code,
33 "date": formatdate(end_of_life),
Anand Doshia43b29e2013-02-20 15:55:10 +053034 "end_of_life_label": webnotes.get_doctype("Item").get_label("end_of_life")
Nabin Hait9d0f6362013-01-07 18:51:11 +053035 }
36
37 _msgprint(msg, verbose)
38
39def validate_is_stock_item(item_code, is_stock_item=None, verbose=1):
40 if not is_stock_item:
41 is_stock_item = webnotes.conn.get_value("Item", item_code, "is_stock_item")
42
43 if is_stock_item != "Yes":
44 msg = (_("Item") + " %(item_code)s: " + _("is not a Stock Item")) % {
45 "item_code": item_code,
46 }
47
48 _msgprint(msg, verbose)
49
50def validate_cancelled_item(item_code, docstatus=None, verbose=1):
51 if docstatus is None:
52 docstatus = webnotes.conn.get_value("Item", item_code, "docstatus")
53
54 if docstatus == 2:
55 msg = (_("Item") + " %(item_code)s: " + _("is a cancelled Item")) % {
56 "item_code": item_code,
57 }
58
59 _msgprint(msg, verbose)
60
61def _msgprint(msg, verbose):
62 if verbose:
63 msgprint(msg, raise_exception=True)
64 else:
65 raise webnotes.ValidationError, msg
66
Nabin Hait9d0f6362013-01-07 18:51:11 +053067def get_incoming_rate(args):
68 """Get Incoming Rate based on valuation method"""
Anand Doshi1b531862013-01-10 19:29:51 +053069 from stock.stock_ledger import get_previous_sle
Nabin Hait9d0f6362013-01-07 18:51:11 +053070
71 in_rate = 0
72 if args.get("serial_no"):
73 in_rate = get_avg_purchase_rate(args.get("serial_no"))
74 elif args.get("bom_no"):
75 result = webnotes.conn.sql("""select ifnull(total_cost, 0) / ifnull(quantity, 1)
76 from `tabBOM` where name = %s and docstatus=1 and is_active=1""", args.get("bom_no"))
77 in_rate = result and flt(result[0][0]) or 0
78 else:
79 valuation_method = get_valuation_method(args.get("item_code"))
80 previous_sle = get_previous_sle(args)
81 if valuation_method == 'FIFO':
Nabin Hait831207f2013-01-16 14:15:48 +053082 if not previous_sle:
83 return 0.0
84 previous_stock_queue = json.loads(previous_sle.get('stock_queue', '[]'))
85 in_rate = previous_stock_queue and \
Nabin Hait6b1f21d2013-01-16 17:17:17 +053086 get_fifo_rate(previous_stock_queue, args.get("qty") or 0) or 0
Nabin Hait9d0f6362013-01-07 18:51:11 +053087 elif valuation_method == 'Moving Average':
88 in_rate = previous_sle.get('valuation_rate') or 0
89 return in_rate
90
91def get_avg_purchase_rate(serial_nos):
92 """get average value of serial numbers"""
93
94 serial_nos = get_valid_serial_nos(serial_nos)
95 return flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0)) from `tabSerial No`
96 where name in (%s)""" % ", ".join(["%s"] * len(serial_nos)),
97 tuple(serial_nos))[0][0])
98
99def get_valuation_method(item_code):
100 """get valuation method from item or default"""
101 val_method = webnotes.conn.get_value('Item', item_code, 'valuation_method')
102 if not val_method:
Rushabh Mehta5117d9c2013-02-19 15:27:31 +0530103 val_method = get_global_default('valuation_method') or "FIFO"
Nabin Hait9d0f6362013-01-07 18:51:11 +0530104 return val_method
105
Nabin Hait831207f2013-01-16 14:15:48 +0530106def get_fifo_rate(previous_stock_queue, qty):
107 """get FIFO (average) Rate from Queue"""
108 if qty >= 0:
109 total = sum(f[0] for f in previous_stock_queue)
110 return total and sum(f[0] * f[1] for f in previous_stock_queue) / flt(total) or 0.0
111 else:
112 outgoing_cost = 0
113 qty_to_pop = abs(qty)
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530114 while qty_to_pop and previous_stock_queue:
Nabin Hait831207f2013-01-16 14:15:48 +0530115 batch = previous_stock_queue[0]
116 if 0 < batch[0] <= qty_to_pop:
117 # if batch qty > 0
118 # not enough or exactly same qty in current batch, clear batch
119 outgoing_cost += flt(batch[0]) * flt(batch[1])
120 qty_to_pop -= batch[0]
121 previous_stock_queue.pop(0)
122 else:
123 # all from current batch
124 outgoing_cost += flt(qty_to_pop) * flt(batch[1])
125 batch[0] -= qty_to_pop
126 qty_to_pop = 0
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530127 # if queue gets blank and qty_to_pop remaining, get average rate of full queue
128 return outgoing_cost / abs(qty) - qty_to_pop
Nabin Hait9d0f6362013-01-07 18:51:11 +0530129
130def get_valid_serial_nos(sr_nos, qty=0, item_code=''):
131 """split serial nos, validate and return list of valid serial nos"""
132 # TODO: remove duplicates in client side
133 serial_nos = cstr(sr_nos).strip().replace(',', '\n').split('\n')
134
135 valid_serial_nos = []
136 for val in serial_nos:
137 if val:
138 val = val.strip()
139 if val in valid_serial_nos:
140 msgprint("You have entered duplicate serial no: '%s'" % val, raise_exception=1)
141 else:
142 valid_serial_nos.append(val)
143
144 if qty and len(valid_serial_nos) != abs(qty):
145 msgprint("Please enter serial nos for "
146 + cstr(abs(qty)) + " quantity against item code: " + item_code,
147 raise_exception=1)
148
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530149 return valid_serial_nos
150
Nabin Haitdc95c152013-02-07 12:08:38 +0530151def get_warehouse_list(doctype, txt, searchfield, start, page_len, filters):
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530152 """used in search queries"""
153 wlist = []
154 for w in webnotes.conn.sql_list("""select name from tabWarehouse
155 where name like '%%%s%%'""" % txt):
156 if webnotes.session.user=="Administrator":
157 wlist.append([w])
158 else:
159 warehouse_users = webnotes.conn.sql_list("""select user from `tabWarehouse User`
160 where parent=%s""", w)
161 if not warehouse_users:
162 wlist.append([w])
163 elif webnotes.session.user in warehouse_users:
164 wlist.append([w])
165 return wlist
Nabin Haita72c5122013-03-06 18:50:53 +0530166
Nabin Hait8c7234f2013-03-11 16:32:33 +0530167def get_buying_amount(item_code, warehouse, qty, voucher_type, voucher_no, voucher_detail_no,
Nabin Haitc3afb252013-03-19 12:01:24 +0530168 stock_ledger_entries, item_sales_bom=None):
169 if item_sales_bom and item_sales_bom.get(item_code):
Nabin Haita72c5122013-03-06 18:50:53 +0530170 # sales bom item
171 buying_amount = 0.0
172 for bom_item in item_sales_bom[item_code]:
Anand Doshi96b189c2013-03-26 18:43:10 +0530173 if bom_item.get("parent_detail_docname")==voucher_detail_no:
Anand Doshi8c454202013-03-28 16:40:30 +0530174 buying_amount += _get_buying_amount(voucher_type, voucher_no, voucher_detail_no,
Anand Doshi96b189c2013-03-26 18:43:10 +0530175 bom_item.item_code, bom_item.warehouse or warehouse,
176 bom_item.total_qty or (bom_item.qty * qty), stock_ledger_entries)
Nabin Haita72c5122013-03-06 18:50:53 +0530177 return buying_amount
178 else:
179 # doesn't have sales bom
Nabin Hait8c7234f2013-03-11 16:32:33 +0530180 return _get_buying_amount(voucher_type, voucher_no, voucher_detail_no,
181 item_code, warehouse, qty, stock_ledger_entries)
Nabin Haita72c5122013-03-06 18:50:53 +0530182
Nabin Hait8c7234f2013-03-11 16:32:33 +0530183def _get_buying_amount(voucher_type, voucher_no, item_row, item_code, warehouse, qty,
184 stock_ledger_entries):
Anand Doshi96b189c2013-03-26 18:43:10 +0530185 relevant_stock_ledger_entries = [sle for sle in stock_ledger_entries
186 if sle.item_code == item_code and sle.warehouse == warehouse]
187
188 for i, sle in enumerate(relevant_stock_ledger_entries):
Nabin Hait0cfbc5f2013-03-12 11:34:56 +0530189 if sle.voucher_type == voucher_type and sle.voucher_no == voucher_no and \
Anand Doshi8c454202013-03-28 16:40:30 +0530190 sle.voucher_detail_no == item_row:
Anand Doshi96b189c2013-03-26 18:43:10 +0530191 previous_stock_value = len(relevant_stock_ledger_entries) > i+1 and \
192 flt(relevant_stock_ledger_entries[i+1].stock_value) or 0.0
193
Nabin Haitc3afb252013-03-19 12:01:24 +0530194 buying_amount = previous_stock_value - flt(sle.stock_value)
Anand Doshi6d8d3b42013-03-21 18:45:02 +0530195
Nabin Haitc3afb252013-03-19 12:01:24 +0530196 return buying_amount
Nabin Hait62d06292013-05-22 16:19:10 +0530197 return 0.0
198
199
200def reorder_item():
201 """ Reorder item if stock reaches reorder level"""
202 if not hasattr(webnotes, "auto_indent"):
203 webnotes.auto_indent = webnotes.conn.get_value('Global Defaults', None, 'auto_indent')
204
205 if webnotes.auto_indent:
206 material_requests = {}
207 bin_list = webnotes.conn.sql("""select item_code, warehouse, projected_qty
208 from tabBin where ifnull(item_code, '') != '' and ifnull(warehouse, '') != ''""",
209 as_dict=True)
210 for bin in bin_list:
211 #check if re-order is required
212 item_reorder = webnotes.conn.get("Item Reorder",
213 {"parent": bin.item_code, "warehouse": bin.warehouse})
214 if item_reorder:
215 reorder_level = item_reorder.warehouse_reorder_level
216 reorder_qty = item_reorder.warehouse_reorder_qty
217 material_request_type = item_reorder.material_request_type or "Purchase"
218 else:
219 reorder_level, reorder_qty = webnotes.conn.get_value("Item", bin.item_code,
220 ["re_order_level", "re_order_qty"])
221 material_request_type = "Purchase"
222
223 if reorder_level and flt(bin.projected_qty) < flt(reorder_level):
224 if flt(reorder_level) - flt(bin.projected_qty) > flt(reorder_qty):
225 reorder_qty = flt(reorder_level) - flt(bin.projected_qty)
226
227 company = webnotes.conn.get_value("Warehouse", bin.warehouse, "company") or \
228 webnotes.defaults.get_defaults()["company"] or \
229 webnotes.conn.sql("""select name from tabCompany limit 1""")[0][0]
230
231 material_requests.setdefault(material_request_type, webnotes._dict()).setdefault(
232 company, []).append(webnotes._dict({
233 "item_code": bin.item_code,
234 "warehouse": bin.warehouse,
235 "reorder_qty": reorder_qty
236 })
237 )
238
239 create_material_request(material_requests)
240
241def create_material_request(material_requests):
242 """ Create indent on reaching reorder level """
243 mr_list = []
244 defaults = webnotes.defaults.get_defaults()
245 for request_type in material_requests:
246 for company in material_requests[request_type]:
247 items = material_requests[request_type][company]
248 if items:
249 mr = [{
250 "doctype": "Material Request",
251 "company": company,
252 "fiscal_year": defaults.fiscal_year,
253 "transaction_date": nowdate(),
254 "material_request_type": request_type,
255 "remark": _("This is an auto generated Material Request.") + \
256 _("""It was raised because the (actual + ordered + indented - reserved)
257 quantity reaches re-order level when the following record was created""")
258 }]
259
260 for d in items:
261 item = webnotes.doc("Item", d.item_code)
262 mr.append({
263 "doctype": "Material Request Item",
264 "parenttype": "Material Request",
265 "parentfield": "indent_details",
266 "item_code": d.item_code,
267 "schedule_date": add_days(nowdate(),cint(item.lead_time_days)),
268 "uom": item.stock_uom,
269 "warehouse": d.warehouse,
270 "item_name": item.item_name,
271 "description": item.description,
272 "item_group": item.item_group,
273 "qty": d.reorder_qty,
274 "brand": item.brand,
275 })
276
277 mr_bean = webnotes.bean(mr)
278 mr_bean.insert()
279 mr_bean.submit()
280 mr_list.append(mr_bean)
281
282 if mr_list:
283 if not hasattr(webnotes, "reorder_email_notify"):
284 webnotes.reorder_email_notify = webnotes.conn.get_value('Global Defaults', None,
285 'reorder_email_notify')
286
287 if(webnotes.reorder_email_notify):
288 send_email_notification(mr_list)
289
290def send_email_notification(mr_list):
291 """ Notify user about auto creation of indent"""
292
293 from webnotes.utils.email_lib import sendmail
294 email_list = webnotes.conn.sql_list("""select distinct r.parent
295 from tabUserRole r, tabProfile p
296 where p.name = r.parent and p.enabled = 1 and p.docstatus < 2
297 and r.role in ('Purchase Manager','Material Manager')
298 and p.name not in ('Administrator', 'All', 'Guest')""")
299
300 msg="""<h3>Following Material Requests has been raised automatically \
301 based on item reorder level:</h3>"""
302 for mr in mr_list:
303 msg += "<p><b><u>" + mr.doc.name + """</u></b></p><table class='table table-bordered'><tr>
304 <th>Item Code</th><th>Warehouse</th><th>Qty</th><th>UOM</th></tr>"""
305 for item in mr.doclist.get({"parentfield": "indent_details"}):
306 msg += "<tr><td>" + item.item_code + "</td><td>" + item.warehouse + "</td><td>" + \
307 cstr(item.qty) + "</td><td>" + cstr(item.uom) + "</td></tr>"
308 msg += "</table>"
309
310 sendmail(email_list, subject='Auto Material Request Generation Notification', msg = msg)