blob: 50e8abfd7541282d458a992eae525f2eeb737729 [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 print('doctype', doctype, timespan, field, start)
17
18 filters = {"modified":(">=", get_date_from_string(timespan))}
Ayush Shuklaa111f782017-06-20 13:04:45 +053019 items = []
20 if doctype == "Customer":
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053021 items = get_all_customers(doctype, filters, [], field)
Ayush Shuklaa111f782017-06-20 13:04:45 +053022 elif doctype == "Item":
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053023 items = get_all_items(doctype, filters, [], field)
Ayush Shuklaa111f782017-06-20 13:04:45 +053024 elif doctype == "Supplier":
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053025 items = get_all_suppliers(doctype, filters, [], field)
Ayush Shuklaa111f782017-06-20 13:04:45 +053026 elif doctype == "Sales Partner":
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053027 items = get_all_sales_partner(doctype, filters, [], field)
28
Ayush Shuklaa111f782017-06-20 13:04:45 +053029 if len(items) > 0:
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053030 return items
Ayush Shuklaa111f782017-06-20 13:04:45 +053031 return []
32
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053033def get_all_customers(doctype, filters, items, field, start=0, limit=20):
34 """return all customers"""
Ayush Shuklaa111f782017-06-20 13:04:45 +053035
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053036 x = frappe.get_list(doctype, filters=filters, limit_start=start, limit_page_length=limit)
Ayush Shuklaa111f782017-06-20 13:04:45 +053037
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053038 for val in x:
39 y = dict(frappe.db.sql('''select name, grand_total from `tabSales Invoice` where customer = %s''', (val.name)))
40 invoice_list = y.keys()
41 if len(invoice_list) > 0:
42 item_count = frappe.db.sql('''select count(name) from `tabSales Invoice Item` where parent in (%s)''' % ", ".join(
43 ['%s'] * len(invoice_list)), tuple(invoice_list))
Ayush Shuklaa111f782017-06-20 13:04:45 +053044
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +053045 value = 0
46 if(field=="total_amount"):
47 value = sum(y.values())
48 elif(field=="total_item_purchased"):
49 value = sum(destructure_tuple_of_tuples(item_count))
50
51 item_obj = {"name": val.name,
52 "total_amount": get_formatted_value(sum(y.values())),
53 "total_item_purchased": sum(destructure_tuple_of_tuples(item_count)),
54 "href":"#Form/Customer/" + val.name,
55 "value": value}
56 items.append(item_obj)
57
58 items.sort(key=lambda k: k['value'], reverse=True)
59 return items
60
61def get_all_items(doctype, filters, items, field, start=0, limit=20):
62 """return all items"""
63
64 x = frappe.get_list(doctype, filters=filters, limit_start=start, limit_page_length=limit)
65 for val in x:
66 data = frappe.db.sql('''select item_code from `tabMaterial Request Item` where item_code = %s''', (val.name), as_list=1)
67 requests = destructure_tuple_of_tuples(data)
68 data = frappe.db.sql('''select price_list_rate from `tabItem Price` where item_code = %s''', (val.name), as_list=1)
69 avg_price = get_avg(destructure_tuple_of_tuples(data))
70 data = frappe.db.sql('''select item_code from `tabPurchase Invoice Item` where item_code = %s''', (val.name), as_list=1)
71 purchases = destructure_tuple_of_tuples(data)
72
73 value = 0
74 if(field=="total_request"):
75 value = len(requests)
76 elif(field=="total_purchase"):
77 value = len(purchases)
78 elif(field=="avg_price"):
79 value=avg_price
80 item_obj = {"name": val.name,
81 "total_request":len(requests),
82 "total_purchase": len(purchases),
83 "avg_price": get_formatted_value(avg_price),
84 "href":"#Form/Item/" + val.name,
85 "value": value}
86 items.append(item_obj)
87
88 print(items)
89
90 items.sort(key=lambda k: k['value'], reverse=True)
91 return items
92
93def get_all_suppliers(doctype, filters, items, field, start=0, limit=20):
94 """return all suppliers"""
95
96 x = frappe.get_list(doctype, filters=filters, limit_start=start, limit_page_length=limit)
97
98 for val in x:
99
100 info = get_dashboard_info(doctype, val.name)
101 value = 0
102 if(field=="annual_billing"):
103 value = info["billing_this_year"]
104 elif(field=="total_unpaid"):
105 value = abs(info["total_unpaid"])
106
107 item_obj = {"name": val.name,
108 "annual_billing": get_formatted_value(info["billing_this_year"]),
109 "total_unpaid": get_formatted_value(abs(info["total_unpaid"])),
110 "href":"#Form/Supplier/" + val.name,
111 "value": value}
112 items.append(item_obj)
113
114 items.sort(key=lambda k: k['value'], reverse=True)
115 return items
116
117def get_all_sales_partner(doctype, filters, items, field, start=0, limit=20):
118 """return all sales partner"""
119
120 x = frappe.get_list(doctype, fields=["name", "commission_rate", "modified"], filters=filters, limit_start=start, limit_page_length=limit)
121 for val in x:
122 y = frappe.db.sql('''select target_qty, target_amount from `tabTarget Detail` where parent = %s''', (val.name), as_dict=1)
123 target_qty = sum([f["target_qty"] for f in y])
124 target_amount = sum([f["target_amount"] for f in y])
125
126 value = 0
127 if(field=="commission_rate"):
128 value = val.commission_rate
129 elif(field=="target_qty"):
130 value = target_qty
131 elif(field=="target_amount"):
132 value = target_qty
133
134 item_obj = {"name": val.name,
135 "commission_rate": get_formatted_value(val.commission_rate, False),
136 "target_qty": target_qty,
137 "target_amount": get_formatted_value(target_qty),
138 "href":"#Form/Sales Partner/" + val.name,
139 "value": value}
140 items.append(item_obj)
141
142 items.sort(key=lambda k: k['value'], reverse=True)
143 return items
Ayush Shuklaa111f782017-06-20 13:04:45 +0530144
145
Ayush Shuklaa111f782017-06-20 13:04:45 +0530146def destructure_tuple_of_tuples(tup_of_tup):
147 """return tuple(tuples) as list"""
148 return [y for x in tup_of_tup for y in x]
149
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +0530150def get_date_from_string(seleted_timespan):
Ayush Shuklaa111f782017-06-20 13:04:45 +0530151 """return string for ex:this week as date:string"""
152 days = months = years = 0
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +0530153 if "month" == seleted_timespan.lower():
Ayush Shuklaa111f782017-06-20 13:04:45 +0530154 months = -1
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +0530155 elif "quarter" == seleted_timespan.lower():
Ayush Shuklaa111f782017-06-20 13:04:45 +0530156 months = -3
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +0530157 elif "year" == seleted_timespan.lower():
Ayush Shuklaa111f782017-06-20 13:04:45 +0530158 years = -1
159 else:
160 days = -7
161
162 return add_to_date(None, years=years, months=months, days=days, as_string=True, as_datetime=True)
163
164def get_filter_list(selected_filter):
165 """return list of keys"""
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +0530166 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 +0530167
168def get_avg(items):
169 """return avg of list items"""
170 length = len(items)
171 if length > 0:
172 return sum(items) / length
173 return 0
174
175def get_formatted_value(value, add_symbol=True):
176 """return formatted value"""
Ayush Shuklaa111f782017-06-20 13:04:45 +0530177 if not add_symbol:
Prateeksha Singh9b4f3cf2017-09-18 16:41:04 +0530178 return '{:.{pre}f}'.format(value, pre=(get_currency_precision() or 2))
179 currency_precision = get_currency_precision() or 2
180 company = frappe.db.get_default("company")
181 currency = frappe.get_doc("Company", company).default_currency or frappe.boot.sysdefaults.currency
182 return fmt_money(value, currency_precision, currency)