blob: 1f501644ffacf7b5b54c935f9b803f85a33802f7 [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
Rushabh Mehtaa65253b2013-08-27 10:32:56 +053011class UserNotAllowedForWarehouse(webnotes.ValidationError): pass
Anand Doshi373680b2013-10-10 16:04:40 +053012class InvalidWarehouseCompany(webnotes.ValidationError): pass
Nabin Hait0dd7be12013-08-02 11:45:43 +053013
Nabin Hait625da792013-09-25 10:32:51 +053014def get_stock_balance_on(warehouse, posting_date=None):
Nabin Hait0dd7be12013-08-02 11:45:43 +053015 if not posting_date: posting_date = nowdate()
16
17 stock_ledger_entries = webnotes.conn.sql("""
18 SELECT
Nabin Hait625da792013-09-25 10:32:51 +053019 item_code, stock_value
Nabin Hait0dd7be12013-08-02 11:45:43 +053020 FROM
21 `tabStock Ledger Entry`
22 WHERE
Nabin Hait625da792013-09-25 10:32:51 +053023 warehouse=%s AND posting_date <= %s
Nabin Hait0dd7be12013-08-02 11:45:43 +053024 ORDER BY timestamp(posting_date, posting_time) DESC, name DESC
Nabin Hait625da792013-09-25 10:32:51 +053025 """, (warehouse, posting_date), as_dict=1)
Nabin Hait0dd7be12013-08-02 11:45:43 +053026
27 sle_map = {}
28 for sle in stock_ledger_entries:
Nabin Hait625da792013-09-25 10:32:51 +053029 sle_map.setdefault(sle.item_code, flt(sle.stock_value))
Nabin Hait0dd7be12013-08-02 11:45:43 +053030
Nabin Hait625da792013-09-25 10:32:51 +053031 return sum(sle_map.values())
Nabin Hait0dd7be12013-08-02 11:45:43 +053032
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 Hait74c281c2013-08-19 16:17:18 +053040
41def get_bin(item_code, warehouse):
42 bin = webnotes.conn.get_value("Bin", {"item_code": item_code, "warehouse": warehouse})
43 if not bin:
44 bin_wrapper = webnotes.bean([{
45 "doctype": "Bin",
46 "item_code": item_code,
47 "warehouse": warehouse,
48 }])
49 bin_wrapper.ignore_permissions = 1
50 bin_wrapper.insert()
51 bin_obj = bin_wrapper.make_controller()
52 else:
53 from webnotes.model.code import get_obj
54 bin_obj = get_obj('Bin', bin)
55 return bin_obj
56
57def update_bin(args):
58 is_stock_item = webnotes.conn.get_value('Item', args.get("item_code"), 'is_stock_item')
59 if is_stock_item == 'Yes':
60 bin = get_bin(args.get("item_code"), args.get("warehouse"))
61 bin.update_stock(args)
62 return bin
63 else:
64 msgprint("[Stock Update] Ignored %s since it is not a stock item"
65 % args.get("item_code"))
Nabin Hait0dd7be12013-08-02 11:45:43 +053066
Nabin Hait9d0f6362013-01-07 18:51:11 +053067def validate_end_of_life(item_code, end_of_life=None, verbose=1):
68 if not end_of_life:
69 end_of_life = webnotes.conn.get_value("Item", item_code, "end_of_life")
70
71 from webnotes.utils import getdate, now_datetime, formatdate
Anand Doshiad6180e2013-06-17 11:57:04 +053072 if end_of_life and getdate(end_of_life) <= now_datetime().date():
Nabin Hait9d0f6362013-01-07 18:51:11 +053073 msg = (_("Item") + " %(item_code)s: " + _("reached its end of life on") + \
74 " %(date)s. " + _("Please check") + ": %(end_of_life_label)s " + \
75 "in Item master") % {
76 "item_code": item_code,
77 "date": formatdate(end_of_life),
Anand Doshia43b29e2013-02-20 15:55:10 +053078 "end_of_life_label": webnotes.get_doctype("Item").get_label("end_of_life")
Nabin Hait9d0f6362013-01-07 18:51:11 +053079 }
80
81 _msgprint(msg, verbose)
82
83def validate_is_stock_item(item_code, is_stock_item=None, verbose=1):
84 if not is_stock_item:
85 is_stock_item = webnotes.conn.get_value("Item", item_code, "is_stock_item")
86
87 if is_stock_item != "Yes":
88 msg = (_("Item") + " %(item_code)s: " + _("is not a Stock Item")) % {
89 "item_code": item_code,
90 }
91
92 _msgprint(msg, verbose)
93
94def validate_cancelled_item(item_code, docstatus=None, verbose=1):
95 if docstatus is None:
96 docstatus = webnotes.conn.get_value("Item", item_code, "docstatus")
97
98 if docstatus == 2:
99 msg = (_("Item") + " %(item_code)s: " + _("is a cancelled Item")) % {
100 "item_code": item_code,
101 }
102
103 _msgprint(msg, verbose)
104
105def _msgprint(msg, verbose):
106 if verbose:
107 msgprint(msg, raise_exception=True)
108 else:
109 raise webnotes.ValidationError, msg
110
Nabin Hait9d0f6362013-01-07 18:51:11 +0530111def get_incoming_rate(args):
112 """Get Incoming Rate based on valuation method"""
Anand Doshi1b531862013-01-10 19:29:51 +0530113 from stock.stock_ledger import get_previous_sle
Nabin Hait9d0f6362013-01-07 18:51:11 +0530114
115 in_rate = 0
116 if args.get("serial_no"):
117 in_rate = get_avg_purchase_rate(args.get("serial_no"))
118 elif args.get("bom_no"):
119 result = webnotes.conn.sql("""select ifnull(total_cost, 0) / ifnull(quantity, 1)
120 from `tabBOM` where name = %s and docstatus=1 and is_active=1""", args.get("bom_no"))
121 in_rate = result and flt(result[0][0]) or 0
122 else:
123 valuation_method = get_valuation_method(args.get("item_code"))
124 previous_sle = get_previous_sle(args)
125 if valuation_method == 'FIFO':
Nabin Hait831207f2013-01-16 14:15:48 +0530126 if not previous_sle:
127 return 0.0
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530128 previous_stock_queue = json.loads(previous_sle.get('stock_queue', '[]') or '[]')
Nabin Hait831207f2013-01-16 14:15:48 +0530129 in_rate = previous_stock_queue and \
Nabin Hait6b1f21d2013-01-16 17:17:17 +0530130 get_fifo_rate(previous_stock_queue, args.get("qty") or 0) or 0
Nabin Hait9d0f6362013-01-07 18:51:11 +0530131 elif valuation_method == 'Moving Average':
132 in_rate = previous_sle.get('valuation_rate') or 0
133 return in_rate
134
135def get_avg_purchase_rate(serial_nos):
136 """get average value of serial numbers"""
137
138 serial_nos = get_valid_serial_nos(serial_nos)
139 return flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0)) from `tabSerial No`
140 where name in (%s)""" % ", ".join(["%s"] * len(serial_nos)),
141 tuple(serial_nos))[0][0])
142
143def get_valuation_method(item_code):
144 """get valuation method from item or default"""
145 val_method = webnotes.conn.get_value('Item', item_code, 'valuation_method')
146 if not val_method:
Rushabh Mehta5117d9c2013-02-19 15:27:31 +0530147 val_method = get_global_default('valuation_method') or "FIFO"
Nabin Hait9d0f6362013-01-07 18:51:11 +0530148 return val_method
149
Nabin Hait831207f2013-01-16 14:15:48 +0530150def get_fifo_rate(previous_stock_queue, qty):
151 """get FIFO (average) Rate from Queue"""
152 if qty >= 0:
153 total = sum(f[0] for f in previous_stock_queue)
154 return total and sum(f[0] * f[1] for f in previous_stock_queue) / flt(total) or 0.0
155 else:
156 outgoing_cost = 0
157 qty_to_pop = abs(qty)
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530158 while qty_to_pop and previous_stock_queue:
Nabin Hait831207f2013-01-16 14:15:48 +0530159 batch = previous_stock_queue[0]
160 if 0 < batch[0] <= qty_to_pop:
161 # if batch qty > 0
162 # not enough or exactly same qty in current batch, clear batch
163 outgoing_cost += flt(batch[0]) * flt(batch[1])
164 qty_to_pop -= batch[0]
165 previous_stock_queue.pop(0)
166 else:
167 # all from current batch
168 outgoing_cost += flt(qty_to_pop) * flt(batch[1])
169 batch[0] -= qty_to_pop
170 qty_to_pop = 0
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530171 # if queue gets blank and qty_to_pop remaining, get average rate of full queue
172 return outgoing_cost / abs(qty) - qty_to_pop
Nabin Hait9d0f6362013-01-07 18:51:11 +0530173
174def get_valid_serial_nos(sr_nos, qty=0, item_code=''):
175 """split serial nos, validate and return list of valid serial nos"""
176 # TODO: remove duplicates in client side
177 serial_nos = cstr(sr_nos).strip().replace(',', '\n').split('\n')
178
179 valid_serial_nos = []
180 for val in serial_nos:
181 if val:
182 val = val.strip()
183 if val in valid_serial_nos:
184 msgprint("You have entered duplicate serial no: '%s'" % val, raise_exception=1)
185 else:
186 valid_serial_nos.append(val)
187
188 if qty and len(valid_serial_nos) != abs(qty):
189 msgprint("Please enter serial nos for "
190 + cstr(abs(qty)) + " quantity against item code: " + item_code,
191 raise_exception=1)
192
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530193 return valid_serial_nos
194
Nabin Haitdc95c152013-02-07 12:08:38 +0530195def get_warehouse_list(doctype, txt, searchfield, start, page_len, filters):
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530196 """used in search queries"""
197 wlist = []
198 for w in webnotes.conn.sql_list("""select name from tabWarehouse
199 where name like '%%%s%%'""" % txt):
200 if webnotes.session.user=="Administrator":
201 wlist.append([w])
202 else:
203 warehouse_users = webnotes.conn.sql_list("""select user from `tabWarehouse User`
204 where parent=%s""", w)
205 if not warehouse_users:
206 wlist.append([w])
207 elif webnotes.session.user in warehouse_users:
208 wlist.append([w])
209 return wlist
Nabin Haita72c5122013-03-06 18:50:53 +0530210
Rushabh Mehtaa65253b2013-08-27 10:32:56 +0530211def validate_warehouse_user(warehouse):
212 if webnotes.session.user=="Administrator":
213 return
214 warehouse_users = [p[0] for p in webnotes.conn.sql("""select user from `tabWarehouse User`
215 where parent=%s""", warehouse)]
216
217 if warehouse_users and not (webnotes.session.user in warehouse_users):
218 webnotes.throw(_("Not allowed entry in Warehouse") \
219 + ": " + warehouse, UserNotAllowedForWarehouse)
Anand Doshi373680b2013-10-10 16:04:40 +0530220
221def validate_warehouse_company(warehouse, company):
222 warehouse_company = webnotes.conn.get_value("Warehouse", warehouse, "company")
223 if warehouse_company and warehouse_company != company:
224 webnotes.msgprint(_("Warehouse does not belong to company.") + " (" + \
225 warehouse + ", " + company +")", raise_exception=InvalidWarehouseCompany)
Rushabh Mehtaa65253b2013-08-27 10:32:56 +0530226
Nabin Hait94c90bd2013-08-30 22:48:19 +0530227def get_sales_bom_buying_amount(item_code, warehouse, voucher_type, voucher_no, voucher_detail_no,
228 stock_ledger_entries, item_sales_bom):
229 # sales bom item
230 buying_amount = 0.0
231 for bom_item in item_sales_bom[item_code]:
232 if bom_item.get("parent_detail_docname")==voucher_detail_no:
233 buying_amount += get_buying_amount(voucher_type, voucher_no, voucher_detail_no,
234 stock_ledger_entries.get((bom_item.item_code, warehouse), []))
235
236 return buying_amount
Nabin Haita72c5122013-03-06 18:50:53 +0530237
Nabin Hait94c90bd2013-08-30 22:48:19 +0530238def get_buying_amount(voucher_type, voucher_no, item_row, stock_ledger_entries):
Anand Doshi5dd6b1d2013-08-07 19:27:30 +0530239 # IMP NOTE
240 # stock_ledger_entries should already be filtered by item_code and warehouse and
241 # sorted by posting_date desc, posting_time desc
242 for i, sle in enumerate(stock_ledger_entries):
Nabin Hait0cfbc5f2013-03-12 11:34:56 +0530243 if sle.voucher_type == voucher_type and sle.voucher_no == voucher_no and \
Anand Doshi8c454202013-03-28 16:40:30 +0530244 sle.voucher_detail_no == item_row:
Anand Doshi5dd6b1d2013-08-07 19:27:30 +0530245 previous_stock_value = len(stock_ledger_entries) > i+1 and \
246 flt(stock_ledger_entries[i+1].stock_value) or 0.0
Nabin Haitc3afb252013-03-19 12:01:24 +0530247 buying_amount = previous_stock_value - flt(sle.stock_value)
Anand Doshi6d8d3b42013-03-21 18:45:02 +0530248
Nabin Haitc3afb252013-03-19 12:01:24 +0530249 return buying_amount
Nabin Hait62d06292013-05-22 16:19:10 +0530250 return 0.0
251
252
253def reorder_item():
254 """ Reorder item if stock reaches reorder level"""
255 if not hasattr(webnotes, "auto_indent"):
Nabin Haitbf5d44c2013-08-12 16:30:48 +0530256 webnotes.auto_indent = cint(webnotes.conn.get_value('Stock Settings', None, 'auto_indent'))
257
Nabin Hait62d06292013-05-22 16:19:10 +0530258 if webnotes.auto_indent:
259 material_requests = {}
260 bin_list = webnotes.conn.sql("""select item_code, warehouse, projected_qty
Anand Doshiad6180e2013-06-17 11:57:04 +0530261 from tabBin where ifnull(item_code, '') != '' and ifnull(warehouse, '') != ''
262 and exists (select name from `tabItem`
263 where `tabItem`.name = `tabBin`.item_code and
264 is_stock_item='Yes' and (is_purchase_item='Yes' or is_sub_contracted_item='Yes') and
Anand Doshi4d47b002013-08-23 16:54:31 +0530265 (ifnull(end_of_life, '')='' or end_of_life > now()))""", as_dict=True)
Nabin Hait62d06292013-05-22 16:19:10 +0530266 for bin in bin_list:
267 #check if re-order is required
268 item_reorder = webnotes.conn.get("Item Reorder",
269 {"parent": bin.item_code, "warehouse": bin.warehouse})
270 if item_reorder:
271 reorder_level = item_reorder.warehouse_reorder_level
272 reorder_qty = item_reorder.warehouse_reorder_qty
273 material_request_type = item_reorder.material_request_type or "Purchase"
274 else:
275 reorder_level, reorder_qty = webnotes.conn.get_value("Item", bin.item_code,
276 ["re_order_level", "re_order_qty"])
277 material_request_type = "Purchase"
278
Anand Doshiad6180e2013-06-17 11:57:04 +0530279 if flt(reorder_level) and flt(bin.projected_qty) < flt(reorder_level):
Nabin Hait62d06292013-05-22 16:19:10 +0530280 if flt(reorder_level) - flt(bin.projected_qty) > flt(reorder_qty):
281 reorder_qty = flt(reorder_level) - flt(bin.projected_qty)
282
283 company = webnotes.conn.get_value("Warehouse", bin.warehouse, "company") or \
284 webnotes.defaults.get_defaults()["company"] or \
285 webnotes.conn.sql("""select name from tabCompany limit 1""")[0][0]
286
287 material_requests.setdefault(material_request_type, webnotes._dict()).setdefault(
288 company, []).append(webnotes._dict({
289 "item_code": bin.item_code,
290 "warehouse": bin.warehouse,
291 "reorder_qty": reorder_qty
292 })
293 )
294
295 create_material_request(material_requests)
296
297def create_material_request(material_requests):
298 """ Create indent on reaching reorder level """
299 mr_list = []
300 defaults = webnotes.defaults.get_defaults()
Anand Doshiad6180e2013-06-17 11:57:04 +0530301 exceptions_list = []
Nabin Hait62d06292013-05-22 16:19:10 +0530302 for request_type in material_requests:
303 for company in material_requests[request_type]:
Anand Doshiad6180e2013-06-17 11:57:04 +0530304 try:
305 items = material_requests[request_type][company]
306 if not items:
307 continue
Anand Doshi6f6e91c2013-07-22 11:28:34 +0530308
Nabin Hait62d06292013-05-22 16:19:10 +0530309 mr = [{
310 "doctype": "Material Request",
311 "company": company,
312 "fiscal_year": defaults.fiscal_year,
313 "transaction_date": nowdate(),
314 "material_request_type": request_type,
315 "remark": _("This is an auto generated Material Request.") + \
316 _("""It was raised because the (actual + ordered + indented - reserved)
317 quantity reaches re-order level when the following record was created""")
318 }]
319
Anand Doshiad6180e2013-06-17 11:57:04 +0530320 for d in items:
321 item = webnotes.doc("Item", d.item_code)
322 mr.append({
323 "doctype": "Material Request Item",
324 "parenttype": "Material Request",
325 "parentfield": "indent_details",
326 "item_code": d.item_code,
327 "schedule_date": add_days(nowdate(),cint(item.lead_time_days)),
328 "uom": item.stock_uom,
329 "warehouse": d.warehouse,
330 "item_name": item.item_name,
331 "description": item.description,
332 "item_group": item.item_group,
333 "qty": d.reorder_qty,
334 "brand": item.brand,
335 })
Nabin Hait62d06292013-05-22 16:19:10 +0530336
Anand Doshiad6180e2013-06-17 11:57:04 +0530337 mr_bean = webnotes.bean(mr)
338 mr_bean.insert()
339 mr_bean.submit()
340 mr_list.append(mr_bean)
Anand Doshi6f6e91c2013-07-22 11:28:34 +0530341
Anand Doshiad6180e2013-06-17 11:57:04 +0530342 except:
343 if webnotes.message_log:
344 exceptions_list.append([] + webnotes.message_log)
345 webnotes.message_log = []
346 else:
347 exceptions_list.append(webnotes.getTraceback())
Nabin Hait62d06292013-05-22 16:19:10 +0530348
349 if mr_list:
350 if not hasattr(webnotes, "reorder_email_notify"):
Nabin Haitbf5d44c2013-08-12 16:30:48 +0530351 webnotes.reorder_email_notify = cint(webnotes.conn.get_value('Stock Settings', None,
352 'reorder_email_notify'))
Nabin Hait62d06292013-05-22 16:19:10 +0530353
354 if(webnotes.reorder_email_notify):
355 send_email_notification(mr_list)
Anand Doshiad6180e2013-06-17 11:57:04 +0530356
357 if exceptions_list:
358 notify_errors(exceptions_list)
Nabin Hait62d06292013-05-22 16:19:10 +0530359
360def send_email_notification(mr_list):
361 """ Notify user about auto creation of indent"""
362
Nabin Hait62d06292013-05-22 16:19:10 +0530363 email_list = webnotes.conn.sql_list("""select distinct r.parent
364 from tabUserRole r, tabProfile p
365 where p.name = r.parent and p.enabled = 1 and p.docstatus < 2
366 and r.role in ('Purchase Manager','Material Manager')
367 and p.name not in ('Administrator', 'All', 'Guest')""")
368
369 msg="""<h3>Following Material Requests has been raised automatically \
370 based on item reorder level:</h3>"""
371 for mr in mr_list:
372 msg += "<p><b><u>" + mr.doc.name + """</u></b></p><table class='table table-bordered'><tr>
373 <th>Item Code</th><th>Warehouse</th><th>Qty</th><th>UOM</th></tr>"""
374 for item in mr.doclist.get({"parentfield": "indent_details"}):
375 msg += "<tr><td>" + item.item_code + "</td><td>" + item.warehouse + "</td><td>" + \
376 cstr(item.qty) + "</td><td>" + cstr(item.uom) + "</td></tr>"
377 msg += "</table>"
Anand Doshiad6180e2013-06-17 11:57:04 +0530378 sendmail(email_list, subject='Auto Material Request Generation Notification', msg = msg)
379
380def notify_errors(exceptions_list):
381 subject = "[Important] [ERPNext] Error(s) while creating Material Requests based on Re-order Levels"
382 msg = """Dear System Manager,
383
384 An error occured for certain Items while creating Material Requests based on Re-order level.
385
386 Please rectify these issues:
387 ---
388
389 %s
390
391 ---
392 Regards,
393 Administrator""" % ("\n\n".join(["\n".join(msg) for msg in exceptions_list]),)
394
395 from webnotes.profile import get_system_managers
396 sendmail(get_system_managers(), subject=subject, msg=msg)
Nabin Hait74c281c2013-08-19 16:17:18 +0530397
398
399def repost():
400 """
401 Repost everything!
402 """
403 from webnotes.model.code import get_obj
404 for wh in webnotes.conn.sql("select name from tabWarehouse"):
Nabin Hait92b0e772013-08-26 16:55:42 +0530405 get_obj('Warehouse', wh[0]).repost_stock()