Ayush Shukla | a111f78 | 2017-06-20 13:04:45 +0530 | [diff] [blame] | 1 | # Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors |
| 2 | # MIT License. See license.txt |
| 3 | |
| 4 | from __future__ import unicode_literals, print_function |
| 5 | import frappe |
| 6 | import json |
| 7 | from operator import itemgetter |
| 8 | from frappe.utils import add_to_date |
| 9 | from erpnext.accounts.party import get_dashboard_info |
| 10 | from erpnext.accounts.utils import get_currency_precision |
| 11 | |
| 12 | @frappe.whitelist() |
| 13 | def get_leaderboard(obj): |
| 14 | """return top 10 items for that doctype based on conditions""" |
| 15 | obj = frappe._dict(json.loads(obj)) |
| 16 | |
| 17 | doctype = obj.selected_doctype |
| 18 | timeline = obj.selected_timeline |
| 19 | filters = {"modified":(">=", get_date_from_string(timeline))} |
| 20 | items = [] |
| 21 | if doctype == "Customer": |
| 22 | items = get_all_customers(doctype, filters, []) |
| 23 | elif doctype == "Item": |
| 24 | items = get_all_items(doctype, filters, []) |
| 25 | elif doctype == "Supplier": |
| 26 | items = get_all_suppliers(doctype, filters, []) |
| 27 | elif doctype == "Sales Partner": |
| 28 | items = get_all_sales_partner(doctype, filters, []) |
| 29 | |
| 30 | if len(items) > 0: |
| 31 | return filter_leaderboard_items(obj, items) |
| 32 | return [] |
| 33 | |
| 34 | |
| 35 | # filters start |
| 36 | def filter_leaderboard_items(obj, items): |
| 37 | """return items based on seleted filters""" |
| 38 | |
| 39 | reverse = False if obj.selected_filter_item and obj.selected_filter_item["value"] == "ASC" else True |
| 40 | # key : (x[field1], x[field2]) while sorting on 2 values |
| 41 | filtered_list = [] |
| 42 | selected_field = obj.selected_filter_item and obj.selected_filter_item["field"] |
| 43 | if selected_field: |
| 44 | filtered_list = sorted(items, key=itemgetter(selected_field), reverse=reverse) |
| 45 | value = items[0].get(selected_field) |
| 46 | |
| 47 | allowed = isinstance(value, unicode) or isinstance(value, str) |
| 48 | # now sort by length |
| 49 | if allowed and '$' in value: |
| 50 | filtered_list.sort(key= lambda x: len(x[selected_field]), reverse=reverse) |
| 51 | |
| 52 | # return only 10 items' |
| 53 | return filtered_list[:10] |
| 54 | |
| 55 | # filters end |
| 56 | |
| 57 | |
| 58 | # utils start |
| 59 | def destructure_tuple_of_tuples(tup_of_tup): |
| 60 | """return tuple(tuples) as list""" |
| 61 | return [y for x in tup_of_tup for y in x] |
| 62 | |
| 63 | def get_date_from_string(seleted_timeline): |
| 64 | """return string for ex:this week as date:string""" |
| 65 | days = months = years = 0 |
| 66 | if "month" == seleted_timeline.lower(): |
| 67 | months = -1 |
| 68 | elif "quarter" == seleted_timeline.lower(): |
| 69 | months = -3 |
| 70 | elif "year" == seleted_timeline.lower(): |
| 71 | years = -1 |
| 72 | else: |
| 73 | days = -7 |
| 74 | |
| 75 | return add_to_date(None, years=years, months=months, days=days, as_string=True, as_datetime=True) |
| 76 | |
| 77 | def get_filter_list(selected_filter): |
| 78 | """return list of keys""" |
| 79 | return map((lambda y : y["field"]), filter(lambda x : not (x["field"] == "title" or x["field"] == "modified"), selected_filter)) |
| 80 | |
| 81 | def get_avg(items): |
| 82 | """return avg of list items""" |
| 83 | length = len(items) |
| 84 | if length > 0: |
| 85 | return sum(items) / length |
| 86 | return 0 |
| 87 | |
| 88 | def get_formatted_value(value, add_symbol=True): |
| 89 | """return formatted value""" |
| 90 | currency_precision = get_currency_precision() or 2 |
| 91 | if not add_symbol: |
| 92 | return '{:.{pre}f}'.format(value, pre=currency_precision) |
| 93 | |
| 94 | company = frappe.db.get_default("company") or frappe.get_all("Company")[0].name |
| 95 | currency = frappe.get_doc("Company", company).default_currency or frappe.boot.sysdefaults.currency; |
| 96 | currency_symbol = frappe.db.get_value("Currency", currency, "symbol") |
| 97 | return currency_symbol + ' ' + '{:.{pre}f}'.format(value, pre=currency_precision) |
| 98 | |
| 99 | # utils end |
| 100 | |
| 101 | |
| 102 | # get data |
| 103 | def get_all_customers(doctype, filters, items, start=0, limit=100): |
| 104 | """return all customers""" |
| 105 | |
| 106 | x = frappe.get_list(doctype, fields=["name", "modified"], filters=filters, limit_start=start, limit_page_length=limit) |
| 107 | |
| 108 | for val in x: |
| 109 | y = dict(frappe.db.sql('''select name, grand_total from `tabSales Invoice` where customer = %s''', (val.name))) |
| 110 | invoice_list = y.keys() |
| 111 | if len(invoice_list) > 0: |
| 112 | item_count = frappe.db.sql('''select count(name) from `tabSales Invoice Item` where parent in (%s)''' % ", ".join( |
| 113 | ['%s'] * len(invoice_list)), tuple(invoice_list)) |
| 114 | items.append({"title": val.name, |
| 115 | "total_amount": get_formatted_value(sum(y.values())), |
| 116 | "href":"#Form/Customer/" + val.name, |
| 117 | "total_item_purchased": sum(destructure_tuple_of_tuples(item_count)), |
| 118 | "modified": str(val.modified)}) |
| 119 | if len(x) > 99: |
| 120 | start = start + 1 |
| 121 | return get_all_customers(doctype, filters, items, start=start) |
| 122 | else: |
| 123 | return items |
| 124 | |
| 125 | def get_all_items(doctype, filters, items, start=0, limit=100): |
| 126 | """return all items""" |
| 127 | |
| 128 | x = frappe.get_list(doctype, fields=["name", "modified"], filters=filters, limit_start=start, limit_page_length=limit) |
| 129 | for val in x: |
| 130 | data = frappe.db.sql('''select item_code from `tabMaterial Request Item` where item_code = %s''', (val.name), as_list=1) |
| 131 | requests = destructure_tuple_of_tuples(data) |
| 132 | data = frappe.db.sql('''select price_list_rate from `tabItem Price` where item_code = %s''', (val.name), as_list=1) |
| 133 | avg_price = get_avg(destructure_tuple_of_tuples(data)) |
| 134 | data = frappe.db.sql('''select item_code from `tabPurchase Invoice Item` where item_code = %s''', (val.name), as_list=1) |
| 135 | purchases = destructure_tuple_of_tuples(data) |
| 136 | |
| 137 | items.append({"title": val.name, |
| 138 | "total_request":len(requests), |
| 139 | "total_purchase": len(purchases), "href":"#Form/Item/" + val.name, |
| 140 | "avg_price": get_formatted_value(avg_price), |
| 141 | "modified": val.modified}) |
| 142 | if len(x) > 99: |
| 143 | return get_all_items(doctype, filters, items, start=start) |
| 144 | else: |
| 145 | return items |
| 146 | |
| 147 | def get_all_suppliers(doctype, filters, items, start=0, limit=100): |
| 148 | """return all suppliers""" |
| 149 | |
| 150 | x = frappe.get_list(doctype, fields=["name", "modified"], filters=filters, limit_start=start, limit_page_length=limit) |
| 151 | |
| 152 | for val in x: |
| 153 | info = get_dashboard_info(doctype, val.name) |
| 154 | items.append({"title": val.name, |
| 155 | "annual_billing": get_formatted_value(info["billing_this_year"]), |
| 156 | "total_unpaid": get_formatted_value(abs(info["total_unpaid"])), |
| 157 | "href":"#Form/Supplier/" + val.name, |
| 158 | "modified": val.modified}) |
| 159 | |
| 160 | if len(x) > 99: |
| 161 | return get_all_suppliers(doctype, filters, items, start=start) |
| 162 | else: |
| 163 | return items |
| 164 | |
| 165 | def get_all_sales_partner(doctype, filters, items, start=0, limit=100): |
| 166 | """return all sales partner""" |
| 167 | |
| 168 | x = frappe.get_list(doctype, fields=["name", "commission_rate", "modified"], filters=filters, limit_start=start, limit_page_length=limit) |
| 169 | for val in x: |
| 170 | y = frappe.db.sql('''select target_qty, target_amount from `tabTarget Detail` where parent = %s''', (val.name), as_dict=1) |
| 171 | target_qty = sum([f["target_qty"] for f in y]) |
| 172 | target_amount = sum([f["target_amount"] for f in y]) |
| 173 | items.append({"title": val.name, |
| 174 | "commission_rate": get_formatted_value(val.commission_rate, False), |
| 175 | "target_qty": target_qty, |
| 176 | "target_amount": get_formatted_value(target_amount), |
| 177 | "href":"#Form/Sales Partner/" + val.name, |
| 178 | "modified": val.modified}) |
| 179 | if len(x) > 99: |
| 180 | return get_all_sales_partner(doctype, filters, items, start=start) |
| 181 | else: |
| 182 | return items |