blob: 58d480e2b61c7ce79cbf8814928ec1d17842e871 [file] [log] [blame]
Ayush Shuklaa111f782017-06-20 13:04:45 +05301# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
2# MIT License. See license.txt
3
4from __future__ import unicode_literals, print_function
5import frappe
6import json
7from operator import itemgetter
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +05308from frappe.utils import add_to_date, fmt_money
Ayush Shuklaa111f782017-06-20 13:04:45 +05309from erpnext.accounts.party import get_dashboard_info
10from erpnext.accounts.utils import get_currency_precision
11
12@frappe.whitelist()
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053013def get_leaderboard(doctype, timespan, field, start=0):
Ayush Shuklaa111f782017-06-20 13:04:45 +053014 """return top 10 items for that doctype based on conditions"""
Ayush Shuklaa111f782017-06-20 13:04:45 +053015
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053016 filters = {"modified":(">=", get_date_from_string(timespan))}
Ayush Shuklaa111f782017-06-20 13:04:45 +053017 items = []
18 if doctype == "Customer":
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053019 items = get_all_customers(doctype, filters, [], field)
Ayush Shuklaa111f782017-06-20 13:04:45 +053020 elif doctype == "Item":
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053021 items = get_all_items(doctype, filters, [], field)
Ayush Shuklaa111f782017-06-20 13:04:45 +053022 elif doctype == "Supplier":
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053023 items = get_all_suppliers(doctype, filters, [], field)
Ayush Shuklaa111f782017-06-20 13:04:45 +053024 elif doctype == "Sales Partner":
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053025 items = get_all_sales_partner(doctype, filters, [], field)
26
Ayush Shuklaa111f782017-06-20 13:04:45 +053027 if len(items) > 0:
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053028 return items
Ayush Shuklaa111f782017-06-20 13:04:45 +053029 return []
30
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053031def get_all_customers(doctype, filters, items, field, start=0, limit=20):
32 """return all customers"""
Ayush Shuklaa111f782017-06-20 13:04:45 +053033
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053034 x = frappe.get_list(doctype, filters=filters, limit_start=start, limit_page_length=limit)
Ayush Shuklaa111f782017-06-20 13:04:45 +053035
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053036 for val in x:
Shreya Shah48351e02018-01-05 12:45:43 +053037 y = dict(frappe.db.sql('''select name, grand_total from `tabSales Invoice`\
38 where customer = %s and docstatus != 2''', (val.name)))
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053039 invoice_list = y.keys()
40 if len(invoice_list) > 0:
41 item_count = frappe.db.sql('''select count(name) from `tabSales Invoice Item` where parent in (%s)''' % ", ".join(
42 ['%s'] * len(invoice_list)), tuple(invoice_list))
Ayush Shuklaa111f782017-06-20 13:04:45 +053043
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053044 value = 0
45 if(field=="total_amount"):
46 value = sum(y.values())
47 elif(field=="total_item_purchased"):
48 value = sum(destructure_tuple_of_tuples(item_count))
49
50 item_obj = {"name": val.name,
51 "total_amount": get_formatted_value(sum(y.values())),
52 "total_item_purchased": sum(destructure_tuple_of_tuples(item_count)),
53 "href":"#Form/Customer/" + val.name,
54 "value": value}
55 items.append(item_obj)
56
57 items.sort(key=lambda k: k['value'], reverse=True)
58 return items
59
60def get_all_items(doctype, filters, items, field, start=0, limit=20):
61 """return all items"""
62
63 x = frappe.get_list(doctype, filters=filters, limit_start=start, limit_page_length=limit)
64 for val in x:
65 data = frappe.db.sql('''select item_code from `tabMaterial Request Item` where item_code = %s''', (val.name), as_list=1)
66 requests = destructure_tuple_of_tuples(data)
67 data = frappe.db.sql('''select price_list_rate from `tabItem Price` where item_code = %s''', (val.name), as_list=1)
68 avg_price = get_avg(destructure_tuple_of_tuples(data))
69 data = frappe.db.sql('''select item_code from `tabPurchase Invoice Item` where item_code = %s''', (val.name), as_list=1)
70 purchases = destructure_tuple_of_tuples(data)
71
72 value = 0
73 if(field=="total_request"):
74 value = len(requests)
75 elif(field=="total_purchase"):
76 value = len(purchases)
77 elif(field=="avg_price"):
78 value=avg_price
79 item_obj = {"name": val.name,
80 "total_request":len(requests),
81 "total_purchase": len(purchases),
82 "avg_price": get_formatted_value(avg_price),
83 "href":"#Form/Item/" + val.name,
84 "value": value}
85 items.append(item_obj)
86
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053087 items.sort(key=lambda k: k['value'], reverse=True)
88 return items
89
90def get_all_suppliers(doctype, filters, items, field, start=0, limit=20):
91 """return all suppliers"""
92
93 x = frappe.get_list(doctype, filters=filters, limit_start=start, limit_page_length=limit)
94
95 for val in x:
96
97 info = get_dashboard_info(doctype, val.name)
98 value = 0
99 if(field=="annual_billing"):
100 value = info["billing_this_year"]
101 elif(field=="total_unpaid"):
102 value = abs(info["total_unpaid"])
103
104 item_obj = {"name": val.name,
105 "annual_billing": get_formatted_value(info["billing_this_year"]),
106 "total_unpaid": get_formatted_value(abs(info["total_unpaid"])),
107 "href":"#Form/Supplier/" + val.name,
108 "value": value}
109 items.append(item_obj)
110
111 items.sort(key=lambda k: k['value'], reverse=True)
112 return items
113
114def get_all_sales_partner(doctype, filters, items, field, start=0, limit=20):
115 """return all sales partner"""
116
117 x = frappe.get_list(doctype, fields=["name", "commission_rate", "modified"], filters=filters, limit_start=start, limit_page_length=limit)
118 for val in x:
119 y = frappe.db.sql('''select target_qty, target_amount from `tabTarget Detail` where parent = %s''', (val.name), as_dict=1)
120 target_qty = sum([f["target_qty"] for f in y])
121 target_amount = sum([f["target_amount"] for f in y])
122
123 value = 0
124 if(field=="commission_rate"):
125 value = val.commission_rate
126 elif(field=="target_qty"):
127 value = target_qty
128 elif(field=="target_amount"):
129 value = target_qty
130
131 item_obj = {"name": val.name,
132 "commission_rate": get_formatted_value(val.commission_rate, False),
133 "target_qty": target_qty,
134 "target_amount": get_formatted_value(target_qty),
135 "href":"#Form/Sales Partner/" + val.name,
136 "value": value}
137 items.append(item_obj)
138
139 items.sort(key=lambda k: k['value'], reverse=True)
140 return items
Ayush Shuklaa111f782017-06-20 13:04:45 +0530141
142
Ayush Shuklaa111f782017-06-20 13:04:45 +0530143def destructure_tuple_of_tuples(tup_of_tup):
144 """return tuple(tuples) as list"""
145 return [y for x in tup_of_tup for y in x]
146
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +0530147def get_date_from_string(seleted_timespan):
Ayush Shuklaa111f782017-06-20 13:04:45 +0530148 """return string for ex:this week as date:string"""
149 days = months = years = 0
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +0530150 if "month" == seleted_timespan.lower():
Ayush Shuklaa111f782017-06-20 13:04:45 +0530151 months = -1
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +0530152 elif "quarter" == seleted_timespan.lower():
Ayush Shuklaa111f782017-06-20 13:04:45 +0530153 months = -3
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +0530154 elif "year" == seleted_timespan.lower():
Ayush Shuklaa111f782017-06-20 13:04:45 +0530155 years = -1
156 else:
157 days = -7
158
159 return add_to_date(None, years=years, months=months, days=days, as_string=True, as_datetime=True)
160
161def get_filter_list(selected_filter):
162 """return list of keys"""
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +0530163 return map((lambda y : y["field"]), filter(lambda x : not (x["field"] == "name" or x["field"] == "modified"), selected_filter))
Ayush Shuklaa111f782017-06-20 13:04:45 +0530164
165def get_avg(items):
166 """return avg of list items"""
167 length = len(items)
168 if length > 0:
169 return sum(items) / length
170 return 0
171
172def get_formatted_value(value, add_symbol=True):
173 """return formatted value"""
Ayush Shuklaa111f782017-06-20 13:04:45 +0530174 if not add_symbol:
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +0530175 return '{:.{pre}f}'.format(value, pre=(get_currency_precision() or 2))
176 currency_precision = get_currency_precision() or 2
177 company = frappe.db.get_default("company")
178 currency = frappe.get_doc("Company", company).default_currency or frappe.boot.sysdefaults.currency
179 return fmt_money(value, currency_precision, currency)