Merge branch 'develop' into shopify

This commit is contained in:
Saurabh 2019-09-30 19:08:44 +05:30 committed by GitHub
commit 039679cad1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 731 additions and 1567 deletions

View File

@ -3,7 +3,7 @@
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe import _, scrub
from frappe.utils import flt, cint
from erpnext.accounts.party import get_partywise_advanced_payment_amount
from erpnext.accounts.report.accounts_receivable.accounts_receivable import ReceivablePayableReport
@ -40,7 +40,7 @@ class AccountsReceivableSummary(ReceivablePayableReport):
row.party = party
if self.party_naming_by == "Naming Series":
row.party_name = frappe.get_cached_value(self.party_type, party, [self.party_type + "_name"])
row.party_name = frappe.get_cached_value(self.party_type, party, scrub(self.party_type) + "_name")
row.update(party_dict)

View File

@ -0,0 +1,30 @@
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
/* eslint-disable */
frappe.query_reports["Fixed Asset Register"] = {
"filters": [
{
fieldname:"company",
label: __("Company"),
fieldtype: "Link",
options: "Company",
default: frappe.defaults.get_user_default("Company"),
reqd: 1
},
{
fieldname:"status",
label: __("Status"),
fieldtype: "Select",
options: "In Store\nDisposed",
default: 'In Store',
reqd: 1
},
{
fieldname:"finance_book",
label: __("Finance Book"),
fieldtype: "Link",
options: "Finance Book"
},
]
};

View File

@ -0,0 +1,27 @@
{
"add_total_row": 0,
"creation": "2019-09-23 16:35:02.836134",
"disable_prepared_report": 0,
"disabled": 0,
"docstatus": 0,
"doctype": "Report",
"idx": 0,
"is_standard": "Yes",
"modified": "2019-09-23 16:35:02.836134",
"modified_by": "Administrator",
"module": "Assets",
"name": "Fixed Asset Register",
"owner": "Administrator",
"prepared_report": 0,
"ref_doctype": "Asset",
"report_name": "Fixed Asset Register",
"report_type": "Script Report",
"roles": [
{
"role": "Accounts User"
},
{
"role": "Quality Manager"
}
]
}

View File

@ -0,0 +1,172 @@
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
def execute(filters=None):
filters = frappe._dict(filters or {})
columns = get_columns(filters)
data = get_data(filters)
return columns, data
def get_columns(filters):
return [
{
"label": _("Asset Id"),
"fieldtype": "Link",
"fieldname": "asset_id",
"options": "Asset",
"width": 100
},
{
"label": _("Asset Name"),
"fieldtype": "Data",
"fieldname": "asset_name",
"width": 140
},
{
"label": _("Asset Category"),
"fieldtype": "Link",
"fieldname": "asset_category",
"options": "Asset Category",
"width": 100
},
{
"label": _("Status"),
"fieldtype": "Data",
"fieldname": "status",
"width": 90
},
{
"label": _("Cost Center"),
"fieldtype": "Link",
"fieldname": "cost_center",
"options": "Cost Center",
"width": 100
},
{
"label": _("Department"),
"fieldtype": "Link",
"fieldname": "department",
"options": "Department",
"width": 100
},
{
"label": _("Location"),
"fieldtype": "Link",
"fieldname": "location",
"options": "Location",
"width": 100
},
{
"label": _("Purchase Date"),
"fieldtype": "Date",
"fieldname": "purchase_date",
"width": 90
},
{
"label": _("Gross Purchase Amount"),
"fieldname": "gross_purchase_amount",
"options": "Currency",
"width": 90
},
{
"label": _("Vendor Name"),
"fieldtype": "Data",
"fieldname": "vendor_name",
"width": 100
},
{
"label": _("Available For Use Date"),
"fieldtype": "Date",
"fieldname": "available_for_use_date",
"width": 90
},
{
"label": _("Current Value"),
"fieldname": "current_value",
"options": "Currency",
"width": 90
},
]
def get_conditions(filters):
conditions = {'docstatus': 1}
status = filters.status
if filters.company:
conditions["company"] = filters.company
# In Store assets are those that are not sold or scrapped
operand = 'not in'
if status not in 'In Store':
operand = 'in'
conditions['status'] = (operand, ['Sold', 'Scrapped'])
return conditions
def get_data(filters):
data = []
conditions = get_conditions(filters)
current_value_map = get_finance_book_value_map(filters.finance_book)
pr_supplier_map = get_purchase_receipt_supplier_map()
pi_supplier_map = get_purchase_invoice_supplier_map()
assets_record = frappe.db.get_all("Asset",
filters=conditions,
fields=["name", "asset_name", "department", "cost_center", "purchase_receipt",
"asset_category", "purchase_date", "gross_purchase_amount", "location",
"available_for_use_date", "status", "purchase_invoice"])
for asset in assets_record:
if current_value_map.get(asset.name) is not None:
row = {
"asset_id": asset.name,
"asset_name": asset.asset_name,
"status": asset.status,
"department": asset.department,
"cost_center": asset.cost_center,
"vendor_name": pr_supplier_map.get(asset.purchase_receipt) or pi_supplier_map.get(asset.purchase_invoice),
"gross_purchase_amount": asset.gross_purchase_amount,
"available_for_use_date": asset.available_for_use_date,
"location": asset.location,
"asset_category": asset.asset_category,
"purchase_date": asset.purchase_date,
"current_value": current_value_map.get(asset.name)
}
data.append(row)
return data
def get_finance_book_value_map(finance_book=''):
return frappe._dict(frappe.db.sql(''' Select
parent, value_after_depreciation
FROM `tabAsset Finance Book`
WHERE
parentfield='finance_books'
AND finance_book=%s''', (finance_book)))
def get_purchase_receipt_supplier_map():
return frappe._dict(frappe.db.sql(''' Select
pr.name, pr.supplier
FROM `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pri
WHERE
pri.parent = pr.name
AND pri.is_fixed_asset=1
AND pr.docstatus=1
AND pr.is_return=0'''))
def get_purchase_invoice_supplier_map():
return frappe._dict(frappe.db.sql(''' Select
pi.name, pi.supplier
FROM `tabPurchase Invoice` pi, `tabPurchase Invoice Item` pii
WHERE
pii.parent = pi.name
AND pii.is_fixed_asset=1
AND pi.docstatus=1
AND pi.is_return=0'''))

File diff suppressed because it is too large Load Diff

View File

@ -4,10 +4,7 @@
from __future__ import unicode_literals
import frappe, time, dateutil, math, csv
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from six import StringIO
import erpnext.erpnext_integrations.doctype.amazon_mws_settings.amazon_mws_api as mws
from frappe import _
@ -26,7 +23,7 @@ def get_products_details():
listings_response = reports.get_report(report_id=report_id)
#Get ASIN Codes
string_io = StringIO(listings_response.original)
string_io = StringIO(frappe.safe_decode(listings_response.original))
csv_rows = list(csv.reader(string_io, delimiter=str('\t')))
asin_list = list(set([row[1] for row in csv_rows[1:]]))
#break into chunks of 10
@ -294,7 +291,8 @@ def create_sales_order(order_json,after_date):
so.submit()
except Exception as e:
frappe.log_error(message=e, title="Create Sales Order")
import traceback
frappe.log_error(message=traceback.format_exc(), title="Create Sales Order")
def create_customer(order_json):
order_customer_name = ""
@ -451,7 +449,7 @@ def get_charges_and_fees(market_place_order_id):
shipment_item_list = return_as_list(shipment_event.ShipmentEvent.ShipmentItemList.ShipmentItem)
for shipment_item in shipment_item_list:
charges, fees = []
charges, fees = [], []
if 'ItemChargeList' in shipment_item.keys():
charges = return_as_list(shipment_item.ItemChargeList.ChargeComponent)

View File

@ -65,7 +65,8 @@ def calc_md5(string):
"""
md = hashlib.md5()
md.update(string)
return base64.encodestring(md.digest()).strip('\n')
return base64.encodestring(md.digest()).strip('\n') if six.PY2 \
else base64.encodebytes(md.digest()).decode().strip()
def remove_empty(d):
"""
@ -87,8 +88,7 @@ class DictWrapper(object):
self.original = xml
self._rootkey = rootkey
self._mydict = xml_utils.xml2dict().fromstring(remove_namespace(xml))
self._response_dict = self._mydict.get(self._mydict.keys()[0],
self._mydict)
self._response_dict = self._mydict.get(list(self._mydict)[0], self._mydict)
@property
def parsed(self):

View File

@ -42,6 +42,8 @@ notification_config = "erpnext.startup.notifications.get_notification_config"
get_help_messages = "erpnext.utilities.activation.get_help_messages"
get_user_progress_slides = "erpnext.utilities.user_progress.get_user_progress_slides"
update_and_get_user_progress = "erpnext.utilities.user_progress_utils.update_default_domain_actions_and_get_state"
leaderboards = "erpnext.startup.leaderboard.get_leaderboards"
on_session_creation = "erpnext.shopping_cart.utils.set_cart_count"
on_logout = "erpnext.shopping_cart.utils.clear_cart_count"

View File

@ -60,7 +60,10 @@ def get_data(filters, leave_types):
data = []
for employee in active_employees:
leave_approvers = department_approver_map.get(employee.department_name, []).append(employee.leave_approver)
leave_approvers = department_approver_map.get(employee.department_name, [])
if employee.leave_approver:
leave_approvers.append(employee.leave_approver)
if (len(leave_approvers) and user in leave_approvers) or (user in ["Administrator", employee.user_id]) or ("HR Manager" in frappe.get_roles(user)):
row = [employee.name, employee.employee_name, employee.department]

View File

@ -195,6 +195,7 @@ class ProductionPlan(Document):
for data in self.po_items:
if data.name == production_plan_item:
data.produced_qty = produced_qty
data.pending_qty = data.planned_qty - data.produced_qty
data.db_update()
self.calculate_total_produced_qty()

View File

@ -545,12 +545,15 @@ erpnext.work_order = {
get_max_transferable_qty: (frm, purpose) => {
let max = 0;
if (frm.doc.skip_transfer) return max;
if (frm.doc.skip_transfer) {
max = flt(frm.doc.qty) - flt(frm.doc.produced_qty);
} else {
if (purpose === 'Manufacture') {
max = flt(frm.doc.material_transferred_for_manufacturing) - flt(frm.doc.produced_qty);
} else {
max = flt(frm.doc.qty) - flt(frm.doc.material_transferred_for_manufacturing);
}
}
return flt(max, precision('qty'));
},

View File

@ -108,7 +108,7 @@
"fieldname": "percent_complete_method",
"fieldtype": "Select",
"label": "% Complete Method",
"options": "Task Completion\nTask Progress\nTask Weight"
"options": "Manual\nTask Completion\nTask Progress\nTask Weight"
},
{
"bold": 1,

View File

@ -87,6 +87,11 @@ class Project(Document):
frappe.db.set_value("Sales Order", self.sales_order, "project", self.name)
def update_percent_complete(self):
if self.percent_complete_method == "Manual":
if self.status == "Completed":
self.percent_complete = 100
return
total = frappe.db.count('Task', dict(project=self.name))
if not total:

View File

@ -19,6 +19,9 @@
{% if(contact_list[i].phone) { %}
{%= __("Phone") %}: {%= contact_list[i].phone %}<span class="text-muted"> ({%= __("Primary") %})</span><br>
{% endif %}
{% if(contact_list[i].mobile_no) { %}
{%= __("Mobile No") %}: {%= contact_list[i].mobile_no %}<span class="text-muted"> ({%= __("Primary") %})</span><br>
{% endif %}
{% if(contact_list[i].phone_nos) { %}
{% for(var j=0, k=contact_list[i].phone_nos.length; j<k; j++) { %}
{%= __("Phone") %}: {%= contact_list[i].phone_nos[j].phone %}<br>

View File

@ -0,0 +1,177 @@
from __future__ import unicode_literals, print_function
import frappe
from frappe.utils import cint
def get_leaderboards():
leaderboards = {
"Customer": {
"fields": [
{'fieldname': 'total_sales_amount', 'fieldtype': 'Currency'},
'total_qty_sold',
{'fieldname': 'outstanding_amount', 'fieldtype': 'Currency'}
],
"method": "erpnext.startup.leaderboard.get_all_customers",
},
"Item": {
"fields": [
{'fieldname': 'total_sales_amount', 'fieldtype': 'Currency'},
'total_qty_sold',
{'fieldname': 'total_purchase_amount', 'fieldtype': 'Currency'},
'total_qty_purchased',
'available_stock_qty',
{'fieldname': 'available_stock_value', 'fieldtype': 'Currency'}
],
"method": "erpnext.startup.leaderboard.get_all_items",
},
"Supplier": {
"fields": [
{'fieldname': 'total_purchase_amount', 'fieldtype': 'Currency'},
'total_qty_purchased',
{'fieldname': 'outstanding_amount', 'fieldtype': 'Currency'}
],
"method": "erpnext.startup.leaderboard.get_all_suppliers",
},
"Sales Partner": {
"fields": [
{'fieldname': 'total_sales_amount', 'fieldtype': 'Currency'},
{'fieldname': 'total_commission', 'fieldtype': 'Currency'}
],
"method": "erpnext.startup.leaderboard.get_all_sales_partner",
},
"Sales Person": {
"fields": [
{'fieldname': 'total_sales_amount', 'fieldtype': 'Currency'}
],
"method": "erpnext.startup.leaderboard.get_all_sales_person",
}
}
return leaderboards
@frappe.whitelist()
def get_all_customers(from_date, company, field, limit = None):
if field == "outstanding_amount":
filters = [['docstatus', '=', '1'], ['company', '=', company]]
if from_date:
filters.append(['posting_date', '>=', from_date])
return frappe.db.get_all('Sales Invoice',
fields = ['customer as name', 'sum(outstanding_amount) as value'],
filters = filters,
group_by = 'customer',
order_by = 'value desc',
limit = limit
)
else:
if field == "total_sales_amount":
select_field = "sum(so_item.base_net_amount)"
elif field == "total_qty_sold":
select_field = "sum(so_item.stock_qty)"
return frappe.db.sql("""
select so.customer as name, {0} as value
FROM `tabSales Order` as so JOIN `tabSales Order Item` as so_item
ON so.name = so_item.parent
where so.docstatus = 1 and so.transaction_date >= %s and so.company = %s
group by so.customer
order by value DESC
limit %s
""".format(select_field), (from_date, company, cint(limit)), as_dict=1) #nosec
@frappe.whitelist()
def get_all_items(from_date, company, field, limit = None):
if field in ("available_stock_qty", "available_stock_value"):
select_field = "sum(actual_qty)" if field=="available_stock_qty" else "sum(stock_value)"
return frappe.db.get_all('Bin',
fields = ['item_code as name', '{0} as value'.format(select_field)],
group_by = 'item_code',
order_by = 'value desc',
limit = limit
)
else:
if field == "total_sales_amount":
select_field = "sum(order_item.base_net_amount)"
select_doctype = "Sales Order"
elif field == "total_purchase_amount":
select_field = "sum(order_item.base_net_amount)"
select_doctype = "Purchase Order"
elif field == "total_qty_sold":
select_field = "sum(order_item.stock_qty)"
select_doctype = "Sales Order"
elif field == "total_qty_purchased":
select_field = "sum(order_item.stock_qty)"
select_doctype = "Purchase Order"
return frappe.db.sql("""
select order_item.item_code as name, {0} as value
from `tab{1}` sales_order join `tab{1} Item` as order_item
on sales_order.name = order_item.parent
where sales_order.docstatus = 1
and sales_order.company = %s and sales_order.transaction_date >= %s
group by order_item.item_code
order by value desc
limit %s
""".format(select_field, select_doctype), (company, from_date, cint(limit)), as_dict=1) #nosec
@frappe.whitelist()
def get_all_suppliers(from_date, company, field, limit = None):
if field == "outstanding_amount":
filters = [['docstatus', '=', '1'], ['company', '=', company]]
if from_date:
filters.append(['posting_date', '>=', from_date])
return frappe.db.get_all('Purchase Invoice',
fields = ['supplier as name', 'sum(outstanding_amount) as value'],
filters = filters,
group_by = 'supplier',
order_by = 'value desc',
limit = limit
)
else:
if field == "total_purchase_amount":
select_field = "sum(purchase_order_item.base_net_amount)"
elif field == "total_qty_purchased":
select_field = "sum(purchase_order_item.stock_qty)"
return frappe.db.sql("""
select purchase_order.supplier as name, {0} as value
FROM `tabPurchase Order` as purchase_order LEFT JOIN `tabPurchase Order Item`
as purchase_order_item ON purchase_order.name = purchase_order_item.parent
where purchase_order.docstatus = 1 and purchase_order.modified >= %s
and purchase_order.company = %s
group by purchase_order.supplier
order by value DESC
limit %s""".format(select_field), (from_date, company, cint(limit)), as_dict=1) #nosec
@frappe.whitelist()
def get_all_sales_partner(from_date, company, field, limit = None):
if field == "total_sales_amount":
select_field = "sum(`base_net_total`)"
elif field == "total_commission":
select_field = "sum(`total_commission`)"
filters = {
'sales_partner': ['!=', ''],
'docstatus': 1,
'company': company
}
if from_date:
filters['transaction_date'] = ['>=', from_date]
return frappe.get_list('Sales Order', fields=[
'`sales_partner` as name',
'{} as value'.format(select_field),
], filters=filters, group_by='sales_partner', order_by='value DESC', limit=limit)
@frappe.whitelist()
def get_all_sales_person(from_date, company, field = None, limit = 0):
return frappe.db.sql("""
select sales_team.sales_person as name, sum(sales_order.base_net_total) as value
from `tabSales Order` as sales_order join `tabSales Team` as sales_team
on sales_order.name = sales_team.parent and sales_team.parenttype = 'Sales Order'
where sales_order.docstatus = 1
and sales_order.transaction_date >= %s
and sales_order.company = %s
group by sales_team.sales_person
order by value DESC
limit %s
""", (from_date, company, cint(limit)), as_dict=1)

View File

@ -115,12 +115,12 @@ erpnext.stock.PurchaseReceiptController = erpnext.buying.BuyingController.extend
cur_frm.add_custom_button(__("Close"), this.close_purchase_receipt, __("Status"))
}
cur_frm.add_custom_button(__('Return'), this.make_purchase_return, __('Create'));
cur_frm.add_custom_button(__('Purchase Return'), this.make_purchase_return, __('Create'));
cur_frm.add_custom_button(__('Make Stock Entry'), cur_frm.cscript['Make Stock Entry'], __('Create'));
if(flt(this.frm.doc.per_billed) < 100) {
cur_frm.add_custom_button(__('Invoice'), this.make_purchase_invoice, __('Create'));
cur_frm.add_custom_button(__('Purchase Invoice'), this.make_purchase_invoice, __('Create'));
}
cur_frm.add_custom_button(__('Retention Stock Entry'), this.make_retention_stock_entry, __('Create'));

View File

@ -107,7 +107,7 @@ def get_item_details(items, sl_entries, include_uom):
if include_uom:
cf_field = ", ucd.conversion_factor"
cf_join = "left join `tabUOM Conversion Detail` ucd on ucd.parent=item.name and ucd.uom='%s'" \
% frappe.db.escape(include_uom)
% (include_uom)
res = frappe.db.sql("""
select

View File

@ -253,31 +253,40 @@ def update_included_uom_in_report(columns, result, include_uom, conversion_facto
return
convertible_cols = {}
for col_idx in reversed(range(0, len(columns))):
col = columns[col_idx]
if isinstance(col, dict) and col.get("convertible") in ['rate', 'qty']:
convertible_cols[col_idx] = col['convertible']
columns.insert(col_idx+1, col.copy())
columns[col_idx+1]['fieldname'] += "_alt"
if convertible_cols[col_idx] == 'rate':
columns[col_idx+1]['label'] += " (per {})".format(include_uom)
else:
columns[col_idx+1]['label'] += " ({})".format(include_uom)
is_dict_obj = False
if isinstance(result[0], dict):
is_dict_obj = True
convertible_columns = {}
for idx, d in enumerate(columns):
key = d.get("fieldname") if is_dict_obj else idx
if d.get("convertible"):
convertible_columns.setdefault(key, d.get("convertible"))
# Add new column to show qty/rate as per the selected UOM
columns.insert(idx+1, {
'label': "{0} (per {1})".format(d.get("label"), include_uom),
'fieldname': "{0}_{1}".format(d.get("fieldname"), frappe.scrub(include_uom)),
'fieldtype': 'Currency' if d.get("convertible") == 'rate' else 'Float'
})
for row_idx, row in enumerate(result):
new_row = []
for col_idx, d in enumerate(row):
new_row.append(d)
if col_idx in convertible_cols:
if conversion_factors[row_idx]:
if convertible_cols[col_idx] == 'rate':
new_row.append(flt(d) * conversion_factors[row_idx])
else:
new_row.append(flt(d) / conversion_factors[row_idx])
else:
new_row.append(None)
data = row.items() if is_dict_obj else enumerate(row)
for key, value in data:
if not key in convertible_columns or not conversion_factors[row_idx]:
continue
result[row_idx] = new_row
if convertible_columns.get(key) == 'rate':
new_value = flt(value) * conversion_factors[row_idx]
else:
new_value = flt(value) / conversion_factors[row_idx]
if not is_dict_obj:
row.insert(key+1, new_value)
else:
new_key = "{0}_{1}".format(key, frappe.scrub(include_uom))
row[new_key] = new_value
def get_available_serial_nos(item_code, warehouse):
return frappe.get_all("Serial No", filters = {'item_code': item_code,

View File

@ -1,54 +0,0 @@
.list-filters {
overflow-y: hidden;
padding: 5px
}
.list-filter-item {
min-width: 150px;
float: left;
margin:5px;
}
.list-item_content{
flex: 1;
padding-right: 15px;
align-items: center;
}
.select-time, .select-doctype, .select-filter, .select-sort {
background: #f0f4f7;
}
.select-time:focus, .select-doctype:focus, .select-filter:focus, .select-sort:focus {
background: #f0f4f7;
}
.header-btn-base{
border:none;
outline:0;
vertical-align:middle;
overflow:hidden;
text-decoration:none;
color:inherit;
background-color:inherit;
cursor:pointer;
white-space:nowrap;
}
.header-btn-grey,.header-btn-grey:hover{
color:#000!important;
background-color:#bbb!important
}
.header-btn-round{
border-radius:4px
}
.item-title-bold{
font-weight: bold;
}
/*
.header-btn-base:hover {
box-shadow:0 8px 16px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19)
}*/

View File

@ -1,307 +0,0 @@
frappe.pages["leaderboard"].on_page_load = function (wrapper) {
frappe.leaderboard = new frappe.Leaderboard(wrapper);
}
frappe.Leaderboard = Class.extend({
init: function (parent) {
frappe.ui.make_app_page({
parent: parent,
title: "Leaderboard",
single_column: false
});
this.parent = parent;
this.page = this.parent.page;
this.page.sidebar.html(`<ul class="module-sidebar-nav overlay-sidebar nav nav-pills nav-stacked"></ul>`);
this.$sidebar_list = this.page.sidebar.find('ul');
// const list of doctypes
this.doctypes = ["Customer", "Item", "Supplier", "Sales Partner","Sales Person"];
this.timespans = ["Week", "Month", "Quarter", "Year"];
this.filters = {
"Customer": ["total_sales_amount", "total_qty_sold", "outstanding_amount", ],
"Item": ["total_sales_amount", "total_qty_sold", "total_purchase_amount",
"total_qty_purchased", "available_stock_qty", "available_stock_value"],
"Supplier": ["total_purchase_amount", "total_qty_purchased", "outstanding_amount"],
"Sales Partner": ["total_sales_amount", "total_commission"],
"Sales Person": ["total_sales_amount"],
};
// for saving current selected filters
// TODO: revert to 0 index for doctype and timespan, and remove preset down
const _initial_doctype = this.doctypes[0];
const _initial_timespan = this.timespans[0];
const _initial_filter = this.filters[_initial_doctype];
this.options = {
selected_doctype: _initial_doctype,
selected_filter: _initial_filter,
selected_filter_item: _initial_filter[0],
selected_timespan: _initial_timespan,
};
this.message = null;
this.make();
},
make: function () {
var me = this;
var $container = $(`<div class="leaderboard page-main-content">
<div class="leaderboard-graph"></div>
<div class="leaderboard-list"></div>
</div>`).appendTo(this.page.main);
this.$graph_area = $container.find('.leaderboard-graph');
this.doctypes.map(doctype => {
this.get_sidebar_item(doctype).appendTo(this.$sidebar_list);
});
this.company_select = this.page.add_field({
fieldname: 'company',
label: __('Company'),
fieldtype:'Link',
options:'Company',
default:frappe.defaults.get_default('company'),
reqd: 1,
change: function() {
me.options.selected_company = this.value;
me.make_request($container);
}
});
this.timespan_select = this.page.add_select(__("Timespan"),
this.timespans.map(d => {
return {"label": __(d), value: d }
})
);
this.type_select = this.page.add_select(__("Type"),
me.options.selected_filter.map(d => {
return {"label": __(frappe.model.unscrub(d)), value: d }
})
);
this.$sidebar_list.on('click', 'li', function(e) {
let $li = $(this);
let doctype = $li.find('span').attr("doctype-value");
me.options.selected_company = frappe.defaults.get_default('company');
me.options.selected_doctype = doctype;
me.options.selected_filter = me.filters[doctype];
me.options.selected_filter_item = me.filters[doctype][0];
me.type_select.empty().add_options(
me.options.selected_filter.map(d => {
return {"label": __(frappe.model.unscrub(d)), value: d }
})
);
me.$sidebar_list.find('li').removeClass('active');
$li.addClass('active');
me.make_request($container);
});
this.timespan_select.on("change", function() {
me.options.selected_timespan = this.value;
me.make_request($container);
});
this.type_select.on("change", function() {
me.options.selected_filter_item = this.value
me.make_request($container);
});
// now get leaderboard
this.$sidebar_list.find('li:first').trigger('click');
},
make_request: function ($container) {
var me = this;
frappe.model.with_doctype(me.options.selected_doctype, function () {
me.get_leaderboard(me.get_leaderboard_data, $container);
});
},
get_leaderboard: function (notify, $container) {
var me = this;
if(!me.options.selected_company) {
frappe.throw(__("Please select Company"));
}
frappe.call({
method: "erpnext.utilities.page.leaderboard.leaderboard.get_leaderboard",
args: {
doctype: me.options.selected_doctype,
timespan: me.options.selected_timespan,
company: me.options.selected_company,
field: me.options.selected_filter_item,
},
callback: function (r) {
let results = r.message || [];
let graph_items = results.slice(0, 10);
me.$graph_area.show().empty();
let args = {
data: {
datasets: [
{
values: graph_items.map(d=>d.value)
}
],
labels: graph_items.map(d=>d.name)
},
colors: ['light-green'],
format_tooltip_x: d=>d[me.options.selected_filter_item],
type: 'bar',
height: 140
};
new frappe.Chart('.leaderboard-graph', args);
notify(me, r, $container);
}
});
},
get_leaderboard_data: function (me, res, $container) {
if (res && res.message) {
me.message = null;
$container.find(".leaderboard-list").html(me.render_list_view(res.message));
} else {
me.$graph_area.hide();
me.message = __("No items found.");
$container.find(".leaderboard-list").html(me.render_list_view());
}
},
render_list_view: function (items = []) {
var me = this;
var html =
`${me.render_message()}
<div class="result" style="${me.message ? "display:none;" : ""}">
${me.render_result(items)}
</div>`;
return $(html);
},
render_result: function (items) {
var me = this;
var html =
`${me.render_list_header()}
${me.render_list_result(items)}`;
return html;
},
render_list_header: function () {
var me = this;
const _selected_filter = me.options.selected_filter
.map(i => frappe.model.unscrub(i));
const fields = ['name', me.options.selected_filter_item];
const html =
`<div class="list-headers">
<div class="list-item list-item--head" data-list-renderer="${"List"}">
${
fields.map(filter => {
const col = frappe.model.unscrub(filter);
return (
`<div class="leaderboard-item list-item_content ellipsis text-muted list-item__content--flex-2
header-btn-base
${(col && _selected_filter.indexOf(col) !== -1) ? "text-right" : ""}">
<span class="list-col-title ellipsis">
${col}
</span>
</div>`);
}).join("")
}
</div>
</div>`;
return html;
},
render_list_result: function (items) {
var me = this;
let _html = items.map((item, index) => {
const $value = $(me.get_item_html(item));
let item_class = "";
if(index == 0) {
item_class = "first";
} else if (index == 1) {
item_class = "second";
} else if(index == 2) {
item_class = "third";
}
const $item_container = $(`<div class="list-item-container ${item_class}">`).append($value);
return $item_container[0].outerHTML;
}).join("");
let html =
`<div class="result-list">
<div class="list-items">
${_html}
</div>
</div>`;
return html;
},
render_message: function () {
var me = this;
let html =
`<div class="no-result text-center" style="${me.message ? "" : "display:none;"}">
<div class="msg-box no-border">
<p>No Item found</p>
</div>
</div>`;
return html;
},
get_item_html: function (item) {
var me = this;
const company = me.options.selected_company;
const currency = frappe.get_doc(":Company", company).default_currency;
const fields = ['name','value'];
const html =
`<div class="list-item">
${
fields.map(col => {
let val = item[col];
if(col=="name") {
var formatted_value = `<a class="grey list-id ellipsis"
href="#Form/${me.options.selected_doctype}/${item["name"]}"> ${val} </a>`
} else {
var formatted_value = `<span class="text-muted ellipsis">
${(me.options.selected_filter_item.indexOf('qty') == -1) ? format_currency(val, currency) : val}</span>`
}
return (
`<div class="list-item_content ellipsis list-item__content--flex-2
${(col == "value") ? "text-right" : ""}">
${formatted_value}
</div>`);
}).join("")
}
</div>`;
return html;
},
get_sidebar_item: function(item) {
return $(`<li class="strong module-sidebar-item">
<a class="module-link">
<span doctype-value="${item}">${ __(item) }</span></a>
</li>`);
}
});

View File

@ -1,19 +0,0 @@
{
"content": null,
"creation": "2017-06-06 02:54:24.785360",
"docstatus": 0,
"doctype": "Page",
"idx": 0,
"modified": "2017-09-12 14:05:26.422064",
"modified_by": "Administrator",
"module": "Utilities",
"name": "leaderboard",
"owner": "Administrator",
"page_name": "leaderboard",
"roles": [],
"script": null,
"standard": "Yes",
"style": null,
"system_page": 0,
"title": "Leaderboard"
}

View File

@ -1,153 +0,0 @@
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals, print_function
import frappe
from frappe.utils import add_to_date
@frappe.whitelist()
def get_leaderboard(doctype, timespan, company, field):
"""return top 10 items for that doctype based on conditions"""
from_date = get_from_date(timespan)
records = []
if doctype == "Customer":
records = get_all_customers(from_date, company, field)
elif doctype == "Item":
records = get_all_items(from_date, company, field)
elif doctype == "Supplier":
records = get_all_suppliers(from_date, company, field)
elif doctype == "Sales Partner":
records = get_all_sales_partner(from_date, company, field)
elif doctype == "Sales Person":
records = get_all_sales_person(from_date, company)
return records
def get_all_customers(from_date, company, field):
if field == "outstanding_amount":
return frappe.db.sql("""
select customer as name, sum(outstanding_amount) as value
FROM `tabSales Invoice`
where docstatus = 1 and posting_date >= %s and company = %s
group by customer
order by value DESC
limit 20
""", (from_date, company), as_dict=1)
else:
if field == "total_sales_amount":
select_field = "sum(so_item.base_net_amount)"
elif field == "total_qty_sold":
select_field = "sum(so_item.stock_qty)"
return frappe.db.sql("""
select so.customer as name, {0} as value
FROM `tabSales Order` as so JOIN `tabSales Order Item` as so_item
ON so.name = so_item.parent
where so.docstatus = 1 and so.transaction_date >= %s and so.company = %s
group by so.customer
order by value DESC
limit 20
""".format(select_field), (from_date, company), as_dict=1)
def get_all_items(from_date, company, field):
if field in ("available_stock_qty", "available_stock_value"):
return frappe.db.sql("""
select item_code as name, {0} as value
from tabBin
group by item_code
order by value desc
limit 20
""".format("sum(actual_qty)" if field=="available_stock_qty" else "sum(stock_value)"), as_dict=1)
else:
if field == "total_sales_amount":
select_field = "sum(order_item.base_net_amount)"
select_doctype = "Sales Order"
elif field == "total_purchase_amount":
select_field = "sum(order_item.base_net_amount)"
select_doctype = "Purchase Order"
elif field == "total_qty_sold":
select_field = "sum(order_item.stock_qty)"
select_doctype = "Sales Order"
elif field == "total_qty_purchased":
select_field = "sum(order_item.stock_qty)"
select_doctype = "Purchase Order"
return frappe.db.sql("""
select order_item.item_code as name, {0} as value
from `tab{1}` sales_order join `tab{1} Item` as order_item
on sales_order.name = order_item.parent
where sales_order.docstatus = 1
and sales_order.company = %s and sales_order.transaction_date >= %s
group by order_item.item_code
order by value desc
limit 20
""".format(select_field, select_doctype), (company, from_date), as_dict=1)
def get_all_suppliers(from_date, company, field):
if field == "outstanding_amount":
return frappe.db.sql("""
select supplier as name, sum(outstanding_amount) as value
FROM `tabPurchase Invoice`
where docstatus = 1 and posting_date >= %s and company = %s
group by supplier
order by value DESC
limit 20""", (from_date, company), as_dict=1)
else:
if field == "total_purchase_amount":
select_field = "sum(purchase_order_item.base_net_amount)"
elif field == "total_qty_purchased":
select_field = "sum(purchase_order_item.stock_qty)"
return frappe.db.sql("""
select purchase_order.supplier as name, {0} as value
FROM `tabPurchase Order` as purchase_order LEFT JOIN `tabPurchase Order Item`
as purchase_order_item ON purchase_order.name = purchase_order_item.parent
where purchase_order.docstatus = 1 and purchase_order.modified >= %s
and purchase_order.company = %s
group by purchase_order.supplier
order by value DESC
limit 20""".format(select_field), (from_date, company), as_dict=1)
def get_all_sales_partner(from_date, company, field):
if field == "total_sales_amount":
select_field = "sum(base_net_total)"
elif field == "total_commission":
select_field = "sum(total_commission)"
return frappe.db.sql("""
select sales_partner as name, {0} as value
from `tabSales Order`
where ifnull(sales_partner, '') != '' and docstatus = 1
and transaction_date >= %s and company = %s
group by sales_partner
order by value DESC
limit 20
""".format(select_field), (from_date, company), as_dict=1)
def get_all_sales_person(from_date, company):
return frappe.db.sql("""
select sales_team.sales_person as name, sum(sales_order.base_net_total) as value
from `tabSales Order` as sales_order join `tabSales Team` as sales_team
on sales_order.name = sales_team.parent and sales_team.parenttype = 'Sales Order'
where sales_order.docstatus = 1
and sales_order.transaction_date >= %s
and sales_order.company = %s
group by sales_team.sales_person
order by value DESC
limit 20
""", (from_date, company), as_dict=1)
def get_from_date(seleted_timespan):
"""return string for ex:this week as date:string"""
days = months = years = 0
if "month" == seleted_timespan.lower():
months = -1
elif "quarter" == seleted_timespan.lower():
months = -3
elif "year" == seleted_timespan.lower():
years = -1
else:
days = -7
return add_to_date(None, years=years, months=months, days=days,
as_string=True, as_datetime=True)