Merge pull request #9373 from sagarvora/gh-9289

Check for align_labels_left before adding text-right class
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
index f27b2c8..394ad49 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
@@ -205,14 +205,14 @@
 		if frappe.db.get_value("Buying Settings", None, "po_required") == 'Yes':
 			for d in self.get('items'):
 				if not d.purchase_order:
-					throw(_("Purchase Order number required for Item {0}").format(d.item_code))
+					throw(_("As per the Buying Settings if Purchase Order Required == 'YES', then for creating Purchase Invoice, user need to create Purchase Order first for item {0}").format(d.item_code))
 
 	def pr_required(self):
 		stock_items = self.get_stock_items()
 		if frappe.db.get_value("Buying Settings", None, "pr_required") == 'Yes':
 			for d in self.get('items'):
 				if not d.purchase_receipt and d.item_code in stock_items:
-					throw(_("Purchase Receipt number required for Item {0}").format(d.item_code))
+					throw(_("As per the Buying Settings if Purchase Reciept Required == 'YES', then for creating Purchase Invoice, user need to create Purchase Receipt first for item {0}").format(d.item_code))
 
 	def validate_write_off_account(self):
 		if self.write_off_amount and not self.write_off_account:
diff --git a/erpnext/docs/user/manual/en/accounts/purchase-invoice.md b/erpnext/docs/user/manual/en/accounts/purchase-invoice.md
index 433219c..3ffd930 100644
--- a/erpnext/docs/user/manual/en/accounts/purchase-invoice.md
+++ b/erpnext/docs/user/manual/en/accounts/purchase-invoice.md
@@ -3,18 +3,29 @@
 accrue expenses to your Supplier. Making a Purchase Invoice is very similar to
 making a Purchase Order.
 
-To make a new Purchase Invoice, go to:
-
-> Accounts > Documents > Purchase Invoice > New Purchase Invoice
+To make a new Purchase Invoice:
+> type "new purchase invoice" into the search bar then select "New Purchase 
+Invoice" from the drop down
 
 or click on “Make Purchase Invoice” in Purchase Order or Purchase Receipt.
 
+You can also create a Purchase Invoice from:
+> Accounts > Billing > Purchase Invoice > New Purchase Invoice
+
 <img class="screenshot" alt="Purchase Invoice" src="{{docs_base_url}}/assets/img/accounts/purchase-invoice.png">
 
 The concept of “Posting Date” is again same as Sales Invoice. “Bill No” and
 “Bill Date” helps to track the bill number as set by your Supplier for
 reference.
 
+#### Is Paid option
+The **Is Paid** checkbox should be checked if there is a part or full payment 
+on the invoice at posting date.
+
+#### Update Stock
+The **Update Stock** checkbox should be checked if you want ERPNext to automatically
+ update your inventory. Consequently, there will be no need for a Delivery Note.
+
 #### Accounting Impact
 
 Like in Sales Invoice, you have to enter an Expense or an Asset account for
@@ -34,7 +45,18 @@
 Credits:
 
   * Supplier
+  
+##### Accounting Treatment When **Is Paid** is checked
+If **Is Paid** is checked, ERPNext will also make the following
+accounting entries:
 
+Debits:
+
+  * Supplier
+  
+Credits:
+  * Bank/Cash Account
+  
 To see entries in your Purchase Invoice after you “Submit”, click on “View
 Ledger”.
 
diff --git a/erpnext/projects/doctype/timesheet/timesheet.js b/erpnext/projects/doctype/timesheet/timesheet.js
index 7d14d9e..2edfa9e 100644
--- a/erpnext/projects/doctype/timesheet/timesheet.js
+++ b/erpnext/projects/doctype/timesheet/timesheet.js
@@ -1,9 +1,9 @@
 // Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
 // License: GNU General Public License v3. See license.txt
-cur_frm.add_fetch('employee', 'employee_name', 'employee_name');
 
 frappe.ui.form.on("Timesheet", {
 	setup: function(frm) {
+		frm.add_fetch('employee', 'employee_name', 'employee_name');
 		frm.fields_dict.employee.get_query = function() {
 			return {
 				filters:{
@@ -51,8 +51,8 @@
 		}
 
 		if(frm.doc.per_billed > 0) {
-			cur_frm.fields_dict["time_logs"].grid.toggle_enable("billing_hours", false);
-			cur_frm.fields_dict["time_logs"].grid.toggle_enable("billable", false);
+			frm.fields_dict["time_logs"].grid.toggle_enable("billing_hours", false);
+			frm.fields_dict["time_logs"].grid.toggle_enable("billable", false);
 		}
 	},
 
@@ -77,7 +77,7 @@
 	},
 
 	from_time: function(frm, cdt, cdn) {
-		calculate_end_time(frm, cdt, cdn)
+		calculate_end_time(frm, cdt, cdn);
 	},
 
 	to_time: function(frm, cdt, cdn) {
@@ -109,18 +109,20 @@
 	},
 
 	activity_type: function(frm, cdt, cdn) {
-		var child = locals[cdt][cdn];
+		frm.script_manager.copy_from_first_row('time_logs', frm.selected_doc,
+			'project');
+
 		frappe.call({
 			method: "erpnext.projects.doctype.timesheet.timesheet.get_activity_cost",
 			args: {
 				employee: frm.doc.employee,
-				activity_type: child.activity_type
+				activity_type: frm.selected_doc.activity_type
 			},
 			callback: function(r){
 				if(r.message){
 					frappe.model.set_value(cdt, cdn, 'billing_rate', r.message['billing_rate']);
 					frappe.model.set_value(cdt, cdn, 'costing_rate', r.message['costing_rate']);
-					calculate_billing_costing_amount(frm, cdt, cdn)
+					calculate_billing_costing_amount(frm, cdt, cdn);
 				}
 			}
 		})
@@ -174,8 +176,8 @@
 		}
 	}
 
-	cur_frm.set_value("total_billable_hours", total_billing_hr);
-	cur_frm.set_value("total_hours", total_working_hr);
-	cur_frm.set_value("total_billable_amount", total_billable_amount);
-	cur_frm.set_value("total_costing_amount", total_costing_amount);
+	frm.set_value("total_billable_hours", total_billing_hr);
+	frm.set_value("total_hours", total_working_hr);
+	frm.set_value("total_billable_amount", total_billable_amount);
+	frm.set_value("total_costing_amount", total_costing_amount);
 }
\ No newline at end of file
diff --git a/erpnext/public/js/controllers/transaction.js b/erpnext/public/js/controllers/transaction.js
index ca822b1..8ad64d2 100644
--- a/erpnext/public/js/controllers/transaction.js
+++ b/erpnext/public/js/controllers/transaction.js
@@ -16,11 +16,11 @@
 					// or set discount
 					item.discount_percentage = 0;
 					item.margin_type = 'Amount';
-					item.margin_rate_or_amount = flt(item.rate - item.price_list_rate, 
+					item.margin_rate_or_amount = flt(item.rate - item.price_list_rate,
 						precision("margin_rate_or_amount", item));
 					item.rate_with_margin = item.rate;
 				} else {
-					item.discount_percentage = flt((1 - item.rate / item.price_list_rate) * 100.0, 
+					item.discount_percentage = flt((1 - item.rate / item.price_list_rate) * 100.0,
 						precision("discount_percentage", item));
 					item.margin_type = '';
 					item.margin_rate_or_amount = 0;
@@ -602,8 +602,10 @@
 
 	toggle_conversion_factor: function(item) {
 		// toggle read only property for conversion factor field if the uom and stock uom are same
-		this.frm.fields_dict.items.grid.toggle_enable("conversion_factor",
-			(item.uom != item.stock_uom)? true: false)
+		if(this.frm.get_field('items').grid.fields_map.conversion_factor) {
+			this.frm.fields_dict.items.grid.toggle_enable("conversion_factor",
+				(item.uom != item.stock_uom)? true: false);
+		}
 	},
 
 	qty: function(doc, cdt, cdn) {
@@ -756,7 +758,7 @@
 		if(this.frm.doc.ignore_pricing_rule) {
 			var me = this;
 			var item_list = [];
-			
+
 			$.each(this.frm.doc["items"] || [], function(i, d) {
 				if (d.item_code) {
 					item_list.push({
@@ -1144,7 +1146,7 @@
 
 		if(!item.item_code) {
 			frappe.throw(__("Please enter Item Code to get batch no"));
-		} else if (doc.doctype == "Purchase Receipt" || 
+		} else if (doc.doctype == "Purchase Receipt" ||
 			(doc.doctype == "Purchase Invoice" && doc.update_stock)) {
 
 			return {
diff --git a/erpnext/public/js/shopping_cart.js b/erpnext/public/js/shopping_cart.js
index 2c56b02..e4e7440 100644
--- a/erpnext/public/js/shopping_cart.js
+++ b/erpnext/public/js/shopping_cart.js
@@ -6,7 +6,7 @@
 var shopping_cart = erpnext.shopping_cart;
 
 frappe.ready(function() {
-	var full_name = frappe.session.user_fullname;
+	var full_name = frappe.session && frappe.session.user_fullname;
 	// update user
 	if(full_name) {
 		$('.navbar li[data-label="User"] a')
@@ -36,8 +36,7 @@
 	},
 
 	update_cart: function(opts) {
-		var full_name = frappe.session.user_fullname;
-		if(!full_name || full_name==="Guest") {
+		if(frappe.session.user==="Guest") {
 			if(localStorage) {
 				localStorage.setItem("last_visited", window.location.pathname);
 			}
diff --git a/erpnext/selling/doctype/sales_order/sales_order.json b/erpnext/selling/doctype/sales_order/sales_order.json
index 7ea550a..7c995f2 100644
--- a/erpnext/selling/doctype/sales_order/sales_order.json
+++ b/erpnext/selling/doctype/sales_order/sales_order.json
@@ -396,7 +396,7 @@
   }, 
   {
    "allow_bulk_edit": 0, 
-   "allow_on_submit": 0, 
+   "allow_on_submit": 1, 
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
@@ -430,7 +430,7 @@
   }, 
   {
    "allow_bulk_edit": 0, 
-   "allow_on_submit": 0, 
+   "allow_on_submit": 1, 
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
@@ -3632,7 +3632,7 @@
  "issingle": 0, 
  "istable": 0, 
  "max_attachments": 0, 
- "modified": "2017-06-13 14:28:50.441767", 
+ "modified": "2017-06-19 13:06:31.736384", 
  "modified_by": "Administrator", 
  "module": "Selling", 
  "name": "Sales Order", 
diff --git a/erpnext/setup/doctype/email_digest/email_digest.py b/erpnext/setup/doctype/email_digest/email_digest.py
index 8c19db5..c85a541 100644
--- a/erpnext/setup/doctype/email_digest/email_digest.py
+++ b/erpnext/setup/doctype/email_digest/email_digest.py
@@ -364,9 +364,9 @@
 		balance = prev_balance = 0.0
 		count = 0
 		for account in accounts:
-			balance += get_balance_on(account, date=self.future_to_date)
+			balance += get_balance_on(account, date=self.future_to_date, in_account_currency=False)
 			count += get_count_on(account, fieldname, date=self.future_to_date)
-			prev_balance += get_balance_on(account, date=self.past_to_date)
+			prev_balance += get_balance_on(account, date=self.past_to_date, in_account_currency=False)
 
 		if fieldname in ("bank_balance","credit_balance"):
 			return {
diff --git a/erpnext/setup/doctype/item_group/item_group.py b/erpnext/setup/doctype/item_group/item_group.py
index 98404a4..9c2a400 100644
--- a/erpnext/setup/doctype/item_group/item_group.py
+++ b/erpnext/setup/doctype/item_group/item_group.py
@@ -37,10 +37,11 @@
 		if not self.route:
 			self.route = ''
 			if self.parent_item_group:
-				parent_route = frappe.get_doc('Item Group', self.parent_item_group).route
+				parent_item_group = frappe.get_doc('Item Group', self.parent_item_group)
 
-				if parent_route:
-					self.route = parent_route + '/'
+				# make parent route only if not root
+				if parent_item_group.parent_item_group and parent_item_group.route:
+					self.route = parent_item_group.route + '/'
 
 			self.route += self.scrub(self.item_group_name)
 
@@ -100,7 +101,7 @@
 				or name like %(search)s)"""
 		search = "%" + cstr(search) + "%"
 
-	query += """order by weightage desc, modified desc limit %s, %s""" % (start, limit)
+	query += """order by weightage desc, item_name, modified desc limit %s, %s""" % (start, limit)
 
 	data = frappe.db.sql(query, {"product_group": product_group,"search": search, "today": nowdate()}, as_dict=1)
 
diff --git a/erpnext/shopping_cart/cart.py b/erpnext/shopping_cart/cart.py
index e73734e..5c7d825 100644
--- a/erpnext/shopping_cart/cart.py
+++ b/erpnext/shopping_cart/cart.py
@@ -75,9 +75,15 @@
 def update_cart(item_code, qty, with_items=False):
 	quotation = _get_cart_quotation()
 
+	empty_card = False
 	qty = flt(qty)
 	if qty == 0:
-		quotation.set("items", quotation.get("items", {"item_code": ["!=", item_code]}))
+		quotation_items = quotation.get("items", {"item_code": ["!=", item_code]})
+		if quotation_items:
+			quotation.set("items", quotation_items)
+		else:
+			empty_card = True
+
 	else:
 		quotation_items = quotation.get("items", {"item_code": item_code})
 		if not quotation_items:
@@ -92,7 +98,11 @@
 	apply_cart_settings(quotation=quotation)
 
 	quotation.flags.ignore_permissions = True
-	quotation.save()
+	if not empty_card:
+		quotation.save()
+	else:
+		quotation.delete()
+		quotation = None
 
 	set_cart_count(quotation)
 
diff --git a/erpnext/stock/doctype/delivery_note/test_delivery_note.py b/erpnext/stock/doctype/delivery_note/test_delivery_note.py
index 4a1c08a..0f3099f 100644
--- a/erpnext/stock/doctype/delivery_note/test_delivery_note.py
+++ b/erpnext/stock/doctype/delivery_note/test_delivery_note.py
@@ -26,7 +26,7 @@
 		target_warehouse = "_Test Warehouse 1 - _TC"
 		company = "_Test Company"
 		if not frappe.db.exists("Account", target_warehouse):
-			parent_account = frappe.db.get_value('Account', 
+			parent_account = frappe.db.get_value('Account',
 				{'company': company, 'is_group':1, 'account_type': 'Stock'},'name')
 			account = create_account(account_name="_Test Warehouse 1", \
 				account_type="Stock", parent_account= parent_account, company=company)
@@ -275,11 +275,20 @@
 	def test_return_entire_bundled_items(self):
 		set_perpetual_inventory()
 
-		create_stock_reconciliation(item_code="_Test Item", target="_Test Warehouse - _TC", qty=50, rate=100)
-		create_stock_reconciliation(item_code="_Test Item Home Desktop 100", target="_Test Warehouse - _TC",
-			qty=50, rate=100)
+		create_stock_reconciliation(item_code="_Test Item",
+			target="_Test Warehouse - _TC", qty=50, rate=100)
+		create_stock_reconciliation(item_code="_Test Item Home Desktop 100",
+			target="_Test Warehouse - _TC", qty=50, rate=100)
 
-		dn = create_delivery_note(item_code="_Test Product Bundle Item", qty=5, rate=500)
+		actual_qty = get_qty_after_transaction()
+		self.assertEquals(actual_qty, 50)
+
+		dn = create_delivery_note(item_code="_Test Product Bundle Item",
+			qty=5, rate=500)
+
+		# qty after return
+		actual_qty = get_qty_after_transaction()
+		self.assertEquals(actual_qty, 25)
 
 		#  return bundled item
 		dn1 = create_delivery_note(item_code='_Test Product Bundle Item', is_return=1,
@@ -532,9 +541,9 @@
 def create_delivery_note(**args):
 	dn = frappe.new_doc("Delivery Note")
 	args = frappe._dict(args)
-	dn.posting_date = args.posting_date or today()
-	if args.posting_time:
-		dn.posting_time = args.posting_time
+	dn.posting_date = args.posting_date or nowdate()
+	dn.posting_time = args.posting_time or nowtime()
+	dn.set_posting_time = 1
 
 	dn.company = args.company or "_Test Company"
 	dn.customer = args.customer or "_Test Customer"
diff --git a/erpnext/stock/doctype/delivery_note/test_records.json b/erpnext/stock/doctype/delivery_note/test_records.json
deleted file mode 100644
index c76bab2..0000000
--- a/erpnext/stock/doctype/delivery_note/test_records.json
+++ /dev/null
@@ -1,39 +0,0 @@
-[
- {
-  "company": "_Test Company",
-  "conversion_rate": 1.0,
-  "currency": "INR",
-  "customer": "_Test Customer",
-  "customer_name": "_Test Customer",
-  "items": [
-   {
-    "base_amount": 100.0,
-    "base_rate": 100.0,
-    "cost_center": "Main - _TC",
-    "description": "CPU",
-    "doctype": "Delivery Note Item",
-    "expense_account": "Cost of Goods Sold - _TC",
-    "item_code": "_Test Item",
-    "item_name": "_Test Item",
-    "parentfield": "items",
-    "qty": 1.0,
-    "rate": 100.0,
-	"uom": "_Test UOM",
-	"conversion_factor": 1,
-    "stock_uom": "_Test UOM",
-    "warehouse": "_Test Warehouse - _TC"
-   }
-  ],
-  "doctype": "Delivery Note",
-  "base_grand_total": 100.0,
-  "grand_total": 100.0,
-  "naming_series": "_T-Delivery Note-",
-  "base_net_total": 100.0,
-  "plc_conversion_rate": 1.0,
-  "posting_date": "2013-02-21",
-  "price_list_currency": "INR",
-  "selling_price_list": "_Test Price List",
-  "status": "Draft",
-  "territory": "_Test Territory"
- }
-]
diff --git a/erpnext/stock/doctype/material_request/material_request.js b/erpnext/stock/doctype/material_request/material_request.js
index 23d1fd4..3361020 100644
--- a/erpnext/stock/doctype/material_request/material_request.js
+++ b/erpnext/stock/doctype/material_request/material_request.js
@@ -30,11 +30,15 @@
 });
 
 frappe.ui.form.on("Material Request Item", {
-	"qty": function (frm, doctype, name) {
+	qty: function (frm, doctype, name) {
 		var d = locals[doctype][name];
 		if (flt(d.qty) < flt(d.min_order_qty)) {
 			frappe.msgprint(__("Warning: Material Requested Qty is less than Minimum Order Qty"));
 		}
+	},
+	item_code: function(frm, doctype, name) {
+		frm.script_manager.copy_from_first_row('items', frm.selected_doc,
+			'schedule_date');
 	}
 });
 
@@ -118,18 +122,6 @@
 
 	},
 
-	schedule_date: function(doc, cdt, cdn) {
-		var val = locals[cdt][cdn].schedule_date;
-		if(val) {
-			$.each((doc.items || []), function(i, d) {
-				if(!d.schedule_date) {
-					d.schedule_date = val;
-				}
-			});
-			refresh_field("items");
-		}
-	},
-
 	get_items_from_bom: function() {
 		var d = new frappe.ui.Dialog({
 			title: __("Get Items from BOM"),
diff --git a/erpnext/stock/report/batch_wise_balance_history/batch_wise_balance_history.py b/erpnext/stock/report/batch_wise_balance_history/batch_wise_balance_history.py
index fca91d6..e7cb9ad 100644
--- a/erpnext/stock/report/batch_wise_balance_history/batch_wise_balance_history.py
+++ b/erpnext/stock/report/batch_wise_balance_history/batch_wise_balance_history.py
@@ -23,7 +23,8 @@
 				if qty_dict.opening_qty or qty_dict.in_qty or qty_dict.out_qty or qty_dict.bal_qty:
 					data.append([item, item_map[item]["item_name"], item_map[item]["description"], wh, batch,
 						flt(qty_dict.opening_qty, float_precision), flt(qty_dict.in_qty, float_precision),
-						flt(qty_dict.out_qty, float_precision), flt(qty_dict.bal_qty, float_precision)
+						flt(qty_dict.out_qty, float_precision), flt(qty_dict.bal_qty, float_precision),
+						 item_map[item]["stock_uom"]
 					])
 
 	return columns, data
@@ -33,7 +34,9 @@
 
 	columns = [_("Item") + ":Link/Item:100"] + [_("Item Name") + "::150"] + [_("Description") + "::150"] + \
 	[_("Warehouse") + ":Link/Warehouse:100"] + [_("Batch") + ":Link/Batch:100"] + [_("Opening Qty") + ":Float:90"] + \
-	[_("In Qty") + ":Float:80"] + [_("Out Qty") + ":Float:80"] + [_("Balance Qty") + ":Float:90"]
+	[_("In Qty") + ":Float:80"] + [_("Out Qty") + ":Float:80"] + [_("Balance Qty") + ":Float:90"] + \
+	[_("UOM") + "::90"]
+
 
 	return columns
 
@@ -87,7 +90,7 @@
 
 def get_item_details(filters):
 	item_map = {}
-	for d in frappe.db.sql("select name, item_name, description from tabItem", as_dict=1):
+	for d in frappe.db.sql("select name, item_name, description, stock_uom from tabItem", as_dict=1):
 		item_map.setdefault(d.name, d)
 
 	return item_map
diff --git a/erpnext/templates/includes/order/order_taxes.html b/erpnext/templates/includes/order/order_taxes.html
index 24ae088..471576f 100644
--- a/erpnext/templates/includes/order/order_taxes.html
+++ b/erpnext/templates/includes/order/order_taxes.html
@@ -6,11 +6,13 @@
 </div>
 {% endif %}
 {% for d in doc.taxes %}
+{% if d.base_tax_amount > 0 %}
 <div class="row tax-row">
     <div class="col-xs-8 text-right">{{ d.description }}</div>
     <div class="col-xs-4 text-right">
         {{ d.get_formatted("base_tax_amount") }}</div>
 </div>
+{% endif %}
 {% endfor %}
 <div class="row tax-grand-total-row">
     <div class="col-xs-8 text-right text-uppercase h6 text-muted">{{ _("Grand Total") }}</div>
diff --git a/erpnext/templates/includes/product_list.js b/erpnext/templates/includes/product_list.js
index 7f63c17..2f9d978 100644
--- a/erpnext/templates/includes/product_list.js
+++ b/erpnext/templates/includes/product_list.js
@@ -39,10 +39,10 @@
 	if(data.length < 10) {
 		if(!table) {
 			$(".more-btn")
-				.replaceWith("<div class='alert alert-warning'>No products found.</div>");
+				.replaceWith("<div class='alert alert-warning'>{{ _("No products found.") }}</div>");
 		} else {
 			$(".more-btn")
-				.replaceWith("<div class='text-muted'>Nothing more to show.</div>");
+				.replaceWith("<div class='text-muted'>{{ _("Nothing more to show.") }}</div>");
 		}
 	} else {
 		$(".more-btn").toggle(true)
diff --git a/erpnext/templates/includes/product_page.js b/erpnext/templates/includes/product_page.js
index e61ead1..3905959 100644
--- a/erpnext/templates/includes/product_page.js
+++ b/erpnext/templates/includes/product_page.js
@@ -15,18 +15,18 @@
 			$(".item-cart").toggleClass("hide", (!!!r.message.price || !!!r.message.in_stock));
 			if(r.message && r.message.price) {
 				$(".item-price")
-					.html(r.message.price.formatted_price + " per " + r.message.uom);
+					.html(r.message.price.formatted_price + " {{ _("per") }} " + r.message.uom);
 
 				if(r.message.in_stock==0) {
-					$(".item-stock").html("<div style='color: red'> <i class='fa fa-close'></i> Not in stock</div>");
+					$(".item-stock").html("<div style='color: red'> <i class='fa fa-close'></i> {{ _("Not in stock") }}</div>");
 				}
 				else if(r.message.in_stock==1) {
-					var qty_display = "In stock";
+					var qty_display = "{{ _("In stock") }}";
 					if (r.message.show_stock_qty) {
-						qty_display = "Available ("+r.message.stock_qty+ " in stock)";
+						qty_display += " ("+r.message.stock_qty+")";
 					}
 					$(".item-stock").html("<div style='color: green'>\
-						<i class='fa fa-check'></i> "+__(qty_display)+"</div>");
+						<i class='fa fa-check'></i> "+qty_display+"</div>");
 				}
 
 				if(r.message.qty) {
diff --git a/erpnext/utilities/page/__init__.py b/erpnext/utilities/page/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/utilities/page/__init__.py
diff --git a/erpnext/utilities/page/leaderboard/__init__.py b/erpnext/utilities/page/leaderboard/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/utilities/page/leaderboard/__init__.py
diff --git a/erpnext/utilities/page/leaderboard/leaderboard.css b/erpnext/utilities/page/leaderboard/leaderboard.css
new file mode 100644
index 0000000..1f4fc51
--- /dev/null
+++ b/erpnext/utilities/page/leaderboard/leaderboard.css
@@ -0,0 +1,54 @@
+.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)
+}*/
diff --git a/erpnext/utilities/page/leaderboard/leaderboard.html b/erpnext/utilities/page/leaderboard/leaderboard.html
new file mode 100644
index 0000000..8df2247
--- /dev/null
+++ b/erpnext/utilities/page/leaderboard/leaderboard.html
@@ -0,0 +1,23 @@
+<div class="frappe-list-area">
+	<div class="frappe-list">
+		<div class="list-filters">
+			<div class="list-filter-item">
+				<select class="form-control select-doctype">
+					{% for (var i=0; i < doctypes.length; i++) { %}
+						<option value="{{doctypes[i]}}">{{ doctypes[i] }}</option>
+					{% } %}
+				</select>
+			</div>
+
+			<div class="list-filter-item">
+				<select class="form-control select-time">
+					{% for (var i=0; i < timelines.length; i++) { %}
+						<option value="{{timelines[i]}}">{{ timelines[i] }}</option>
+					{% } %}
+				</select>
+			</div>
+		</div>
+		<div class="leaderboard">
+		</div>
+	</div>
+</div>
\ No newline at end of file
diff --git a/erpnext/utilities/page/leaderboard/leaderboard.js b/erpnext/utilities/page/leaderboard/leaderboard.js
new file mode 100644
index 0000000..eed9bd1
--- /dev/null
+++ b/erpnext/utilities/page/leaderboard/leaderboard.js
@@ -0,0 +1,248 @@
+
+frappe.Leaderboard = Class.extend({
+
+	init: function (parent) {
+		this.page = frappe.ui.make_app_page({
+			parent: parent,
+			title: "Leaderboard",
+			single_column: true
+		});
+
+		// const list of doctypes
+		this.doctypes = ["Customer", "Item", "Supplier", "Sales Partner"];
+		this.timelines = ["Week", "Month", "Quarter", "Year"];
+		this.desc_fields = ["total_amount", "total_request", "annual_billing", "commission_rate"];
+		this.filters = {
+			"Customer": this.map_array(["title", "total_amount", "total_item_purchased", "modified"]),
+			"Item": this.map_array(["title", "total_request", "total_purchase", "avg_price", "modified"]),
+			"Supplier": this.map_array(["title", "annual_billing", "total_unpaid", "modified"]),
+			"Sales Partner": this.map_array(["title", "commission_rate", "target_qty", "target_amount", "modified"]),
+		};
+
+		// for saving current selected filters
+		const _selected_filter = this.filters[this.doctypes[0]];
+		this.options = {
+			selected_doctype: this.doctypes[0],
+			selected_filter: _selected_filter,
+			selected_filter_item: _selected_filter[1],
+			selected_timeline: this.timelines[0],
+		};
+
+		this.message = null;
+		this.make();
+	},
+
+
+
+	make: function () {
+		var me = this;
+
+		var $leaderboard = $(frappe.render_template("leaderboard", this)).appendTo(this.page.main);
+
+		// events
+		$leaderboard.find(".select-doctype")
+			.on("change", function () {
+				me.options.selected_doctype = this.value;
+				me.options.selected_filter = me.filters[this.value];
+				me.options.selected_filter_item = me.filters[this.value][1];
+				me.make_request($leaderboard);
+			});
+
+		$leaderboard.find(".select-time")
+			.on("change", function () {
+				me.options.selected_timeline = this.value;
+				me.make_request($leaderboard);
+			});
+
+		// now get leaderboard
+		me.make_request($leaderboard);
+	},
+
+	make_request: function ($leaderboard) {
+		var me = this;
+
+		frappe.model.with_doctype(me.options.selected_doctype, function () {
+			me.get_leaderboard(me.get_leaderboard_data, $leaderboard);
+		});
+	},
+
+	get_leaderboard: function (notify, $leaderboard) {
+		var me = this;
+
+		frappe.call({
+			method: "erpnext.utilities.page.leaderboard.leaderboard.get_leaderboard",
+			args: {
+				obj: JSON.stringify(me.options)
+			},
+			callback: function (res) {
+				console.log(res)
+				notify(me, res, $leaderboard);
+			}
+		});
+	},
+
+	get_leaderboard_data: function (me, res, $leaderboard) {
+		if (res && res.message) {
+			me.message = null;
+			$leaderboard.find(".leaderboard").html(me.render_list_view(res.message));
+
+			// event to change arrow
+			$leaderboard.find(".leaderboard-item")
+				.click(function () {
+					const field = this.innerText.trim().toLowerCase().replace(new RegExp(" ", "g"), "_");
+					if (field && field !== "title") {
+						const _selected_filter_item = me.options.selected_filter
+							.filter(i => i.field === field);
+						if (_selected_filter_item.length > 0) {
+							me.options.selected_filter_item = _selected_filter_item[0];
+							me.options.selected_filter_item.value = _selected_filter_item[0].value === "ASC" ? "DESC" : "ASC";
+
+							const new_class_name = `icon-${me.options.selected_filter_item.field} fa fa-chevron-${me.options.selected_filter_item.value === "ASC" ? "up" : "down"}`;
+							$leaderboard.find(`.icon-${me.options.selected_filter_item.field}`)
+								.attr("class", new_class_name);
+
+							// now make request to web
+							me.make_request($leaderboard);
+						}
+					}
+				});
+		} else {
+			me.message = "No items found.";
+			$leaderboard.find(".leaderboard").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 => me.map_field(i.field)).slice(1);
+
+		const html =
+			`<div class="list-headers">
+				<div class="list-item list-item--head" data-list-renderer="${"List"}">
+					${
+					me.options.selected_filter
+						.map(filter => {
+							const col = me.map_field(filter.field);
+							return (
+								`<div class="leaderboard-item list-item_content ellipsis text-muted list-item__content--flex-2
+									header-btn-base ${(col !== "Title" && col !== "Modified") ? "hidden-xs" : ""}
+									${(col && _selected_filter.indexOf(col) !== -1) ? "text-right" : ""}">
+									<span class="list-col-title ellipsis">
+										${col}
+										<i class="${"icon-" + filter.field} fa ${filter.value === "ASC" ? "fa-chevron-up" : "fa-chevron-down"}"
+											style="${col === "Title" ? "display:none;" : ""}"></i>
+									</span>
+								</div>`);
+						}).join("")
+					}
+				</div>
+			</div>`;
+		return html;
+	},
+
+	render_list_result: function (items) {
+		var me = this;
+
+		let _html = items.map((item) => {
+			const $value = $(me.get_item_html(item));
+			const $item_container = $(`<div class="list-item-container">`).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 _selected_filter = me.options.selected_filter
+			.map(i => me.map_field(i.field)).slice(1);
+
+		const html =
+			`<div class="list-item">
+				${
+			me.options.selected_filter
+				.map(filter => {
+					const col = me.map_field(filter.field);
+					let val = item[filter.field];
+					if (col === "Modified") {
+						val = comment_when(val);
+					}
+					return (
+						`<div class="list-item_content ellipsis list-item__content--flex-2
+							${(col !== "Title" && col !== "Modified") ? "hidden-xs" : ""}
+							${(col && _selected_filter.indexOf(col) !== -1) ? "text-right" : ""}">
+							${
+								col === "Title"	
+									? `<a class="grey list-id ellipsis" href="${item["href"]}"> ${val} </a>` 
+									: `<span class="text-muted ellipsis"> ${val}</span>`
+							}
+						</div>`);
+					}).join("")
+				}
+			</div>`;
+
+		return html;
+	},
+
+	map_field: function (field) {
+		return field.replace(new RegExp("_", "g"), " ").replace(/(^|\s)[a-z]/g, f => f.toUpperCase())
+	},
+
+	map_array: function (_array) {
+		var me = this;
+		return _array.map((str) => {
+			let value = me.desc_fields.indexOf(str) > -1 ? "DESC" : "ASC";
+			return {
+				field: str,
+				value: value
+			};
+		});
+	}
+});
+
+frappe.pages["leaderboard"].on_page_load = function (wrapper) {
+	frappe.leaderboard = new frappe.Leaderboard(wrapper);
+}
diff --git a/erpnext/utilities/page/leaderboard/leaderboard.json b/erpnext/utilities/page/leaderboard/leaderboard.json
new file mode 100644
index 0000000..8cba765
--- /dev/null
+++ b/erpnext/utilities/page/leaderboard/leaderboard.json
@@ -0,0 +1,19 @@
+{
+ "content": null, 
+ "creation": "2017-06-06 02:54:24.785360", 
+ "docstatus": 0, 
+ "doctype": "Page", 
+ "idx": 0, 
+ "modified": "2017-06-06 02:54:27.504048", 
+ "modified_by": "Administrator", 
+ "module": "Utilities", 
+ "name": "leaderboard", 
+ "owner": "Administrator", 
+ "page_name": "leaderboard", 
+ "roles": [], 
+ "script": null, 
+ "standard": "Yes", 
+ "style": null, 
+ "system_page": 0, 
+ "title": "LeaderBoard"
+}
\ No newline at end of file
diff --git a/erpnext/utilities/page/leaderboard/leaderboard.py b/erpnext/utilities/page/leaderboard/leaderboard.py
new file mode 100644
index 0000000..0a75410
--- /dev/null
+++ b/erpnext/utilities/page/leaderboard/leaderboard.py
@@ -0,0 +1,182 @@
+# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
+# MIT License. See license.txt
+
+from __future__ import unicode_literals, print_function
+import frappe
+import json
+from operator import itemgetter
+from frappe.utils import add_to_date
+from erpnext.accounts.party import get_dashboard_info
+from erpnext.accounts.utils import get_currency_precision
+
+@frappe.whitelist()
+def get_leaderboard(obj):
+	"""return top 10 items for that doctype based on conditions"""
+	obj = frappe._dict(json.loads(obj))
+
+	doctype = obj.selected_doctype
+	timeline = obj.selected_timeline
+	filters = {"modified":(">=", get_date_from_string(timeline))}
+	items = []
+	if doctype == "Customer":
+		items = get_all_customers(doctype, filters, [])
+	elif  doctype == "Item":
+		items = get_all_items(doctype, filters, [])
+	elif  doctype == "Supplier":
+		items = get_all_suppliers(doctype, filters, [])
+	elif  doctype == "Sales Partner":
+		items = get_all_sales_partner(doctype, filters, [])
+	
+	if len(items) > 0:
+		return filter_leaderboard_items(obj, items)
+	return []
+
+
+# filters start
+def filter_leaderboard_items(obj, items):
+	"""return items based on seleted filters"""
+	
+	reverse = False if obj.selected_filter_item and obj.selected_filter_item["value"] == "ASC" else True
+	# key : (x[field1], x[field2]) while sorting on 2 values
+	filtered_list = []
+	selected_field = obj.selected_filter_item and obj.selected_filter_item["field"]
+	if selected_field:
+		filtered_list  = sorted(items, key=itemgetter(selected_field), reverse=reverse)
+		value = items[0].get(selected_field)
+
+		allowed = isinstance(value, unicode) or isinstance(value, str)
+		# now sort by length
+		if allowed and '$' in value:
+			filtered_list.sort(key= lambda x: len(x[selected_field]), reverse=reverse)
+	
+	# return only 10 items'
+	return filtered_list[:10]
+
+# filters end
+
+
+# utils start
+def destructure_tuple_of_tuples(tup_of_tup):
+	"""return tuple(tuples) as list"""
+	return [y for x in tup_of_tup for y in x]
+
+def get_date_from_string(seleted_timeline):
+	"""return string for ex:this week as date:string"""
+	days = months = years = 0
+	if "month" == seleted_timeline.lower():
+		months = -1
+	elif "quarter" == seleted_timeline.lower():
+		months = -3
+	elif "year" == seleted_timeline.lower():
+		years = -1
+	else:
+		days = -7
+
+	return add_to_date(None, years=years, months=months, days=days, as_string=True, as_datetime=True)
+
+def get_filter_list(selected_filter):
+	"""return list of keys"""
+	return map((lambda y : y["field"]), filter(lambda x : not (x["field"] == "title" or x["field"] == "modified"), selected_filter))
+
+def get_avg(items):
+	"""return avg of list items"""
+	length = len(items)
+	if length > 0:
+		return sum(items) / length
+	return 0
+
+def get_formatted_value(value, add_symbol=True):
+	"""return formatted value"""
+	currency_precision = get_currency_precision() or 2
+	if not add_symbol:
+		return '{:.{pre}f}'.format(value, pre=currency_precision)
+	
+	company = frappe.db.get_default("company") or frappe.get_all("Company")[0].name
+	currency = frappe.get_doc("Company", company).default_currency or frappe.boot.sysdefaults.currency;
+	currency_symbol = frappe.db.get_value("Currency", currency, "symbol")
+	return  currency_symbol + ' ' + '{:.{pre}f}'.format(value, pre=currency_precision)
+
+# utils end
+
+
+# get data
+def get_all_customers(doctype, filters, items, start=0, limit=100):
+	"""return all customers"""
+
+	x = frappe.get_list(doctype, fields=["name", "modified"], filters=filters, limit_start=start, limit_page_length=limit)
+	
+	for val in x:
+		y = dict(frappe.db.sql('''select name, grand_total from `tabSales Invoice` where customer = %s''', (val.name)))
+		invoice_list = y.keys()
+		if len(invoice_list) > 0:
+			item_count = frappe.db.sql('''select count(name) from `tabSales Invoice Item` where parent in (%s)''' % ", ".join(
+				['%s'] * len(invoice_list)), tuple(invoice_list))
+			items.append({"title": val.name,
+				"total_amount": get_formatted_value(sum(y.values())),
+				"href":"#Form/Customer/" + val.name,
+				"total_item_purchased": sum(destructure_tuple_of_tuples(item_count)),
+				"modified": str(val.modified)})
+	if len(x) > 99:
+		start = start + 1
+		return get_all_customers(doctype, filters, items, start=start)
+	else:
+		return items
+
+def get_all_items(doctype, filters, items, start=0, limit=100):
+	"""return all items"""
+
+	x = frappe.get_list(doctype, fields=["name", "modified"], filters=filters, limit_start=start, limit_page_length=limit)
+	for val in x:
+		data = frappe.db.sql('''select item_code from `tabMaterial Request Item` where item_code = %s''', (val.name), as_list=1)
+		requests = destructure_tuple_of_tuples(data)
+		data = frappe.db.sql('''select price_list_rate from `tabItem Price` where item_code = %s''', (val.name), as_list=1)
+		avg_price = get_avg(destructure_tuple_of_tuples(data))
+		data = frappe.db.sql('''select item_code from `tabPurchase Invoice Item` where item_code = %s''', (val.name), as_list=1)
+		purchases = destructure_tuple_of_tuples(data)
+		
+		items.append({"title": val.name,
+			"total_request":len(requests),
+			"total_purchase": len(purchases), "href":"#Form/Item/" + val.name,
+			"avg_price": get_formatted_value(avg_price),
+			"modified": val.modified})
+	if len(x) > 99:
+		return get_all_items(doctype, filters, items, start=start)
+	else:
+		return items
+
+def get_all_suppliers(doctype, filters, items, start=0, limit=100):
+	"""return all suppliers"""
+
+	x = frappe.get_list(doctype, fields=["name", "modified"], filters=filters, limit_start=start, limit_page_length=limit)
+	
+	for val in x:
+		info = get_dashboard_info(doctype, val.name)
+		items.append({"title": val.name,
+		"annual_billing":  get_formatted_value(info["billing_this_year"]),
+		"total_unpaid": get_formatted_value(abs(info["total_unpaid"])),
+		"href":"#Form/Supplier/" + val.name,
+		"modified": val.modified})
+
+	if len(x) > 99:
+		return get_all_suppliers(doctype, filters, items, start=start)
+	else:
+		return items
+
+def get_all_sales_partner(doctype, filters, items, start=0, limit=100):
+	"""return all sales partner"""
+	
+	x = frappe.get_list(doctype, fields=["name", "commission_rate", "modified"], filters=filters, limit_start=start, limit_page_length=limit)
+	for val in x:
+		y = frappe.db.sql('''select target_qty, target_amount from `tabTarget Detail` where parent = %s''', (val.name), as_dict=1)
+		target_qty = sum([f["target_qty"] for f in y])
+		target_amount = sum([f["target_amount"] for f in y])
+		items.append({"title": val.name,
+			"commission_rate": get_formatted_value(val.commission_rate, False),
+			"target_qty": target_qty,
+			"target_amount": get_formatted_value(target_amount),
+			"href":"#Form/Sales Partner/" + val.name,
+			"modified": val.modified})
+	if len(x) > 99:
+		return get_all_sales_partner(doctype, filters, items, start=start)
+	else:
+		return items
\ No newline at end of file
diff --git a/erpnext/utilities/page/leaderboard/leaderboard_main_head.html b/erpnext/utilities/page/leaderboard/leaderboard_main_head.html
new file mode 100644
index 0000000..257d4ed
--- /dev/null
+++ b/erpnext/utilities/page/leaderboard/leaderboard_main_head.html
@@ -0,0 +1,8 @@
+<div class="list-item__content ellipsis text-muted list-item__content--flex-2
+	{% if(col !== "Title" && col !== "Modified") { %}
+		hidden-xs
+	{% } %}
+	{% if(col && selected_filter.indexOf(col) !== -1) { %}text-right{% } %}">
+	
+	<span class="list-col-title ellipsis">{{col}}</span>
+</div>
\ No newline at end of file
diff --git a/erpnext/utilities/page/leaderboard/leaderboard_row_head.html b/erpnext/utilities/page/leaderboard/leaderboard_row_head.html
new file mode 100644
index 0000000..5a4e1dd
--- /dev/null
+++ b/erpnext/utilities/page/leaderboard/leaderboard_row_head.html
@@ -0,0 +1,3 @@
+<div class="list-item list-item--head" data-list-renderer="{{__(" List ")}}">
+	{{ main }}
+</div>
\ No newline at end of file