Merge pull request #5924 from KanchanChauhan/salary-structure-changes

Formula based Salary Structure
diff --git a/erpnext/__init__.py b/erpnext/__init__.py
index c433ddb..7c5133a 100644
--- a/erpnext/__init__.py
+++ b/erpnext/__init__.py
@@ -2,7 +2,7 @@
 from __future__ import unicode_literals
 import frappe
 
-__version__ = '7.0.28'
+__version__ = '7.0.31'
 
 def get_default_company(user=None):
 	'''Get default company for user'''
diff --git a/erpnext/accounts/doctype/budget/budget.json b/erpnext/accounts/doctype/budget/budget.json
index 4946304..d9464a5 100644
--- a/erpnext/accounts/doctype/budget/budget.json
+++ b/erpnext/accounts/doctype/budget/budget.json
@@ -8,6 +8,7 @@
  "docstatus": 0, 
  "doctype": "DocType", 
  "document_type": "", 
+ "editable_grid": 1, 
  "fields": [
   {
    "allow_on_submit": 0, 
@@ -65,24 +66,24 @@
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
-   "fieldname": "monthly_distribution", 
+   "fieldname": "company", 
    "fieldtype": "Link", 
    "hidden": 0, 
    "ignore_user_permissions": 0, 
    "ignore_xss_filter": 0, 
    "in_filter": 0, 
    "in_list_view": 0, 
-   "label": "Monthly Distribution", 
+   "label": "Company", 
    "length": 0, 
    "no_copy": 0, 
-   "options": "Monthly Distribution", 
+   "options": "Company", 
    "permlevel": 0, 
    "precision": "", 
    "print_hide": 0, 
    "print_hide_if_no_value": 0, 
    "read_only": 0, 
    "report_hide": 0, 
-   "reqd": 0, 
+   "reqd": 1, 
    "search_index": 0, 
    "set_only_once": 0, 
    "unique": 0
@@ -170,24 +171,25 @@
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
-   "fieldname": "company", 
+   "depends_on": "eval:in_list([\"Stop\", \"Warn\"], doc.action_if_accumulated_monthly_budget_exceeded)", 
+   "fieldname": "monthly_distribution", 
    "fieldtype": "Link", 
    "hidden": 0, 
    "ignore_user_permissions": 0, 
    "ignore_xss_filter": 0, 
    "in_filter": 0, 
    "in_list_view": 0, 
-   "label": "Company", 
+   "label": "Monthly Distribution", 
    "length": 0, 
    "no_copy": 0, 
-   "options": "Company", 
+   "options": "Monthly Distribution", 
    "permlevel": 0, 
    "precision": "", 
    "print_hide": 0, 
    "print_hide_if_no_value": 0, 
    "read_only": 0, 
    "report_hide": 0, 
-   "reqd": 1, 
+   "reqd": 0, 
    "search_index": 0, 
    "set_only_once": 0, 
    "unique": 0
@@ -271,13 +273,14 @@
  "hide_heading": 0, 
  "hide_toolbar": 0, 
  "idx": 0, 
+ "image_view": 0, 
  "in_create": 0, 
  "in_dialog": 0, 
  "is_submittable": 1, 
  "issingle": 0, 
  "istable": 0, 
  "max_attachments": 0, 
- "modified": "2016-05-16 15:00:40.233685", 
+ "modified": "2016-08-18 14:46:02.653081", 
  "modified_by": "Administrator", 
  "module": "Accounts", 
  "name": "Budget", 
diff --git a/erpnext/accounts/doctype/budget/budget.py b/erpnext/accounts/doctype/budget/budget.py
index 819a635..529401c 100644
--- a/erpnext/accounts/doctype/budget/budget.py
+++ b/erpnext/accounts/doctype/budget/budget.py
@@ -5,7 +5,7 @@
 from __future__ import unicode_literals
 import frappe
 from frappe import _
-from frappe.utils import flt, getdate, add_months, get_last_day
+from frappe.utils import flt, getdate, add_months, get_last_day, fmt_money
 from frappe.model.naming import make_autoname
 from frappe.model.document import Document
 
@@ -73,25 +73,30 @@
 						args.posting_date, args.fiscal_year, budget.budget_amount)
 
 					args["month_end_date"] = get_last_day(args.posting_date)
-
+						
 					compare_expense_with_budget(args, budget.cost_center,
 						budget_amount, _("Accumulated Monthly"), monthly_action)
 
-				elif yearly_action in ["Stop", "Warn"]:
-					compare_expense_with_budget(args, budget.cost_center,
-						flt(budget.budget_amount), _("Annual"), yearly_action)
+				if yearly_action in ("Stop", "Warn") and monthly_action != "Stop" \
+					and yearly_action != monthly_action:
+						compare_expense_with_budget(args, budget.cost_center,
+							flt(budget.budget_amount), _("Annual"), yearly_action)
 
 def compare_expense_with_budget(args, cost_center, budget_amount, action_for, action):
 	actual_expense = get_actual_expense(args, cost_center)
 	if actual_expense > budget_amount:
 		diff = actual_expense - budget_amount
+		currency = frappe.db.get_value('Company', frappe.db.get_value('Cost Center',
+			cost_center, 'company'), 'default_currency')
 
-		msg = _("{0} Budget for Account {1} against Cost Center {2} is {3}. It will exceed by {4}").format(_(action_for), args.account, cost_center, budget_amount, diff)
+		msg = _("{0} Budget for Account {1} against Cost Center {2} is {3}. It will exceed by {4}").format(_(action_for),
+			frappe.bold(args.account), frappe.bold(cost_center),
+			frappe.bold(fmt_money(budget_amount, currency=currency)), frappe.bold(fmt_money(diff, currency=currency)))
 
 		if action=="Stop":
 			frappe.throw(msg, BudgetError)
 		else:
-			frappe.msgprint(msg)
+			frappe.msgprint(msg, indicator='orange')
 
 def get_accumulated_monthly_budget(monthly_distribution, posting_date, fiscal_year, annual_budget):
 	distribution = {}
diff --git a/erpnext/accounts/doctype/cost_center/cost_center.js b/erpnext/accounts/doctype/cost_center/cost_center.js
index dea87f3..83ecc9f 100644
--- a/erpnext/accounts/doctype/cost_center/cost_center.js
+++ b/erpnext/accounts/doctype/cost_center/cost_center.js
@@ -32,8 +32,13 @@
 	cur_frm.toggle_display('sb1', doc.is_group==0)
 	cur_frm.set_intro(intro_txt);
 
-	cur_frm.add_custom_button(__('Chart of Cost Centers'),
-		function() { frappe.set_route("Tree", "Cost Center"); }, __("View"))
+	if(!cur_frm.doc.__islocal) {
+		cur_frm.add_custom_button(__('Chart of Cost Centers'),
+			function() { frappe.set_route("Tree", "Cost Center"); });
+
+		cur_frm.add_custom_button(__('Budget'),
+			function() { frappe.set_route("List", "Budget", {'cost_center': cur_frm.doc.name}); });
+	}
 }
 
 cur_frm.cscript.parent_cost_center = function(doc, cdt, cdn) {
diff --git a/erpnext/accounts/doctype/pos_profile/pos_profile.json b/erpnext/accounts/doctype/pos_profile/pos_profile.json
index cb637d2..01a87c4 100644
--- a/erpnext/accounts/doctype/pos_profile/pos_profile.json
+++ b/erpnext/accounts/doctype/pos_profile/pos_profile.json
@@ -122,6 +122,32 @@
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
+   "fieldname": "campaign", 
+   "fieldtype": "Link", 
+   "hidden": 0, 
+   "ignore_user_permissions": 0, 
+   "ignore_xss_filter": 0, 
+   "in_filter": 0, 
+   "in_list_view": 0, 
+   "label": "Campaign", 
+   "length": 0, 
+   "no_copy": 0, 
+   "options": "Campaign", 
+   "permlevel": 0, 
+   "precision": "", 
+   "print_hide": 0, 
+   "print_hide_if_no_value": 0, 
+   "read_only": 0, 
+   "report_hide": 0, 
+   "reqd": 0, 
+   "search_index": 0, 
+   "set_only_once": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
    "fieldname": "ignore_pricing_rule", 
    "fieldtype": "Check", 
    "hidden": 0, 
@@ -694,6 +720,32 @@
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
+   "fieldname": "account_for_change_amount", 
+   "fieldtype": "Link", 
+   "hidden": 0, 
+   "ignore_user_permissions": 0, 
+   "ignore_xss_filter": 0, 
+   "in_filter": 0, 
+   "in_list_view": 0, 
+   "label": "Account for Change Amount", 
+   "length": 0, 
+   "no_copy": 0, 
+   "options": "Account", 
+   "permlevel": 0, 
+   "precision": "", 
+   "print_hide": 0, 
+   "print_hide_if_no_value": 0, 
+   "read_only": 0, 
+   "report_hide": 0, 
+   "reqd": 0, 
+   "search_index": 0, 
+   "set_only_once": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
    "fieldname": "taxes_and_charges", 
    "fieldtype": "Link", 
    "hidden": 0, 
@@ -833,7 +885,7 @@
  "issingle": 0, 
  "istable": 0, 
  "max_attachments": 0, 
- "modified": "2016-08-06 17:05:59.990031", 
+ "modified": "2016-08-17 15:12:56.713748", 
  "modified_by": "Administrator", 
  "module": "Accounts", 
  "name": "POS Profile", 
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
index c655626..c51231e 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
@@ -232,7 +232,8 @@
 
 cur_frm.fields_dict['items'].grid.get_field("item_code").get_query = function(doc, cdt, cdn) {
 	return {
-		query: "erpnext.controllers.queries.item_query"
+		query: "erpnext.controllers.queries.item_query",
+		filters: {'is_purchase_item': 1}
 	}
 }
 
diff --git a/erpnext/accounts/doctype/purchase_taxes_and_charges_template/purchase_taxes_and_charges_template.js b/erpnext/accounts/doctype/purchase_taxes_and_charges_template/purchase_taxes_and_charges_template.js
index 433cda7..a1d8bf8 100644
--- a/erpnext/accounts/doctype/purchase_taxes_and_charges_template/purchase_taxes_and_charges_template.js
+++ b/erpnext/accounts/doctype/purchase_taxes_and_charges_template/purchase_taxes_and_charges_template.js
@@ -18,3 +18,13 @@
 	}
 	refresh_field('add_deduct_tax', d.name, 'taxes');
 });
+
+frappe.ui.form.on("Purchase Taxes and Charges", "category", function(doc, cdt, cdn) {
+	var d = locals[cdt][cdn];
+
+	if (d.category != 'Total' && d.add_deduct_tax == 'Deduct') {
+		msgprint(__("Cannot deduct when category is for 'Valuation' or 'Vaulation and Total'"));
+		d.add_deduct_tax = '';
+	}
+	refresh_field('add_deduct_tax', d.name, 'taxes');
+});
diff --git a/erpnext/accounts/doctype/sales_invoice/pos.py b/erpnext/accounts/doctype/sales_invoice/pos.py
index 33032bf..599e9b1 100644
--- a/erpnext/accounts/doctype/sales_invoice/pos.py
+++ b/erpnext/accounts/doctype/sales_invoice/pos.py
@@ -13,9 +13,9 @@
 @frappe.whitelist()
 def get_pos_data():
 	doc = frappe.new_doc('Sales Invoice')
-	doc.update_stock = 1;
 	doc.is_pos = 1;
 	pos_profile = get_pos_profile(doc.company) or {}
+	doc.update_stock = pos_profile.get('update_stock')
 
 	if pos_profile.get('name'):
 		pos_profile = frappe.get_doc('POS Profile', pos_profile.get('name'))
@@ -35,7 +35,6 @@
 		'customers': get_customers(pos_profile, doc),
 		'pricing_rules': get_pricing_rules(doc),
 		'print_template': print_template,
-		'write_off_account': pos_profile.get('write_off_account'),
 		'meta': {
 			'invoice': frappe.get_meta('Sales Invoice'),
 			'items': frappe.get_meta('Sales Invoice Item'),
@@ -45,7 +44,12 @@
 
 def update_pos_profile_data(doc, pos_profile):
 	company_data = frappe.db.get_value('Company', doc.company, '*', as_dict=1)
+	doc.campaign = pos_profile.get('campaign')
 
+	doc.write_off_account = pos_profile.get('write_off_account') or \
+		company_data.write_off_account
+	doc.change_amount_account = pos_profile.get('change_amount_account') or \
+		company_data.default_cash_account
 	doc.taxes_and_charges = pos_profile.get('taxes_and_charges')
 	if doc.taxes_and_charges:
 		update_tax_table(doc)
@@ -54,7 +58,8 @@
 	doc.conversion_rate = 1.0
 	if doc.currency != company_data.default_currency:
 		doc.conversion_rate = get_exchange_rate(doc.currency, company_data.default_currency)
-	doc.selling_price_list = pos_profile.get('selling_price_list') or frappe.db.get_value('Selling Settings', None, 'selling_price_list')
+	doc.selling_price_list = pos_profile.get('selling_price_list') or \
+		frappe.db.get_value('Selling Settings', None, 'selling_price_list')
 	doc.naming_series = pos_profile.get('naming_series') or 'SINV-'
 	doc.letter_head = pos_profile.get('letter_head') or company_data.default_letter_head
 	doc.ignore_pricing_rule = pos_profile.get('ignore_pricing_rule') or 0
@@ -100,7 +105,7 @@
 
 def get_items(doc, pos_profile):
 	item_list = []
-	for item in frappe.get_all("Item", fields=["*"], filters={'disabled': 0, 'has_variants': 0}):
+	for item in frappe.get_all("Item", fields=["*"], filters={'disabled': 0, 'has_variants': 0, 'is_sales_item': 1}):
 		item_doc = frappe.get_doc('Item', item.name)
 		if item_doc.taxes:
 			item.taxes = json.dumps(dict(([d.tax_type, d.tax_rate] for d in
@@ -157,10 +162,11 @@
 def get_pricing_rules(doc):
 	pricing_rules = ""
 	if doc.ignore_pricing_rule == 0:
-		pricing_rules = frappe.db.sql(""" Select * from `tabPricing Rule` where docstatus < 2 and disable = 0
-						and selling = 1 and ifnull(company, '') in (%(company)s, '') and
-						ifnull(for_price_list, '') in (%(price_list)s, '')  and %(date)s between
-						ifnull(valid_from, '2000-01-01') and ifnull(valid_upto, '2500-12-31') order by priority desc, name desc""",
+		pricing_rules = frappe.db.sql(""" Select * from `tabPricing Rule` where docstatus < 2
+						and ifnull(for_price_list, '') in (%(price_list)s, '') and selling = 1
+						and ifnull(company, '') in (%(company)s, '') and disable = 0 and %(date)s
+						between ifnull(valid_from, '2000-01-01') and ifnull(valid_upto, '2500-12-31')
+						order by priority desc, name desc""",
 						{'company': doc.company, 'price_list': doc.selling_price_list, 'date': nowdate()}, as_dict=1)
 	return pricing_rules
 
@@ -173,9 +179,9 @@
 
 	for docs in doc_list:
 		for name, doc in docs.items():
-			if not frappe.db.exists('Sales Invoice', {'offline_pos_name': name}):
-				validate_customer(doc)
-				validate_item(doc)
+			if not frappe.db.exists('Sales Invoice',
+				{'offline_pos_name': name, 'docstatus': ("<", "2")}):
+				validate_records(doc)
 				si_doc = frappe.new_doc('Sales Invoice')
 				si_doc.offline_pos_name = name
 				si_doc.update(doc)
@@ -186,6 +192,10 @@
 
 	return name_list
 
+def validate_records(doc):
+	validate_customer(doc)
+	validate_item(doc)
+
 def validate_customer(doc):
 	if not frappe.db.exists('Customer', doc.get('customer')):
 		customer_doc = frappe.new_doc('Customer')
@@ -197,8 +207,6 @@
 		frappe.db.commit()
 		doc['customer'] = customer_doc.name
 
-	return doc
-
 def validate_item(doc):
 	for item in doc.get('items'):
 		if not frappe.db.exists('Item', item.get('item_code')):
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
index b73673f..3245e78 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
@@ -267,6 +267,16 @@
 
 	amount: function(){
 		this.write_off_outstanding_amount_automatically()
+	},
+
+	change_amount: function(){
+		if(this.frm.doc.paid_amount > this.frm.doc.grand_total){
+			this.calculate_write_off_amount()
+		}else {
+			this.frm.set_value("change_amount", 0.0)
+		}
+
+		this.frm.refresh_fields();
 	}
 });
 
@@ -458,7 +468,7 @@
 				]
 			}
 		}
-	},
+	}
 })
 
 frappe.ui.form.on('Sales Invoice Timesheet', {
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.json b/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
index 06bc635..a2e930c 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
@@ -2204,32 +2204,6 @@
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
-   "fieldname": "base_change_amount", 
-   "fieldtype": "Currency", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_list_view": 0, 
-   "label": "Base Change Amount (Company Currency)", 
-   "length": 0, 
-   "no_copy": 1, 
-   "options": "Company:company:default_currency", 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 1, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 1, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "unique": 0
-  }, 
-  {
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
    "fieldname": "column_break_86", 
    "fieldtype": "Column Break", 
    "hidden": 0, 
@@ -2282,6 +2256,80 @@
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
+   "fieldname": "section_break_88", 
+   "fieldtype": "Section Break", 
+   "hidden": 0, 
+   "ignore_user_permissions": 0, 
+   "ignore_xss_filter": 0, 
+   "in_filter": 0, 
+   "in_list_view": 0, 
+   "length": 0, 
+   "no_copy": 0, 
+   "permlevel": 0, 
+   "precision": "", 
+   "print_hide": 0, 
+   "print_hide_if_no_value": 0, 
+   "read_only": 0, 
+   "report_hide": 0, 
+   "reqd": 0, 
+   "search_index": 0, 
+   "set_only_once": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
+   "fieldname": "base_change_amount", 
+   "fieldtype": "Currency", 
+   "hidden": 0, 
+   "ignore_user_permissions": 0, 
+   "ignore_xss_filter": 0, 
+   "in_filter": 0, 
+   "in_list_view": 0, 
+   "label": "Base Change Amount (Company Currency)", 
+   "length": 0, 
+   "no_copy": 1, 
+   "options": "Company:company:default_currency", 
+   "permlevel": 0, 
+   "precision": "", 
+   "print_hide": 1, 
+   "print_hide_if_no_value": 0, 
+   "read_only": 1, 
+   "report_hide": 0, 
+   "reqd": 0, 
+   "search_index": 0, 
+   "set_only_once": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
+   "fieldname": "column_break_90", 
+   "fieldtype": "Column Break", 
+   "hidden": 0, 
+   "ignore_user_permissions": 0, 
+   "ignore_xss_filter": 0, 
+   "in_filter": 0, 
+   "in_list_view": 0, 
+   "length": 0, 
+   "no_copy": 0, 
+   "permlevel": 0, 
+   "precision": "", 
+   "print_hide": 0, 
+   "print_hide_if_no_value": 0, 
+   "read_only": 0, 
+   "report_hide": 0, 
+   "reqd": 0, 
+   "search_index": 0, 
+   "set_only_once": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
    "fieldname": "change_amount", 
    "fieldtype": "Currency", 
    "hidden": 0, 
@@ -2297,7 +2345,33 @@
    "precision": "", 
    "print_hide": 1, 
    "print_hide_if_no_value": 0, 
-   "read_only": 1, 
+   "read_only": 0, 
+   "report_hide": 0, 
+   "reqd": 0, 
+   "search_index": 0, 
+   "set_only_once": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
+   "fieldname": "account_for_change_amount", 
+   "fieldtype": "Link", 
+   "hidden": 0, 
+   "ignore_user_permissions": 0, 
+   "ignore_xss_filter": 0, 
+   "in_filter": 0, 
+   "in_list_view": 0, 
+   "label": "Account for Change Amount", 
+   "length": 0, 
+   "no_copy": 0, 
+   "options": "Account", 
+   "permlevel": 0, 
+   "precision": "", 
+   "print_hide": 0, 
+   "print_hide_if_no_value": 0, 
+   "read_only": 0, 
    "report_hide": 0, 
    "reqd": 0, 
    "search_index": 0, 
@@ -3677,7 +3751,7 @@
  "istable": 0, 
  "max_attachments": 0, 
  "menu_index": 0, 
- "modified": "2016-08-03 11:50:49.680278", 
+ "modified": "2016-08-17 15:12:39.357372", 
  "modified_by": "Administrator", 
  "module": "Accounts", 
  "name": "Sales Invoice", 
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
index f055140..871a151 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
@@ -61,6 +61,7 @@
 		self.clear_unallocated_advances("Sales Invoice Advance", "advances")
 		self.add_remarks()
 		self.validate_write_off_account()
+		self.validate_account_for_change_amount()
 		self.validate_fixed_asset()
 		self.set_income_account_for_fixed_assets()
 
@@ -233,12 +234,22 @@
 		from erpnext.stock.get_item_details import get_pos_profile_item_details, get_pos_profile
 		pos = get_pos_profile(self.company)
 
+		if not self.get('payments'):
+			pos_profile = frappe.get_doc('POS Profile', pos.name) if pos else None
+			update_multi_mode_option(self, pos_profile)
+
+		if not self.account_for_change_amount:
+			self.account_for_change_amount = frappe.db.get_value('Company', self.company, 'default_cash_account')
+
 		if pos:
 			if not for_validate and not self.customer:
 				self.customer = pos.customer
 				self.mode_of_payment = pos.mode_of_payment
 				# self.set_customer_defaults()
 
+			if pos.get('account_for_change_amount'):
+				self.account_for_change_amount = pos.get('account_for_change_amount')
+
 			for fieldname in ('territory', 'naming_series', 'currency', 'taxes_and_charges', 'letter_head', 'tc_name',
 				'selling_price_list', 'company', 'select_print_heading', 'cash_bank_account',
 				'write_off_account', 'write_off_cost_center'):
@@ -265,10 +276,6 @@
 			if self.taxes_and_charges and not len(self.get("taxes")):
 				self.set_taxes()
 
-			if not self.get('payments'):
-				pos_profile = frappe.get_doc('POS Profile', pos.name)
-				update_multi_mode_option(self, pos_profile)
-
 		return pos
 
 	def get_company_abbr(self):
@@ -379,6 +386,9 @@
 		if flt(self.write_off_amount) and not self.write_off_account:
 			msgprint(_("Please enter Write Off Account"), raise_exception=1)
 
+	def validate_account_for_change_amount(self):
+		if flt(self.change_amount) and not self.account_for_change_amount:
+			msgprint(_("Please enter Account for Change Amount"), raise_exception=1)
 
 	def validate_c_form(self):
 		""" Blank C-form no if C-form applicable marked as 'No'"""
@@ -502,7 +512,7 @@
 		gl_entries = merge_similar_entries(gl_entries)
 
 		self.make_pos_gl_entries(gl_entries)
-		self.make_gle_for_change(gl_entries)
+		self.make_gle_for_change_amount(gl_entries)
 
 		self.make_write_off_gl_entry(gl_entries)
 
@@ -606,16 +616,15 @@
 						}, payment_mode_account_currency)
 					)
 				
-	def make_gle_for_change(self, gl_entries):
+	def make_gle_for_change_amount(self, gl_entries):
 		if cint(self.is_pos) and self.change_amount:
-			cash_account = self.get_cash_account()
-			if cash_account:
+			if self.account_for_change_amount:
 				gl_entries.append(
 					self.get_gl_dict({
 						"account": self.debit_to,
 						"party_type": "Customer",
 						"party": self.customer,
-						"against": cash_account,
+						"against": self.account_for_change_amount,
 						"debit": flt(self.base_change_amount),
 						"debit_in_account_currency": flt(self.base_change_amount) \
 							if self.party_account_currency==self.company_currency else flt(self.change_amount),
@@ -626,22 +635,13 @@
 				
 				gl_entries.append(
 					self.get_gl_dict({
-						"account": cash_account,
+						"account": self.account_for_change_amount,
 						"against": self.customer,
 						"credit": self.base_change_amount
 					})
 				)
-		
-				
-	def get_cash_account(self):
-		cash_account = [d.account for d in self.payments if d.type=="Cash"]
-		if cash_account:
-			cash_account = cash_account[0]
-		else:
-			cash_account = frappe.db.get_value("Account", 
-				filters={"company": self.company, "account_type": "Cash", "is_group": 0})
-				
-		return cash_account
+			else:
+				frappe.throw(_("Select change amount account"), title="Mandatory Field")
 		
 	def make_write_off_gl_entry(self, gl_entries):
 		# write off entries, applicable if only pos
diff --git a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
index dd28059..1bb7b1c 100644
--- a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
@@ -455,6 +455,25 @@
 
 		self.pos_gl_entry(si, pos, 300)
 
+	def test_pos_change_amount(self):
+		set_perpetual_inventory()
+		self.make_pos_profile()
+
+		self._insert_purchase_receipt()
+		pos = copy.deepcopy(test_records[1])
+		pos["is_pos"] = 1
+		pos["update_stock"] = 1
+		pos["payments"] = [{'mode_of_payment': 'Bank Draft', 'account': '_Test Bank - _TC', 'amount': 300},
+							{'mode_of_payment': 'Cash', 'account': 'Cash - _TC', 'amount': 340}]
+
+		si = frappe.copy_doc(pos)
+		si.change_amount = 5.0
+		si.insert()
+		si.submit()
+
+		self.assertEquals(si.grand_total, 630.0)
+		self.assertEquals(si.write_off_amount, -5)
+
 	def test_make_pos_invoice(self):
 		from erpnext.accounts.doctype.sales_invoice.pos import make_invoice
 
diff --git a/erpnext/accounts/page/pos/pos.js b/erpnext/accounts/page/pos/pos.js
index 0d3e019..06606a9 100644
--- a/erpnext/accounts/page/pos/pos.js
+++ b/erpnext/accounts/page/pos/pos.js
@@ -183,6 +183,14 @@
 		if(this.frm.doc.customer){
 			this.party_field.$input.val(this.frm.doc.customer);
 		}
+
+		if(!this.frm.doc.write_off_account){
+			this.frm.doc.write_off_account = doc.write_off_account
+		}
+
+		if(!this.frm.doc.account_for_change_amount){
+			this.frm.doc.account_for_change_amount = doc.account_for_change_amount
+		}
 	},
 
 	get_invoice_doc: function(si_docs){
@@ -209,7 +217,6 @@
 				window.meta = r.message.meta;
 				window.print_template = r.message.print_template;
 				me.default_customer = r.message.default_customer || null;
-				me.write_off_account = r.message.write_off_account;
 				localStorage.setItem('doc', JSON.stringify(r.message.doc));
 				if(callback){
 					callback();
@@ -485,11 +492,8 @@
 
 		this.remove_item = []
 		$.each(this.frm.doc["items"] || [], function(i, d) {
-			if (d.item_code == item_code && d.serial_no
-				&& field == 'qty' && cint(value) != value) {
-				d.qty = 0.0;
-				me.refresh();
-				frappe.throw(__("Serial no item cannot be a fraction"))
+			if(d.serial_no){
+				me.validate_serial_no_qty(d, item_code, field, value)
 			}
 
 			if (d.item_code == item_code) {
@@ -723,49 +727,6 @@
 		}, 1000)
 	},
 
-	write_off_amount: function(){
-		var me = this;
-		var value = 0.0;
-
-		if(this.frm.doc.outstanding_amount > 0){
-			dialog = new frappe.ui.Dialog({
-				title: 'Write Off Amount',
-				fields: [
-					{fieldtype: "Check", fieldname: "write_off_amount", label: __("Write off Outstanding Amount")},
-					{fieldtype: "Link", options:"Account", default:this.write_off_account, fieldname: "write_off_account", 
-					label: __("Write off Account"), get_query: function() {
-						return {
-							filters: {'is_group': 0, 'report_type': 'Profit and Loss'}
-						}
-					}}
-				]
-			});
-
-			dialog.show();
-
-			dialog.fields_dict.write_off_amount.$input.change(function(){
-				write_off_amount = dialog.get_values().write_off_amount;
-				me.frm.doc.write_off_outstanding_amount_automatically = write_off_amount;
-				me.frm.doc.base_write_off_amount = (write_off_amount==1) ? flt(me.frm.doc.grand_total - me.frm.doc.paid_amount, precision("outstanding_amount")) : 0;
-				me.frm.doc.write_off_account = (write_off_amount==1) ? dialog.get_values().write_off_account : '';
-				me.frm.doc.write_off_amount = flt(me.frm.doc.base_write_off_amount * me.frm.doc.conversion_rate, precision("write_off_amount"))
-				me.calculate_outstanding_amount();
-				me.set_primary_action();
-			})
-
-			dialog.fields_dict.write_off_account.$input.change(function(){
-				me.frm.doc.write_off_account = dialog.get_values().write_off_account;
-			})
-
-			dialog.set_primary_action(__("Submit"), function(){
-				dialog.hide()
-				me.submit_invoice()
-			})
-		}else{
-			this.submit_invoice()
-		}
-	},
-
 	submit_invoice: function(){
 		var me = this;
 		frappe.confirm(__("Do you really want to submit the invoice?"), function () {
@@ -951,6 +912,23 @@
 		}
 	},
 
+	validate_serial_no_qty: function(args, item_code, field, value){
+		var me = this;
+		if (args.item_code == item_code && args.serial_no
+			&& field == 'qty' && cint(value) != value) {
+			args.qty = 0.0;
+			this.refresh();
+			frappe.throw(__("Serial no item cannot be a fraction"))
+		}
+
+		if(args.serial_no && args.serial_no.split('\n').length != cint(value)){
+			args.qty = 0.0;
+			args.serial_no = ''
+			this.refresh();
+			frappe.throw(__("Total nos of serial no is not equal to quantity."))
+		}
+	},
+
 	mandatory_batch_no: function(){
 		var me = this;
 		if(this.items[0].has_batch_no && !this.item_batch_no[this.items[0].item_code]){
@@ -978,11 +956,13 @@
 	get_pricing_rule: function(item){
 		var me = this;
 		return $.grep(this.pricing_rules, function(data){
-			if(data.item_code == item.item_code || in_list(['All Item Groups', item.item_group], data.item_group)) {
-				if(in_list(['Customer', 'Customer Group', 'Territory'], data.applicable_for)){
-					return me.validate_condition(data)
-				}else{
-					return true
+			if(item.qty >= data.min_qty && (item.qty <= (data.max_qty ? data.max_qty : item.qty)) ){
+				if(data.item_code == item.item_code || in_list(['All Item Groups', item.item_group], data.item_group)) {
+					if(in_list(['Customer', 'Customer Group', 'Territory', 'Campaign'], data.applicable_for)){
+						return me.validate_condition(data)
+					}else{
+						return true
+					}
 				}
 			}
 		})
@@ -1001,6 +981,7 @@
 			'Customer': [data.customer, [this.frm.doc.customer]],
 			'Customer Group': [data.customer_group, [this.frm.doc.customer_group, 'All Customer Groups']],
 			'Territory': [data.territory, [this.frm.doc.territory, 'All Territories']],
+			'Campaign': [data.campaign, [this.frm.doc.campaign]],
 		}
 	},
 
diff --git a/erpnext/accounts/report/accounts_receivable/accounts_receivable.py b/erpnext/accounts/report/accounts_receivable/accounts_receivable.py
index 843937f..ed429d6 100644
--- a/erpnext/accounts/report/accounts_receivable/accounts_receivable.py
+++ b/erpnext/accounts/report/accounts_receivable/accounts_receivable.py
@@ -66,7 +66,8 @@
 		columns.append({
 			"fieldname": "currency",
 			"label": _("Currency"),
-			"fieldtype": "Data",
+			"fieldtype": "Link",
+			"options": "Currency",
 			"width": 100
 		})
 		if args.get("party_type") == "Customer":
diff --git a/erpnext/accounts/report/accounts_receivable_summary/accounts_receivable_summary.py b/erpnext/accounts/report/accounts_receivable_summary/accounts_receivable_summary.py
index 36e9734..8c627b6 100644
--- a/erpnext/accounts/report/accounts_receivable_summary/accounts_receivable_summary.py
+++ b/erpnext/accounts/report/accounts_receivable_summary/accounts_receivable_summary.py
@@ -34,7 +34,8 @@
 		columns.append({
 			"fieldname": "currency",
 			"label": _("Currency"),
-			"fieldtype": "Data",
+			"fieldtype": "Link",
+			"options": "Currency",
 			"width": 80
 		})
 
diff --git a/erpnext/buying/doctype/purchase_common/purchase_common.js b/erpnext/buying/doctype/purchase_common/purchase_common.js
index 2e76516..6e27546 100644
--- a/erpnext/buying/doctype/purchase_common/purchase_common.js
+++ b/erpnext/buying/doctype/purchase_common/purchase_common.js
@@ -79,7 +79,8 @@
 				}
 			} else {
 				return{
-					query: "erpnext.controllers.queries.item_query"
+					query: "erpnext.controllers.queries.item_query",
+					filters: {'is_purchase_item': 1}
 				}
 			}
 		});
diff --git a/erpnext/buying/report/quoted_item_comparison/quoted_item_comparison.js b/erpnext/buying/report/quoted_item_comparison/quoted_item_comparison.js
index 45bc738..0f44baa 100644
--- a/erpnext/buying/report/quoted_item_comparison/quoted_item_comparison.js
+++ b/erpnext/buying/report/quoted_item_comparison/quoted_item_comparison.js
@@ -11,5 +11,72 @@
 		"default": ""
 		
 	}
-	]
+	],
+	onload: function(report) {
+		//Create a button for setting the default supplier
+		report.page.add_inner_button(__("Select Default Supplier"), function() {
+
+			var reporter = frappe.query_reports["Quoted Item Comparison"];
+			
+			//Always make a new one so that the latest values get updated
+			reporter.make_default_supplier_dialog(report);
+			report.dialog.show();
+			setTimeout(function() { report.dialog.input.focus(); }, 1000);
+				
+		}, 'Tools');
+		
+	},
+	"make_default_supplier_dialog": function (report) {
+		//Get the name of the item to change
+		var filters = report.get_values();
+		var item_code = filters.item;
+		
+		//Get a list of the suppliers (with a blank as well) for the user to select
+		var select_options = "";
+		for (let supplier of report.data)
+		{
+			select_options += supplier.supplier_name+ '\n'
+		}
+		
+		//Create a dialog window for the user to pick their supplier
+		var d = new frappe.ui.Dialog({
+			title: __('Select Default Supplier'),
+			fields: [
+			{fieldname: 'supplier', fieldtype:'Select', label:'Supplier', reqd:1,options:select_options},
+			{fieldname: 'ok_button', fieldtype:'Button', label:'Set Default Supplier'},
+			]
+		});
+		
+		//On the user clicking the ok button
+		d.fields_dict.ok_button.input.onclick = function() {
+			var btn = d.fields_dict.ok_button.input;
+			var v = report.dialog.get_values();
+			if(v) {
+				$(btn).set_working();
+				
+				//Set the default_supplier field of the appropriate Item to the selected supplier
+				frappe.call({
+					method: "frappe.client.set_value",
+					args: {
+						doctype: "Item", 
+						name: item_code,
+						fieldname: "default_supplier",
+						value: v.supplier, 
+					},
+					callback: function (r){
+						$(btn).done_working();
+						msgprint("Successfully Set Supplier");
+						report.dialog.hide();
+
+					}
+				});
+			}
+		}
+		report.dialog = d;
+		
+		
+	}
+	
 }
+
+
diff --git a/erpnext/controllers/taxes_and_totals.py b/erpnext/controllers/taxes_and_totals.py
index 28b2f7c..125f4fe 100644
--- a/erpnext/controllers/taxes_and_totals.py
+++ b/erpnext/controllers/taxes_and_totals.py
@@ -440,6 +440,7 @@
 			paid_amount = self.doc.paid_amount \
 				if self.doc.party_account_currency == self.doc.currency else self.doc.base_paid_amount
 
+			self.calculate_write_off_amount()
 			self.calculate_change_amount()
 
 			self.doc.outstanding_amount = flt(total_amount_to_pay - flt(paid_amount) +
@@ -468,6 +469,12 @@
 		self.doc.base_change_amount = flt(self.doc.change_amount * self.doc.conversion_rate, 
 			self.doc.precision("base_change_amount"))
 
+	def calculate_write_off_amount(self):
+		if flt(self.doc.change_amount) > 0:
+			self.doc.write_off_amount = self.doc.grand_total - self.doc.paid_amount + self.doc.change_amount
+			self.doc.base_write_off_amount = flt(self.doc.write_off_amount * self.doc.conversion_rate,
+				self.doc.precision("base_write_off_amount"))
+
 	def calculate_margin(self, item):
 		total_margin = 0.0
 		if item.price_list_rate:
diff --git a/erpnext/crm/doctype/opportunity/opportunity.js b/erpnext/crm/doctype/opportunity/opportunity.js
index 21a7429..c9f1ffb 100644
--- a/erpnext/crm/doctype/opportunity/opportunity.js
+++ b/erpnext/crm/doctype/opportunity/opportunity.js
@@ -51,7 +51,8 @@
 
 		this.frm.set_query("item_code", "items", function() {
 			return {
-				query: "erpnext.controllers.queries.item_query"
+				query: "erpnext.controllers.queries.item_query",
+				filters: {'is_sales_item': 1}
 			};
 		});
 
diff --git a/erpnext/hr/doctype/employee/employee_list.js b/erpnext/hr/doctype/employee/employee_list.js
index 697900c..c786004 100644
--- a/erpnext/hr/doctype/employee/employee_list.js
+++ b/erpnext/hr/doctype/employee/employee_list.js
@@ -1,5 +1,5 @@
 frappe.listview_settings['Employee'] = {
-	add_fields: ["status", "branch", "department", "designation"],
+	add_fields: ["status", "branch", "department", "designation","image"],
 	filters: [["status","=", "Active"]],
 	get_indicator: function(doc) {
 		var indicator = [__(doc.status), frappe.utils.guess_colour(doc.status), "status,=," + doc.status];
diff --git a/erpnext/patches/v5_2/change_item_selects_to_checks.py b/erpnext/patches/v5_2/change_item_selects_to_checks.py
index dde0b56..1ee8f6c 100644
--- a/erpnext/patches/v5_2/change_item_selects_to_checks.py
+++ b/erpnext/patches/v5_2/change_item_selects_to_checks.py
@@ -4,8 +4,7 @@
 
 def execute():
 	fields = ("is_stock_item", "is_asset_item", "has_batch_no", "has_serial_no",
-		"inspection_required", "is_sub_contracted_item")
-
+		"is_sales_item", "is_purchase_item", "inspection_required", "is_sub_contracted_item")
 
 	# convert to 1 or 0
 	update_str = ", ".join(["`{0}`=if(`{0}`='Yes',1,0)".format(f) for f in fields])
diff --git a/erpnext/patches/v7_0/calculate_total_costing_amount.py b/erpnext/patches/v7_0/calculate_total_costing_amount.py
index 4da839f..11fdff9 100644
--- a/erpnext/patches/v7_0/calculate_total_costing_amount.py
+++ b/erpnext/patches/v7_0/calculate_total_costing_amount.py
@@ -13,4 +13,5 @@
 			ts.flags.ignore_validate = True
 			ts.flags.ignore_mandatory = True
 			ts.flags.ignore_validate_update_after_submit = True
+			ts.flags.ignore_links = True
 			ts.save()
diff --git a/erpnext/patches/v7_0/convert_timelog_to_timesheet.py b/erpnext/patches/v7_0/convert_timelog_to_timesheet.py
index 072ba13..b802656 100644
--- a/erpnext/patches/v7_0/convert_timelog_to_timesheet.py
+++ b/erpnext/patches/v7_0/convert_timelog_to_timesheet.py
@@ -1,23 +1,30 @@
 import frappe
 from erpnext.manufacturing.doctype.production_order.production_order \
 	import make_timesheet, add_timesheet_detail
-from erpnext.projects.doctype.timesheet.timesheet import OverlapError
 
 def execute():
 	frappe.reload_doc('projects', 'doctype', 'timesheet')
 
 	for data in frappe.get_all('Time Log', fields=["*"], filters = [["docstatus", "<", "2"]]):
-		try:
-			time_sheet = make_timesheet(data.production_order)
-			args = get_timelog_data(data)
-			add_timesheet_detail(time_sheet, args)
-			time_sheet.docstatus = data.docstatus
-			time_sheet.note = data.note
-			time_sheet.company = frappe.db.get_single_value('Global Defaults', 'default_company')
-			time_sheet.save(ignore_permissions=True)
-		except OverlapError:
-			time_sheet.flags.ignore_validate = True
-			time_sheet.save(ignore_permissions=True)
+		if data.task:
+			company = frappe.db.get_value("Task", data.task, "company")
+		elif data.production_order:
+			company = frappe.db.get_value("Prodction Order", data.production_order, "company")
+		else:
+			company = frappe.db.get_single_value('Global Defaults', 'default_company')
+		
+		time_sheet = make_timesheet(data.production_order)
+		args = get_timelog_data(data)
+		add_timesheet_detail(time_sheet, args)
+		time_sheet.docstatus = data.docstatus
+		time_sheet.note = data.note
+		time_sheet.company = company
+		
+		time_sheet.set_status()
+		time_sheet.update_cost()
+		time_sheet.calculate_total_amounts()
+		time_sheet.flags.ignore_validate = True
+		time_sheet.save(ignore_permissions=True)
 
 def get_timelog_data(data):
 	return {
diff --git a/erpnext/patches/v7_0/make_guardian.py b/erpnext/patches/v7_0/make_guardian.py
index f654b79..0839c4f 100644
--- a/erpnext/patches/v7_0/make_guardian.py
+++ b/erpnext/patches/v7_0/make_guardian.py
@@ -2,19 +2,25 @@
 import frappe
 
 def execute():
-	if frappe.db.exists("DocType", "Student") and "father_name" in frappe.db.get_table_columns("Student"):
-		frappe.reload_doc("schools", "doctype", "student")
-		frappe.reload_doc("schools", "doctype", "guardian")
-		frappe.reload_doc("schools", "doctype", "guardian_interest")
-		frappe.reload_doc("hr", "doctype", "interest")
+	if frappe.db.exists("DocType", "Student"):
+		student_table_cols = frappe.db.get_table_columns("Student")
+		if "father_name" in student_table_cols:
+			frappe.reload_doc("schools", "doctype", "student")
+			frappe.reload_doc("schools", "doctype", "guardian")
+			frappe.reload_doc("schools", "doctype", "guardian_interest")
+			frappe.reload_doc("hr", "doctype", "interest")
+		
+			fields = ["name", "father_name", "mother_name"]
+			
+			if "father_email_id" in student_table_cols:
+				fields += ["father_email_id", "mother_email_id"]
 	
-		students = frappe.get_all("Student", fields=["name", "father_name", "father_email_id", 
-			"mother_name", "mother_email_id"])
-		for stud in students:
-			if stud.father_name:
-				make_guardian(stud.father_name, stud.name, stud.father_email_id)
-			if stud.mother_name:
-				make_guardian(stud.mother_name, stud.name, stud.mother_email_id)
+			students = frappe.get_all("Student", fields)
+			for stud in students:
+				if stud.father_name:
+					make_guardian(stud.father_name, stud.name, stud.father_email_id)
+				if stud.mother_name:
+					make_guardian(stud.mother_name, stud.name, stud.mother_email_id)
 		
 def make_guardian(name, student, email=None):
 	frappe.get_doc({
diff --git a/erpnext/patches/v7_0/migrate_schools_to_erpnext.py b/erpnext/patches/v7_0/migrate_schools_to_erpnext.py
index 80e9eac..f64f400 100644
--- a/erpnext/patches/v7_0/migrate_schools_to_erpnext.py
+++ b/erpnext/patches/v7_0/migrate_schools_to_erpnext.py
@@ -1,5 +1,6 @@
 from __future__ import unicode_literals
 import frappe, os
+from frappe.installer import remove_from_installed_apps
 
 def execute():
 	reload_doctypes_for_schools_icons()
@@ -10,18 +11,15 @@
 
 	if 'schools' in frappe.get_installed_apps():
 		frappe.db.sql("""delete from `tabDesktop Icon`""")
-		if not frappe.db.exists('Module Def', 'Schools'):
-			frappe.get_doc({
-				'doctype': 'Module Def',
-				'module_name': 'Schools',
-				'app_name': 'erpnext'
-			}).insert()
-		frappe.db.sql("""update `tabDocType` set module='Schools' where module='Academics'""")
-		from frappe.installer import remove_from_installed_apps
+		
+		if not frappe.db.exists('Module Def', 'Schools') and frappe.db.exists('Module Def', 'Academics'):
+			frappe.rename_doc("Module Def", "Academics", "Schools")
+			
 		remove_from_installed_apps("schools")
 
 def reload_doctypes_for_schools_icons():
 	base_path = frappe.get_app_path('erpnext', 'schools', 'doctype')
 	for doctype in os.listdir(base_path):
-		if os.path.exists(os.path.join(base_path, doctype, doctype + '.json')):
-			frappe.reload_doc('schools', 'doctype', doctype)
+		if os.path.exists(os.path.join(base_path, doctype, doctype + '.json')) \
+			and doctype not in ("fee_component", "assessment", "assessment_result"):
+			frappe.reload_doc('schools', 'doctype', doctype)
\ No newline at end of file
diff --git a/erpnext/patches/v7_0/rename_examination_to_assessment.py b/erpnext/patches/v7_0/rename_examination_to_assessment.py
index 3c79c51..1d6e688 100644
--- a/erpnext/patches/v7_0/rename_examination_to_assessment.py
+++ b/erpnext/patches/v7_0/rename_examination_to_assessment.py
@@ -9,7 +9,9 @@
 def execute():
 	if frappe.db.exists("DocType", "Examination"):
 		frappe.rename_doc("DocType", "Examination", "Assessment")
-		frappe.reload_doctype("Assessment")
+		frappe.rename_doc("DocType", "Examination Result", "Assessment Result")
+		frappe.reload_doc("schools", "doctype", "assessment")
+		frappe.reload_doc("schools", "doctype", "assessment_result")
 		rename_field("Assessment", "exam_name", "assessment_name")
 		rename_field("Assessment", "exam_code", "assessment_code")
 	
diff --git a/erpnext/projects/doctype/timesheet/timesheet.py b/erpnext/projects/doctype/timesheet/timesheet.py
index 9140927..0379f90 100644
--- a/erpnext/projects/doctype/timesheet/timesheet.py
+++ b/erpnext/projects/doctype/timesheet/timesheet.py
@@ -159,8 +159,8 @@
 
 		existing = self.get_overlap_for(fieldname, args, value)
 		if existing:
-			frappe.throw(_("Row {0}: From Time and To Time overlap with existing from and to time").format(args.idx),
-				OverlapError)
+			frappe.throw(_("Row {0}: From Time and To Time of {1} is overlapping with {2}")
+				.format(args.idx, self.name, existing.name), OverlapError)
 
 	def get_overlap_for(self, fieldname, args, value):
 		cond = "ts.`{0}`".format(fieldname)
diff --git a/erpnext/public/css/erpnext.css b/erpnext/public/css/erpnext.css
index d67f9e0..535f83a 100644
--- a/erpnext/public/css/erpnext.css
+++ b/erpnext/public/css/erpnext.css
@@ -138,12 +138,14 @@
   font-size: 15px;
 }
 .pos-payment-row .col-xs-6 {
-  padding: 10px;
+  padding: 15px;
 }
 .pos-payment-row {
   border-bottom: 1px solid #d1d8dd;
   margin: 2px 0px 5px 0px;
   height: 60px;
+  margin-top: 0px;
+  margin-bottom: 0px;
 }
 .pos-payment-row:hover,
 .pos-keyboard-key:hover {
@@ -203,3 +205,8 @@
 .pos-invoice-list {
   padding: 15px 10px;
 }
+.write_off_amount,
+.change_amount {
+  margin: 15px;
+  width: 130px;
+}
diff --git a/erpnext/public/js/controllers/taxes_and_totals.js b/erpnext/public/js/controllers/taxes_and_totals.js
index 576bc71..c3f4b70 100644
--- a/erpnext/public/js/controllers/taxes_and_totals.js
+++ b/erpnext/public/js/controllers/taxes_and_totals.js
@@ -615,4 +615,18 @@
 		this.frm.doc.base_change_amount = flt(this.frm.doc.change_amount * this.frm.doc.conversion_rate,
 			precision("base_change_amount"));
 	},
+
+	calculate_write_off_amount: function(){
+		if(this.frm.doc.paid_amount > this.frm.doc.grand_total){
+			this.frm.doc.write_off_amount = flt(this.frm.doc.grand_total - this.frm.doc.paid_amount + this.frm.doc.change_amount,
+					precision("write_off_amount"))
+		
+			this.frm.doc.base_write_off_amount = flt(this.frm.doc.write_off_amount * this.frm.doc.conversion_rate,
+				precision("base_write_off_amount"));
+		}else{
+			this.frm.doc.paid_amount = 0.0
+		}
+		
+		this.calculate_outstanding_amount(false)
+	}
 })
diff --git a/erpnext/public/js/payment/payment_details.html b/erpnext/public/js/payment/payment_details.html
index 18f9d03..596f139 100644
--- a/erpnext/public/js/payment/payment_details.html
+++ b/erpnext/public/js/payment/payment_details.html
@@ -1,5 +1,5 @@
 <div class="row pos-payment-row" type="{{type}}" idx={{idx}}>
-    <div class="col-xs-6">{{mode_of_payment}}</div>
+    <div class="col-xs-6" style="padding:20px">{{mode_of_payment}}</div>
 	<div class="col-xs-6">
 		<div class="input-group">
 			<input disabled class="form-control text-right amount" idx="{{idx}}" type="text" value="{{format_number(amount, 2)}}">
diff --git a/erpnext/public/js/payment/payments.js b/erpnext/public/js/payment/payments.js
index 7437f2a..06df425 100644
--- a/erpnext/public/js/payment/payments.js
+++ b/erpnext/public/js/payment/payments.js
@@ -13,6 +13,14 @@
 		this.$body = this.dialog.body;
 		this.set_payment_primary_action();
 		this.make_keyboard();
+		this.select_text()
+	},
+
+	select_text: function(){
+		var me = this;
+		$(this.$body).find('.form-control').click(function(){
+			$(this).select();
+		})
 	},
 
 	set_payment_primary_action: function(){
@@ -20,7 +28,7 @@
 	
 		this.dialog.set_primary_action(__("Submit"), function() {
 			me.dialog.hide()
-			me.write_off_amount()
+			me.submit_invoice()
 		})
 	},
 
@@ -78,7 +86,7 @@
 			//When user first time click on row
 			this.payment_val = flt(this.frm.doc.outstanding_amount)
 			this.selected_mode.val(format_number(this.payment_val, 2));
-			this.update_paid_amount()
+			this.update_payment_amount()
 		}else if(flt(this.selected_mode.val()) > 0){
 			//If user click on existing row which has value
 			this.payment_val = flt(this.selected_mode.val());
@@ -90,17 +98,29 @@
 	bind_keyboard_event: function(){
 		var me = this;
 		this.payment_val = '';
-		this.bind_payment_mode_keys_event();
-		this.bind_keyboard_keys_event();
+		this.bind_form_control_event();
+		this.bind_numeric_keys_event();
 	},
 
-	bind_payment_mode_keys_event: function(){
+	bind_form_control_event: function(){
 		var me = this;
 		$(this.$body).find('.pos-payment-row').click(function(){
-			if(me.frm.doc.outstanding_amount > 0){
-				me.idx = $(this).attr("idx");
-				me.set_outstanding_amount()
-			}
+			me.idx = $(this).attr("idx");
+			me.set_outstanding_amount()
+		})
+		
+		$(this.$body).find('.form-control').click(function(){
+			me.idx = $(this).attr("idx");
+			me.set_outstanding_amount();
+			me.update_paid_amount();
+		})
+		
+		$(this.$body).find('.write_off_amount').change(function(){
+			me.write_off_amount(flt($(this).val()));
+		})
+		
+		$(this.$body).find('.change_amount').change(function(){
+			me.change_amount(flt($(this).val()));
 		})
 	},
 
@@ -113,13 +133,13 @@
 		this.selected_mode.attr('disabled', false);
 	},
 	
-	bind_keyboard_keys_event: function(){
+	bind_numeric_keys_event: function(){
 		var me = this;
 		$(this.$body).find('.pos-keyboard-key').click(function(){
 			me.payment_val += $(this).text();
 			me.selected_mode.val(format_number(me.payment_val, 2))
 			me.idx = me.selected_mode.attr("idx")
-			me.update_paid_amount()
+			me.selected_mode.change()
 		})
 		
 		$(this.$body).find('.delete-btn').click(function(){
@@ -137,15 +157,11 @@
 			me.payment_val =  flt($(this).val()) || 0.0;
 			me.selected_mode.val(format_number(me.payment_val, 2))
 			me.idx = me.selected_mode.attr("idx")
-			me.update_paid_amount()
-		})
-
-		this.selected_mode.click(function(){
-			me.selected_mode.select();
+			me.update_payment_amount()
 		})
 	},
 
-	clear_amount: function(){
+	clear_amount: function() {
 		var me = this;
 		$(this.$body).find('.clr').click(function(e){
 			e.stopPropagation();
@@ -154,25 +170,65 @@
 			me.payment_val = 0.0;
 			me.selected_mode.val(0.0);
 			me.highlight_selected_row();
-			me.update_paid_amount();
+			me.update_payment_amount();
 		})
 	},
 
-	update_paid_amount: function(){
+	write_off_amount: function(write_off_amount) {
 		var me = this;
+
+		if(this.frm.doc.paid_amount > 0){
+			this.frm.doc.write_off_amount = write_off_amount;
+			this.frm.doc.base_write_off_amount = flt(this.frm.doc.write_off_amount * this.frm.doc.conversion_rate,
+				precision("base_write_off_amount"));
+			this.calculate_outstanding_amount(false)
+			this.show_amounts()
+		}
+	},
+
+	change_amount: function(change_amount) {
+		var me = this;
+
+		this.frm.doc.change_amount = change_amount;
+		this.calculate_write_off_amount()
+		this.show_amounts()
+	},
+
+	update_paid_amount: function() {
+		var me = this;
+		if(in_list(['change_amount', 'write_off_amount'], this.idx)){
+			value = flt(me.selected_mode.val(), 2)
+			if(me.idx == 'change_amount'){
+				me.change_amount(value)
+			} else{
+				if(value == 0) { 
+					value = me.frm.doc.outstanding_amount;
+				}
+				me.write_off_amount(value)
+			}
+		}else{
+			this.update_payment_amount()
+		}
+	},
+
+	update_payment_amount: function(){
+		var me = this;
+
 		$.each(this.frm.doc.payments, function(index, data){
 			if(cint(me.idx) == cint(data.idx)){
 				data.amount = flt(me.selected_mode.val(), 2)
 			}
 		})
+
 		this.calculate_outstanding_amount(false);
 		this.show_amounts();
 	},
-	
+
 	show_amounts: function(){
 		var me = this;
+		$(this.$body).find(".write_off_amount").val(format_number(this.frm.doc.write_off_amount, 2));
 		$(this.$body).find('.paid_amount').text(format_currency(this.frm.doc.paid_amount, this.frm.doc.currency));
-		$(this.$body).find('.change_amount').text(format_currency(this.frm.doc.change_amount, this.frm.doc.currency))
+		$(this.$body).find('.change_amount').val(format_number(this.frm.doc.change_amount, 2))
 		$(this.$body).find('.outstanding_amount').text(format_currency(this.frm.doc.outstanding_amount, this.frm.doc.currency))
 		this.update_invoice();
 	}
diff --git a/erpnext/public/js/payment/pos_payment.html b/erpnext/public/js/payment/pos_payment.html
index c5d963a..e94f3a5 100644
--- a/erpnext/public/js/payment/pos_payment.html
+++ b/erpnext/public/js/payment/pos_payment.html
@@ -1,22 +1,28 @@
 <div class="pos_payment row">
+	<div class="row" style="padding: 0px 30px;">
+		<h3>Total Amount: <span class="label label-default" style="font-size:20px;padding:5px">{%= format_currency(grand_total, currency) %}</span></h3>
+	</div>
 	<div class="row amount-row">
 		<div class="col-xs-6 col-sm-3 text-center">
-			<p class="amount-label"> Total <h3>{%= format_currency(grand_total, currency) %} </h3></p>
-		</div>
-		<div class="col-xs-6 col-sm-3 text-center">
 			<p class="amount-label"> Paid <h3 class="paid_amount">{%= format_currency(paid_amount, currency) %}</h3></p>
 		</div>
 		<div class="col-xs-6 col-sm-3 text-center">
 			<p class="amount-label"> Outstanding <h3 class="outstanding_amount">{%= format_currency(outstanding_amount, currency) %} </h3></p>
 		</div>
 		<div class="col-xs-6 col-sm-3 text-center">
-			<p class="amount-label"> Change <h3 class="change_amount">{%= format_currency(change_amount, currency) %}</h3>
+			<p class="amount-label"> Change <input class="form-control text-right change_amount bold" type="text" idx="change_amount" value="{{format_number(change_amount, 2)}}">
+			</p>
+		</div>
+		<div class="col-xs-6 col-sm-3 text-center">
+			<p class="amount-label"> Write off <input class="form-control text-right write_off_amount bold" type="text" idx="write_off_amount" value="{{format_number(write_off_amount, 2)}}">
 			</p>
 		</div>
 	</div>
 	<hr>
 	<div class="row">
-		<div class="col-sm-6 multimode-payments">
+		<div class="col-sm-6 ">
+			<div class ="row multimode-payments">
+			</div>
 		</div>
 		<div class="col-sm-6 payment-toolbar">
 			{% for(var i=0; i<3; i++) { %}
diff --git a/erpnext/public/less/erpnext.less b/erpnext/public/less/erpnext.less
index d39f924..2d74b5f 100644
--- a/erpnext/public/less/erpnext.less
+++ b/erpnext/public/less/erpnext.less
@@ -176,13 +176,15 @@
 }
 
 .pos-payment-row .col-xs-6 {
-	padding :10px;
+	padding :15px;
 }
 
 .pos-payment-row {
 	border-bottom:1px solid #d1d8dd;
     	margin: 2px 0px 5px 0px;
 	height: 60px;
+	margin-top: 0px;
+	margin-bottom: 0px;
 }
 
 .pos-payment-row:hover, .pos-keyboard-key:hover{
@@ -248,3 +250,8 @@
 .pos-invoice-list {
 	padding: 15px 10px;
 }
+
+.write_off_amount, .change_amount {
+	margin: 15px;
+	width: 130px;
+}
diff --git a/erpnext/schools/doctype/program_enrollment_tool/program_enrollment_tool.json b/erpnext/schools/doctype/program_enrollment_tool/program_enrollment_tool.json
index cbbc774..b5547d3 100644
--- a/erpnext/schools/doctype/program_enrollment_tool/program_enrollment_tool.json
+++ b/erpnext/schools/doctype/program_enrollment_tool/program_enrollment_tool.json
@@ -191,6 +191,7 @@
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
+   "depends_on": "eval:doc.get_students_from==\"Program Enrollments\"", 
    "fieldname": "new_program", 
    "fieldtype": "Link", 
    "hidden": 0, 
@@ -217,6 +218,7 @@
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
+   "depends_on": "eval:doc.get_students_from==\"Program Enrollments\"", 
    "fieldname": "new_academic_year", 
    "fieldtype": "Link", 
    "hidden": 0, 
@@ -275,7 +277,7 @@
  "issingle": 1, 
  "istable": 0, 
  "max_attachments": 0, 
- "modified": "2016-07-25 01:24:05.632746", 
+ "modified": "2016-08-17 07:50:40.399492", 
  "modified_by": "Administrator", 
  "module": "Schools", 
  "name": "Program Enrollment Tool", 
diff --git a/erpnext/schools/doctype/program_enrollment_tool/program_enrollment_tool.py b/erpnext/schools/doctype/program_enrollment_tool/program_enrollment_tool.py
index b483ef5..6c10880 100644
--- a/erpnext/schools/doctype/program_enrollment_tool/program_enrollment_tool.py
+++ b/erpnext/schools/doctype/program_enrollment_tool/program_enrollment_tool.py
@@ -6,6 +6,7 @@
 import frappe
 from frappe import _
 from frappe.model.document import Document
+from erpnext.schools.api import enroll_student
 
 class ProgramEnrollmentTool(Document):
 	def get_students(self):
@@ -29,11 +30,16 @@
 			
 	def enroll_students(self):
 		for stud in self.students:
-			prog_enrollment = frappe.new_doc("Program Enrollment")
-			prog_enrollment.student = stud.student
-			prog_enrollment.student_name = stud.student_name
-			prog_enrollment.program = self.new_program
-			prog_enrollment.academic_year = self.new_academic_year
-			prog_enrollment.save()
+			if stud.student:
+				prog_enrollment = frappe.new_doc("Program Enrollment")
+				prog_enrollment.student = stud.student
+				prog_enrollment.student_name = stud.student_name
+				prog_enrollment.program = self.new_program
+				prog_enrollment.academic_year = self.new_academic_year
+				prog_enrollment.save()
+			elif stud.student_applicant:
+				prog_enrollment = enroll_student(stud.student_applicant)
+				prog_enrollment.academic_year = self.academic_year
+				prog_enrollment.save()
 		frappe.msgprint("Students have been enrolled.")
 			
\ No newline at end of file
diff --git a/erpnext/selling/sales_common.js b/erpnext/selling/sales_common.js
index d58adce..1ec8029 100644
--- a/erpnext/selling/sales_common.js
+++ b/erpnext/selling/sales_common.js
@@ -66,7 +66,8 @@
 		if(this.frm.fields_dict["items"].grid.get_field('item_code')) {
 			this.frm.set_query("item_code", "items", function() {
 				return {
-					query: "erpnext.controllers.queries.item_query"
+					query: "erpnext.controllers.queries.item_query",
+					filters: {'is_sales_item': 1}
 				}
 			});
 		}
@@ -79,7 +80,7 @@
 				} else {
 					filters = {
 						'item_code': item.item_code,
-						'posting_date': me.frm.doc.posting_date || nowdate(),
+						'posting_date': me.frm.doc.posting_date || frappe.datetime.nowdate(),
 					}
 					if(item.warehouse) filters["warehouse"] = item.warehouse
 
diff --git a/erpnext/setup/setup_wizard/sample_data.py b/erpnext/setup/setup_wizard/sample_data.py
index 8078ebc..955f663 100644
--- a/erpnext/setup/setup_wizard/sample_data.py
+++ b/erpnext/setup/setup_wizard/sample_data.py
@@ -11,7 +11,7 @@
 def make_sample_data():
 	"""Create a few opportunities, quotes, material requests, issues, todos, projects
 	to help the user get started"""
-	items = frappe.get_all("Item")
+	items = frappe.get_all("Item", {'is_sales_item': 1})
 
 	customers = frappe.get_all("Customer")
 	warehouses = frappe.get_all("Warehouse")
@@ -25,7 +25,7 @@
 	make_projects()
 
 	if items and warehouses:
-		make_material_request(items)
+		make_material_request(frappe.get_all("Item"))
 
 	frappe.db.commit()
 
diff --git a/erpnext/setup/setup_wizard/setup_wizard.py b/erpnext/setup/setup_wizard/setup_wizard.py
index c9679bd..191f169 100644
--- a/erpnext/setup/setup_wizard/setup_wizard.py
+++ b/erpnext/setup/setup_wizard/setup_wizard.py
@@ -318,6 +318,8 @@
 					"item_name": item,
 					"description": item,
 					"show_in_website": 1,
+					"is_sales_item": is_sales_item,
+					"is_purchase_item": is_purchase_item,
 					"is_stock_item": is_stock_item and 1 or 0,
 					"item_group": item_group,
 					"stock_uom": args.get("item_uom_" + str(i)),
diff --git a/erpnext/stock/doctype/delivery_note/delivery_note.js b/erpnext/stock/doctype/delivery_note/delivery_note.js
index 65658d6..ec2da53 100644
--- a/erpnext/stock/doctype/delivery_note/delivery_note.js
+++ b/erpnext/stock/doctype/delivery_note/delivery_note.js
@@ -12,6 +12,9 @@
 			return (doc.docstatus==1 || doc.qty<=doc.actual_qty) ? "green" : "orange"
 		})
 
+	erpnext.queries.setup_queries(frm, "Warehouse", function() {
+		return erpnext.queries.warehouse(frm.doc);
+	});
 })
 
 erpnext.stock.DeliveryNoteController = erpnext.selling.SellingController.extend({
diff --git a/erpnext/stock/doctype/item/item.json b/erpnext/stock/doctype/item/item.json
index b86378d..18fdad7 100644
--- a/erpnext/stock/doctype/item/item.json
+++ b/erpnext/stock/doctype/item/item.json
@@ -1058,6 +1058,32 @@
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
+   "default": "1", 
+   "fieldname": "is_purchase_item", 
+   "fieldtype": "Check", 
+   "hidden": 0, 
+   "ignore_user_permissions": 0, 
+   "ignore_xss_filter": 0, 
+   "in_filter": 0, 
+   "in_list_view": 0, 
+   "label": "Is Purchase Item", 
+   "length": 0, 
+   "no_copy": 0, 
+   "permlevel": 0, 
+   "precision": "", 
+   "print_hide": 0, 
+   "print_hide_if_no_value": 0, 
+   "read_only": 0, 
+   "report_hide": 0, 
+   "reqd": 0, 
+   "search_index": 0, 
+   "set_only_once": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
    "default": "0.00", 
    "depends_on": "is_stock_item", 
    "description": "", 
@@ -1487,6 +1513,32 @@
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
+   "default": "1", 
+   "fieldname": "is_sales_item", 
+   "fieldtype": "Check", 
+   "hidden": 0, 
+   "ignore_user_permissions": 0, 
+   "ignore_xss_filter": 0, 
+   "in_filter": 0, 
+   "in_list_view": 0, 
+   "label": "Is Sales Item", 
+   "length": 0, 
+   "no_copy": 0, 
+   "permlevel": 0, 
+   "precision": "", 
+   "print_hide": 0, 
+   "print_hide_if_no_value": 0, 
+   "read_only": 0, 
+   "report_hide": 0, 
+   "reqd": 0, 
+   "search_index": 0, 
+   "set_only_once": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
    "default": "0", 
    "description": "Publish Item to hub.erpnext.com", 
    "fieldname": "publish_in_hub", 
@@ -2335,7 +2387,7 @@
  "issingle": 0, 
  "istable": 0, 
  "max_attachments": 1, 
- "modified": "2016-08-03 17:30:51.323382", 
+ "modified": "2016-08-17 17:30:51.323382", 
  "modified_by": "Administrator", 
  "module": "Stock", 
  "name": "Item", 
diff --git a/erpnext/support/page/support_analytics/support_analytics.js b/erpnext/support/page/support_analytics/support_analytics.js
index 562a169..79a7fd6 100644
--- a/erpnext/support/page/support_analytics/support_analytics.js
+++ b/erpnext/support/page/support_analytics/support_analytics.js
@@ -44,7 +44,7 @@
 		var std_columns = [
 			{id: "_check", name: __("Plot"), field: "_check", width: 30,
 				formatter: this.check_formatter},
-			{id: "status", name: __("Status"), field: "status", width: 100},
+			{id: "name", name: __("Status"), field: "name", width: 100},
 		];
 		this.make_date_range_columns();
 		this.columns = std_columns.concat(this.columns);
@@ -54,14 +54,14 @@
 		// add Opening, Closing, Totals rows
 		// if filtered by account and / or voucher
 		var me = this;
-		var total_tickets = {status:"All Tickets", "id": "all-tickets",
+		var total_tickets = {name:"All Tickets", "id": "all-tickets",
 			checked:true};
-		var days_to_close = {status:"Days to Close", "id":"days-to-close",
+		var days_to_close = {name:"Days to Close", "id":"days-to-close",
 			checked:false};
 		var total_closed = {};
-		var hours_to_close = {status:"Hours to Close", "id":"hours-to-close",
+		var hours_to_close = {name:"Hours to Close", "id":"hours-to-close",
 			checked:false};
-		var hours_to_respond = {status:"Hours to Respond", "id":"hours-to-respond",
+		var hours_to_respond = {name:"Hours to Respond", "id":"hours-to-respond",
 			checked:false};
 		var total_responded = {};