blob: 17149faca40863f14a6c219569a7e0336bf5c29c [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
13def get_stock_balance_on(warehouse_list, posting_date=None):
14 if not posting_date: posting_date = nowdate()
15
16 stock_ledger_entries = webnotes.conn.sql("""
17 SELECT
18 item_code, warehouse, stock_value
19 FROM
20 `tabStock Ledger Entry`
21 WHERE
22 warehouse in (%s)
23 AND posting_date <= %s
24 ORDER BY timestamp(posting_date, posting_time) DESC, name DESC
25 """ % (', '.join(['%s']*len(warehouse_list)), '%s'),
26 tuple(warehouse_list + [posting_date]), as_dict=1)
27
28 sle_map = {}
29 for sle in stock_ledger_entries:
30 sle_map.setdefault(sle.warehouse, {}).setdefault(sle.item_code, flt(sle.stock_value))
31
32 return sum([sum(item_dict.values()) for item_dict in sle_map.values()])
33
Nabin Hait47dc3182013-08-06 15:58:16 +053034def get_latest_stock_balance():
35 bin_map = {}
Nabin Hait469ee712013-08-07 12:33:37 +053036 for d in webnotes.conn.sql("""SELECT item_code, warehouse, stock_value as stock_value
Nabin Hait47dc3182013-08-06 15:58:16 +053037 FROM tabBin""", as_dict=1):
Nabin Hait469ee712013-08-07 12:33:37 +053038 bin_map.setdefault(d.warehouse, {}).setdefault(d.item_code, flt(d.stock_value))
Nabin Hait47dc3182013-08-06 15:58:16 +053039
40 return bin_map
Nabin Hait74c281c2013-08-19 16:17:18 +053041
42def get_bin(item_code, warehouse):
43 bin = webnotes.conn.get_value("Bin", {"item_code": item_code, "warehouse": warehouse})
44 if not bin:
45 bin_wrapper = webnotes.bean([{
46 "doctype": "Bin",
47 "item_code": item_code,
48 "warehouse": warehouse,
49 }])
50 bin_wrapper.ignore_permissions = 1
51 bin_wrapper.insert()
52 bin_obj = bin_wrapper.make_controller()
53 else:
54 from webnotes.model.code import get_obj
55 bin_obj = get_obj('Bin', bin)
56 return bin_obj
57
58def update_bin(args):
59 is_stock_item = webnotes.conn.get_value('Item', args.get("item_code"), 'is_stock_item')
60 if is_stock_item == 'Yes':
61 bin = get_bin(args.get("item_code"), args.get("warehouse"))
62 bin.update_stock(args)
63 return bin
64 else:
65 msgprint("[Stock Update] Ignored %s since it is not a stock item"
66 % args.get("item_code"))
Nabin Hait0dd7be12013-08-02 11:45:43 +053067
Nabin Hait9d0f6362013-01-07 18:51:11 +053068def validate_end_of_life(item_code, end_of_life=None, verbose=1):
69 if not end_of_life:
70 end_of_life = webnotes.conn.get_value("Item", item_code, "end_of_life")
71
72 from webnotes.utils import getdate, now_datetime, formatdate
Anand Doshiad6180e2013-06-17 11:57:04 +053073 if end_of_life and getdate(end_of_life) <= now_datetime().date():
Nabin Hait9d0f6362013-01-07 18:51:11 +053074 msg = (_("Item") + " %(item_code)s: " + _("reached its end of life on") + \
75 " %(date)s. " + _("Please check") + ": %(end_of_life_label)s " + \
76 "in Item master") % {
77 "item_code": item_code,
78 "date": formatdate(end_of_life),
Anand Doshia43b29e2013-02-20 15:55:10 +053079 "end_of_life_label": webnotes.get_doctype("Item").get_label("end_of_life")
Nabin Hait9d0f6362013-01-07 18:51:11 +053080 }
81
82 _msgprint(msg, verbose)
83
84def validate_is_stock_item(item_code, is_stock_item=None, verbose=1):
85 if not is_stock_item:
86 is_stock_item = webnotes.conn.get_value("Item", item_code, "is_stock_item")
87
88 if is_stock_item != "Yes":
89 msg = (_("Item") + " %(item_code)s: " + _("is not a Stock Item")) % {
90 "item_code": item_code,
91 }
92
93 _msgprint(msg, verbose)
94
95def validate_cancelled_item(item_code, docstatus=None, verbose=1):
96 if docstatus is None:
97 docstatus = webnotes.conn.get_value("Item", item_code, "docstatus")
98
99 if docstatus == 2:
100 msg = (_("Item") + " %(item_code)s: " + _("is a cancelled Item")) % {
101 "item_code": item_code,
102 }
103
104 _msgprint(msg, verbose)
105
106def _msgprint(msg, verbose):
107 if verbose:
108 msgprint(msg, raise_exception=True)
109 else:
110 raise webnotes.ValidationError, msg
111
Nabin Hait9d0f6362013-01-07 18:51:11 +0530112def get_incoming_rate(args):
113 """Get Incoming Rate based on valuation method"""
Anand Doshi1b531862013-01-10 19:29:51 +0530114 from stock.stock_ledger import get_previous_sle
Nabin Hait9d0f6362013-01-07 18:51:11 +0530115
116 in_rate = 0
117 if args.get("serial_no"):
118 in_rate = get_avg_purchase_rate(args.get("serial_no"))
119 elif args.get("bom_no"):
120 result = webnotes.conn.sql("""select ifnull(total_cost, 0) / ifnull(quantity, 1)
121 from `tabBOM` where name = %s and docstatus=1 and is_active=1""", args.get("bom_no"))
122 in_rate = result and flt(result[0][0]) or 0
123 else:
124 valuation_method = get_valuation_method(args.get("item_code"))
125 previous_sle = get_previous_sle(args)
126 if valuation_method == 'FIFO':
Nabin Hait831207f2013-01-16 14:15:48 +0530127 if not previous_sle:
128 return 0.0
Rushabh Mehta4c17f942013-08-12 14:18:09 +0530129 previous_stock_queue = json.loads(previous_sle.get('stock_queue', '[]') or '[]')
Nabin Hait831207f2013-01-16 14:15:48 +0530130 in_rate = previous_stock_queue and \
Nabin Hait6b1f21d2013-01-16 17:17:17 +0530131 get_fifo_rate(previous_stock_queue, args.get("qty") or 0) or 0
Nabin Hait9d0f6362013-01-07 18:51:11 +0530132 elif valuation_method == 'Moving Average':
133 in_rate = previous_sle.get('valuation_rate') or 0
134 return in_rate
135
136def get_avg_purchase_rate(serial_nos):
137 """get average value of serial numbers"""
138
139 serial_nos = get_valid_serial_nos(serial_nos)
140 return flt(webnotes.conn.sql("""select avg(ifnull(purchase_rate, 0)) from `tabSerial No`
141 where name in (%s)""" % ", ".join(["%s"] * len(serial_nos)),
142 tuple(serial_nos))[0][0])
143
144def get_valuation_method(item_code):
145 """get valuation method from item or default"""
146 val_method = webnotes.conn.get_value('Item', item_code, 'valuation_method')
147 if not val_method:
Rushabh Mehta5117d9c2013-02-19 15:27:31 +0530148 val_method = get_global_default('valuation_method') or "FIFO"
Nabin Hait9d0f6362013-01-07 18:51:11 +0530149 return val_method
150
Nabin Hait831207f2013-01-16 14:15:48 +0530151def get_fifo_rate(previous_stock_queue, qty):
152 """get FIFO (average) Rate from Queue"""
153 if qty >= 0:
154 total = sum(f[0] for f in previous_stock_queue)
155 return total and sum(f[0] * f[1] for f in previous_stock_queue) / flt(total) or 0.0
156 else:
157 outgoing_cost = 0
158 qty_to_pop = abs(qty)
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530159 while qty_to_pop and previous_stock_queue:
Nabin Hait831207f2013-01-16 14:15:48 +0530160 batch = previous_stock_queue[0]
161 if 0 < batch[0] <= qty_to_pop:
162 # if batch qty > 0
163 # not enough or exactly same qty in current batch, clear batch
164 outgoing_cost += flt(batch[0]) * flt(batch[1])
165 qty_to_pop -= batch[0]
166 previous_stock_queue.pop(0)
167 else:
168 # all from current batch
169 outgoing_cost += flt(qty_to_pop) * flt(batch[1])
170 batch[0] -= qty_to_pop
171 qty_to_pop = 0
Nabin Hait64d7c4b2013-01-17 12:22:59 +0530172 # if queue gets blank and qty_to_pop remaining, get average rate of full queue
173 return outgoing_cost / abs(qty) - qty_to_pop
Nabin Hait9d0f6362013-01-07 18:51:11 +0530174
175def get_valid_serial_nos(sr_nos, qty=0, item_code=''):
176 """split serial nos, validate and return list of valid serial nos"""
177 # TODO: remove duplicates in client side
178 serial_nos = cstr(sr_nos).strip().replace(',', '\n').split('\n')
179
180 valid_serial_nos = []
181 for val in serial_nos:
182 if val:
183 val = val.strip()
184 if val in valid_serial_nos:
185 msgprint("You have entered duplicate serial no: '%s'" % val, raise_exception=1)
186 else:
187 valid_serial_nos.append(val)
188
189 if qty and len(valid_serial_nos) != abs(qty):
190 msgprint("Please enter serial nos for "
191 + cstr(abs(qty)) + " quantity against item code: " + item_code,
192 raise_exception=1)
193
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530194 return valid_serial_nos
195
Nabin Haitdc95c152013-02-07 12:08:38 +0530196def get_warehouse_list(doctype, txt, searchfield, start, page_len, filters):
Rushabh Mehta0dbe8982013-02-04 13:56:50 +0530197 """used in search queries"""
198 wlist = []
199 for w in webnotes.conn.sql_list("""select name from tabWarehouse
200 where name like '%%%s%%'""" % txt):
201 if webnotes.session.user=="Administrator":
202 wlist.append([w])
203 else:
204 warehouse_users = webnotes.conn.sql_list("""select user from `tabWarehouse User`
205 where parent=%s""", w)
206 if not warehouse_users:
207 wlist.append([w])
208 elif webnotes.session.user in warehouse_users:
209 wlist.append([w])
210 return wlist
Nabin Haita72c5122013-03-06 18:50:53 +0530211
Rushabh Mehtaa65253b2013-08-27 10:32:56 +0530212def validate_warehouse_user(warehouse):
213 if webnotes.session.user=="Administrator":
214 return
215 warehouse_users = [p[0] for p in webnotes.conn.sql("""select user from `tabWarehouse User`
216 where parent=%s""", warehouse)]
217
218 if warehouse_users and not (webnotes.session.user in warehouse_users):
219 webnotes.throw(_("Not allowed entry in Warehouse") \
220 + ": " + warehouse, UserNotAllowedForWarehouse)
221
Nabin Hait94c90bd2013-08-30 22:48:19 +0530222def get_sales_bom_buying_amount(item_code, warehouse, voucher_type, voucher_no, voucher_detail_no,
223 stock_ledger_entries, item_sales_bom):
224 # sales bom item
225 buying_amount = 0.0
226 for bom_item in item_sales_bom[item_code]:
227 if bom_item.get("parent_detail_docname")==voucher_detail_no:
228 buying_amount += get_buying_amount(voucher_type, voucher_no, voucher_detail_no,
229 stock_ledger_entries.get((bom_item.item_code, warehouse), []))
230
231 return buying_amount
Nabin Haita72c5122013-03-06 18:50:53 +0530232
Nabin Hait94c90bd2013-08-30 22:48:19 +0530233def get_buying_amount(voucher_type, voucher_no, item_row, stock_ledger_entries):
Anand Doshi5dd6b1d2013-08-07 19:27:30 +0530234 # IMP NOTE
235 # stock_ledger_entries should already be filtered by item_code and warehouse and
236 # sorted by posting_date desc, posting_time desc
237 for i, sle in enumerate(stock_ledger_entries):
Nabin Hait0cfbc5f2013-03-12 11:34:56 +0530238 if sle.voucher_type == voucher_type and sle.voucher_no == voucher_no and \
Anand Doshi8c454202013-03-28 16:40:30 +0530239 sle.voucher_detail_no == item_row:
Anand Doshi5dd6b1d2013-08-07 19:27:30 +0530240 previous_stock_value = len(stock_ledger_entries) > i+1 and \
241 flt(stock_ledger_entries[i+1].stock_value) or 0.0
Nabin Haitc3afb252013-03-19 12:01:24 +0530242 buying_amount = previous_stock_value - flt(sle.stock_value)
Anand Doshi6d8d3b42013-03-21 18:45:02 +0530243
Nabin Haitc3afb252013-03-19 12:01:24 +0530244 return buying_amount
Nabin Hait62d06292013-05-22 16:19:10 +0530245 return 0.0
246
247
248def reorder_item():
249 """ Reorder item if stock reaches reorder level"""
250 if not hasattr(webnotes, "auto_indent"):
Nabin Haitbf5d44c2013-08-12 16:30:48 +0530251 webnotes.auto_indent = cint(webnotes.conn.get_value('Stock Settings', None, 'auto_indent'))
252
Nabin Hait62d06292013-05-22 16:19:10 +0530253 if webnotes.auto_indent:
254 material_requests = {}
255 bin_list = webnotes.conn.sql("""select item_code, warehouse, projected_qty
Anand Doshiad6180e2013-06-17 11:57:04 +0530256 from tabBin where ifnull(item_code, '') != '' and ifnull(warehouse, '') != ''
257 and exists (select name from `tabItem`
258 where `tabItem`.name = `tabBin`.item_code and
259 is_stock_item='Yes' and (is_purchase_item='Yes' or is_sub_contracted_item='Yes') and
Anand Doshi4d47b002013-08-23 16:54:31 +0530260 (ifnull(end_of_life, '')='' or end_of_life > now()))""", as_dict=True)
Nabin Hait62d06292013-05-22 16:19:10 +0530261 for bin in bin_list:
262 #check if re-order is required
263 item_reorder = webnotes.conn.get("Item Reorder",
264 {"parent": bin.item_code, "warehouse": bin.warehouse})
265 if item_reorder:
266 reorder_level = item_reorder.warehouse_reorder_level
267 reorder_qty = item_reorder.warehouse_reorder_qty
268 material_request_type = item_reorder.material_request_type or "Purchase"
269 else:
270 reorder_level, reorder_qty = webnotes.conn.get_value("Item", bin.item_code,
271 ["re_order_level", "re_order_qty"])
272 material_request_type = "Purchase"
273
Anand Doshiad6180e2013-06-17 11:57:04 +0530274 if flt(reorder_level) and flt(bin.projected_qty) < flt(reorder_level):
Nabin Hait62d06292013-05-22 16:19:10 +0530275 if flt(reorder_level) - flt(bin.projected_qty) > flt(reorder_qty):
276 reorder_qty = flt(reorder_level) - flt(bin.projected_qty)
277
278 company = webnotes.conn.get_value("Warehouse", bin.warehouse, "company") or \
279 webnotes.defaults.get_defaults()["company"] or \
280 webnotes.conn.sql("""select name from tabCompany limit 1""")[0][0]
281
282 material_requests.setdefault(material_request_type, webnotes._dict()).setdefault(
283 company, []).append(webnotes._dict({
284 "item_code": bin.item_code,
285 "warehouse": bin.warehouse,
286 "reorder_qty": reorder_qty
287 })
288 )
289
290 create_material_request(material_requests)
291
292def create_material_request(material_requests):
293 """ Create indent on reaching reorder level """
294 mr_list = []
295 defaults = webnotes.defaults.get_defaults()
Anand Doshiad6180e2013-06-17 11:57:04 +0530296 exceptions_list = []
Nabin Hait62d06292013-05-22 16:19:10 +0530297 for request_type in material_requests:
298 for company in material_requests[request_type]:
Anand Doshiad6180e2013-06-17 11:57:04 +0530299 try:
300 items = material_requests[request_type][company]
301 if not items:
302 continue
Anand Doshi6f6e91c2013-07-22 11:28:34 +0530303
Nabin Hait62d06292013-05-22 16:19:10 +0530304 mr = [{
305 "doctype": "Material Request",
306 "company": company,
307 "fiscal_year": defaults.fiscal_year,
308 "transaction_date": nowdate(),
309 "material_request_type": request_type,
310 "remark": _("This is an auto generated Material Request.") + \
311 _("""It was raised because the (actual + ordered + indented - reserved)
312 quantity reaches re-order level when the following record was created""")
313 }]
314
Anand Doshiad6180e2013-06-17 11:57:04 +0530315 for d in items:
316 item = webnotes.doc("Item", d.item_code)
317 mr.append({
318 "doctype": "Material Request Item",
319 "parenttype": "Material Request",
320 "parentfield": "indent_details",
321 "item_code": d.item_code,
322 "schedule_date": add_days(nowdate(),cint(item.lead_time_days)),
323 "uom": item.stock_uom,
324 "warehouse": d.warehouse,
325 "item_name": item.item_name,
326 "description": item.description,
327 "item_group": item.item_group,
328 "qty": d.reorder_qty,
329 "brand": item.brand,
330 })
Nabin Hait62d06292013-05-22 16:19:10 +0530331
Anand Doshiad6180e2013-06-17 11:57:04 +0530332 mr_bean = webnotes.bean(mr)
333 mr_bean.insert()
334 mr_bean.submit()
335 mr_list.append(mr_bean)
Anand Doshi6f6e91c2013-07-22 11:28:34 +0530336
Anand Doshiad6180e2013-06-17 11:57:04 +0530337 except:
338 if webnotes.message_log:
339 exceptions_list.append([] + webnotes.message_log)
340 webnotes.message_log = []
341 else:
342 exceptions_list.append(webnotes.getTraceback())
Nabin Hait62d06292013-05-22 16:19:10 +0530343
344 if mr_list:
345 if not hasattr(webnotes, "reorder_email_notify"):
Nabin Haitbf5d44c2013-08-12 16:30:48 +0530346 webnotes.reorder_email_notify = cint(webnotes.conn.get_value('Stock Settings', None,
347 'reorder_email_notify'))
Nabin Hait62d06292013-05-22 16:19:10 +0530348
349 if(webnotes.reorder_email_notify):
350 send_email_notification(mr_list)
Anand Doshiad6180e2013-06-17 11:57:04 +0530351
352 if exceptions_list:
353 notify_errors(exceptions_list)
Nabin Hait62d06292013-05-22 16:19:10 +0530354
355def send_email_notification(mr_list):
356 """ Notify user about auto creation of indent"""
357
Nabin Hait62d06292013-05-22 16:19:10 +0530358 email_list = webnotes.conn.sql_list("""select distinct r.parent
359 from tabUserRole r, tabProfile p
360 where p.name = r.parent and p.enabled = 1 and p.docstatus < 2
361 and r.role in ('Purchase Manager','Material Manager')
362 and p.name not in ('Administrator', 'All', 'Guest')""")
363
364 msg="""<h3>Following Material Requests has been raised automatically \
365 based on item reorder level:</h3>"""
366 for mr in mr_list:
367 msg += "<p><b><u>" + mr.doc.name + """</u></b></p><table class='table table-bordered'><tr>
368 <th>Item Code</th><th>Warehouse</th><th>Qty</th><th>UOM</th></tr>"""
369 for item in mr.doclist.get({"parentfield": "indent_details"}):
370 msg += "<tr><td>" + item.item_code + "</td><td>" + item.warehouse + "</td><td>" + \
371 cstr(item.qty) + "</td><td>" + cstr(item.uom) + "</td></tr>"
372 msg += "</table>"
Anand Doshiad6180e2013-06-17 11:57:04 +0530373 sendmail(email_list, subject='Auto Material Request Generation Notification', msg = msg)
374
375def notify_errors(exceptions_list):
376 subject = "[Important] [ERPNext] Error(s) while creating Material Requests based on Re-order Levels"
377 msg = """Dear System Manager,
378
379 An error occured for certain Items while creating Material Requests based on Re-order level.
380
381 Please rectify these issues:
382 ---
383
384 %s
385
386 ---
387 Regards,
388 Administrator""" % ("\n\n".join(["\n".join(msg) for msg in exceptions_list]),)
389
390 from webnotes.profile import get_system_managers
391 sendmail(get_system_managers(), subject=subject, msg=msg)
Nabin Hait74c281c2013-08-19 16:17:18 +0530392
393
394def repost():
395 """
396 Repost everything!
397 """
398 from webnotes.model.code import get_obj
399 for wh in webnotes.conn.sql("select name from tabWarehouse"):
Nabin Hait92b0e772013-08-26 16:55:42 +0530400 get_obj('Warehouse', wh[0]).repost_stock()