blob: 6e7eabc8261b1a24af90d26654d6ecbe1606aa60 [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:
37 y = dict(frappe.db.sql('''select name, grand_total from `tabSales Invoice` where customer = %s''', (val.name)))
38 invoice_list = y.keys()
39 if len(invoice_list) > 0:
40 item_count = frappe.db.sql('''select count(name) from `tabSales Invoice Item` where parent in (%s)''' % ", ".join(
41 ['%s'] * len(invoice_list)), tuple(invoice_list))
Ayush Shuklaa111f782017-06-20 13:04:45 +053042
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053043 value = 0
44 if(field=="total_amount"):
45 value = sum(y.values())
46 elif(field=="total_item_purchased"):
47 value = sum(destructure_tuple_of_tuples(item_count))
48
49 item_obj = {"name": val.name,
50 "total_amount": get_formatted_value(sum(y.values())),
51 "total_item_purchased": sum(destructure_tuple_of_tuples(item_count)),
52 "href":"#Form/Customer/" + val.name,
53 "value": value}
54 items.append(item_obj)
55
56 items.sort(key=lambda k: k['value'], reverse=True)
57 return items
58
59def get_all_items(doctype, filters, items, field, start=0, limit=20):
60 """return all items"""
61
62 x = frappe.get_list(doctype, filters=filters, limit_start=start, limit_page_length=limit)
63 for val in x:
64 data = frappe.db.sql('''select item_code from `tabMaterial Request Item` where item_code = %s''', (val.name), as_list=1)
65 requests = destructure_tuple_of_tuples(data)
66 data = frappe.db.sql('''select price_list_rate from `tabItem Price` where item_code = %s''', (val.name), as_list=1)
67 avg_price = get_avg(destructure_tuple_of_tuples(data))
68 data = frappe.db.sql('''select item_code from `tabPurchase Invoice Item` where item_code = %s''', (val.name), as_list=1)
69 purchases = destructure_tuple_of_tuples(data)
70
71 value = 0
72 if(field=="total_request"):
73 value = len(requests)
74 elif(field=="total_purchase"):
75 value = len(purchases)
76 elif(field=="avg_price"):
77 value=avg_price
78 item_obj = {"name": val.name,
79 "total_request":len(requests),
80 "total_purchase": len(purchases),
81 "avg_price": get_formatted_value(avg_price),
82 "href":"#Form/Item/" + val.name,
83 "value": value}
84 items.append(item_obj)
85
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053086 items.sort(key=lambda k: k['value'], reverse=True)
87 return items
88
89def get_all_suppliers(doctype, filters, items, field, start=0, limit=20):
90 """return all suppliers"""
91
92 x = frappe.get_list(doctype, filters=filters, limit_start=start, limit_page_length=limit)
93
94 for val in x:
95
96 info = get_dashboard_info(doctype, val.name)
97 value = 0
98 if(field=="annual_billing"):
99 value = info["billing_this_year"]
100 elif(field=="total_unpaid"):
101 value = abs(info["total_unpaid"])
102
103 item_obj = {"name": val.name,
104 "annual_billing": get_formatted_value(info["billing_this_year"]),
105 "total_unpaid": get_formatted_value(abs(info["total_unpaid"])),
106 "href":"#Form/Supplier/" + val.name,
107 "value": value}
108 items.append(item_obj)
109
110 items.sort(key=lambda k: k['value'], reverse=True)
111 return items
112
113def get_all_sales_partner(doctype, filters, items, field, start=0, limit=20):
114 """return all sales partner"""
115
116 x = frappe.get_list(doctype, fields=["name", "commission_rate", "modified"], filters=filters, limit_start=start, limit_page_length=limit)
117 for val in x:
118 y = frappe.db.sql('''select target_qty, target_amount from `tabTarget Detail` where parent = %s''', (val.name), as_dict=1)
119 target_qty = sum([f["target_qty"] for f in y])
120 target_amount = sum([f["target_amount"] for f in y])
121
122 value = 0
123 if(field=="commission_rate"):
124 value = val.commission_rate
125 elif(field=="target_qty"):
126 value = target_qty
127 elif(field=="target_amount"):
128 value = target_qty
129
130 item_obj = {"name": val.name,
131 "commission_rate": get_formatted_value(val.commission_rate, False),
132 "target_qty": target_qty,
133 "target_amount": get_formatted_value(target_qty),
134 "href":"#Form/Sales Partner/" + val.name,
135 "value": value}
136 items.append(item_obj)
137
138 items.sort(key=lambda k: k['value'], reverse=True)
139 return items
Ayush Shuklaa111f782017-06-20 13:04:45 +0530140
141
Ayush Shuklaa111f782017-06-20 13:04:45 +0530142def destructure_tuple_of_tuples(tup_of_tup):
143 """return tuple(tuples) as list"""
144 return [y for x in tup_of_tup for y in x]
145
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +0530146def get_date_from_string(seleted_timespan):
Ayush Shuklaa111f782017-06-20 13:04:45 +0530147 """return string for ex:this week as date:string"""
148 days = months = years = 0
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +0530149 if "month" == seleted_timespan.lower():
Ayush Shuklaa111f782017-06-20 13:04:45 +0530150 months = -1
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +0530151 elif "quarter" == seleted_timespan.lower():
Ayush Shuklaa111f782017-06-20 13:04:45 +0530152 months = -3
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +0530153 elif "year" == seleted_timespan.lower():
Ayush Shuklaa111f782017-06-20 13:04:45 +0530154 years = -1
155 else:
156 days = -7
157
158 return add_to_date(None, years=years, months=months, days=days, as_string=True, as_datetime=True)
159
160def get_filter_list(selected_filter):
161 """return list of keys"""
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +0530162 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 +0530163
164def get_avg(items):
165 """return avg of list items"""
166 length = len(items)
167 if length > 0:
168 return sum(items) / length
169 return 0
170
171def get_formatted_value(value, add_symbol=True):
172 """return formatted value"""
Ayush Shuklaa111f782017-06-20 13:04:45 +0530173 if not add_symbol:
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +0530174 return '{:.{pre}f}'.format(value, pre=(get_currency_precision() or 2))
175 currency_precision = get_currency_precision() or 2
176 company = frappe.db.get_default("company")
177 currency = frappe.get_doc("Company", company).default_currency or frappe.boot.sysdefaults.currency
178 return fmt_money(value, currency_precision, currency)