blob: 8836c6c991f5adfd773c438050932aae2e3f98e5 [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
Nabin Hait0dd7be12013-08-02 11:45:43 +053012
Nabin Hait625da792013-09-25 10:32:51 +053013def get_stock_balance_on(warehouse, posting_date=None):
Nabin Hait0dd7be12013-08-02 11:45:43 +053014 if not posting_date: posting_date = nowdate()
15
16 stock_ledger_entries = webnotes.conn.sql("""
17 SELECT
Nabin Hait625da792013-09-25 10:32:51 +053018 item_code, stock_value
Nabin Hait0dd7be12013-08-02 11:45:43 +053019 FROM
20 `tabStock Ledger Entry`
21 WHERE
Nabin Hait625da792013-09-25 10:32:51 +053022 warehouse=%s AND posting_date <= %s
Nabin Hait0dd7be12013-08-02 11:45:43 +053023 ORDER BY timestamp(posting_date, posting_time) DESC, name DESC
Nabin Hait625da792013-09-25 10:32:51 +053024 """, (warehouse, posting_date), as_dict=1)
Nabin Hait0dd7be12013-08-02 11:45:43 +053025
26 sle_map = {}
27 for sle in stock_ledger_entries:
Nabin Hait625da792013-09-25 10:32:51 +053028 sle_map.setdefault(sle.item_code, flt(sle.stock_value))
Nabin Hait0dd7be12013-08-02 11:45:43 +053029
Nabin Hait625da792013-09-25 10:32:51 +053030 return sum(sle_map.values())
Nabin Hait0dd7be12013-08-02 11:45:43 +053031
Nabin Hait47dc3182013-08-06 15:58:16 +053032def get_latest_stock_balance():
33 bin_map = {}
Nabin Hait469ee712013-08-07 12:33:37 +053034 for d in webnotes.conn.sql("""SELECT item_code, warehouse, stock_value as stock_value
Nabin Hait47dc3182013-08-06 15:58:16 +053035 FROM tabBin""", as_dict=1):
Nabin Hait469ee712013-08-07 12:33:37 +053036 bin_map.setdefault(d.warehouse, {}).setdefault(d.item_code, flt(d.stock_value))
Nabin Hait47dc3182013-08-06 15:58:16 +053037
38 return bin_map
Nabin Hait74c281c2013-08-19 16:17:18 +053039
40def get_bin(item_code, warehouse):
41 bin = webnotes.conn.get_value("Bin", {"item_code": item_code, "warehouse": warehouse})
42 if not bin:
43 bin_wrapper = webnotes.bean([{
44 "doctype": "Bin",
45 "item_code": item_code,
46 "warehouse": warehouse,
47 }])
48 bin_wrapper.ignore_permissions = 1
49 bin_wrapper.insert()
50 bin_obj = bin_wrapper.make_controller()
51 else:
52 from webnotes.model.code import get_obj
53 bin_obj = get_obj('Bin', bin)
54 return bin_obj
55
56def update_bin(args):
57 is_stock_item = webnotes.conn.get_value('Item', args.get("item_code"), 'is_stock_item')
58 if is_stock_item == 'Yes':
59 bin = get_bin(args.get("item_code"), args.get("warehouse"))
60 bin.update_stock(args)
61 return bin
62 else:
63 msgprint("[Stock Update] Ignored %s since it is not a stock item"
64 % args.get("item_code"))
Nabin Hait0dd7be12013-08-02 11:45:43 +053065
Nabin Hait9d0f6362013-01-07 18:51:11 +053066def validate_end_of_life(item_code, end_of_life=None, verbose=1):
67 if not end_of_life:
68 end_of_life = webnotes.conn.get_value("Item", item_code, "end_of_life")
69
70 from webnotes.utils import getdate, now_datetime, formatdate
Anand Doshiad6180e2013-06-17 11:57:04 +053071 if end_of_life and getdate(end_of_life) <= now_datetime().date():
Nabin Hait9d0f6362013-01-07 18:51:11 +053072 msg = (_("Item") + " %(item_code)s: " + _("reached its end of life on") + \
73 " %(date)s. " + _("Please check") + ": %(end_of_life_label)s " + \
74 "in Item master") % {
75 "item_code": item_code,
76 "date": formatdate(end_of_life),
Anand Doshia43b29e2013-02-20 15:55:10 +053077 "end_of_life_label": webnotes.get_doctype("Item").get_label("end_of_life")
Nabin Hait9d0f6362013-01-07 18:51:11 +053078 }
79
80 _msgprint(msg, verbose)
81
82def validate_is_stock_item(item_code, is_stock_item=None, verbose=1):
83 if not is_stock_item:
84 is_stock_item = webnotes.conn.get_value("Item", item_code, "is_stock_item")
85
86 if is_stock_item != "Yes":
87 msg = (_("Item") + " %(item_code)s: " + _("is not a Stock Item")) % {
88 "item_code": item_code,
89 }
90
91 _msgprint(msg, verbose)
92
93def validate_cancelled_item(item_code, docstatus=None, verbose=1):
94 if docstatus is None:
95 docstatus = webnotes.conn.get_value("Item", item_code, "docstatus")
96
97 if docstatus == 2:
98 msg = (_("Item") + " %(item_code)s: " + _("is a cancelled Item")) % {
99 "item_code": item_code,
100 }
101
102 _msgprint(msg, verbose)
103
104def _msgprint(msg, verbose):
105 if verbose:
106 msgprint(msg, raise_exception=True)
107 else:
108 raise webnotes.ValidationError, msg
109
Nabin Hait9d0f6362013-01-07 18:51:11 +0530110def get_incoming_rate(args):
111 """Get Incoming Rate based on valuation method"""
Anand Doshi1b531862013-01-10 19:29:51 +0530112 from stock.stock_ledger import get_previous_sle
Nabin Hait9d0f6362013-01-07 18:51:11 +0530113
114 in_rate = 0
115 if args.get("serial_no"):
116 in_rate = get_avg_purchase_rate(args.get("serial_no"))
117 elif args.get("bom_no"):
118 result = webnotes.conn.sql("""select ifnull(total_cost, 0) / ifnull(quantity, 1)
119 from `tabBOM` where name = %s and docstatus=1 and is_active=1""", args.get("bom_no"))
120 in_rate = result and flt(result[0][0]) or 0
121 else:
122 valuation_method = get_valuation_method(args.get("item_code"))
123 previous_sle = get_previous_sle(args)
124 if valuation_method == 'FIFO':
Nabin Hait831207f2013-01-16 14:15:48 +0530125 if not previous_sle:
126 return 0.0
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530127 previous_stock_queue = json.loads(previous_sle.get('stock_queue', '[]') or '[]')
Nabin Hait831207f2013-01-16 14:15:48 +0530128 in_rate = previous_stock_queue and \
Nabin Hait6b1f21d2013-01-16 17:17:17 +0530129 get_fifo_rate(previous_stock_queue, args.get("qty") or 0) or 0
Nabin Hait9d0f6362013-01-07 18:51:11 +0530130 elif valuation_method == 'Moving Average':
131 in_rate = previous_sle.get('valuation_rate') or 0
132 return in_rate
133
134def get_avg_purchase_rate(serial_nos):
135 """get average value of serial numbers"""
136
137 serial_nos = get_valid_serial_nos(serial_nos)
138 return flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0)) from `tabSerial No`
139 where name in (%s)""" % ", ".join(["%s"] * len(serial_nos)),
140 tuple(serial_nos))[0][0])
141
142def get_valuation_method(item_code):
143 """get valuation method from item or default"""
144 val_method = webnotes.conn.get_value('Item', item_code, 'valuation_method')
145 if not val_method:
Rushabh Mehta5117d9c2013-02-19 15:27:31 +0530146 val_method = get_global_default('valuation_method') or "FIFO"
Nabin Hait9d0f6362013-01-07 18:51:11 +0530147 return val_method
148
Nabin Hait831207f2013-01-16 14:15:48 +0530149def get_fifo_rate(previous_stock_queue, qty):
150 """get FIFO (average) Rate from Queue"""
151 if qty >= 0:
152 total = sum(f[0] for f in previous_stock_queue)
153 return total and sum(f[0] * f[1] for f in previous_stock_queue) / flt(total) or 0.0
154 else:
155 outgoing_cost = 0
156 qty_to_pop = abs(qty)
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530157 while qty_to_pop and previous_stock_queue:
Nabin Hait831207f2013-01-16 14:15:48 +0530158 batch = previous_stock_queue[0]
159 if 0 < batch[0] <= qty_to_pop:
160 # if batch qty > 0
161 # not enough or exactly same qty in current batch, clear batch
162 outgoing_cost += flt(batch[0]) * flt(batch[1])
163 qty_to_pop -= batch[0]
164 previous_stock_queue.pop(0)
165 else:
166 # all from current batch
167 outgoing_cost += flt(qty_to_pop) * flt(batch[1])
168 batch[0] -= qty_to_pop
169 qty_to_pop = 0
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530170 # if queue gets blank and qty_to_pop remaining, get average rate of full queue
171 return outgoing_cost / abs(qty) - qty_to_pop
Nabin Hait9d0f6362013-01-07 18:51:11 +0530172
173def get_valid_serial_nos(sr_nos, qty=0, item_code=''):
174 """split serial nos, validate and return list of valid serial nos"""
175 # TODO: remove duplicates in client side
176 serial_nos = cstr(sr_nos).strip().replace(',', '\n').split('\n')
177
178 valid_serial_nos = []
179 for val in serial_nos:
180 if val:
181 val = val.strip()
182 if val in valid_serial_nos:
183 msgprint("You have entered duplicate serial no: '%s'" % val, raise_exception=1)
184 else:
185 valid_serial_nos.append(val)
186
187 if qty and len(valid_serial_nos) != abs(qty):
188 msgprint("Please enter serial nos for "
189 + cstr(abs(qty)) + " quantity against item code: " + item_code,
190 raise_exception=1)
191
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530192 return valid_serial_nos
193
Nabin Haitdc95c152013-02-07 12:08:38 +0530194def get_warehouse_list(doctype, txt, searchfield, start, page_len, filters):
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530195 """used in search queries"""
196 wlist = []
197 for w in webnotes.conn.sql_list("""select name from tabWarehouse
198 where name like '%%%s%%'""" % txt):
199 if webnotes.session.user=="Administrator":
200 wlist.append([w])
201 else:
202 warehouse_users = webnotes.conn.sql_list("""select user from `tabWarehouse User`
203 where parent=%s""", w)
204 if not warehouse_users:
205 wlist.append([w])
206 elif webnotes.session.user in warehouse_users:
207 wlist.append([w])
208 return wlist
Nabin Haita72c5122013-03-06 18:50:53 +0530209
Rushabh Mehtaa65253b2013-08-27 10:32:56 +0530210def validate_warehouse_user(warehouse):
211 if webnotes.session.user=="Administrator":
212 return
213 warehouse_users = [p[0] for p in webnotes.conn.sql("""select user from `tabWarehouse User`
214 where parent=%s""", warehouse)]
215
216 if warehouse_users and not (webnotes.session.user in warehouse_users):
217 webnotes.throw(_("Not allowed entry in Warehouse") \
218 + ": " + warehouse, UserNotAllowedForWarehouse)
219
Nabin Hait94c90bd2013-08-30 22:48:19 +0530220def get_sales_bom_buying_amount(item_code, warehouse, voucher_type, voucher_no, voucher_detail_no,
221 stock_ledger_entries, item_sales_bom):
222 # sales bom item
223 buying_amount = 0.0
224 for bom_item in item_sales_bom[item_code]:
225 if bom_item.get("parent_detail_docname")==voucher_detail_no:
226 buying_amount += get_buying_amount(voucher_type, voucher_no, voucher_detail_no,
227 stock_ledger_entries.get((bom_item.item_code, warehouse), []))
228
229 return buying_amount
Nabin Haita72c5122013-03-06 18:50:53 +0530230
Nabin Hait94c90bd2013-08-30 22:48:19 +0530231def get_buying_amount(voucher_type, voucher_no, item_row, stock_ledger_entries):
Anand Doshi5dd6b1d2013-08-07 19:27:30 +0530232 # IMP NOTE
233 # stock_ledger_entries should already be filtered by item_code and warehouse and
234 # sorted by posting_date desc, posting_time desc
235 for i, sle in enumerate(stock_ledger_entries):
Nabin Hait0cfbc5f2013-03-12 11:34:56 +0530236 if sle.voucher_type == voucher_type and sle.voucher_no == voucher_no and \
Anand Doshi8c454202013-03-28 16:40:30 +0530237 sle.voucher_detail_no == item_row:
Anand Doshi5dd6b1d2013-08-07 19:27:30 +0530238 previous_stock_value = len(stock_ledger_entries) > i+1 and \
239 flt(stock_ledger_entries[i+1].stock_value) or 0.0
Nabin Haitc3afb252013-03-19 12:01:24 +0530240 buying_amount = previous_stock_value - flt(sle.stock_value)
Anand Doshi6d8d3b42013-03-21 18:45:02 +0530241
Nabin Haitc3afb252013-03-19 12:01:24 +0530242 return buying_amount
Nabin Hait62d06292013-05-22 16:19:10 +0530243 return 0.0
244
245
246def reorder_item():
247 """ Reorder item if stock reaches reorder level"""
248 if not hasattr(webnotes, "auto_indent"):
Nabin Haitbf5d44c2013-08-12 16:30:48 +0530249 webnotes.auto_indent = cint(webnotes.conn.get_value('Stock Settings', None, 'auto_indent'))
250
Nabin Hait62d06292013-05-22 16:19:10 +0530251 if webnotes.auto_indent:
252 material_requests = {}
253 bin_list = webnotes.conn.sql("""select item_code, warehouse, projected_qty
Anand Doshiad6180e2013-06-17 11:57:04 +0530254 from tabBin where ifnull(item_code, '') != '' and ifnull(warehouse, '') != ''
255 and exists (select name from `tabItem`
256 where `tabItem`.name = `tabBin`.item_code and
257 is_stock_item='Yes' and (is_purchase_item='Yes' or is_sub_contracted_item='Yes') and
Anand Doshi4d47b002013-08-23 16:54:31 +0530258 (ifnull(end_of_life, '')='' or end_of_life > now()))""", as_dict=True)
Nabin Hait62d06292013-05-22 16:19:10 +0530259 for bin in bin_list:
260 #check if re-order is required
261 item_reorder = webnotes.conn.get("Item Reorder",
262 {"parent": bin.item_code, "warehouse": bin.warehouse})
263 if item_reorder:
264 reorder_level = item_reorder.warehouse_reorder_level
265 reorder_qty = item_reorder.warehouse_reorder_qty
266 material_request_type = item_reorder.material_request_type or "Purchase"
267 else:
268 reorder_level, reorder_qty = webnotes.conn.get_value("Item", bin.item_code,
269 ["re_order_level", "re_order_qty"])
270 material_request_type = "Purchase"
271
Anand Doshiad6180e2013-06-17 11:57:04 +0530272 if flt(reorder_level) and flt(bin.projected_qty) < flt(reorder_level):
Nabin Hait62d06292013-05-22 16:19:10 +0530273 if flt(reorder_level) - flt(bin.projected_qty) > flt(reorder_qty):
274 reorder_qty = flt(reorder_level) - flt(bin.projected_qty)
275
276 company = webnotes.conn.get_value("Warehouse", bin.warehouse, "company") or \
277 webnotes.defaults.get_defaults()["company"] or \
278 webnotes.conn.sql("""select name from tabCompany limit 1""")[0][0]
279
280 material_requests.setdefault(material_request_type, webnotes._dict()).setdefault(
281 company, []).append(webnotes._dict({
282 "item_code": bin.item_code,
283 "warehouse": bin.warehouse,
284 "reorder_qty": reorder_qty
285 })
286 )
287
288 create_material_request(material_requests)
289
290def create_material_request(material_requests):
291 """ Create indent on reaching reorder level """
292 mr_list = []
293 defaults = webnotes.defaults.get_defaults()
Anand Doshiad6180e2013-06-17 11:57:04 +0530294 exceptions_list = []
Nabin Hait62d06292013-05-22 16:19:10 +0530295 for request_type in material_requests:
296 for company in material_requests[request_type]:
Anand Doshiad6180e2013-06-17 11:57:04 +0530297 try:
298 items = material_requests[request_type][company]
299 if not items:
300 continue
Anand Doshi6f6e91c2013-07-22 11:28:34 +0530301
Nabin Hait62d06292013-05-22 16:19:10 +0530302 mr = [{
303 "doctype": "Material Request",
304 "company": company,
305 "fiscal_year": defaults.fiscal_year,
306 "transaction_date": nowdate(),
307 "material_request_type": request_type,
308 "remark": _("This is an auto generated Material Request.") + \
309 _("""It was raised because the (actual + ordered + indented - reserved)
310 quantity reaches re-order level when the following record was created""")
311 }]
312
Anand Doshiad6180e2013-06-17 11:57:04 +0530313 for d in items:
314 item = webnotes.doc("Item", d.item_code)
315 mr.append({
316 "doctype": "Material Request Item",
317 "parenttype": "Material Request",
318 "parentfield": "indent_details",
319 "item_code": d.item_code,
320 "schedule_date": add_days(nowdate(),cint(item.lead_time_days)),
321 "uom": item.stock_uom,
322 "warehouse": d.warehouse,
323 "item_name": item.item_name,
324 "description": item.description,
325 "item_group": item.item_group,
326 "qty": d.reorder_qty,
327 "brand": item.brand,
328 })
Nabin Hait62d06292013-05-22 16:19:10 +0530329
Anand Doshiad6180e2013-06-17 11:57:04 +0530330 mr_bean = webnotes.bean(mr)
331 mr_bean.insert()
332 mr_bean.submit()
333 mr_list.append(mr_bean)
Anand Doshi6f6e91c2013-07-22 11:28:34 +0530334
Anand Doshiad6180e2013-06-17 11:57:04 +0530335 except:
336 if webnotes.message_log:
337 exceptions_list.append([] + webnotes.message_log)
338 webnotes.message_log = []
339 else:
340 exceptions_list.append(webnotes.getTraceback())
Nabin Hait62d06292013-05-22 16:19:10 +0530341
342 if mr_list:
343 if not hasattr(webnotes, "reorder_email_notify"):
Nabin Haitbf5d44c2013-08-12 16:30:48 +0530344 webnotes.reorder_email_notify = cint(webnotes.conn.get_value('Stock Settings', None,
345 'reorder_email_notify'))
Nabin Hait62d06292013-05-22 16:19:10 +0530346
347 if(webnotes.reorder_email_notify):
348 send_email_notification(mr_list)
Anand Doshiad6180e2013-06-17 11:57:04 +0530349
350 if exceptions_list:
351 notify_errors(exceptions_list)
Nabin Hait62d06292013-05-22 16:19:10 +0530352
353def send_email_notification(mr_list):
354 """ Notify user about auto creation of indent"""
355
Nabin Hait62d06292013-05-22 16:19:10 +0530356 email_list = webnotes.conn.sql_list("""select distinct r.parent
357 from tabUserRole r, tabProfile p
358 where p.name = r.parent and p.enabled = 1 and p.docstatus < 2
359 and r.role in ('Purchase Manager','Material Manager')
360 and p.name not in ('Administrator', 'All', 'Guest')""")
361
362 msg="""<h3>Following Material Requests has been raised automatically \
363 based on item reorder level:</h3>"""
364 for mr in mr_list:
365 msg += "<p><b><u>" + mr.doc.name + """</u></b></p><table class='table table-bordered'><tr>
366 <th>Item Code</th><th>Warehouse</th><th>Qty</th><th>UOM</th></tr>"""
367 for item in mr.doclist.get({"parentfield": "indent_details"}):
368 msg += "<tr><td>" + item.item_code + "</td><td>" + item.warehouse + "</td><td>" + \
369 cstr(item.qty) + "</td><td>" + cstr(item.uom) + "</td></tr>"
370 msg += "</table>"
Anand Doshiad6180e2013-06-17 11:57:04 +0530371 sendmail(email_list, subject='Auto Material Request Generation Notification', msg = msg)
372
373def notify_errors(exceptions_list):
374 subject = "[Important] [ERPNext] Error(s) while creating Material Requests based on Re-order Levels"
375 msg = """Dear System Manager,
376
377 An error occured for certain Items while creating Material Requests based on Re-order level.
378
379 Please rectify these issues:
380 ---
381
382 %s
383
384 ---
385 Regards,
386 Administrator""" % ("\n\n".join(["\n".join(msg) for msg in exceptions_list]),)
387
388 from webnotes.profile import get_system_managers
389 sendmail(get_system_managers(), subject=subject, msg=msg)
Nabin Hait74c281c2013-08-19 16:17:18 +0530390
391
392def repost():
393 """
394 Repost everything!
395 """
396 from webnotes.model.code import get_obj
397 for wh in webnotes.conn.sql("select name from tabWarehouse"):
Nabin Hait92b0e772013-08-26 16:55:42 +0530398 get_obj('Warehouse', wh[0]).repost_stock()