Merge pull request #12130 from manassolanki/leaderboard

remove the print statements
diff --git a/erpnext/accounts/doctype/gl_entry/gl_entry.json b/erpnext/accounts/doctype/gl_entry/gl_entry.json
index e27eaab..4412661 100644
--- a/erpnext/accounts/doctype/gl_entry/gl_entry.json
+++ b/erpnext/accounts/doctype/gl_entry/gl_entry.json
@@ -80,36 +80,6 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
-   "fieldname": "due_date", 
-   "fieldtype": "Date", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 0, 
-   "in_standard_filter": 0, 
-   "label": "Due Date", 
-   "length": 0, 
-   "no_copy": 0, 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "unique": 0
-  }, 
-  {
-   "allow_bulk_edit": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
    "fieldname": "account", 
    "fieldtype": "Link", 
    "hidden": 0, 
@@ -748,7 +718,7 @@
  "issingle": 0, 
  "istable": 0, 
  "max_attachments": 0, 
- "modified": "2017-08-10 18:06:44.904081", 
+ "modified": "2017-12-20 12:40:09.611951", 
  "modified_by": "Administrator", 
  "module": "Accounts", 
  "name": "GL Entry", 
@@ -824,4 +794,4 @@
  "sort_order": "DESC", 
  "track_changes": 0, 
  "track_seen": 0
-}
\ No newline at end of file
+}
diff --git a/erpnext/accounts/doctype/journal_entry/journal_entry.js b/erpnext/accounts/doctype/journal_entry/journal_entry.js
index c92a728..48062a3 100644
--- a/erpnext/accounts/doctype/journal_entry/journal_entry.js
+++ b/erpnext/accounts/doctype/journal_entry/journal_entry.js
@@ -61,16 +61,6 @@
 				}
 			}
 		});
-	},
-
-	accounts_on_form_rendered: function(frm) {
-		const options = frm.doc.__onload;
-
-		if (options && frm.cur_grid) {
-			frm.cur_grid.get_field("reference_due_date")
-				.df.options = options[frm.cur_grid.get_field('reference_name').value];
-			frm.cur_grid.refresh_field('reference_due_date');
-		}
 	}
 });
 
@@ -204,39 +194,8 @@
 		})
 	},
 
-	due_date_options_cache: {},
-
 	reference_name: function(doc, cdt, cdn) {
 		var d = frappe.get_doc(cdt, cdn);
-		var me = this;
-
-		const get_invoice_due_dates = invoice_name => {
-			const options = this.due_date_options_cache[invoice_name];
-			const input = $(cur_frm.fields_dict["accounts"].wrapper).find("select[data-fieldname=reference_due_date]");
-
-			if (options) {
-				input.empty();
-				input.add_options(options);
-				frappe.model.set_value(cdt, cdn, "reference_due_date", options[0]);
-			}
-			else {
-				frappe.call({
-					method: "erpnext.accounts.doctype.journal_entry.journal_entry.get_invoice_due_dates",
-					args: {name: invoice_name},
-					callback: function(r) {
-						const options = [];
-						$.each(r.message, function(key, value) {
-							options.push(value.due_date);
-						});
-						input.empty();
-						input.add_options(options);
-						frappe.model.set_value(cdt, cdn, "reference_due_date", options[0]);
-						me.frm.cur_grid.get_field("reference_due_date").df.options = options.join('\n');
-						me.due_date_options_cache[d.reference_name] = options;
-					}
-				});
-			}
-		}
 
 		if(d.reference_name) {
 			if (d.reference_type==="Purchase Invoice" && !flt(d.debit)) {
@@ -246,32 +205,6 @@
 			} else if (d.reference_type==="Journal Entry" && !flt(d.credit) && !flt(d.debit)) {
 				this.get_outstanding('Journal Entry', d.reference_name, doc.company, d);
 			}
-
-			if( in_list(["Sales Invoice", "Purchase Invoice"]), d.reference_type) {
-				get_invoice_due_dates(d.reference_name);
-			}
-		}
-	},
-
-	reference_due_date: function(doc, cdt, cdn) {
-		const d = frappe.get_doc(cdt, cdn);
-
-		if (d.reference_type && d.reference_name && d.reference_due_date) {
-			if (in_list(["Sales Invoice", "Purchase Invoice"], d.reference_type)) {
-				frappe.model.set_value(cdt, cdn, 'debit_in_account_currency', '');
-				frappe.model.set_value(cdt, cdn, 'credit_in_account_currency', '');
-			}
-			if (d.reference_type==="Purchase Invoice") {
-				this.get_outstanding(
-					'Purchase Invoice', d.reference_name, doc.company, d, d.reference_due_date
-				);
-			} else if (d.reference_type==="Sales Invoice") {
-				this.get_outstanding(
-					'Sales Invoice', d.reference_name, doc.company, d, d.reference_due_date
-				);
-			}
-
-			frappe.model.set_value(cdt, cdn, 'reference_due_date', d.reference_due_date);
 		}
 	},
 
@@ -286,8 +219,6 @@
 			"company": company
 		}
 
-		if (due_date) args.due_date = due_date;
-
 		return frappe.call({
 			method: "erpnext.accounts.doctype.journal_entry.journal_entry.get_outstanding",
 			args: { args: args},
diff --git a/erpnext/accounts/doctype/journal_entry/journal_entry.py b/erpnext/accounts/doctype/journal_entry/journal_entry.py
index 0c3503b..5e67e44 100644
--- a/erpnext/accounts/doctype/journal_entry/journal_entry.py
+++ b/erpnext/accounts/doctype/journal_entry/journal_entry.py
@@ -3,7 +3,7 @@
 
 from __future__ import unicode_literals
 import frappe, erpnext, json
-from frappe.utils import cstr, flt, fmt_money, formatdate, getdate, DATE_FORMAT
+from frappe.utils import cstr, flt, fmt_money, formatdate, getdate
 from frappe import msgprint, _, scrub
 from erpnext.controllers.accounts_controller import AccountsController
 from erpnext.accounts.utils import get_balance_on, get_account_currency
@@ -434,8 +434,7 @@
 						"against_voucher": d.reference_name,
 						"remarks": self.remark,
 						"cost_center": d.cost_center,
-						"project": d.project,
-						"due_date": d.reference_due_date
+						"project": d.project
 					})
 				)
 
@@ -687,54 +686,22 @@
 		"remark": args.get("remarks")
 	})
 
-	if not ref_doc.payment_schedule:
-		je.append("accounts", {
-			"account": args.get("party_account"),
-			"party_type": args.get("party_type"),
-			"party": ref_doc.get(args.get("party_type").lower()),
-			"cost_center": cost_center,
-			"account_type": frappe.db.get_value("Account", args.get("party_account"), "account_type"),
-			"account_currency": args.get("party_account_currency") or \
-								get_account_currency(args.get("party_account")),
-			"balance": get_balance_on(args.get("party_account")),
-			"party_balance": get_balance_on(party=args.get("party"), party_type=args.get("party_type")),
-			"exchange_rate": exchange_rate,
-			args.get("amount_field_party"): args.get("amount"),
-			"is_advance": args.get("is_advance"),
-			"reference_type": ref_doc.doctype,
-			"reference_name": ref_doc.name
-		})
-
-	else:
-		options_ref_name_list = [
-			d.due_date.strftime(DATE_FORMAT) for d in ref_doc.payment_schedule
-			if d.get('due_date')
-		]
-
-		for payment_term in ref_doc.payment_schedule:
-			je.append("accounts", {
-				"account": args.get("party_account"),
-				"party_type": args.get("party_type"),
-				"party": ref_doc.get(args.get("party_type").lower()),
-				"cost_center": cost_center,
-				"account_type": frappe.db.get_value("Account", args.get("party_account"), "account_type"),
-				"account_currency": args.get("party_account_currency") or \
-									get_account_currency(args.get("party_account")),
-				"balance": get_balance_on(args.get("party_account")),
-				"party_balance": get_balance_on(party=args.get("party"), party_type=args.get("party_type")),
-				"exchange_rate": exchange_rate,
-				args.get("amount_field_party"): payment_term.payment_amount,
-				"is_advance": args.get("is_advance"),
-				"reference_type": ref_doc.doctype,
-				"reference_name": ref_doc.name,
-				"reference_due_date": payment_term.due_date
-			})
-			je.set_onload(ref_doc.name, '\n'.join(options_ref_name_list))
-
-	# First multi currency check
-	for row in je.accounts:
-		if row.account_currency != ref_doc.company_currency:
-			je.multi_currency = 1
+	party_row = je.append("accounts", {
+		"account": args.get("party_account"),
+		"party_type": args.get("party_type"),
+		"party": ref_doc.get(args.get("party_type").lower()),
+		"cost_center": cost_center,
+		"account_type": frappe.db.get_value("Account", args.get("party_account"), "account_type"),
+		"account_currency": args.get("party_account_currency") or \
+							get_account_currency(args.get("party_account")),
+		"balance": get_balance_on(args.get("party_account")),
+		"party_balance": get_balance_on(party=args.get("party"), party_type=args.get("party_type")),
+		"exchange_rate": exchange_rate,
+		args.get("amount_field_party"): args.get("amount"),
+		"is_advance": args.get("is_advance"),
+		"reference_type": ref_doc.doctype,
+		"reference_name": ref_doc.name
+	})
 
 	bank_row = je.append("accounts")
 
@@ -758,8 +725,8 @@
 		bank_row.set(args.get("amount_field_bank"), amount * exchange_rate)
 
 	# Multi currency check again
-	if not je.multi_currency:
-		if bank_row.account_currency and bank_row.account_currency != ref_doc.company_currency:
+	if party_row.account_currency != ref_doc.company_currency \
+		or (bank_row.account_currency and bank_row.account_currency != ref_doc.company_currency):
 			je.multi_currency = 1
 
 	je.set_amounts_in_company_currency()
@@ -816,7 +783,8 @@
 		}
 	elif args.get("doctype") in ("Sales Invoice", "Purchase Invoice"):
 		party_type = "Customer" if args.get("doctype") == "Sales Invoice" else "Supplier"
-		invoice = frappe.get_doc(args['doctype'], args['docname']).as_dict()
+		invoice = frappe.db.get_value(args["doctype"], args["docname"],
+			["outstanding_amount", "conversion_rate", scrub(party_type)], as_dict=1)
 
 		exchange_rate = invoice.conversion_rate if (args.get("account_currency") != company_currency) else 1
 
@@ -827,23 +795,13 @@
 			amount_field = "debit_in_account_currency" \
 				if flt(invoice.outstanding_amount) > 0 else "credit_in_account_currency"
 
-		if args.get('due_date'):
-			outstanding = ''
-			for d in invoice.payment_schedule:
-				if d.due_date == getdate(args['due_date']):
-					outstanding = abs(flt(d.payment_amount))
-					break
-		else:
-			outstanding = abs(flt(invoice.outstanding_amount))
-
 		return {
-			amount_field: outstanding,
+			amount_field: abs(flt(invoice.outstanding_amount)),
 			"exchange_rate": exchange_rate,
 			"party_type": party_type,
 			"party": invoice.get(scrub(party_type))
 		}
 
-
 @frappe.whitelist()
 def get_party_account_and_balance(company, party_type, party):
 	if not frappe.has_permission("Account"):
@@ -941,15 +899,4 @@
 		bank_balance_in_company_currency = get_balance_on(account, in_account_currency=False)
 		exchange_rate = bank_balance_in_company_currency / bank_balance_in_account_currency
 
-	return exchange_rate
-
-
-@frappe.whitelist()
-def get_invoice_due_dates(name):
-	result = frappe.get_list(
-		doctype='GL Entry',
-		filters={'voucher_no': name, "ifnull(due_date, '')": ('!=', '')},
-		fields=['due_date'], distinct=True
-	)
-
-	return result
+	return exchange_rate
\ No newline at end of file
diff --git a/erpnext/accounts/doctype/journal_entry_account/journal_entry_account.json b/erpnext/accounts/doctype/journal_entry_account/journal_entry_account.json
index 23b6399..76ff727 100644
--- a/erpnext/accounts/doctype/journal_entry_account/journal_entry_account.json
+++ b/erpnext/accounts/doctype/journal_entry_account/journal_entry_account.json
@@ -661,39 +661,7 @@
    "search_index": 0, 
    "set_only_once": 0, 
    "unique": 0
-  }, 
-  {
-   "allow_bulk_edit": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "depends_on": "eval:doc.reference_type&&!in_list(doc.reference_type, ['Expense Claim', 'Asset', 'Employee Loan', 'Employee Advance'])", 
-   "fieldname": "reference_due_date", 
-   "fieldtype": "Select", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 0, 
-   "in_standard_filter": 0, 
-   "label": "Reference Due Date", 
-   "length": 0, 
-   "no_copy": 0, 
-   "options": "", 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "unique": 0
-  }, 
+  },
   {
    "allow_bulk_edit": 0, 
    "allow_on_submit": 0, 
diff --git a/erpnext/accounts/doctype/payment_entry/payment_entry.py b/erpnext/accounts/doctype/payment_entry/payment_entry.py
index ca247ef..1fac8e9 100644
--- a/erpnext/accounts/doctype/payment_entry/payment_entry.py
+++ b/erpnext/accounts/doctype/payment_entry/payment_entry.py
@@ -71,9 +71,10 @@
 	def validate_duplicate_entry(self):
 		reference_names = []
 		for d in self.get("references"):
-			if (d.reference_doctype, d.reference_name, d.due_date) in reference_names:
-				frappe.throw(_("Row #{0}: Duplicate entry in References {1} {2}").format(d.idx, d.reference_doctype, d.reference_name))
-			reference_names.append((d.reference_doctype, d.reference_name, d.due_date))
+			if (d.reference_doctype, d.reference_name) in reference_names:
+				frappe.throw(_("Row #{0}: Duplicate entry in References {1} {2}")
+					.format(d.idx, d.reference_doctype, d.reference_name))
+			reference_names.append((d.reference_doctype, d.reference_name))
 
 	def validate_allocated_amount(self):
 		for d in self.get("references"):
@@ -413,8 +414,7 @@
 				gle = party_gl_dict.copy()
 				gle.update({
 					"against_voucher_type": d.reference_doctype,
-					"against_voucher": d.reference_name,
-					"due_date": d.due_date
+					"against_voucher": d.reference_name
 				})
 
 				allocated_amount_in_company_currency = flt(flt(d.allocated_amount) * flt(d.exchange_rate),
@@ -545,10 +545,8 @@
 def get_orders_to_be_billed(posting_date, party_type, party, party_account_currency, company_currency):
 	if party_type == "Customer":
 		voucher_type = 'Sales Order'
-		payment_dr_or_cr = "credit_in_account_currency - debit_in_account_currency"
 	elif party_type == "Supplier":
 		voucher_type = 'Purchase Order'
-		payment_dr_or_cr = "debit_in_account_currency - credit_in_account_currency"
 	elif party_type == "Employee":
 		voucher_type = None
 
@@ -557,131 +555,36 @@
 		ref_field = "base_grand_total" if party_account_currency == company_currency else "grand_total"
 
 		orders = frappe.db.sql("""
-					select
-						name as voucher_no,
-						{ref_field} as invoice_amount,
-						({ref_field} - advance_paid) as outstanding_amount,
-						transaction_date as posting_date
-					from
-						`tab{voucher_type}`
-					where
-						{party_type} = %s
-						and docstatus = 1
-						and ifnull(status, "") != "Closed"
-						and {ref_field} > advance_paid
-						and abs(100 - per_billed) > 0.01
-					order by
-						transaction_date, name
-					""".format(**{
-			"ref_field": ref_field,
-			"voucher_type": voucher_type,
-			"party_type": scrub(party_type)
-		}), party, as_dict=True)
-
-	if voucher_type and party_type is not "Employee":
-		ref_field = "base_grand_total" if party_account_currency == company_currency else "grand_total"
-
-		# find orders without considering if they have Payment Schedule
-		orders_without_schedule = frappe.db.sql("""
-					select
-						name as voucher_no,
-						{ref_field} as invoice_amount,
-						({ref_field} - advance_paid) as outstanding_amount,
-						transaction_date as posting_date
-					from
-						`tab{voucher_type}`
-					where
-						{party_type} = %s
-						and docstatus = 1
-						and ifnull(status, "") != "Closed"
-						and {ref_field} > advance_paid
-						and abs(100 - per_billed) > 0.01
-					order by
-						transaction_date, name
-					""".format(**{
-			"ref_field": ref_field,
-			"voucher_type": voucher_type,
-			"party_type": scrub(party_type)
-		}), party, as_dict=True)
-
-	# find orders considering if they have Payment Schedule
-	if voucher_type and party_type is not "Employee":
-		ref_field = "base_grand_total" if party_account_currency == company_currency else "grand_total"
-
-		orders_with_schedule = frappe.db.sql("""
 			select
-				VT.name as voucher_no,
-				PS.payment_amount as invoice_amount,
-				PS.payment_amount - (select
-										ifnull(sum({payment_dr_or_cr}), 0)
-										from `tabGL Entry`
-										where 
-											against_voucher = VT.name
-											and due_date = PS.due_date
-									) as outstanding_amount,
-				VT.transaction_date as posting_date,
-				PS.due_date
+				name as voucher_no,
+				{ref_field} as invoice_amount,
+				({ref_field} - advance_paid) as outstanding_amount,
+				transaction_date as posting_date
 			from
-				`tab{voucher_type}` VT
-			join 
-				`tabPayment Schedule` PS on VT.name = PS.parent
+				`tab{voucher_type}`
 			where
 				{party_type} = %s
-				and VT.docstatus = 1
+				and docstatus = 1
 				and ifnull(status, "") != "Closed"
 				and {ref_field} > advance_paid
 				and abs(100 - per_billed) > 0.01
 			order by
-				VT.transaction_date, VT.name
-			""".format(**{
-				"ref_field": ref_field,
-				"voucher_type": voucher_type,
-				"party_type": scrub(party_type),
-				"payment_dr_or_cr": payment_dr_or_cr
-			}), party, as_dict=True)
-
-	# reconcile both results such that we have a list that contains unique entries.
-	# Where both lists contain a record that is common, we select the one with
-	# linked Payment Schedule
-	orders = _merge_query_results(orders_without_schedule, orders_with_schedule, 'voucher_no')
+				transaction_date, name
+		""".format(**{
+			"ref_field": ref_field,
+			"voucher_type": voucher_type,
+			"party_type": scrub(party_type)
+		}), party, as_dict=True)
 
 	order_list = []
 	for d in orders:
 		d["voucher_type"] = voucher_type
 		# This assumes that the exchange rate required is the one in the SO
-		d["exchange_rate"] = get_exchange_rate(party_account_currency,
-			company_currency, posting_date)
+		d["exchange_rate"] = get_exchange_rate(party_account_currency, company_currency, posting_date)
 		order_list.append(d)
 
 	return order_list
 
-
-def _merge_query_results(result1, result2, dict_key):
-	"""
-	Merges two list of query results that are dictionaries.
-	For every item in result1 that is found in result2, the item is removed from
-	result1. At the end of processing result1, result1 and result2 are concatenated
-	and returned.
-
-	:param result1: List of dict
-	:param result2: List of dict
-	:return: List of dict
-	"""
-	for item in result1[:]:
-		found = False
-		for item2 in result2:
-			if item[dict_key] == item2[dict_key]:
-				found = True
-				break
-
-		if found:
-			result1.remove(item)
-
-	final_result = result1 + result2
-
-	return final_result
-
-
 def get_negative_outstanding_invoices(party_type, party, party_account, party_account_currency, company_currency):
 	voucher_type = "Sales Invoice" if party_type == "Customer" else "Purchase Invoice"
 	if party_account_currency == company_currency:
@@ -900,40 +803,15 @@
 	pe.allocate_payment_amount = 1
 	pe.letter_head = doc.get("letter_head")
 
-	if dt == "Employee Advance":
-		pe.append("references", {
-			'reference_doctype': dt,
-			'reference_name': dn,
-			'total_amount': grand_total,
-			'outstanding_amount': outstanding_amount,
-			'allocated_amount': outstanding_amount
-		})
-	else:
-		args = {
-			'party_account': party_account,
-			'company': pe.company,
-			'party_type': pe.party_type,
-			'party': pe.party,
-			'posting_date': pe.posting_date,
-			'voucher_type': dt,
-			'voucher_no': dn
-		}
-		references = get_outstanding_reference_documents(args=args)
-
-		for reference in references:
-			if reference.voucher_no == dn:
-				allocated_amount = min(paid_amount, reference.outstanding_amount)
-				pe.append("references", {
-					'reference_doctype': reference.voucher_type,
-					'reference_name': reference.voucher_no,
-					'due_date': reference.due_date,
-					'total_amount': reference.invoice_amount,
-					'outstanding_amount': reference.outstanding_amount,
-					'allocated_amount': allocated_amount,
-					"bill_no": reference.get("bill_no")
-				})
-				if paid_amount:
-					paid_amount -= allocated_amount
+	pe.append("references", {
+		'reference_doctype': dt,
+		'reference_name': dn,
+		"bill_no": doc.get("bill_no"),
+		"due_date": doc.get("due_date"),
+		'total_amount': grand_total,
+		'outstanding_amount': outstanding_amount,
+		'allocated_amount': outstanding_amount
+	})
 
 	pe.setup_party_account_field()
 	pe.set_missing_values()
diff --git a/erpnext/accounts/doctype/payment_entry/test_payment_entry.py b/erpnext/accounts/doctype/payment_entry/test_payment_entry.py
index a3a78a3..7ec8245 100644
--- a/erpnext/accounts/doctype/payment_entry/test_payment_entry.py
+++ b/erpnext/accounts/doctype/payment_entry/test_payment_entry.py
@@ -66,18 +66,6 @@
 		outstanding_amount = flt(frappe.db.get_value("Sales Invoice", si.name, "outstanding_amount"))
 		self.assertEqual(outstanding_amount, 100)
 
-	def test_payment_entry_against_si_multi_due_dates(self):
-		si = create_sales_invoice(do_not_save=1)
-		si.payment_terms_template = '_Test Payment Term Template'
-		si.insert()
-		si.submit()
-
-		pe = get_payment_entry(si.doctype, si.name)
-		pe.reference_no = "1"
-		pe.reference_date = "2016-01-01"
-		pe.insert()
-		pe.submit()
-
 	def test_payment_entry_against_pi(self):
 		pi = make_purchase_invoice(supplier="_Test Supplier USD", debit_to="_Test Payable USD - _TC",
 			currency="USD", conversion_rate=50)
diff --git a/erpnext/accounts/doctype/payment_schedule/payment_schedule.json b/erpnext/accounts/doctype/payment_schedule/payment_schedule.json
index 854def0..2fcd44f 100644
--- a/erpnext/accounts/doctype/payment_schedule/payment_schedule.json
+++ b/erpnext/accounts/doctype/payment_schedule/payment_schedule.json
@@ -67,7 +67,7 @@
    "precision": "", 
    "print_hide": 0, 
    "print_hide_if_no_value": 0, 
-   "read_only": 1, 
+   "read_only": 0, 
    "remember_last_selected_value": 0, 
    "report_hide": 0, 
    "reqd": 0, 
@@ -98,7 +98,7 @@
    "precision": "", 
    "print_hide": 0, 
    "print_hide_if_no_value": 0, 
-   "read_only": 1, 
+   "read_only": 0, 
    "remember_last_selected_value": 0, 
    "report_hide": 0, 
    "reqd": 1, 
@@ -160,7 +160,7 @@
    "precision": "", 
    "print_hide": 0, 
    "print_hide_if_no_value": 0, 
-   "read_only": 1, 
+   "read_only": 0, 
    "remember_last_selected_value": 0, 
    "report_hide": 0, 
    "reqd": 1, 
@@ -179,8 +179,8 @@
  "issingle": 0, 
  "istable": 1, 
  "max_attachments": 0, 
- "modified": "2017-11-23 12:39:02.013040", 
- "modified_by": "Administrator", 
+ "modified": "2017-12-19 16:20:33.546984", 
+ "modified_by": "nabinhait@gmail.com", 
  "module": "Accounts", 
  "name": "Payment Schedule", 
  "name_case": "", 
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json
index 59b7c96..f282afe 100755
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json
@@ -192,7 +192,7 @@
    "oldfieldname": "due_date", 
    "oldfieldtype": "Date", 
    "permlevel": 0, 
-   "print_hide": 1, 
+   "print_hide": 0, 
    "print_hide_if_no_value": 0, 
    "read_only": 0, 
    "remember_last_selected_value": 0, 
@@ -3117,7 +3117,7 @@
    "options": "Payment Schedule", 
    "permlevel": 0, 
    "precision": "", 
-   "print_hide": 0, 
+   "print_hide": 1, 
    "print_hide_if_no_value": 0, 
    "read_only": 0, 
    "remember_last_selected_value": 0, 
@@ -3914,7 +3914,7 @@
  "istable": 0, 
  "max_attachments": 0, 
  "menu_index": 0, 
- "modified": "2017-12-15 17:49:51.230092", 
+ "modified": "2017-12-20 17:49:51.230092", 
  "modified_by": "Administrator", 
  "module": "Accounts", 
  "name": "Purchase Invoice", 
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
index b1dab50..07c136b 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
@@ -363,27 +363,7 @@
 
 	def make_supplier_gl_entry(self, gl_entries):
 		grand_total = self.rounded_total or self.grand_total
-		if self.get("payment_schedule"):
-			for d in self.get("payment_schedule"):
-				payment_amount_in_company_currency = flt(d.payment_amount * self.conversion_rate,
-					d.precision("payment_amount"))
-
-				gl_entries.append(
-					self.get_gl_dict({
-						"account": self.credit_to,
-						"party_type": "Supplier",
-						"party": self.supplier,
-						"due_date": d.due_date,
-						"against": self.against_expense_account,
-						"credit": payment_amount_in_company_currency,
-						"credit_in_account_currency": payment_amount_in_company_currency \
-							if self.party_account_currency==self.company_currency else d.payment_amount,
-						"against_voucher": self.return_against if cint(self.is_return) else self.name,
-						"against_voucher_type": self.doctype
-					}, self.party_account_currency)
-				)
-
-		elif grand_total:
+		if grand_total:
 			# Didnot use base_grand_total to book rounding loss gle
 			grand_total_in_company_currency = flt(grand_total * self.conversion_rate,
 				self.precision("grand_total"))
diff --git a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
index 3ac521a..4b0b991 100644
--- a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
@@ -6,7 +6,7 @@
 import unittest
 import frappe, erpnext
 import frappe.model
-from frappe.utils import cint, flt, today, nowdate, getdate, add_days
+from frappe.utils import cint, flt, today, nowdate, add_days
 import frappe.defaults
 from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import set_perpetual_inventory, \
 	test_records as pr_test_records
@@ -647,39 +647,6 @@
 		self.assertEquals(pi.total_taxes_and_charges, 462.3)
 		self.assertEquals(pi.grand_total, 1712.3)	
 
-	def test_gl_entry_based_on_payment_schedule(self):
-		pi = make_purchase_invoice(do_not_save=True, supplier="_Test Supplier P")
-		pi.append("payment_schedule", {
-			"due_date": add_days(nowdate(), 15),
-			"payment_amount": 100,
-			"invoice_portion": 40.00
-		})
-		pi.append("payment_schedule", {
-			"due_date": add_days(nowdate(), 25),
-			"payment_amount": 150,
-			"invoice_portion": 60.00
-		})
-
-		pi.save()
-		pi.submit()
-
-		gl_entries = frappe.db.sql("""select account, debit, credit, due_date
-			from `tabGL Entry` where voucher_type='Purchase Invoice' and voucher_no=%s
-			order by account asc, debit asc""", pi.name, as_dict=1)
-		self.assertTrue(gl_entries)
-
-		expected_gl_entries = sorted([
-			[pi.credit_to, 0.0, 100.0, add_days(nowdate(), 15)],
-			[pi.credit_to, 0.0, 150.0, add_days(nowdate(), 25)],
-			["_Test Account Cost for Goods Sold - _TC", 250.0, 0.0, None]
-		])
-
-		for i, gle in enumerate(sorted(gl_entries, key=lambda gle: gle.account)):
-			self.assertEquals(expected_gl_entries[i][0], gle.account)
-			self.assertEquals(expected_gl_entries[i][1], gle.debit)
-			self.assertEquals(expected_gl_entries[i][2], gle.credit)
-			self.assertEquals(getdate(expected_gl_entries[i][3]), getdate(gle.due_date))
-
 	def test_make_pi_without_terms(self):
 		pi = make_purchase_invoice(do_not_save=1)
 
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.json b/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
index b85c623..d1e64bc 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
@@ -503,7 +503,7 @@
    "oldfieldname": "due_date",
    "oldfieldtype": "Date",
    "permlevel": 0,
-   "print_hide": 1,
+   "print_hide": 0,
    "print_hide_if_no_value": 0,
    "read_only": 0,
    "remember_last_selected_value": 0,
@@ -2864,7 +2864,7 @@
    "options": "Payment Schedule",
    "permlevel": 0,
    "precision": "",
-   "print_hide": 0,
+   "print_hide": 1,
    "print_hide_if_no_value": 0,
    "read_only": 0,
    "remember_last_selected_value": 0,
@@ -4563,7 +4563,7 @@
  "istable": 0,
  "max_attachments": 0,
  "menu_index": 0,
- "modified": "2017-11-29 17:36:05.216046",
+ "modified": "2017-12-20 17:36:05.216046",
  "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 76b50c2..c457f9a 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
@@ -637,27 +637,7 @@
 
 	def make_customer_gl_entry(self, gl_entries):
 		grand_total = self.rounded_total or self.grand_total
-		if self.get("payment_schedule"):
-			for d in self.get("payment_schedule"):
-				payment_amount_in_company_currency = flt(d.payment_amount * self.conversion_rate,
-					d.precision("payment_amount"))
-
-				gl_entries.append(
-					self.get_gl_dict({
-						"account": self.debit_to,
-						"party_type": "Customer",
-						"party": self.customer,
-						"due_date": d.due_date,
-						"against": self.against_income_account,
-						"debit": payment_amount_in_company_currency,
-						"debit_in_account_currency": payment_amount_in_company_currency \
-							if self.party_account_currency==self.company_currency else d.payment_amount,
-						"against_voucher": self.return_against if cint(self.is_return) else self.name,
-						"against_voucher_type": self.doctype
-					}, self.party_account_currency)
-				)
-
-		elif grand_total:
+		if grand_total:
 			# Didnot use base_grand_total to book rounding loss gle
 			grand_total_in_company_currency = flt(grand_total * self.conversion_rate,
 				self.precision("grand_total"))
diff --git a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
index b3a143c..b866794 100644
--- a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
@@ -5,7 +5,7 @@
 import frappe
 
 import unittest, copy, time
-from frappe.utils import nowdate, add_days, flt, getdate, cint
+from frappe.utils import nowdate, flt, getdate, cint
 from frappe.model.dynamic_links import get_dynamic_link_map
 from erpnext.stock.doctype.stock_entry.test_stock_entry import make_stock_entry, get_qty_after_transaction
 from erpnext.accounts.doctype.purchase_invoice.test_purchase_invoice import unlink_payment_on_cancel_of_invoice
@@ -1321,40 +1321,6 @@
 		})
 		si.insert()
 		return si
-	
-	def test_gl_entry_based_on_payment_schedule(self):
-		si = create_sales_invoice(do_not_save=True, customer="_Test Customer P")
-		si.append("payment_schedule", {
-			"due_date": add_days(nowdate(), 15),
-			"payment_amount": 20,
-			"invoice_portion": 20.00
-		})
-		si.append("payment_schedule", {
-			"due_date": add_days(nowdate(), 45),
-			"payment_amount": 80,
-			"invoice_portion": 80.00
-		})
-		
-		si.save()
-		si.submit()
-		
-		gl_entries = frappe.db.sql("""select account, debit, credit, due_date
-			from `tabGL Entry` where voucher_type='Sales Invoice' and voucher_no=%s
-			order by account asc, debit asc""", si.name, as_dict=1)
-		self.assertTrue(gl_entries)
-
-		expected_gl_entries = sorted([
-			[si.debit_to, 20.0, 0.0, add_days(nowdate(), 15)],
-			[si.debit_to, 80.0, 0.0, add_days(nowdate(), 45)],
-			["Sales - _TC", 0.0, 100.0, None]
-		])
-
-		for i, gle in enumerate(sorted(gl_entries, key=lambda gle: gle.account)):
-			self.assertEquals(expected_gl_entries[i][0], gle.account)
-			self.assertEquals(expected_gl_entries[i][1], gle.debit)
-			self.assertEquals(expected_gl_entries[i][2], gle.credit)
-			self.assertEquals(getdate(expected_gl_entries[i][3]), getdate(gle.due_date))
-
 
 	def test_company_monthly_sales(self):
 		existing_current_month_sales = frappe.db.get_value("Company", "_Test Company", "total_monthly_sales")
diff --git a/erpnext/accounts/general_ledger.py b/erpnext/accounts/general_ledger.py
index d370c49..c575d59 100644
--- a/erpnext/accounts/general_ledger.py
+++ b/erpnext/accounts/general_ledger.py
@@ -3,7 +3,7 @@
 
 from __future__ import unicode_literals
 import frappe, erpnext
-from frappe.utils import flt, cstr, cint, getdate
+from frappe.utils import flt, cstr, cint
 from frappe import _
 from frappe.model.meta import get_field_precision
 from erpnext.accounts.doctype.budget.budget import validate_expense_against_budget
@@ -75,8 +75,7 @@
 			and cstr(e.get('against_voucher'))==cstr(gle.get('against_voucher')) \
 			and cstr(e.get('against_voucher_type')) == cstr(gle.get('against_voucher_type')) \
 			and cstr(e.get('cost_center')) == cstr(gle.get('cost_center')) \
-			and cstr(e.get('project')) == cstr(gle.get('project')) \
-			and getdate(e.get('due_date')) == getdate(gle.get('due_date')):
+			and cstr(e.get('project')) == cstr(gle.get('project')):
 				return e
 
 def save_entries(gl_map, adv_adj, update_outstanding, from_repost=False):
diff --git a/erpnext/accounts/report/accounts_receivable/accounts_receivable.py b/erpnext/accounts/report/accounts_receivable/accounts_receivable.py
index 300e6a8..522abe8 100644
--- a/erpnext/accounts/report/accounts_receivable/accounts_receivable.py
+++ b/erpnext/accounts/report/accounts_receivable/accounts_receivable.py
@@ -113,7 +113,7 @@
 						row += [self.get_party_name(gle.party_type, gle.party)]
 
 					# get due date
-					due_date = gle.due_date or voucher_details.get(gle.voucher_no, {}).get("due_date", "")
+					due_date = voucher_details.get(gle.voucher_no, {}).get("due_date", "")
 
 					row += [gle.voucher_type, gle.voucher_no, due_date]
 
@@ -188,8 +188,7 @@
 		reverse_dr_or_cr = "credit" if dr_or_cr=="debit" else "debit"
 
 		for e in self.get_gl_entries_for(gle.party, gle.party_type, gle.voucher_type, gle.voucher_no):
-			if getdate(e.posting_date) <= report_date and e.name!=gle.name \
-				and (not gle.due_date or getdate(e.due_date) == getdate(gle.due_date)):
+			if getdate(e.posting_date) <= report_date and e.name!=gle.name:
 				amount = flt(e.get(reverse_dr_or_cr)) - flt(e.get(dr_or_cr))
 				if e.voucher_no not in return_entries:
 					payment_amount += amount
@@ -251,11 +250,11 @@
 				select_fields = "sum(debit) as debit, sum(credit) as credit"
 
 			self.gl_entries = frappe.db.sql("""select name, posting_date, account, party_type, party, 
-				voucher_type, voucher_no, against_voucher_type, against_voucher, due_date,
+				voucher_type, voucher_no, against_voucher_type, against_voucher,
 				account_currency, remarks, {0}
 				from `tabGL Entry`
 				where docstatus < 2 and party_type=%s and (party is not null and party != '') {1}
-				group by voucher_type, voucher_no, against_voucher_type, against_voucher, party, due_date
+				group by voucher_type, voucher_no, against_voucher_type, against_voucher, party
 				order by posting_date, party"""
 				.format(select_fields, conditions), values, as_dict=True)
 
diff --git a/erpnext/accounts/utils.py b/erpnext/accounts/utils.py
index 9c42f64..bd223b5 100644
--- a/erpnext/accounts/utils.py
+++ b/erpnext/accounts/utils.py
@@ -583,9 +583,10 @@
 		dr_or_cr = "credit_in_account_currency - debit_in_account_currency"
 		payment_dr_or_cr = "payment_gl_entry.debit_in_account_currency - payment_gl_entry.credit_in_account_currency"
 
+	invoice = 'Sales Invoice' if party_type == 'Customer' else 'Purchase Invoice'
 	invoice_list = frappe.db.sql("""
 		select
-			voucher_no,	voucher_type, posting_date, ifnull(sum({dr_or_cr}), 0) as invoice_amount, due_date,
+			voucher_no, voucher_type, posting_date, ifnull(sum({dr_or_cr}), 0) as invoice_amount,
 			(
 				select ifnull(sum({payment_dr_or_cr}), 0)
 				from `tabGL Entry` payment_gl_entry
@@ -596,7 +597,6 @@
 					and payment_gl_entry.party_type = invoice_gl_entry.party_type
 					and payment_gl_entry.party = invoice_gl_entry.party
 					and payment_gl_entry.account = invoice_gl_entry.account
-					and payment_gl_entry.due_date = invoice_gl_entry.due_date
 					and {payment_dr_or_cr} > 0
 			) as payment_amount
 		from
@@ -608,10 +608,11 @@
 			and ((voucher_type = 'Journal Entry'
 					and (against_voucher = '' or against_voucher is null))
 				or (voucher_type not in ('Journal Entry', 'Payment Entry')))
-		group by voucher_type, voucher_no, due_date
+		group by voucher_type, voucher_no
 		having (invoice_amount - payment_amount) > 0.005
 		order by posting_date, name, due_date""".format(
 			dr_or_cr=dr_or_cr,
+			invoice = invoice,
 			payment_dr_or_cr=payment_dr_or_cr,
 			condition=condition or ""
 		), {
@@ -621,12 +622,8 @@
 		}, as_dict=True)
 
 	for d in invoice_list:
-		due_date = d.due_date or (
-			frappe.db.get_value(
-				d.voucher_type, d.voucher_no,
-				"posting_date" if party_type == "Employee" else "due_date"
-			)
-		)
+		due_date = frappe.db.get_value(d.voucher_type, d.voucher_no,
+			"posting_date" if party_type == "Employee" else "due_date")
 
 		outstanding_invoices.append(
 			frappe._dict({
diff --git a/erpnext/assets/doctype/asset/asset.json b/erpnext/assets/doctype/asset/asset.json
index ee6b12c..45c9a65 100644
--- a/erpnext/assets/doctype/asset/asset.json
+++ b/erpnext/assets/doctype/asset/asset.json
@@ -193,7 +193,7 @@
    "read_only": 0, 
    "remember_last_selected_value": 0, 
    "report_hide": 0, 
-   "reqd": 1, 
+   "reqd": 0, 
    "search_index": 0, 
    "set_only_once": 0, 
    "unique": 0
@@ -1221,7 +1221,7 @@
  "issingle": 0, 
  "istable": 0, 
  "max_attachments": 0, 
- "modified": "2017-12-08 12:58:44.137460", 
+ "modified": "2017-12-19 12:58:44.137460", 
  "modified_by": "Administrator", 
  "module": "Assets", 
  "name": "Asset", 
diff --git a/erpnext/buying/doctype/purchase_order/purchase_order.json b/erpnext/buying/doctype/purchase_order/purchase_order.json
index fffc5ab..2191a55 100644
--- a/erpnext/buying/doctype/purchase_order/purchase_order.json
+++ b/erpnext/buying/doctype/purchase_order/purchase_order.json
@@ -2552,7 +2552,7 @@
    "options": "Payment Schedule", 
    "permlevel": 0, 
    "precision": "", 
-   "print_hide": 0, 
+   "print_hide": 1, 
    "print_hide_if_no_value": 0, 
    "read_only": 0, 
    "remember_last_selected_value": 0, 
@@ -3261,8 +3261,8 @@
  "issingle": 0, 
  "istable": 0, 
  "max_attachments": 0, 
- "modified": "2017-11-29 14:06:33.636401", 
- "modified_by": "Administrator", 
+ "modified": "2017-12-19 14:53:03.986840", 
+ "modified_by": "nabinhait@gmail.com", 
  "module": "Buying", 
  "name": "Purchase Order", 
  "owner": "Administrator", 
diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index 0c36c6a..c55f7d6 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -64,16 +64,14 @@
 	def validate_invoice_documents_schedule(self):
 		self.validate_payment_schedule_dates()
 		self.set_due_date()
-		self.validate_invoice_portion()
 		self.set_payment_schedule()
 		self.validate_payment_schedule_amount()
 		self.validate_due_date()
 		self.validate_advance_entries()
 
 	def validate_non_invoice_documents_schedule(self):
-		self.validate_payment_schedule_dates()
-		self.validate_invoice_portion()
 		self.set_payment_schedule()
+		self.validate_payment_schedule_dates()
 		self.validate_payment_schedule_amount()
 
 	def validate_all_documents_schedule(self):
@@ -652,6 +650,8 @@
 		date = self.get("due_date")
 		due_date = date or posting_date
 		grand_total = self.get("rounded_total") or self.grand_total
+		if self.doctype in ("Sales Invoice", "Purchase Invoice"):
+			grand_total = grand_total - flt(self.write_off_amount)
 
 		if not self.get("payment_schedule"):
 			if self.get("payment_terms_template"):
@@ -663,7 +663,8 @@
 				self.append("payment_schedule", data)
 		else:
 			for d in self.get("payment_schedule"):
-				d.payment_amount = grand_total * flt(d.invoice_portion) / 100
+				if d.invoice_portion:
+					d.payment_amount = grand_total * flt(d.invoice_portion) / 100
 
 	def set_due_date(self):
 		due_dates = [d.due_date for d in self.get("payment_schedule") if d.due_date]
@@ -673,12 +674,9 @@
 	def validate_payment_schedule_dates(self):
 		dates = []
 		li = []
-		if self.get('posting_date'):
-			if self.due_date and getdate(self.due_date) < getdate(self.posting_date):
-				frappe.throw(_("Due Date cannot be before posting date"))
 
 		for d in self.get("payment_schedule"):
-			if self.get('posting_date') and getdate(d.due_date) < getdate(self.posting_date):
+			if self.doctype == "Sales Order" and getdate(d.due_date) < getdate(self.transaction_date):
 				frappe.throw(_("Row {0}: Due Date cannot be before posting date").format(d.idx))
 			elif d.due_date in dates:
 				li.append('{0} in row {1}'.format(d.due_date, d.idx))
@@ -697,18 +695,11 @@
 			total = flt(total, self.precision("grand_total"))
 
 			grand_total = flt(self.get("rounded_total") or self.grand_total, self.precision('grand_total'))
+			if self.doctype in ("Sales Invoice", "Purchase Invoice"):
+				grand_total = grand_total - flt(self.write_off_amount)
 			if total != grand_total:
 				frappe.throw(_("Total Payment Amount in Payment Schedule must be equal to Grand / Rounded Total"))
 
-	def validate_invoice_portion(self):
-		if self.get("payment_schedule"):
-			total_portion = 0
-			for term in self.payment_schedule:
-				total_portion += flt(term.get('invoice_portion', 0))
-
-			if flt(total_portion, 2) != 100.00:
-				frappe.msgprint(_('Combined invoice portion must equal 100%'), indicator='red', raise_exception=1)
-
 	def is_rounded_total_disabled(self):
 		if self.meta.get_field("disable_rounded_total"):
 			return self.disable_rounded_total
diff --git a/erpnext/docs/user/manual/en/fleet_management/index.md b/erpnext/docs/user/manual/en/fleet_management/index.md
index 4582716..564cb28 100644
--- a/erpnext/docs/user/manual/en/fleet_management/index.md
+++ b/erpnext/docs/user/manual/en/fleet_management/index.md
@@ -19,15 +19,15 @@
 
 * Enter License Plate,Make,Model,Odometer Value,Fuel Type and Fuel UOM for a quick entry.
 
-	<img class="screenshot" alt="Vehicle" src="/docs/assets/img/fleet-management/vehicle-1.1.png">
+	<img class="screenshot" alt="Vehicle" src="/docs/assets/img/human-resources/vehicle-1.1.png">
 
 * Enter details like Insurance,Chassis,Vehicle Value,Location and Employee.
 
-	<img class="screenshot" alt="Vehicle" src="/docs/assets/img/fleet-management/vehicle-1.2.png">
+	<img class="screenshot" alt="Vehicle" src="/docs/assets/img/human-resources/vehicle-1.2.png">
 
 * Enter Vehicle attributes like color,wheels,doors and last carbon check 
 
-	<img class="screenshot" alt="Vehicle" src="/docs/assets/img/fleet-management/vehicle-1.3.png">
+	<img class="screenshot" alt="Vehicle" src="/docs/assets/img/human-resources/vehicle-1.3.png">
 
 ### Vehicle Log
 
@@ -39,17 +39,17 @@
 
 * Enter License Plate,Employee,Date,Odometer reading for a quick entry.
 
-	<img class="screenshot" alt="Vehicle Log" src="/docs/assets/img/fleet-management/vehicle-log-2.1.png">
+	<img class="screenshot" alt="Vehicle Log" src="/docs/assets/img/human-resources/vehicle-log-2.1.png">
 
 * Enter Refuelling details,Service details if applicable.
 
-	<img class="screenshot" alt="Vehicle Log" src="/docs/assets/img/fleet-management/vehicle-log-2.2.png">
+	<img class="screenshot" alt="Vehicle Log" src="/docs/assets/img/human-resources/vehicle-log-2.2.png">
 
 ### Make Expense Claim
 
 * Click on Make Expense Claim button .This button appears only in case of Submitted Vehicle Logs.
 
-	<img class="screenshot" alt="Vehicle Log" src="/docs/assets/img/fleet-management/expense-claim-3.1.png">
+	<img class="screenshot" alt="Vehicle Log" src="/docs/assets/img/human-resources/expense-claim-3.1.png">
 
 When you click on 'Make Expense Claim',
 
@@ -57,10 +57,10 @@
   2. The sum of Fuel Expenses and Service Expenses is copied over to Expense Claim Amount.
   3. Employee can submit the Expense Claim for further processing.
 
-	<img class="screenshot" alt="Vehicle Log" src="/docs/assets/img/fleet-management/expense-claim-3.2.png">
+	<img class="screenshot" alt="Vehicle Log" src="/docs/assets/img/human-resources/expense-claim-3.2.png">
 
 ### Vehicle Expenses Report
 
 * To track and monitor Vehicle Expenses you can use the Vehicle Expenses report.This report gives a one stop view of all your vehicle expenses month wise.
 
-	<img class="screenshot" alt="Vehicle Log" src="/docs/assets/img/fleet-management/vehicle-expenses.png">
+	<img class="screenshot" alt="Vehicle Log" src="/docs/assets/img/human-resources/vehicle-expenses.png">
diff --git a/erpnext/hooks.py b/erpnext/hooks.py
index b65908a..573c180 100644
--- a/erpnext/hooks.py
+++ b/erpnext/hooks.py
@@ -26,7 +26,7 @@
 
 # setup wizard
 setup_wizard_requires = "assets/erpnext/js/setup_wizard.js"
-setup_wizard_complete = "erpnext.setup.setup_wizard.setup_wizard.setup_complete"
+setup_wizard_stages = "erpnext.setup.setup_wizard.setup_wizard.get_setup_stages"
 setup_wizard_test = "erpnext.setup.setup_wizard.test_setup_wizard.run_setup_wizard_test"
 
 before_install = "erpnext.setup.install.check_setup_wizard_not_completed"
diff --git a/erpnext/patches.txt b/erpnext/patches.txt
index 9a7ec7c..7966d81 100644
--- a/erpnext/patches.txt
+++ b/erpnext/patches.txt
@@ -485,4 +485,3 @@
 erpnext.patches.v10_0.update_asset_calculate_depreciation
 erpnext.patches.v10_0.enabled_regional_print_format_based_on_country
 erpnext.patches.v10_0.update_asset_calculate_depreciation
-erpnext.patches.v10_0.update_due_date_in_gle_and_payment_entries
diff --git a/erpnext/patches/v10_0/update_due_date_in_gle_and_payment_entries.py b/erpnext/patches/v10_0/update_due_date_in_gle_and_payment_entries.py
deleted file mode 100644
index 268b843..0000000
--- a/erpnext/patches/v10_0/update_due_date_in_gle_and_payment_entries.py
+++ /dev/null
@@ -1,100 +0,0 @@
-from __future__ import unicode_literals
-import frappe
-from frappe.utils import update_progress_bar
-
-def execute():
-	frappe.reload_doc("accounts", "doctype", "gl_entry")
-	frappe.reload_doc("accounts", "doctype", "payment_entry_reference")
-	frappe.reload_doc("accounts", "doctype", "journal_entry_account")
-	
-	print "Updating Due Date in GL Entry, Journal Entry and Payment Entry"
-	for doctype in ("Sales Invoice", "Purchase Invoice"):
-		invoice_due_dates = frappe.db.sql("""select name, due_date from `tab{0}`
-			where docstatus=1 order by name""".format(doctype))
-
-		# update gle
-		count = 0
-		total_count = len(invoice_due_dates)
-		batch_size = 1000
-		
-		while(count < total_count):
-			update_progress_bar("Based on {0}".format(doctype), count, total_count)
-			sub_set = invoice_due_dates[count:count+batch_size]
-			invoices = [d[0] for d in sub_set]
-
-			update_gl_entries(doctype, invoices, sub_set)
-			update_payment_entries(doctype, invoices, sub_set)
-		
-			count += batch_size
-
-def update_gl_entries(doctype, invoices, invoice_due_dates):
-	when_then = get_when_then_for_gle(doctype, invoice_due_dates)
-
-	frappe.db.sql("""
-		UPDATE `tabGL Entry`
-		SET due_date = CASE
-			%s
-			ELSE `due_date` END
-		WHERE
-			(
-				(voucher_type = %s and voucher_no in (%s))
-				or (voucher_type in ('Journal Entry', 'Payment Entry')
-					and against_voucher in (%s))
-			)
-			and ifnull(party, '') != ''
-			and ifnull(due_date, '') = ''
-	""" % (when_then, '%s', ', '.join(['%s']*len(invoices)), ', '.join(['%s']*len(invoices))),
-		tuple([doctype] + invoices + invoices))
-
-def get_when_then_for_gle(doctype, data):
-	cond = ""
-	for d in data:
-		cond += """
-		 	WHEN (
-				(voucher_type = '{voucher_type}' and voucher_no = '{voucher_no}')
-				or (voucher_type in ('Journal Entry', 'Payment Entry')
-					and against_voucher = '{voucher_no}')
-			) THEN '{date}'
-		""".format(voucher_type=doctype, voucher_no=frappe.db.escape(d[0]), date=d[1])
-
-	return cond
-
-def update_payment_entries(ref_doctype, invoices, invoice_due_dates):
-	for d in (
-		("Payment Entry Reference", "reference_doctype", "due_date"),
-		("Journal Entry Account", "reference_type", "reference_due_date")):
-
-		when_then = get_when_then_for_payment_entries(ref_doctype, d[1], invoice_due_dates)
-
-		frappe.db.sql("""
-			UPDATE `tab{doctype}`
-			SET {due_date_field} = CASE
-				{when_then}
-				ELSE `{due_date_field}` END
-			WHERE
-				{ref_doctype_fieldname} = '{ref_doctype}'
-				and reference_name in ({reference_names})
-				and ifnull({due_date_field}, '') = ''
-		""".format(
-			doctype = d[0],
-			due_date_field = d[2],
-			when_then = when_then,
-			ref_doctype_fieldname = d[1],
-			ref_doctype = ref_doctype,
-			reference_names = ', '.join(['%s']*len(invoices))
-		), tuple(invoices))
-
-def get_when_then_for_payment_entries(ref_doctype, ref_doctype_fieldname, data):
-	cond = ""
-	for d in data:
-		cond += """
-		 	WHEN {ref_doctype_fieldname} = '{ref_doctype}'
-				and reference_name = '{voucher_no}'
-			THEN '{date}'
-		""".format(
-			ref_doctype_fieldname=ref_doctype_fieldname,
-			ref_doctype=ref_doctype,
-			voucher_no=frappe.db.escape(d[0]),
-			date=d[1])
-
-	return cond
\ No newline at end of file
diff --git a/erpnext/patches/v7_1/update_lead_source.py b/erpnext/patches/v7_1/update_lead_source.py
index 444159d..7fd4c14 100644
--- a/erpnext/patches/v7_1/update_lead_source.py
+++ b/erpnext/patches/v7_1/update_lead_source.py
@@ -2,7 +2,7 @@
 from frappe import _
 
 def execute():
-	from erpnext.setup.setup_wizard.install_fixtures import default_lead_sources
+	from erpnext.setup.setup_wizard.operations.install_fixtures import default_lead_sources
 
 	frappe.reload_doc('selling', 'doctype', 'lead_source')
 
diff --git a/erpnext/selling/doctype/quotation/quotation.json b/erpnext/selling/doctype/quotation/quotation.json
index 1fec2ed..1c40ec3 100644
--- a/erpnext/selling/doctype/quotation/quotation.json
+++ b/erpnext/selling/doctype/quotation/quotation.json
@@ -2266,7 +2266,7 @@
    "options": "Payment Schedule", 
    "permlevel": 0, 
    "precision": "", 
-   "print_hide": 0, 
+   "print_hide": 1, 
    "print_hide_if_no_value": 0, 
    "read_only": 0, 
    "remember_last_selected_value": 0, 
@@ -2881,8 +2881,8 @@
  "istable": 0, 
  "max_attachments": 1, 
  "menu_index": 0, 
- "modified": "2017-11-29 14:10:44.067669", 
- "modified_by": "Administrator", 
+ "modified": "2017-12-19 14:52:28.966139", 
+ "modified_by": "nabinhait@gmail.com", 
  "module": "Selling", 
  "name": "Quotation", 
  "owner": "Administrator", 
diff --git a/erpnext/selling/doctype/sales_order/sales_order.json b/erpnext/selling/doctype/sales_order/sales_order.json
index cdd27ff..7c23687 100644
--- a/erpnext/selling/doctype/sales_order/sales_order.json
+++ b/erpnext/selling/doctype/sales_order/sales_order.json
@@ -2445,7 +2445,7 @@
    "options": "Payment Schedule", 
    "permlevel": 0, 
    "precision": "", 
-   "print_hide": 0, 
+   "print_hide": 1, 
    "print_hide_if_no_value": 0, 
    "read_only": 0, 
    "remember_last_selected_value": 0, 
@@ -3529,8 +3529,8 @@
  "issingle": 0, 
  "istable": 0, 
  "max_attachments": 0, 
- "modified": "2017-11-29 13:43:33.076893", 
- "modified_by": "Administrator", 
+ "modified": "2017-12-19 14:51:52.710612", 
+ "modified_by": "nabinhait@gmail.com", 
  "module": "Selling", 
  "name": "Sales Order", 
  "owner": "Administrator", 
diff --git a/erpnext/setup/setup_wizard/data/__init__.py b/erpnext/setup/setup_wizard/data/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/setup/setup_wizard/data/__init__.py
diff --git a/erpnext/setup/setup_wizard/industry_type.py b/erpnext/setup/setup_wizard/data/industry_type.py
similarity index 100%
rename from erpnext/setup/setup_wizard/industry_type.py
rename to erpnext/setup/setup_wizard/data/industry_type.py
diff --git a/erpnext/setup/setup_wizard/operations/__init__.py b/erpnext/setup/setup_wizard/operations/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/setup/setup_wizard/operations/__init__.py
diff --git a/erpnext/setup/setup_wizard/operations/company_setup.py b/erpnext/setup/setup_wizard/operations/company_setup.py
new file mode 100644
index 0000000..7fe7f0c
--- /dev/null
+++ b/erpnext/setup/setup_wizard/operations/company_setup.py
@@ -0,0 +1,125 @@
+# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
+# License: GNU General Public License v3. See license.txt
+
+from __future__ import unicode_literals
+import frappe
+from frappe import _
+from frappe.utils import cstr, getdate
+from frappe.utils.file_manager import save_file
+from .default_website import website_maker
+from erpnext.accounts.doctype.account.account import RootNotEditable
+
+def create_fiscal_year_and_company(args):
+	if (args.get('fy_start_date')):
+		curr_fiscal_year = get_fy_details(args.get('fy_start_date'), args.get('fy_end_date'))
+		frappe.get_doc({
+			"doctype":"Fiscal Year",
+			'year': curr_fiscal_year,
+			'year_start_date': args.get('fy_start_date'),
+			'year_end_date': args.get('fy_end_date'),
+		}).insert()
+
+	if (args.get('company_name')):
+		frappe.get_doc({
+			"doctype":"Company",
+			'company_name':args.get('company_name'),
+			'enable_perpetual_inventory': 1,
+			'abbr':args.get('company_abbr'),
+			'default_currency':args.get('currency'),
+			'country': args.get('country'),
+			'create_chart_of_accounts_based_on': 'Standard Template',
+			'chart_of_accounts': args.get('chart_of_accounts'),
+			'domain': args.get('domains')[0]
+		}).insert()
+
+def enable_shopping_cart(args):
+	# Needs price_lists
+	frappe.get_doc({
+		"doctype": "Shopping Cart Settings",
+		"enabled": 1,
+		'company': args.get('company_name')	,
+		'price_list': frappe.db.get_value("Price List", {"selling": 1}),
+		'default_customer_group': _("Individual"),
+		'quotation_series': "QTN-",
+	}).insert()
+
+def create_bank_account(args):
+	if args.get("bank_account"):
+		company_name = args.get('company_name')
+		bank_account_group =  frappe.db.get_value("Account",
+			{"account_type": "Bank", "is_group": 1, "root_type": "Asset",
+				"company": company_name})
+		if bank_account_group:
+			bank_account = frappe.get_doc({
+				"doctype": "Account",
+				'account_name': args.get("bank_account"),
+				'parent_account': bank_account_group,
+				'is_group':0,
+				'company': company_name,
+				"account_type": "Bank",
+			})
+			try:
+				return bank_account.insert()
+			except RootNotEditable:
+				frappe.throw(_("Bank account cannot be named as {0}").format(args.get("bank_account")))
+			except frappe.DuplicateEntryError:
+				# bank account same as a CoA entry
+				pass
+
+def create_email_digest():
+	from frappe.utils.user import get_system_managers
+	system_managers = get_system_managers(only_name=True)
+	if not system_managers:
+		return
+
+	companies = frappe.db.sql_list("select name FROM `tabCompany`")
+	for company in companies:
+		if not frappe.db.exists("Email Digest", "Default Weekly Digest - " + company):
+			edigest = frappe.get_doc({
+				"doctype": "Email Digest",
+				"name": "Default Weekly Digest - " + company,
+				"company": company,
+				"frequency": "Weekly",
+				"recipient_list": "\n".join(system_managers)
+			})
+
+			for df in edigest.meta.get("fields", {"fieldtype": "Check"}):
+				if df.fieldname != "scheduler_errors":
+					edigest.set(df.fieldname, 1)
+
+			edigest.insert()
+
+	# scheduler errors digest
+	if companies:
+		edigest = frappe.new_doc("Email Digest")
+		edigest.update({
+			"name": "Scheduler Errors",
+			"company": companies[0],
+			"frequency": "Daily",
+			"recipient_list": "\n".join(system_managers),
+			"scheduler_errors": 1,
+			"enabled": 1
+		})
+		edigest.insert()
+
+def create_logo(args):
+	if args.get("attach_logo"):
+		attach_logo = args.get("attach_logo").split(",")
+		if len(attach_logo)==3:
+			filename, filetype, content = attach_logo
+			fileurl = save_file(filename, content, "Website Settings", "Website Settings",
+				decode=True).file_url
+			frappe.db.set_value("Website Settings", "Website Settings", "brand_html",
+				"<img src='{0}' style='max-width: 40px; max-height: 25px;'> {1}".format(fileurl, args.get("company_name")	))
+
+def create_website(args):
+	if args.get('setup_website'):
+		website_maker(args)
+
+def get_fy_details(fy_start_date, fy_end_date):
+	start_year = getdate(fy_start_date).year
+	if start_year == getdate(fy_end_date).year:
+		fy = cstr(start_year)
+	else:
+		fy = cstr(start_year) + '-' + cstr(start_year + 1)
+	return fy
\ No newline at end of file
diff --git a/erpnext/setup/setup_wizard/default_website.py b/erpnext/setup/setup_wizard/operations/default_website.py
similarity index 100%
rename from erpnext/setup/setup_wizard/default_website.py
rename to erpnext/setup/setup_wizard/operations/default_website.py
diff --git a/erpnext/setup/setup_wizard/operations/defaults_setup.py b/erpnext/setup/setup_wizard/operations/defaults_setup.py
new file mode 100644
index 0000000..b54d94e
--- /dev/null
+++ b/erpnext/setup/setup_wizard/operations/defaults_setup.py
@@ -0,0 +1,126 @@
+# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
+# License: GNU General Public License v3. See license.txt
+
+from __future__ import unicode_literals
+import frappe
+from frappe import _
+from frappe.utils import cstr, getdate
+from frappe.core.doctype.communication.comment import add_info_comment
+
+def set_default_settings(args):
+	# enable default currency
+	frappe.db.set_value("Currency", args.get("currency"), "enabled", 1)
+
+	global_defaults = frappe.get_doc("Global Defaults", "Global Defaults")
+	global_defaults.update({
+		'current_fiscal_year': get_fy_details(args.get('fy_start_date'), args.get('fy_end_date')),
+		'default_currency': args.get('currency'),
+		'default_company':args.get('company_name')	,
+		"country": args.get("country"),
+	})
+
+	global_defaults.save()
+
+	system_settings = frappe.get_doc("System Settings")
+	system_settings.email_footer_address = args.get("company_name")
+	system_settings.save()
+
+	domain_settings = frappe.get_single('Domain Settings')
+	domain_settings.set_active_domains(args.get('domains'))
+	domain_settings.save()
+
+	stock_settings = frappe.get_doc("Stock Settings")
+	stock_settings.item_naming_by = "Item Code"
+	stock_settings.valuation_method = "FIFO"
+	stock_settings.default_warehouse = frappe.db.get_value('Warehouse', {'warehouse_name': _('Stores')})
+	stock_settings.stock_uom = _("Nos")
+	stock_settings.auto_indent = 1
+	stock_settings.auto_insert_price_list_rate_if_missing = 1
+	stock_settings.automatically_set_serial_nos_based_on_fifo = 1
+	stock_settings.save()
+
+	selling_settings = frappe.get_doc("Selling Settings")
+	selling_settings.cust_master_name = "Customer Name"
+	selling_settings.so_required = "No"
+	selling_settings.dn_required = "No"
+	selling_settings.allow_multiple_items = 1
+	selling_settings.save()
+
+	buying_settings = frappe.get_doc("Buying Settings")
+	buying_settings.supp_master_name = "Supplier Name"
+	buying_settings.po_required = "No"
+	buying_settings.pr_required = "No"
+	buying_settings.maintain_same_rate = 1
+	buying_settings.allow_multiple_items = 1
+	buying_settings.save()
+
+	notification_control = frappe.get_doc("Notification Control")
+	notification_control.quotation = 1
+	notification_control.sales_invoice = 1
+	notification_control.purchase_order = 1
+	notification_control.save()
+
+	hr_settings = frappe.get_doc("HR Settings")
+	hr_settings.emp_created_by = "Naming Series"
+	hr_settings.save()
+
+def set_no_copy_fields_in_variant_settings():
+	# set no copy fields of an item doctype to item variant settings
+	doc = frappe.get_doc('Item Variant Settings')
+	doc.set_default_fields()
+	doc.save()
+
+def create_price_lists(args):
+	for pl_type, pl_name in (("Selling", _("Standard Selling")), ("Buying", _("Standard Buying"))):
+		frappe.get_doc({
+			"doctype": "Price List",
+			"price_list_name": pl_name,
+			"enabled": 1,
+			"buying": 1 if pl_type == "Buying" else 0,
+			"selling": 1 if pl_type == "Selling" else 0,
+			"currency": args["currency"]
+		}).insert()
+
+def create_employee_for_self(args):
+	if frappe.session.user == 'Administrator':
+		return
+
+	# create employee for self
+	emp = frappe.get_doc({
+		"doctype": "Employee",
+		"employee_name": " ".join(filter(None, [args.get("first_name"), args.get("last_name")])),
+		"user_id": frappe.session.user,
+		"status": "Active",
+		"company": args.get("company_name")
+	})
+	emp.flags.ignore_mandatory = True
+	emp.insert(ignore_permissions = True)
+
+def create_territories():
+	"""create two default territories, one for home country and one named Rest of the World"""
+	from frappe.utils.nestedset import get_root_of
+	country = frappe.db.get_default("country")
+	root_territory = get_root_of("Territory")
+
+	for name in (country, _("Rest Of The World")):
+		if name and not frappe.db.exists("Territory", name):
+			frappe.get_doc({
+				"doctype": "Territory",
+				"territory_name": name.replace("'", ""),
+				"parent_territory": root_territory,
+				"is_group": "No"
+			}).insert()
+
+def create_feed_and_todo():
+	"""update Activity feed and create todo for creation of item, customer, vendor"""
+	add_info_comment(**{
+		"subject": _("ERPNext Setup Complete!")
+	})
+
+def get_fy_details(fy_start_date, fy_end_date):
+	start_year = getdate(fy_start_date).year
+	if start_year == getdate(fy_end_date).year:
+		fy = cstr(start_year)
+	else:
+		fy = cstr(start_year) + '-' + cstr(start_year + 1)
+	return fy
diff --git a/erpnext/setup/setup_wizard/install_fixtures.py b/erpnext/setup/setup_wizard/operations/install_fixtures.py
similarity index 99%
rename from erpnext/setup/setup_wizard/install_fixtures.py
rename to erpnext/setup/setup_wizard/operations/install_fixtures.py
index 68a1578..dce3c28 100644
--- a/erpnext/setup/setup_wizard/install_fixtures.py
+++ b/erpnext/setup/setup_wizard/operations/install_fixtures.py
@@ -248,7 +248,7 @@
 
 	]
 
-	from erpnext.setup.setup_wizard.industry_type import get_industry_types
+	from erpnext.setup.setup_wizard.data.industry_type import get_industry_types
 	records += [{"doctype":"Industry Type", "industry": d} for d in get_industry_types()]
 	# records += [{"doctype":"Operation", "operation": d} for d in get_operations()]
 
diff --git a/erpnext/setup/setup_wizard/sample_data.py b/erpnext/setup/setup_wizard/operations/sample_data.py
similarity index 100%
rename from erpnext/setup/setup_wizard/sample_data.py
rename to erpnext/setup/setup_wizard/operations/sample_data.py
diff --git a/erpnext/setup/setup_wizard/operations/taxes_setup.py b/erpnext/setup/setup_wizard/operations/taxes_setup.py
new file mode 100644
index 0000000..ee225d3
--- /dev/null
+++ b/erpnext/setup/setup_wizard/operations/taxes_setup.py
@@ -0,0 +1,95 @@
+# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
+# License: GNU General Public License v3. See license.txt
+
+from __future__ import unicode_literals
+import frappe, copy, os, json
+from frappe.utils import flt
+from erpnext.accounts.doctype.account.account import RootNotEditable
+
+def create_sales_tax(args):
+	country_wise_tax = get_country_wise_tax(args.get("country"))
+	if country_wise_tax and len(country_wise_tax) > 0:
+		for sales_tax, tax_data in country_wise_tax.items():
+			make_tax_account_and_template(
+				args.get("company_name"),
+				tax_data.get('account_name'),
+				tax_data.get('tax_rate'), sales_tax)
+
+def make_tax_account_and_template(company, account_name, tax_rate, template_name=None):
+	try:
+		if not isinstance(account_name, (list, tuple)):
+			account_name = [account_name]
+			tax_rate = [tax_rate]
+
+		accounts = []
+		for i, name in enumerate(account_name):
+			tax_account = make_tax_account(company, account_name[i], tax_rate[i])
+			if tax_account:
+				accounts.append(tax_account)
+
+		if accounts:
+			make_sales_and_purchase_tax_templates(accounts, template_name)
+	except frappe.NameError:
+		pass
+	except RootNotEditable:
+		pass
+
+def make_tax_account(company, account_name, tax_rate):
+	tax_group = get_tax_account_group(company)
+	if tax_group:
+		return frappe.get_doc({
+			"doctype":"Account",
+			"company": company,
+			"parent_account": tax_group,
+			"account_name": account_name,
+			"is_group": 0,
+			"report_type": "Balance Sheet",
+			"root_type": "Liability",
+			"account_type": "Tax",
+			"tax_rate": flt(tax_rate) if tax_rate else None
+		}).insert(ignore_permissions=True)
+
+def make_sales_and_purchase_tax_templates(accounts, template_name=None):
+	if not template_name:
+		template_name = accounts[0].name
+
+	sales_tax_template = {
+		"doctype": "Sales Taxes and Charges Template",
+		"title": template_name,
+		"company": accounts[0].company,
+		'taxes': []
+	}
+
+	for account in accounts:
+		sales_tax_template['taxes'].append({
+			"category": "Valuation and Total",
+			"charge_type": "On Net Total",
+			"account_head": account.name,
+			"description": "{0} @ {1}".format(account.account_name, account.tax_rate),
+			"rate": account.tax_rate
+		})
+	# Sales
+	frappe.get_doc(copy.deepcopy(sales_tax_template)).insert(ignore_permissions=True)
+
+	# Purchase
+	purchase_tax_template = copy.deepcopy(sales_tax_template)
+	purchase_tax_template["doctype"] = "Purchase Taxes and Charges Template"
+
+	doc = frappe.get_doc(purchase_tax_template)
+	doc.insert(ignore_permissions=True)
+
+def get_tax_account_group(company):
+	tax_group = frappe.db.get_value("Account",
+		{"account_name": "Duties and Taxes", "is_group": 1, "company": company})
+	if not tax_group:
+		tax_group = frappe.db.get_value("Account", {"is_group": 1, "root_type": "Liability",
+				"account_type": "Tax", "company": company})
+
+	return tax_group
+
+def get_country_wise_tax(country):
+	data = {}
+	with open (os.path.join(os.path.dirname(__file__), "..", "data", "country_wise_tax.json")) as countrywise_tax:
+		data = json.load(countrywise_tax).get(country)
+
+	return data
\ No newline at end of file
diff --git a/erpnext/setup/setup_wizard/setup_wizard.py b/erpnext/setup/setup_wizard/setup_wizard.py
index e861a96..2c5f7e8 100644
--- a/erpnext/setup/setup_wizard/setup_wizard.py
+++ b/erpnext/setup/setup_wizard/setup_wizard.py
@@ -2,393 +2,139 @@
 # License: GNU General Public License v3. See license.txt
 
 from __future__ import unicode_literals
-import frappe, copy
 
-import os
-import json
-from frappe.utils import cstr, flt, getdate
+import frappe
 from frappe import _
-from frappe.utils.file_manager import save_file
-from .default_website import website_maker
-import install_fixtures
-from .sample_data import make_sample_data
-from erpnext.accounts.doctype.account.account import RootNotEditable
-from frappe.core.doctype.communication.comment import add_info_comment
-from erpnext.setup.doctype.company.company import install_country_fixtures
+from operations import install_fixtures, taxes_setup, defaults_setup, company_setup, sample_data
+
+def get_setup_stages(args=None):
+	if frappe.db.sql("select name from tabCompany"):
+		stages = [
+			{
+				'status': _('Wrapping up'),
+				'fail_msg': _('Failed to login'),
+				'tasks': [
+					{
+						'fn': fin,
+						'args': args,
+						'fail_msg': _("Failed to login")
+					}
+				]
+			}
+		]
+	else:
+		stages = [
+			{
+				'status': _('Installing presets'),
+				'fail_msg': _('Failed to install presets'),
+				'tasks': [
+					{
+						'fn': stage_fixtures,
+						'args': args,
+						'fail_msg': _("Failed to install presets")
+					}
+				]
+			},
+			{
+				'status': _('Setting up company and taxes'),
+				'fail_msg': _('Failed to setup company'),
+				'tasks': [
+					{
+						'fn': setup_company,
+						'args': args,
+						'fail_msg': _("Failed to setup company")
+					},
+					{
+						'fn': setup_taxes,
+						'args': args,
+						'fail_msg': _("Failed to setup taxes")
+					}
+				]
+			},
+			{
+				'status': _('Setting defaults'),
+				'fail_msg': 'Failed to set defaults',
+				'tasks': [
+					{
+						'fn': stage_three,
+						'args': args,
+						'fail_msg': _("Failed to set defaults")
+					}
+				]
+			},
+			{
+				'status': _('Making website'),
+				'fail_msg': _('Failed to create website'),
+				'tasks': [
+					{
+						'fn': stage_four,
+						'args': args,
+						'fail_msg': _("Failed to create website")
+					}
+				]
+			},
+			{
+				'status': _('Wrapping up'),
+				'fail_msg': _('Failed to login'),
+				'tasks': [
+					{
+						'fn': fin,
+						'args': args,
+						'fail_msg': _("Failed to login")
+					}
+				]
+			}
+		]
+
+	return stages
 
 def setup_complete(args=None):
-	if frappe.db.sql("select name from tabCompany"):
-		frappe.throw(_("Setup Already Complete!!"))
+	stage_fixtures(args)
+	setup_company(args)
+	setup_taxes(args)
+	stage_three(args)
+	stage_four(args)
+	fin(args)
 
+def stage_fixtures(args):
 	install_fixtures.install(args.get("country"))
 
-	create_price_lists(args)
-	create_fiscal_year_and_company(args)
-	create_sales_tax(args)
-	create_employee_for_self(args)
-	set_defaults(args)
-	create_territories()
-	create_feed_and_todo()
-	create_email_digest()
-	create_letter_head(args)
-	set_no_copy_fields_in_variant_settings()
+def setup_company(args):
+	defaults_setup.create_price_lists(args)
+	company_setup.create_fiscal_year_and_company(args)
+	company_setup.enable_shopping_cart(args)
+	company_setup.create_bank_account(args)
 
-	if args.get('setup_website'):
-		website_maker(args)
+def setup_taxes(args):
+	taxes_setup.create_sales_tax(args)
 
-	create_logo(args)
+def stage_three(args):
+	defaults_setup.create_employee_for_self(args)
+	defaults_setup.set_default_settings(args)
+	defaults_setup.create_territories()
+	defaults_setup.create_feed_and_todo()
+	defaults_setup.set_no_copy_fields_in_variant_settings()
 
+def stage_four(args):
+	company_setup.create_website(args)
+	company_setup.create_email_digest()
+	company_setup.create_logo(args)
+
+def fin(args):
 	frappe.local.message_log = []
-
-	domains = args.get('domains')
-	domain_settings = frappe.get_single('Domain Settings')
-	domain_settings.set_active_domains(domains)
-
-	frappe.db.commit()
 	login_as_first_user(args)
 
-	frappe.db.commit()
-	frappe.clear_cache()
+	make_sample_data(args.get('domains'))
 
+def make_sample_data(domains):
 	try:
-		make_sample_data(domains)
-		frappe.clear_cache()
+		sample_data.make_sample_data(domains)
 	except:
 		# clear message
 		if frappe.message_log:
 			frappe.message_log.pop()
-
 		pass
 
-def create_fiscal_year_and_company(args):
-	if (args.get('fy_start_date')):
-		curr_fiscal_year = get_fy_details(args.get('fy_start_date'), args.get('fy_end_date'))
-		frappe.get_doc({
-			"doctype":"Fiscal Year",
-			'year': curr_fiscal_year,
-			'year_start_date': args.get('fy_start_date'),
-			'year_end_date': args.get('fy_end_date'),
-		}).insert()
-		args["curr_fiscal_year"] = curr_fiscal_year
-
-	# Company
-	if (args.get('company_name')):
-		frappe.get_doc({
-			"doctype":"Company",
-			'company_name':args.get('company_name'),
-			'enable_perpetual_inventory': 1,
-			'abbr':args.get('company_abbr'),
-			'default_currency':args.get('currency'),
-			'country': args.get('country'),
-			'create_chart_of_accounts_based_on': 'Standard Template',
-			'chart_of_accounts': args.get('chart_of_accounts'),
-			'domain': args.get('domains')[0]
-		}).insert()
-
-		#Enable shopping cart
-		enable_shopping_cart(args)
-
-		# Bank Account
-		create_bank_account(args)
-
-def enable_shopping_cart(args):
-	frappe.get_doc({
-		"doctype": "Shopping Cart Settings",
-		"enabled": 1,
-		'company': args.get('company_name')	,
-		'price_list': frappe.db.get_value("Price List", {"selling": 1}),
-		'default_customer_group': _("Individual"),
-		'quotation_series': "QTN-",
-	}).insert()
-
-def create_bank_account(args):
-	if args.get("bank_account"):
-		company_name = args.get('company_name')
-		bank_account_group =  frappe.db.get_value("Account",
-			{"account_type": "Bank", "is_group": 1, "root_type": "Asset",
-				"company": company_name})
-		if bank_account_group:
-			bank_account = frappe.get_doc({
-				"doctype": "Account",
-				'account_name': args.get("bank_account"),
-				'parent_account': bank_account_group,
-				'is_group':0,
-				'company': company_name,
-				"account_type": "Bank",
-			})
-			try:
-				return bank_account.insert()
-			except RootNotEditable:
-				frappe.throw(_("Bank account cannot be named as {0}").format(args.get("bank_account")))
-			except frappe.DuplicateEntryError:
-				# bank account same as a CoA entry
-				pass
-
-def create_price_lists(args):
-	for pl_type, pl_name in (("Selling", _("Standard Selling")), ("Buying", _("Standard Buying"))):
-		frappe.get_doc({
-			"doctype": "Price List",
-			"price_list_name": pl_name,
-			"enabled": 1,
-			"buying": 1 if pl_type == "Buying" else 0,
-			"selling": 1 if pl_type == "Selling" else 0,
-			"currency": args["currency"]
-		}).insert()
-
-def set_defaults(args):
-	# enable default currency
-	frappe.db.set_value("Currency", args.get("currency"), "enabled", 1)
-
-	global_defaults = frappe.get_doc("Global Defaults", "Global Defaults")
-	global_defaults.update({
-		'current_fiscal_year': args.get('curr_fiscal_year'),
-		'default_currency': args.get('currency'),
-		'default_company':args.get('company_name')	,
-		"country": args.get("country"),
-	})
-
-	global_defaults.save()
-
-	system_settings = frappe.get_doc("System Settings")
-	system_settings.email_footer_address = args.get("company")
-	system_settings.save()
-
-	stock_settings = frappe.get_doc("Stock Settings")
-	stock_settings.item_naming_by = "Item Code"
-	stock_settings.valuation_method = "FIFO"
-	stock_settings.default_warehouse = frappe.db.get_value('Warehouse', {'warehouse_name': _('Stores')})
-	stock_settings.stock_uom = _("Nos")
-	stock_settings.auto_indent = 1
-	stock_settings.auto_insert_price_list_rate_if_missing = 1
-	stock_settings.automatically_set_serial_nos_based_on_fifo = 1
-	stock_settings.save()
-
-	selling_settings = frappe.get_doc("Selling Settings")
-	selling_settings.cust_master_name = "Customer Name"
-	selling_settings.so_required = "No"
-	selling_settings.dn_required = "No"
-	selling_settings.allow_multiple_items = 1
-	selling_settings.save()
-
-	buying_settings = frappe.get_doc("Buying Settings")
-	buying_settings.supp_master_name = "Supplier Name"
-	buying_settings.po_required = "No"
-	buying_settings.pr_required = "No"
-	buying_settings.maintain_same_rate = 1
-	buying_settings.allow_multiple_items = 1
-	buying_settings.save()
-
-	notification_control = frappe.get_doc("Notification Control")
-	notification_control.quotation = 1
-	notification_control.sales_invoice = 1
-	notification_control.purchase_order = 1
-	notification_control.save()
-
-	hr_settings = frappe.get_doc("HR Settings")
-	hr_settings.emp_created_by = "Naming Series"
-	hr_settings.save()
-
-def create_feed_and_todo():
-	"""update Activity feed and create todo for creation of item, customer, vendor"""
-	add_info_comment(**{
-		"subject": _("ERPNext Setup Complete!")
-	})
-
-def create_email_digest():
-	from frappe.utils.user import get_system_managers
-	system_managers = get_system_managers(only_name=True)
-	if not system_managers:
-		return
-
-	companies = frappe.db.sql_list("select name FROM `tabCompany`")
-	for company in companies:
-		if not frappe.db.exists("Email Digest", "Default Weekly Digest - " + company):
-			edigest = frappe.get_doc({
-				"doctype": "Email Digest",
-				"name": "Default Weekly Digest - " + company,
-				"company": company,
-				"frequency": "Weekly",
-				"recipient_list": "\n".join(system_managers)
-			})
-
-			for df in edigest.meta.get("fields", {"fieldtype": "Check"}):
-				if df.fieldname != "scheduler_errors":
-					edigest.set(df.fieldname, 1)
-
-			edigest.insert()
-
-	# scheduler errors digest
-	if companies:
-		edigest = frappe.new_doc("Email Digest")
-		edigest.update({
-			"name": "Scheduler Errors",
-			"company": companies[0],
-			"frequency": "Daily",
-			"recipient_list": "\n".join(system_managers),
-			"scheduler_errors": 1,
-			"enabled": 1
-		})
-		edigest.insert()
-
-def get_fy_details(fy_start_date, fy_end_date):
-	start_year = getdate(fy_start_date).year
-	if start_year == getdate(fy_end_date).year:
-		fy = cstr(start_year)
-	else:
-		fy = cstr(start_year) + '-' + cstr(start_year + 1)
-	return fy
-
-def create_sales_tax(args):
-	country_wise_tax = get_country_wise_tax(args.get("country"))
-	if country_wise_tax and len(country_wise_tax) > 0:
-		for sales_tax, tax_data in country_wise_tax.items():
-			make_tax_account_and_template(
-				args.get("company_name"),
-				tax_data.get('account_name'),
-				tax_data.get('tax_rate'), sales_tax)
-
-# Tax utils start
-def make_tax_account_and_template(company, account_name, tax_rate, template_name=None):
-	try:
-		if not isinstance(account_name, (list, tuple)):
-			account_name = [account_name]
-			tax_rate = [tax_rate]
-
-		accounts = []
-		for i, name in enumerate(account_name):
-			tax_account = make_tax_account(company, account_name[i], tax_rate[i])
-			if tax_account:
-				accounts.append(tax_account)
-
-		if accounts:
-			make_sales_and_purchase_tax_templates(accounts, template_name)
-	except frappe.NameError:
-		pass
-	except RootNotEditable:
-		pass
-
-def make_tax_account(company, account_name, tax_rate):
-	tax_group = get_tax_account_group(company)
-	if tax_group:
-		return frappe.get_doc({
-			"doctype":"Account",
-			"company": company,
-			"parent_account": tax_group,
-			"account_name": account_name,
-			"is_group": 0,
-			"report_type": "Balance Sheet",
-			"root_type": "Liability",
-			"account_type": "Tax",
-			"tax_rate": flt(tax_rate) if tax_rate else None
-		}).insert(ignore_permissions=True)
-
-def make_sales_and_purchase_tax_templates(accounts, template_name=None):
-	if not template_name:
-		template_name = accounts[0].name
-
-	sales_tax_template = {
-		"doctype": "Sales Taxes and Charges Template",
-		"title": template_name,
-		"company": accounts[0].company,
-		'taxes': []
-	}
-
-	for account in accounts:
-		sales_tax_template['taxes'].append({
-			"category": "Valuation and Total",
-			"charge_type": "On Net Total",
-			"account_head": account.name,
-			"description": "{0} @ {1}".format(account.account_name, account.tax_rate),
-			"rate": account.tax_rate
-		})
-	# Sales
-	frappe.get_doc(copy.deepcopy(sales_tax_template)).insert(ignore_permissions=True)
-
-	# Purchase
-	purchase_tax_template = copy.deepcopy(sales_tax_template)
-	purchase_tax_template["doctype"] = "Purchase Taxes and Charges Template"
-
-	doc = frappe.get_doc(purchase_tax_template)
-	doc.insert(ignore_permissions=True)
-
-def get_tax_account_group(company):
-	tax_group = frappe.db.get_value("Account",
-		{"account_name": "Duties and Taxes", "is_group": 1, "company": company})
-	if not tax_group:
-		tax_group = frappe.db.get_value("Account", {"is_group": 1, "root_type": "Liability",
-				"account_type": "Tax", "company": company})
-
-	return tax_group
-
-# Tax utils end
-
-def get_country_wise_tax(country):
-	data = {}
-	with open (os.path.join(os.path.dirname(__file__), "data", "country_wise_tax.json")) as countrywise_tax:
-		data = json.load(countrywise_tax).get(country)
-
-	return data
-
-def create_letter_head(args):
-	if args.get("attach_letterhead"):
-		frappe.get_doc({
-			"doctype":"Letter Head",
-			"letter_head_name": _("Standard"),
-			"is_default": 1
-		}).insert()
-
-		attach_letterhead = args.get("attach_letterhead").split(",")
-		if len(attach_letterhead)==3:
-			filename, filetype, content = attach_letterhead
-			fileurl = save_file(filename, content, "Letter Head", _("Standard"), decode=True).file_url
-			frappe.db.set_value("Letter Head", _("Standard"), "content", "<img src='%s' style='max-width: 100%%;'>" % fileurl)
-
-def set_no_copy_fields_in_variant_settings():
-	# set no copy fields of an item doctype to item variant settings
-	doc = frappe.get_doc('Item Variant Settings')
-	doc.set_default_fields()
-	doc.save()
-
-def create_logo(args):
-	if args.get("attach_logo"):
-		attach_logo = args.get("attach_logo").split(",")
-		if len(attach_logo)==3:
-			filename, filetype, content = attach_logo
-			fileurl = save_file(filename, content, "Website Settings", "Website Settings",
-				decode=True).file_url
-			frappe.db.set_value("Website Settings", "Website Settings", "brand_html",
-				"<img src='{0}' style='max-width: 40px; max-height: 25px;'> {1}".format(fileurl, args.get("company_name")	))
-
-def create_territories():
-	"""create two default territories, one for home country and one named Rest of the World"""
-	from frappe.utils.nestedset import get_root_of
-	country = frappe.db.get_default("country")
-	root_territory = get_root_of("Territory")
-	for name in (country, _("Rest Of The World")):
-		if name and not frappe.db.exists("Territory", name):
-			frappe.get_doc({
-				"doctype": "Territory",
-				"territory_name": name.replace("'", ""),
-				"parent_territory": root_territory,
-				"is_group": "No"
-			}).insert()
-
 def login_as_first_user(args):
 	if args.get("email") and hasattr(frappe.local, "login_manager"):
 		frappe.local.login_manager.login_as(args.get("email"))
-
-def create_employee_for_self(args):
-	if frappe.session.user == 'Administrator':
-		return
-
-	# create employee for self
-	emp = frappe.get_doc({
-		"doctype": "Employee",
-		"employee_name": " ".join(filter(None, [args.get("first_name"), args.get("last_name")])),
-		"user_id": frappe.session.user,
-		"status": "Active",
-		"company": args.get("company_name")
-	})
-	emp.flags.ignore_mandatory = True
-	emp.insert(ignore_permissions = True)
-
diff --git a/erpnext/stock/doctype/delivery_trip/delivery_trip.json b/erpnext/stock/doctype/delivery_trip/delivery_trip.json
index 50e4999..98aaa1c 100644
--- a/erpnext/stock/doctype/delivery_trip/delivery_trip.json
+++ b/erpnext/stock/doctype/delivery_trip/delivery_trip.json
@@ -539,8 +539,8 @@
  "issingle": 0, 
  "istable": 0, 
  "max_attachments": 0, 
- "modified": "2017-11-13 03:56:09.885801", 
- "modified_by": "Administrator", 
+ "modified": "2017-12-19 12:00:49.226226", 
+ "modified_by": "nabinhait@gmail.com", 
  "module": "Stock", 
  "name": "Delivery Trip", 
  "name_case": "", 
@@ -565,6 +565,26 @@
    "share": 1, 
    "submit": 1, 
    "write": 1
+  }, 
+  {
+   "amend": 1, 
+   "apply_user_permissions": 0, 
+   "cancel": 1, 
+   "create": 1, 
+   "delete": 1, 
+   "email": 1, 
+   "export": 1, 
+   "if_owner": 0, 
+   "import": 0, 
+   "permlevel": 0, 
+   "print": 1, 
+   "read": 1, 
+   "report": 1, 
+   "role": "Stock User", 
+   "set_user_permissions": 0, 
+   "share": 1, 
+   "submit": 1, 
+   "write": 1
   }
  ], 
  "quick_entry": 0, 
diff --git a/erpnext/stock/doctype/stock_entry/test_stock_entry.py b/erpnext/stock/doctype/stock_entry/test_stock_entry.py
index 551ad9f2..b590822 100644
--- a/erpnext/stock/doctype/stock_entry/test_stock_entry.py
+++ b/erpnext/stock/doctype/stock_entry/test_stock_entry.py
@@ -496,10 +496,10 @@
 		frappe.get_doc("User", "test2@example.com")\
 			.add_roles("Sales User", "Sales Manager", "Stock User", "Stock Manager")
 
-		frappe.set_user("test@example.com")
 		st1 = frappe.copy_doc(test_records[0])
 		st1.company = "_Test Company 1"
 		set_perpetual_inventory(0, st1.company)
+		frappe.set_user("test@example.com")
 		st1.get("items")[0].t_warehouse="_Test Warehouse 2 - _TC1"
 		self.assertRaises(frappe.PermissionError, st1.insert)