Merge pull request #16749 from Alchez/hotfix-cancelled-payments

fix(payments): Only check for Draft or Submitted payments while cancelling payment requests
diff --git a/.travis.yml b/.travis.yml
index 14260e3..869fe95 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -15,7 +15,7 @@
   - sudo rm /etc/apt/sources.list.d/docker.list
   - sudo apt-get install hhvm && rm -rf /home/travis/.kiex/
   - sudo apt-get purge -y mysql-common mysql-server mysql-client
-  - nvm install v7.10.0
+  - nvm install 10
   - pip install python-coveralls
   - wget https://raw.githubusercontent.com/frappe/bench/master/playbooks/install.py
   - sudo python install.py --develop --user travis --without-bench-setup
diff --git a/erpnext/__init__.py b/erpnext/__init__.py
index 049a8a0..8ac608e 100644
--- a/erpnext/__init__.py
+++ b/erpnext/__init__.py
@@ -5,7 +5,7 @@
 from erpnext.hooks import regional_overrides
 from frappe.utils import getdate
 
-__version__ = '11.1.9'
+__version__ = '11.1.15'
 
 def get_default_company(user=None):
 	'''Get default company for user'''
diff --git a/erpnext/accounts/doctype/account/account.json b/erpnext/accounts/doctype/account/account.json
index e47f8d2..460c025 100644
--- a/erpnext/accounts/doctype/account/account.json
+++ b/erpnext/accounts/doctype/account/account.json
@@ -632,6 +632,39 @@
    "set_only_once": 0, 
    "translatable": 0, 
    "unique": 0
+  }, 
+  {
+   "allow_bulk_edit": 0, 
+   "allow_in_quick_entry": 0, 
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
+   "columns": 0, 
+   "depends_on": "eval:(doc.report_type == 'Profit and Loss' && !doc.is_group)", 
+   "fieldname": "include_in_gross", 
+   "fieldtype": "Check", 
+   "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": "Include in gross", 
+   "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, 
+   "translatable": 0, 
+   "unique": 0
   }
  ], 
  "has_web_view": 0, 
@@ -645,7 +678,7 @@
  "issingle": 0, 
  "istable": 0, 
  "max_attachments": 0, 
- "modified": "2019-01-07 16:52:02.557837", 
+ "modified": "2019-03-04 14:42:07.208893", 
  "modified_by": "Administrator", 
  "module": "Accounts", 
  "name": "Account", 
diff --git a/erpnext/accounts/doctype/account/account.py b/erpnext/accounts/doctype/account/account.py
index 5d504b9..427f3db 100644
--- a/erpnext/accounts/doctype/account/account.py
+++ b/erpnext/accounts/doctype/account/account.py
@@ -5,7 +5,7 @@
 import frappe
 from frappe.utils import cint, cstr
 from frappe import throw, _
-from frappe.utils.nestedset import NestedSet
+from frappe.utils.nestedset import NestedSet, get_ancestors_of, get_descendants_of
 
 class RootNotEditable(frappe.ValidationError): pass
 class BalanceMismatchError(frappe.ValidationError): pass
@@ -41,6 +41,7 @@
 		self.validate_frozen_accounts_modifier()
 		self.validate_balance_must_be_debit_or_credit()
 		self.validate_account_currency()
+		self.validate_root_company_and_sync_account_to_children()
 
 	def validate_parent(self):
 		"""Fetch Parent Details and validate parent account"""
@@ -90,6 +91,34 @@
 		if not self.parent_account and not self.is_group:
 			frappe.throw(_("Root Account must be a group"))
 
+	def validate_root_company_and_sync_account_to_children(self):
+		# ignore validation while creating new compnay or while syncing to child companies
+		if frappe.local.flags.ignore_root_company_validation or self.flags.ignore_root_company_validation:
+			return
+
+		ancestors = get_root_company(self.company)
+		if ancestors:
+			frappe.throw(_("Please add the account to root level Company - %s" % ancestors[0]))
+		else:
+			descendants = get_descendants_of('Company', self.company)
+			if not descendants: return
+
+			acc_name_map = {}
+			acc_name = frappe.db.get_value('Account', self.parent_account, "account_name")
+			for d in frappe.db.get_values('Account',
+				{"company": ["in", descendants], "account_name": acc_name},
+				["company", "name"], as_dict=True):
+				acc_name_map[d["company"]] = d["name"]
+
+			for company in descendants:
+				doc = frappe.copy_doc(self)
+				doc.flags.ignore_root_company_validation = True
+				doc.update({"company": company, "account_currency": None,
+					"parent": acc_name_map[company], "parent_account": acc_name_map[company]})
+				doc.save()
+				frappe.msgprint(_("Account {0} is added in the child company {1}")
+					.format(doc.name, company))
+
 	def validate_group_or_ledger(self):
 		if self.get("__islocal"):
 			return
@@ -250,3 +279,9 @@
 	frappe.rename_doc("Account", old, new, merge=1, ignore_permissions=1)
 
 	return new
+
+@frappe.whitelist()
+def get_root_company(company):
+	# return the topmost company in the hierarchy
+	ancestors = get_ancestors_of('Company', company, "lft asc")
+	return [ancestors[0]] if ancestors else []
diff --git a/erpnext/accounts/doctype/account/account_tree.js b/erpnext/accounts/doctype/account/account_tree.js
index a9cbdd5..df0486c 100644
--- a/erpnext/accounts/doctype/account/account_tree.js
+++ b/erpnext/accounts/doctype/account/account_tree.js
@@ -4,13 +4,38 @@
 	breadcrumbs: "Accounts",
 	title: __("Chart Of Accounts"),
 	get_tree_root: false,
-	filters: [{
-		fieldname: "company",
-		fieldtype:"Select",
-		options: erpnext.utils.get_tree_options("company"),
-		label: __("Company"),
-		default: erpnext.utils.get_tree_default("company")
-	}],
+	filters: [
+		{
+			fieldname: "company",
+			fieldtype:"Select",
+			options: erpnext.utils.get_tree_options("company"),
+			label: __("Company"),
+			default: erpnext.utils.get_tree_default("company"),
+			on_change: function() {
+				var me = frappe.treeview_settings['Account'].treeview;
+				var company = me.page.fields_dict.company.get_value();
+				frappe.call({
+					method: "erpnext.accounts.doctype.account.account.get_root_company",
+					args: {
+						company: company,
+					},
+					callback: function(r) {
+						if(r.message) {
+							let root_company = r.message.length ? r.message[0] : "";
+							me.page.fields_dict.root_company.set_value(root_company);
+						}
+					}
+				});
+			}
+		},
+		{
+			fieldname: "root_company",
+			fieldtype:"Data",
+			label: __("Root Company"),
+			hidden: true,
+			disable_onchange: true
+		}
+	],
 	root_label: "Accounts",
 	get_tree_nodes: 'erpnext.accounts.utils.get_children',
 	add_tree_node: 'erpnext.accounts.utils.add_ac',
@@ -42,8 +67,8 @@
 	],
 	ignore_fields:["parent_account"],
 	onload: function(treeview) {
-		frappe.treeview_settings['Account'].page = {};
-		$.extend(frappe.treeview_settings['Account'].page, treeview.page);
+		frappe.treeview_settings['Account'].treeview = {};
+		$.extend(frappe.treeview_settings['Account'].treeview, treeview);
 		function get_company() {
 			return treeview.page.fields_dict.company.get_value();
 		}
@@ -78,6 +103,18 @@
 		}
 
 	},
+	post_render: function(treeview) {
+		frappe.treeview_settings['Account'].treeview["tree"] = treeview.tree;
+		treeview.page.set_primary_action(__("New"), function() {
+			let root_company = treeview.page.fields_dict.root_company.get_value();
+
+			if(root_company) {
+				frappe.throw(__("Please add the account to root level Company - ") + root_company);
+			} else {
+				treeview.new_node();
+			}
+		}, "octicon octicon-plus");
+	},
 	onrender: function(node) {
 		if(frappe.boot.user.can_read.indexOf("GL Entry") !== -1){
 			var dr_or_cr = node.data.balance < 0 ? "Cr" : "Dr";
@@ -94,6 +131,19 @@
 	},
 	toolbar: [
 		{
+			label:__("Add Child"),
+			condition: function(node) {
+				return frappe.boot.user.can_create.indexOf("Account") !== -1 &&
+				!frappe.treeview_settings['Account'].treeview.page.fields_dict.root_company.get_value() &&
+					node.expandable && !node.hide_add;
+			},
+			click: function() {
+				var me = frappe.treeview_settings['Account'].treeview;
+				me.new_node();
+			},
+			btnClass: "hidden-xs"
+		},
+		{
 			condition: function(node) {
 				return !node.root && frappe.boot.user.can_read.indexOf("GL Entry") !== -1
 			},
@@ -103,7 +153,7 @@
 					"account": node.label,
 					"from_date": frappe.sys_defaults.year_start_date,
 					"to_date": frappe.sys_defaults.year_end_date,
-					"company": frappe.treeview_settings['Account'].page.fields_dict.company.get_value()
+					"company": frappe.treeview_settings['Account'].treeview.page.fields_dict.company.get_value()
 				};
 				frappe.set_route("query-report", "General Ledger");
 			},
diff --git a/erpnext/accounts/doctype/account/test_account.py b/erpnext/accounts/doctype/account/test_account.py
index acaa096..4c057d9 100644
--- a/erpnext/accounts/doctype/account/test_account.py
+++ b/erpnext/accounts/doctype/account/test_account.py
@@ -97,6 +97,19 @@
 		self.assertRaises(frappe.ValidationError, merge_account, "Capital Stock - _TC",\
 			"Softwares - _TC", doc.is_group, doc.root_type, doc.company)
 
+	def test_account_sync(self):
+		del frappe.local.flags["ignore_root_company_validation"]
+		acc = frappe.new_doc("Account")
+		acc.account_name = "Test Sync Account"
+		acc.parent_account = "Temporary Accounts - _TC3"
+		acc.company = "_Test Company 3"
+		acc.insert()
+
+		acc_tc_4 = frappe.db.get_value('Account', {'account_name': "Test Sync Account", "company": "_Test Company 4"})
+		acc_tc_5 = frappe.db.get_value('Account', {'account_name': "Test Sync Account", "company": "_Test Company 5"})
+		self.assertEqual(acc_tc_4, "Test Sync Account - _TC4")
+		self.assertEqual(acc_tc_5, "Test Sync Account - _TC5")
+
 def _make_test_records(verbose):
 	from frappe.test_runner import make_test_objects
 
diff --git a/erpnext/accounts/doctype/bank_account/bank_account.json b/erpnext/accounts/doctype/bank_account/bank_account.json
index 4897097..84a8e68 100644
--- a/erpnext/accounts/doctype/bank_account/bank_account.json
+++ b/erpnext/accounts/doctype/bank_account/bank_account.json
@@ -1,5 +1,6 @@
 {
  "allow_copy": 0, 
+ "allow_events_in_timeline": 0, 
  "allow_guest_to_view": 0, 
  "allow_import": 0, 
  "allow_rename": 1, 
@@ -290,7 +291,7 @@
    "in_list_view": 1, 
    "in_standard_filter": 0, 
    "label": "IBAN", 
-   "length": 25, 
+   "length": 30, 
    "no_copy": 0, 
    "permlevel": 0, 
    "precision": "", 
@@ -669,7 +670,7 @@
  "issingle": 0, 
  "istable": 0, 
  "max_attachments": 0, 
- "modified": "2018-07-20 13:55:36.996465", 
+ "modified": "2019-03-05 17:56:05.103238", 
  "modified_by": "Administrator", 
  "module": "Accounts", 
  "name": "Bank Account", 
diff --git a/erpnext/accounts/doctype/cashier_closing/cashier_closing.json b/erpnext/accounts/doctype/cashier_closing/cashier_closing.json
index 14e9070..115728d 100644
--- a/erpnext/accounts/doctype/cashier_closing/cashier_closing.json
+++ b/erpnext/accounts/doctype/cashier_closing/cashier_closing.json
@@ -1,426 +1,434 @@
 {
- "allow_copy": 0, 
- "allow_events_in_timeline": 0, 
- "allow_guest_to_view": 0, 
- "allow_import": 0, 
- "allow_rename": 0, 
- "autoname": "naming_series:", 
- "beta": 0, 
- "creation": "2018-06-18 16:51:49.994750", 
- "custom": 0, 
- "docstatus": 0, 
- "doctype": "DocType", 
- "document_type": "", 
- "editable_grid": 1, 
- "engine": "InnoDB", 
- "fields": [
-  {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "default": "Cashier-closing-", 
-   "fieldname": "naming_series", 
-   "fieldtype": "Select", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 1, 
-   "in_global_search": 1, 
-   "in_list_view": 0, 
-   "in_standard_filter": 1, 
-   "label": "Series", 
-   "length": 0, 
-   "no_copy": 0, 
-   "options": "Cashier-closing-", 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 1, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
-  {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "user", 
-   "fieldtype": "Link", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 1, 
-   "in_global_search": 0, 
-   "in_list_view": 1, 
-   "in_standard_filter": 1, 
-   "label": "User", 
-   "length": 0, 
-   "no_copy": 0, 
-   "options": "User", 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 1, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 1, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
-  {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "default": "Today", 
-   "fieldname": "date", 
-   "fieldtype": "Date", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 1, 
-   "in_global_search": 0, 
-   "in_list_view": 0, 
-   "in_standard_filter": 1, 
-   "label": "Date", 
-   "length": 0, 
-   "no_copy": 0, 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 1, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
-  {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "from_time", 
-   "fieldtype": "Time", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 1, 
-   "in_global_search": 0, 
-   "in_list_view": 0, 
-   "in_standard_filter": 1, 
-   "label": "From Time", 
-   "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": 1, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
-  {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "default": "", 
-   "fieldname": "time", 
-   "fieldtype": "Time", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 1, 
-   "in_global_search": 0, 
-   "in_list_view": 0, 
-   "in_standard_filter": 1, 
-   "label": "To Time", 
-   "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": 1, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
-  {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "default": "0.00", 
-   "fieldname": "expense", 
-   "fieldtype": "Float", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 1, 
-   "in_global_search": 0, 
-   "in_list_view": 0, 
-   "in_standard_filter": 0, 
-   "label": "Expense", 
-   "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, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
-  {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "default": "0.00", 
-   "fieldname": "custody", 
-   "fieldtype": "Float", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 1, 
-   "in_global_search": 0, 
-   "in_list_view": 0, 
-   "in_standard_filter": 0, 
-   "label": "Custody", 
-   "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, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
-  {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "default": "0.00", 
-   "fieldname": "outstanding_amount", 
-   "fieldtype": "Float", 
-   "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": "Outstanding Amount", 
-   "length": 0, 
-   "no_copy": 0, 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 1, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
-  {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "default": "0.0", 
-   "fieldname": "payments", 
-   "fieldtype": "Table", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 1, 
-   "in_global_search": 0, 
-   "in_list_view": 0, 
-   "in_standard_filter": 0, 
-   "label": "Payments", 
-   "length": 0, 
-   "no_copy": 0, 
-   "options": "Cashier Closing Payments", 
-   "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, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
-  {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "net_amount", 
-   "fieldtype": "Float", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 1, 
-   "in_global_search": 0, 
-   "in_list_view": 1, 
-   "in_standard_filter": 1, 
-   "label": "Net Amount", 
-   "length": 0, 
-   "no_copy": 0, 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 1, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
-  {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "amended_from", 
-   "fieldtype": "Link", 
-   "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": "Amended From", 
-   "length": 0, 
-   "no_copy": 1, 
-   "options": "Cashier Closing", 
-   "permlevel": 0, 
-   "print_hide": 1, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 1, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "translatable": 0, 
-   "unique": 0
-  }
- ], 
- "has_web_view": 0, 
- "hide_heading": 0, 
- "hide_toolbar": 0, 
- "idx": 0, 
- "image_view": 0, 
- "in_create": 0, 
- "is_submittable": 1, 
- "issingle": 0, 
- "istable": 0, 
- "max_attachments": 0, 
- "modified": "2019-02-19 08:35:23.157327", 
- "modified_by": "Administrator", 
- "module": "Accounts", 
- "name": "Cashier Closing", 
- "name_case": "", 
- "owner": "Administrator", 
- "permissions": [
-  {
-   "amend": 0, 
-   "cancel": 0, 
-   "create": 1, 
-   "delete": 1, 
-   "email": 1, 
-   "export": 1, 
-   "if_owner": 0, 
-   "import": 0, 
-   "permlevel": 0, 
-   "print": 1, 
-   "read": 1, 
-   "report": 1, 
-   "role": "System Manager", 
-   "set_user_permissions": 0, 
-   "share": 1, 
-   "submit": 1, 
-   "write": 1
-  }
- ], 
- "quick_entry": 0, 
- "read_only": 0, 
- "read_only_onload": 0, 
- "show_name_in_global_search": 0, 
- "sort_field": "modified", 
- "sort_order": "DESC", 
- "track_changes": 1, 
- "track_seen": 0, 
- "track_views": 0
-}
\ No newline at end of file
+    "allow_copy": 0, 
+    "allow_guest_to_view": 0, 
+    "allow_import": 0, 
+    "allow_rename": 0, 
+    "autoname": "naming_series:", 
+    "beta": 0, 
+    "creation": "2018-06-18 16:51:49.994750", 
+    "custom": 0, 
+    "docstatus": 0, 
+    "doctype": "DocType", 
+    "document_type": "", 
+    "editable_grid": 1, 
+    "engine": "InnoDB", 
+    "fields": [
+     {
+      "allow_bulk_edit": 0, 
+      "allow_on_submit": 0, 
+      "bold": 0, 
+      "collapsible": 0, 
+      "columns": 0, 
+      "default": "POS-CLO-", 
+      "fieldname": "naming_series", 
+      "fieldtype": "Select", 
+      "hidden": 0, 
+      "ignore_user_permissions": 0, 
+      "ignore_xss_filter": 0, 
+      "in_filter": 1, 
+      "in_global_search": 1, 
+      "in_list_view": 0, 
+      "in_standard_filter": 1, 
+      "label": "Series", 
+      "length": 0, 
+      "no_copy": 0, 
+      "options": "POS-CLO-", 
+      "permlevel": 0, 
+      "precision": "", 
+      "print_hide": 0, 
+      "print_hide_if_no_value": 0, 
+      "read_only": 1, 
+      "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": "user", 
+      "fieldtype": "Link", 
+      "hidden": 0, 
+      "ignore_user_permissions": 0, 
+      "ignore_xss_filter": 0, 
+      "in_filter": 1, 
+      "in_global_search": 0, 
+      "in_list_view": 1, 
+      "in_standard_filter": 1, 
+      "label": "User", 
+      "length": 0, 
+      "no_copy": 0, 
+      "options": "User", 
+      "permlevel": 0, 
+      "precision": "", 
+      "print_hide": 0, 
+      "print_hide_if_no_value": 0, 
+      "read_only": 1, 
+      "remember_last_selected_value": 0, 
+      "report_hide": 0, 
+      "reqd": 1, 
+      "search_index": 0, 
+      "set_only_once": 0, 
+      "unique": 0
+     }, 
+     {
+      "allow_bulk_edit": 0, 
+      "allow_on_submit": 0, 
+      "bold": 0, 
+      "collapsible": 0, 
+      "columns": 0, 
+      "default": "Today", 
+      "fieldname": "date", 
+      "fieldtype": "Date", 
+      "hidden": 0, 
+      "ignore_user_permissions": 0, 
+      "ignore_xss_filter": 0, 
+      "in_filter": 1, 
+      "in_global_search": 0, 
+      "in_list_view": 0, 
+      "in_standard_filter": 1, 
+      "label": "Date", 
+      "length": 0, 
+      "no_copy": 0, 
+      "permlevel": 0, 
+      "precision": "", 
+      "print_hide": 0, 
+      "print_hide_if_no_value": 0, 
+      "read_only": 1, 
+      "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": "from_time", 
+      "fieldtype": "Time", 
+      "hidden": 0, 
+      "ignore_user_permissions": 0, 
+      "ignore_xss_filter": 0, 
+      "in_filter": 1, 
+      "in_global_search": 0, 
+      "in_list_view": 0, 
+      "in_standard_filter": 1, 
+      "label": "From Time", 
+      "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": 1, 
+      "search_index": 0, 
+      "set_only_once": 0, 
+      "unique": 0
+     }, 
+     {
+      "allow_bulk_edit": 0, 
+      "allow_on_submit": 0, 
+      "bold": 0, 
+      "collapsible": 0, 
+      "columns": 0, 
+      "default": "", 
+      "fieldname": "time", 
+      "fieldtype": "Time", 
+      "hidden": 0, 
+      "ignore_user_permissions": 0, 
+      "ignore_xss_filter": 0, 
+      "in_filter": 1, 
+      "in_global_search": 0, 
+      "in_list_view": 0, 
+      "in_standard_filter": 1, 
+      "label": "To Time", 
+      "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": 1, 
+      "search_index": 0, 
+      "set_only_once": 0, 
+      "unique": 0
+     }, 
+     {
+      "allow_bulk_edit": 0, 
+      "allow_on_submit": 0, 
+      "bold": 0, 
+      "collapsible": 0, 
+      "columns": 0, 
+      "default": "0.00", 
+      "fieldname": "expense", 
+      "fieldtype": "Float", 
+      "hidden": 0, 
+      "ignore_user_permissions": 0, 
+      "ignore_xss_filter": 0, 
+      "in_filter": 1, 
+      "in_global_search": 0, 
+      "in_list_view": 0, 
+      "in_standard_filter": 0, 
+      "label": "Expense", 
+      "length": 0, 
+      "no_copy": 0, 
+      "permlevel": 0, 
+      "precision": "2", 
+      "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, 
+      "default": "0.00", 
+      "fieldname": "custody", 
+      "fieldtype": "Float", 
+      "hidden": 0, 
+      "ignore_user_permissions": 0, 
+      "ignore_xss_filter": 0, 
+      "in_filter": 1, 
+      "in_global_search": 0, 
+      "in_list_view": 0, 
+      "in_standard_filter": 0, 
+      "label": "Custody", 
+      "length": 0, 
+      "no_copy": 0, 
+      "permlevel": 0, 
+      "precision": "2", 
+      "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, 
+      "default": "0.00", 
+      "fieldname": "returns", 
+      "fieldtype": "Float", 
+      "hidden": 0, 
+      "ignore_user_permissions": 0, 
+      "ignore_xss_filter": 0, 
+      "in_filter": 1, 
+      "in_global_search": 0, 
+      "in_list_view": 0, 
+      "in_standard_filter": 0, 
+      "label": "Returns", 
+      "length": 0, 
+      "no_copy": 0, 
+      "permlevel": 0, 
+      "precision": "2", 
+      "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, 
+      "default": "0.00", 
+      "fieldname": "outstanding_amount", 
+      "fieldtype": "Float", 
+      "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": "Outstanding Amount", 
+      "length": 0, 
+      "no_copy": 0, 
+      "permlevel": 0, 
+      "precision": "2", 
+      "print_hide": 0, 
+      "print_hide_if_no_value": 0, 
+      "read_only": 1, 
+      "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, 
+      "default": "0.0", 
+      "fieldname": "payments", 
+      "fieldtype": "Table", 
+      "hidden": 0, 
+      "ignore_user_permissions": 0, 
+      "ignore_xss_filter": 0, 
+      "in_filter": 1, 
+      "in_global_search": 0, 
+      "in_list_view": 0, 
+      "in_standard_filter": 0, 
+      "label": "Payments", 
+      "length": 0, 
+      "no_copy": 0, 
+      "options": "Cashier Closing Payments", 
+      "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": "net_amount", 
+      "fieldtype": "Float", 
+      "hidden": 0, 
+      "ignore_user_permissions": 0, 
+      "ignore_xss_filter": 0, 
+      "in_filter": 1, 
+      "in_global_search": 0, 
+      "in_list_view": 1, 
+      "in_standard_filter": 1, 
+      "label": "Net Amount", 
+      "length": 0, 
+      "no_copy": 0, 
+      "permlevel": 0, 
+      "precision": "", 
+      "print_hide": 0, 
+      "print_hide_if_no_value": 0, 
+      "read_only": 1, 
+      "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": "amended_from", 
+      "fieldtype": "Link", 
+      "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": "Amended From", 
+      "length": 0, 
+      "no_copy": 1, 
+      "options": "Cashier Closing", 
+      "permlevel": 0, 
+      "print_hide": 1, 
+      "print_hide_if_no_value": 0, 
+      "read_only": 1, 
+      "remember_last_selected_value": 0, 
+      "report_hide": 0, 
+      "reqd": 0, 
+      "search_index": 0, 
+      "set_only_once": 0, 
+      "unique": 0
+     }
+    ], 
+    "has_web_view": 0, 
+    "hide_heading": 0, 
+    "hide_toolbar": 0, 
+    "idx": 0, 
+    "image_view": 0, 
+    "in_create": 0, 
+    "is_submittable": 1, 
+    "issingle": 0, 
+    "istable": 0, 
+    "max_attachments": 0, 
+    "modified": "2019-03-14 09:14:26.727129", 
+    "modified_by": "Administrator", 
+    "module": "Accounts", 
+    "name": "Cashier Closing", 
+    "name_case": "", 
+    "owner": "Administrator", 
+    "permissions": [
+     {
+      "amend": 0, 
+      "apply_user_permissions": 0, 
+      "cancel": 0, 
+      "create": 1, 
+      "delete": 1, 
+      "email": 1, 
+      "export": 1, 
+      "if_owner": 0, 
+      "import": 0, 
+      "permlevel": 0, 
+      "print": 1, 
+      "read": 1, 
+      "report": 1, 
+      "role": "System Manager", 
+      "set_user_permissions": 0, 
+      "share": 1, 
+      "submit": 1, 
+      "write": 1
+     }
+    ], 
+    "quick_entry": 0, 
+    "read_only": 0, 
+    "read_only_onload": 0, 
+    "show_name_in_global_search": 0, 
+    "sort_field": "modified", 
+    "sort_order": "DESC", 
+    "track_changes": 1, 
+    "track_seen": 0
+   }
\ No newline at end of file
diff --git a/erpnext/accounts/doctype/cashier_closing/cashier_closing.py b/erpnext/accounts/doctype/cashier_closing/cashier_closing.py
index 906bc7f..6de62ee 100644
--- a/erpnext/accounts/doctype/cashier_closing/cashier_closing.py
+++ b/erpnext/accounts/doctype/cashier_closing/cashier_closing.py
@@ -29,8 +29,8 @@
 		for i in self.payments:
 			total += flt(i.amount)
 
-		self.net_amount = total + self.outstanding_amount + self.expense - self.custody
+		self.net_amount = total + self.outstanding_amount + self.expense - self.custody + self.returns
 
 	def validate_time(self):
 		if self.from_time >= self.time:
-			frappe.throw(_("From Time Should Be Less Than To Time"))	
+			frappe.throw(_("From Time Should Be Less Than To Time"))
\ No newline at end of file
diff --git a/erpnext/accounts/doctype/gl_entry/gl_entry.py b/erpnext/accounts/doctype/gl_entry/gl_entry.py
index 810b6f7..5c76799 100644
--- a/erpnext/accounts/doctype/gl_entry/gl_entry.py
+++ b/erpnext/accounts/doctype/gl_entry/gl_entry.py
@@ -74,7 +74,8 @@
 
 	def check_pl_account(self):
 		if self.is_opening=='Yes' and \
-				frappe.db.get_value("Account", self.account, "report_type")=="Profit and Loss":
+				frappe.db.get_value("Account", self.account, "report_type")=="Profit and Loss" and \
+				self.voucher_type not in ['Purchase Invoice', 'Sales Invoice']:
 			frappe.throw(_("{0} {1}: 'Profit and Loss' type account {2} not allowed in Opening Entry")
 				.format(self.voucher_type, self.voucher_no, self.account))
 
diff --git a/erpnext/accounts/doctype/journal_entry/journal_entry.py b/erpnext/accounts/doctype/journal_entry/journal_entry.py
index 259172e..7c48b5c 100644
--- a/erpnext/accounts/doctype/journal_entry/journal_entry.py
+++ b/erpnext/accounts/doctype/journal_entry/journal_entry.py
@@ -52,6 +52,12 @@
 		self.update_loan()
 		self.update_inter_company_jv()
 
+	def before_print(self):
+		self.gl_entries = frappe.get_list("GL Entry",filters={"voucher_type": "Journal Entry",
+			"voucher_no": self.name} ,
+			fields=["account", "party_type", "party", "debit", "credit", "remarks"]
+		)
+
 	def get_title(self):
 		return self.pay_to_recd_from or self.accounts[0].account
 
diff --git a/erpnext/accounts/doctype/payment_entry/payment_entry.py b/erpnext/accounts/doctype/payment_entry/payment_entry.py
index f303301..f356ef8 100644
--- a/erpnext/accounts/doctype/payment_entry/payment_entry.py
+++ b/erpnext/accounts/doctype/payment_entry/payment_entry.py
@@ -6,7 +6,7 @@
 import frappe, erpnext, json
 from frappe import _, scrub, ValidationError
 from frappe.utils import flt, comma_or, nowdate, getdate
-from erpnext.accounts.utils import get_outstanding_invoices, get_account_currency, get_balance_on
+from erpnext.accounts.utils import get_outstanding_invoices, get_account_currency, get_balance_on, get_allow_cost_center_in_entry_of_bs_account
 from erpnext.accounts.party import get_party_account
 from erpnext.accounts.doctype.journal_entry.journal_entry import get_default_bank_cash_account
 from erpnext.setup.utils import get_exchange_rate
@@ -70,6 +70,12 @@
 		self.update_advance_paid()
 		self.update_expense_claim()
 
+	def before_print(self):
+		self.gl_entries = frappe.get_list("GL Entry",filters={"voucher_type": "Payment Entry",
+			"voucher_no": self.name} ,
+			fields=["account", "party_type", "party", "debit", "credit", "remarks"]
+		)
+
 	def on_cancel(self):
 		self.setup_party_account_field()
 		self.make_gl_entries(cancel=1)
@@ -564,8 +570,8 @@
 			.format(frappe.db.escape(args["voucher_type"]), frappe.db.escape(args["voucher_no"]))
 
 	# Add cost center condition
-	if args.get("cost_center"):
-		condition += " and cost_center='%s'" % args.get("cost_center")
+	if args.get("cost_center") and get_allow_cost_center_in_entry_of_bs_account():
+			condition += " and cost_center='%s'" % args.get("cost_center")
 
 	outstanding_invoices = get_outstanding_invoices(args.get("party_type"), args.get("party"),
 		args.get("party_account"), condition=condition)
diff --git a/erpnext/accounts/doctype/payment_terms_template/payment_terms_template.js b/erpnext/accounts/doctype/payment_terms_template/payment_terms_template.js
index 558297f..f5c5bca 100644
--- a/erpnext/accounts/doctype/payment_terms_template/payment_terms_template.js
+++ b/erpnext/accounts/doctype/payment_terms_template/payment_terms_template.js
@@ -8,5 +8,6 @@
 		frm.add_fetch("payment_term", "due_date_based_on", "due_date_based_on");
 		frm.add_fetch("payment_term", "credit_days", "credit_days");
 		frm.add_fetch("payment_term", "credit_months", "credit_months");
+		frm.add_fetch("payment_term", "mode_of_payment", "mode_of_payment");
 	}
 });
diff --git a/erpnext/accounts/doctype/pos_profile/pos_profile.js b/erpnext/accounts/doctype/pos_profile/pos_profile.js
index 13d53d1..a6386dd 100755
--- a/erpnext/accounts/doctype/pos_profile/pos_profile.js
+++ b/erpnext/accounts/doctype/pos_profile/pos_profile.js
@@ -33,6 +33,14 @@
 			};
 		});
 
+		frm.set_query("account_for_change_amount", function() {
+			return {
+				filters: {
+					account_type: ['in', ["Cash", "Bank"]]
+				}
+			};
+		});
+
 		frm.set_query("print_format", function() {
 			return { filters: { doc_type: "Sales Invoice", print_format_type: "Js"} };
 		});
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
index b4fd91f..c94c85c 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
@@ -510,6 +510,15 @@
 				}
 			}
 		}
+
+		frm.set_query("cost_center", function() {
+			return {
+				filters: {
+					company: frm.doc.company,
+					is_group: 0
+				}
+			};
+		});
 	},
 
 	onload: function(frm) {
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
index 0dd716d..bc44bc8 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
@@ -8,6 +8,7 @@
 from frappe import _, throw
 import frappe.defaults
 
+from erpnext.assets.doctype.asset_category.asset_category import get_asset_category_account
 from erpnext.controllers.buying_controller import BuyingController
 from erpnext.accounts.party import get_party_account, get_due_date
 from erpnext.accounts.utils import get_account_currency, get_fiscal_year
@@ -17,7 +18,7 @@
 from erpnext.accounts.doctype.gl_entry.gl_entry import update_outstanding_amt
 from erpnext.buying.utils import check_for_closed_status
 from erpnext.accounts.general_ledger import get_round_off_account_and_cost_center
-from erpnext.assets.doctype.asset.asset import get_asset_account
+from erpnext.assets.doctype.asset.asset import get_asset_account, is_cwip_accounting_disabled
 from frappe.model.mapper import get_mapped_doc
 from six import iteritems
 from erpnext.accounts.doctype.sales_invoice.sales_invoice import validate_inter_company_party, update_linked_invoice,\
@@ -46,6 +47,7 @@
 		}]
 
 	def onload(self):
+		super(PurchaseInvoice, self).onload()
 		supplier_tds = frappe.db.get_value("Supplier", self.supplier, "tax_withholding_category")
 		self.set_onload("supplier_tds", supplier_tds)
 
@@ -53,6 +55,12 @@
 		if not self.on_hold:
 			self.release_date = ''
 
+	def before_print(self):
+		self.gl_entries = frappe.get_list("GL Entry",filters={"voucher_type": "Purchase Invoice",
+			"voucher_no": self.name} ,
+			fields=["account", "party_type", "party", "debit", "credit"]
+		)
+
 	def invoice_is_blocked(self):
 		return self.on_hold and (not self.release_date or self.release_date > getdate(nowdate()))
 
@@ -231,6 +239,13 @@
 					item.expense_account = warehouse_account[item.warehouse]["account"]
 				else:
 					item.expense_account = stock_not_billed_account
+			elif item.is_fixed_asset and is_cwip_accounting_disabled():
+				if not item.asset:
+					frappe.throw(_("Row {0}: asset is required for item {1}")
+						.format(item.idx, item.item_code))
+
+				item.expense_account = get_asset_category_account(item.asset, 'fixed_asset_account',
+					company = self.company)
 			elif item.is_fixed_asset and item.pr_detail:
 				item.expense_account = asset_received_but_not_billed
 			elif not item.expense_account and for_validate:
@@ -376,7 +391,9 @@
 
 		self.make_supplier_gl_entry(gl_entries)
 		self.make_item_gl_entries(gl_entries)
-		self.get_asset_gl_entry(gl_entries)
+		if not is_cwip_accounting_disabled():
+			self.get_asset_gl_entry(gl_entries)
+
 		self.make_tax_gl_entries(gl_entries)
 
 		gl_entries = merge_similar_entries(gl_entries)
@@ -468,7 +485,7 @@
 							"remarks": self.get("remarks") or _("Accounting Entry for Stock"),
 							"credit": flt(item.rm_supp_cost)
 						}, warehouse_account[self.supplier_warehouse]["account_currency"]))
-				elif not item.is_fixed_asset:
+				elif not item.is_fixed_asset or (item.is_fixed_asset and is_cwip_accounting_disabled()):
 					gl_entries.append(
 						self.get_gl_dict({
 							"account": item.expense_account if not item.enable_deferred_expense else item.deferred_expense_account,
@@ -513,7 +530,7 @@
 				base_asset_amount = flt(item.base_net_amount + item.item_tax_amount)
 
 				if (not item.expense_account or frappe.db.get_value('Account',
-					item.expense_account, 'account_type') != 'Asset Received But Not Billed'):
+					item.expense_account, 'account_type') not in ['Asset Received But Not Billed', 'Fixed Asset']):
 					arbnb_account = self.get_company_default("asset_received_but_not_billed")
 					item.expense_account = arbnb_account
 
diff --git a/erpnext/accounts/doctype/sales_invoice/regional/italy.js b/erpnext/accounts/doctype/sales_invoice/regional/italy.js
new file mode 100644
index 0000000..1c47d3a
--- /dev/null
+++ b/erpnext/accounts/doctype/sales_invoice/regional/italy.js
@@ -0,0 +1,3 @@
+{% include "erpnext/regional/italy/sales_invoice.js" %}
+
+erpnext.setup_e_invoice_button('Sales Invoice')
\ No newline at end of file
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
index 8911ddf..0399cf9 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
@@ -201,7 +201,8 @@
 					get_query: function() {
 						var filters = {
 							docstatus: 1,
-							company: me.frm.doc.company
+							company: me.frm.doc.company,
+							is_return: 0
 						};
 						if(me.frm.doc.customer) filters["customer"] = me.frm.doc.customer;
 						return {
@@ -555,6 +556,23 @@
 		frm.add_fetch('payment_term', 'invoice_portion', 'invoice_portion');
 		frm.add_fetch('payment_term', 'description', 'description');
 
+		frm.set_query("account_for_change_amount", function() {
+			return {
+				filters: {
+					account_type: ['in', ["Cash", "Bank"]]
+				}
+			};
+		});
+
+		frm.set_query("cost_center", function() {
+			return {
+				filters: {
+					company: frm.doc.company,
+					is_group: 0
+				}
+			};
+		});
+
 		frm.custom_make_buttons = {
 			'Delivery Note': 'Delivery',
 			'Sales Invoice': 'Sales Return',
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
index 895ca07..9539b0a 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
@@ -205,6 +205,12 @@
 	def before_cancel(self):
 		self.update_time_sheet(None)
 
+	def before_print(self):
+		self.gl_entries = frappe.get_list("GL Entry",filters={"voucher_type": "Sales Invoice",
+			"voucher_no": self.name} ,
+			fields=["account", "party_type", "party", "debit", "credit"]
+		)
+
 	def on_cancel(self):
 		self.check_close_sales_order("sales_order")
 
@@ -399,7 +405,7 @@
 
 			for fieldname in ('territory', 'naming_series', 'currency', 'taxes_and_charges', 'letter_head', 'tc_name',
 				'company', 'select_print_heading', 'cash_bank_account', 'company_address',
-				'write_off_account', 'write_off_cost_center', 'apply_discount_on'):
+				'write_off_account', 'write_off_cost_center', 'apply_discount_on', 'cost_center'):
 					if (not for_validate) or (for_validate and not self.get(fieldname)):
 						self.set(fieldname, pos.get(fieldname))
 
@@ -523,8 +529,8 @@
 
 	def validate_pos(self):
 		if self.is_return:
-			if flt(self.paid_amount) + flt(self.write_off_amount) - flt(self.grand_total) < \
-				1/(10**(self.precision("grand_total") + 1)):
+			if flt(self.paid_amount) + flt(self.write_off_amount) - flt(self.grand_total) > \
+				1.0/(10.0**(self.precision("grand_total") + 1.0)):
 					frappe.throw(_("Paid amount + Write Off Amount can not be greater than Grand Total"))
 
 	def validate_item_code(self):
@@ -1012,9 +1018,10 @@
 			for serial_no in item.serial_no.split("\n"):
 				sales_invoice = frappe.db.get_value("Serial No", serial_no, "sales_invoice")
 				if sales_invoice and self.name != sales_invoice:
-					frappe.throw(_("Serial Number: {0} is already referenced in Sales Invoice: {1}".format(
-						serial_no, sales_invoice
-					)))
+					sales_invoice_company = frappe.db.get_value("Sales Invoice", sales_invoice, "company")
+					if sales_invoice_company == self.company:
+						frappe.throw(_("Serial Number: {0} is already referenced in Sales Invoice: {1}"
+							.format(serial_no, sales_invoice)))
 
 	def update_project(self):
 		if self.project:
diff --git a/erpnext/accounts/doctype/sales_invoice_payment/sales_invoice_payment.json b/erpnext/accounts/doctype/sales_invoice_payment/sales_invoice_payment.json
index ccdabfe..1c5962a 100644
--- a/erpnext/accounts/doctype/sales_invoice_payment/sales_invoice_payment.json
+++ b/erpnext/accounts/doctype/sales_invoice_payment/sales_invoice_payment.json
@@ -20,6 +20,7 @@
    "collapsible": 0, 
    "columns": 0, 
    "depends_on": "eval:parent.doctype == 'POS Profile'", 
+   "fetch_if_empty": 0, 
    "fieldname": "default", 
    "fieldtype": "Check", 
    "hidden": 0, 
@@ -52,6 +53,7 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "mode_of_payment", 
    "fieldtype": "Link", 
    "hidden": 0, 
@@ -85,8 +87,9 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
-   "default": "", 
+   "default": "0", 
    "depends_on": "eval:parent.doctype == 'Sales Invoice'", 
+   "fetch_if_empty": 0, 
    "fieldname": "amount", 
    "fieldtype": "Currency", 
    "hidden": 0, 
@@ -120,6 +123,7 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "column_break_3", 
    "fieldtype": "Column Break", 
    "hidden": 0, 
@@ -151,6 +155,7 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "account", 
    "fieldtype": "Link", 
    "hidden": 0, 
@@ -185,6 +190,7 @@
    "collapsible": 0, 
    "columns": 0, 
    "fetch_from": "mode_of_payment.type", 
+   "fetch_if_empty": 0, 
    "fieldname": "type", 
    "fieldtype": "Read Only", 
    "hidden": 0, 
@@ -218,6 +224,7 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "base_amount", 
    "fieldtype": "Currency", 
    "hidden": 0, 
@@ -251,6 +258,7 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "clearance_date", 
    "fieldtype": "Date", 
    "hidden": 0, 
@@ -287,7 +295,7 @@
  "issingle": 0, 
  "istable": 1, 
  "max_attachments": 0, 
- "modified": "2019-02-18 15:03:59.720469", 
+ "modified": "2019-03-06 15:58:37.839241", 
  "modified_by": "Administrator", 
  "module": "Accounts", 
  "name": "Sales Invoice Payment", 
diff --git a/erpnext/accounts/party.py b/erpnext/accounts/party.py
index 5855ac3..70e4800 100644
--- a/erpnext/accounts/party.py
+++ b/erpnext/accounts/party.py
@@ -576,8 +576,10 @@
 def get_partywise_advanced_payment_amount(party_type="Customer"):
 	data = frappe.db.sql(""" SELECT party, sum({0}) as amount
 		FROM `tabGL Entry`
-		WHERE party_type = %s and against_voucher is null GROUP BY party"""
-		.format(("credit - debit") if party_type == "Customer" else "debit") , party_type)
+		WHERE
+			party_type = %s and against_voucher is null
+			GROUP BY party"""
+		.format(("credit") if party_type == "Customer" else "debit") , party_type)
 
 	if data:
 		return frappe._dict(data)
\ No newline at end of file
diff --git a/erpnext/accounts/print_format/bank_and_cash_payment_voucher/__init__.py b/erpnext/accounts/print_format/bank_and_cash_payment_voucher/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/accounts/print_format/bank_and_cash_payment_voucher/__init__.py
diff --git a/erpnext/accounts/print_format/bank_and_cash_payment_voucher/bank_and_cash_payment_voucher.html b/erpnext/accounts/print_format/bank_and_cash_payment_voucher/bank_and_cash_payment_voucher.html
new file mode 100644
index 0000000..2eadb2a
--- /dev/null
+++ b/erpnext/accounts/print_format/bank_and_cash_payment_voucher/bank_and_cash_payment_voucher.html
@@ -0,0 +1,82 @@
+{%- from "templates/print_formats/standard_macros.html" import add_header -%}
+<style>
+    .table-bordered td.top-bottom {border-top: none !important;border-bottom: none !important;}
+    .table-bordered td.right{border-right: none !important;}
+    .table-bordered td.left{border-left: none !important;}
+
+
+</style>
+<div class="page-break">
+    {%- if not doc.get("print_heading") and not doc.get("select_print_heading")
+        and doc.set("select_print_heading", _("Payment Entry")) -%}{%- endif -%}
+    {{ add_header(0, 1, doc, letter_head, no_letterhead, print_settings) }}
+    <div class="row margin-bottom">
+            <div class="col-sm-6">
+                <table>
+                <tr><td><strong>Voucher No: </strong></td><td>{{ doc.name }}</td></tr>
+                </table>
+            </div>
+            <div>
+                <table>
+                    <tr><td><strong>Date: </strong></td><td>{{ frappe.utils.formatdate(doc.creation) }}</td></tr>
+                </table>
+            </div>
+    </div>
+    <div class="margin-top">
+        <table class="table table-bordered table-condensed">
+            <tr>
+                <th>Account</th>
+                <th>Party Type</th>
+                <th>Party</th>
+                <th>Amount</th>
+            </tr>
+            <tr>
+                    <td class="top-bottom" colspan="5"><strong>Credit</strong></td>
+            </tr>
+            {% set total_credit = 0 -%}
+            {% for entries in doc.gl_entries %}
+            {% if entries.debit == 0.0 %}
+            <tr>
+                <td class="right top-bottom">{{ entries.account }}</td>
+                <td class="right left top-bottom">{{ entries.party_type }}</td>
+                <td class="right left top-bottom">{{ entries.party }}</td>
+                <td class="left top-bottom">{{ entries.credit }}</td>
+                {% set total_credit = total_credit + entries.credit -%}
+            </tr>
+            <tr>
+                <td class="top-bottom" colspan="4"><strong> Narration </strong><br>{{ entries.remarks }}</td>
+            </tr>
+            <tr>
+                    <td class="right" colspan="3"><strong>Total (credit) </strong></td>
+                    <td class="left" >{{total_credit}}</td>
+            </tr>
+            {% endif %}
+            {% endfor %}
+            <tr>
+                    <td class="top-bottom" colspan="4"> </td>
+            </tr>
+            <tr>
+                    <td class="top-bottom" colspan="5"><strong>Debit</strong></td>
+            </tr>
+            {% set total_debit = 0 -%}
+            {% for entries in doc.gl_entries %}
+            {% if entries.credit == 0.0 %}
+            <tr>
+                <td class="right top-bottom">{{ entries.account }}</td>
+                <td class="right left top-bottom">{{ entries.party_type }}</td>
+                <td class="right left top-bottom">{{ entries.party }}</td>
+                {% set total_debit = total_debit + entries.debit -%}
+                <td class="left top-bottom">{{ entries.debit }}</td>
+            </tr>
+            <tr>
+                <td class="top-bottom"colspan="4"><strong> Narration </strong><br>{{ entries.remarks }}</td>
+            </tr>
+            <tr>
+                    <td class="right" colspan="3" ><strong>Total (debit) </strong></td>
+                    <td class="left" >{{total_debit}}</td>
+            </tr>
+            {% endif %}
+            {% endfor %}
+        </table>
+    <div>
+</div>
\ No newline at end of file
diff --git a/erpnext/accounts/print_format/bank_and_cash_payment_voucher/bank_and_cash_payment_voucher.json b/erpnext/accounts/print_format/bank_and_cash_payment_voucher/bank_and_cash_payment_voucher.json
new file mode 100644
index 0000000..e3afaec
--- /dev/null
+++ b/erpnext/accounts/print_format/bank_and_cash_payment_voucher/bank_and_cash_payment_voucher.json
@@ -0,0 +1,22 @@
+{
+ "align_labels_right": 0, 
+ "creation": "2019-02-15 11:49:08.608619", 
+ "custom_format": 0, 
+ "default_print_language": "en", 
+ "disabled": 0, 
+ "doc_type": "Payment Entry", 
+ "docstatus": 0, 
+ "doctype": "Print Format", 
+ "font": "Default", 
+ "idx": 0, 
+ "line_breaks": 0, 
+ "modified": "2019-02-15 11:49:08.608619", 
+ "modified_by": "Administrator", 
+ "module": "Accounts", 
+ "name": "Bank and Cash Payment Voucher", 
+ "owner": "Administrator", 
+ "print_format_builder": 0, 
+ "print_format_type": "Server", 
+ "show_section_headings": 0, 
+ "standard": "Yes"
+}
\ No newline at end of file
diff --git a/erpnext/accounts/print_format/gst_purchase_invoice/gst_purchase_invoice.json b/erpnext/accounts/print_format/gst_purchase_invoice/gst_purchase_invoice.json
index 2b7f9ce..6d7c3d3 100644
--- a/erpnext/accounts/print_format/gst_purchase_invoice/gst_purchase_invoice.json
+++ b/erpnext/accounts/print_format/gst_purchase_invoice/gst_purchase_invoice.json
@@ -7,10 +7,10 @@
  "docstatus": 0, 
  "doctype": "Print Format", 
  "font": "Default", 
- "format_data": "[{\"fieldname\": \"print_heading_template\", \"fieldtype\": \"Custom HTML\", \"options\": \"<div class=\\\"print-heading\\\">\\t\\t\\t\\t<h2>Purchase Invoice<br><small>{{ doc.name }}</small>\\t\\t\\t\\t</h2></div>\"}, {\"fieldtype\": \"Section Break\", \"label\": \"\"}, {\"fieldtype\": \"Column Break\"}, {\"print_hide\": 0, \"fieldname\": \"supplier_name\", \"label\": \"Supplier Name\"}, {\"print_hide\": 0, \"fieldname\": \"due_date\", \"label\": \"Due Date\"}, {\"fieldtype\": \"Column Break\"}, {\"fieldtype\": \"Section Break\", \"label\": \"Address\"}, {\"fieldtype\": \"Column Break\"}, {\"print_hide\": 0, \"fieldname\": \"address_display\", \"label\": \"Address\"}, {\"print_hide\": 0, \"fieldname\": \"contact_display\", \"label\": \"Contact\"}, {\"print_hide\": 0, \"fieldname\": \"contact_mobile\", \"label\": \"Mobile No\"}, {\"fieldtype\": \"Column Break\"}, {\"fieldtype\": \"Section Break\", \"label\": \"\"}, {\"fieldtype\": \"Column Break\"}, {\"visible_columns\": [{\"print_hide\": 0, \"fieldname\": \"item_name\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"description\", \"print_width\": \"300px\"}, {\"print_hide\": 0, \"fieldname\": \"image\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"received_qty\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"qty\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"rejected_qty\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"discount_percentage\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"rate\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"amount\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"pricing_rule\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"weight_per_unit\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"total_weight\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"weight_uom\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"warehouse\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"rejected_warehouse\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"batch_no\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"serial_no\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"bom\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"asset\", \"print_width\": \"\"}], \"print_hide\": 0, \"fieldname\": \"items\", \"label\": \"Items\"}, {\"fieldtype\": \"Section Break\", \"label\": \"\"}, {\"fieldtype\": \"Column Break\"}, {\"fieldtype\": \"Column Break\"}, {\"print_hide\": 0, \"fieldname\": \"total\", \"label\": \"Total\"}, {\"fieldtype\": \"Section Break\", \"label\": \"\"}, {\"fieldtype\": \"Column Break\"}, {\"visible_columns\": [{\"print_hide\": 0, \"fieldname\": \"category\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"add_deduct_tax\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"charge_type\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"row_id\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"included_in_print_rate\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"account_head\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"cost_center\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"description\", \"print_width\": \"300px\"}, {\"print_hide\": 0, \"fieldname\": \"rate\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"tax_amount\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"total\", \"print_width\": \"\"}], \"print_hide\": 0, \"fieldname\": \"taxes\", \"label\": \"Purchase Taxes and Charges\"}, {\"fieldtype\": \"Section Break\", \"label\": \"\"}, {\"fieldtype\": \"Column Break\"}, {\"fieldtype\": \"Column Break\"}, {\"print_hide\": 0, \"fieldname\": \"grand_total\", \"label\": \"Grand Total\"}, {\"print_hide\": 0, \"fieldname\": \"in_words\", \"label\": \"In Words\"}, {\"print_hide\": 0, \"fieldname\": \"disable_rounded_total\", \"label\": \"Disable Rounded Total\"}, {\"fieldtype\": \"Section Break\", \"label\": \"Payments\"}, {\"fieldtype\": \"Column Break\"}, {\"print_hide\": 0, \"fieldname\": \"cash_bank_account\", \"label\": \"Cash/Bank Account\"}, {\"fieldtype\": \"Column Break\"}, {\"fieldtype\": \"Section Break\", \"label\": \"\"}, {\"fieldtype\": \"Column Break\"}, {\"print_hide\": 0, \"fieldname\": \"other_charges_calculation\", \"align\": \"left\", \"label\": \"Tax Breakup\"}, {\"fieldtype\": \"Section Break\", \"label\": \"Raw\"}, {\"fieldtype\": \"Column Break\"}, {\"visible_columns\": [{\"print_hide\": 0, \"fieldname\": \"main_item_code\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"rm_item_code\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"description\", \"print_width\": \"300px\"}, {\"print_hide\": 0, \"fieldname\": \"batch_no\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"serial_no\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"required_qty\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"consumed_qty\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"stock_uom\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"rate\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"amount\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"conversion_factor\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"current_stock\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"reference_name\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"bom_detail_no\", \"print_width\": \"\"}], \"print_hide\": 0, \"fieldname\": \"supplied_items\", \"label\": \"Supplied Items\"}, {\"fieldtype\": \"Section Break\", \"label\": \"Terms\"}, {\"fieldtype\": \"Column Break\"}, {\"print_hide\": 0, \"fieldname\": \"terms\", \"label\": \"Terms and Conditions1\"}]", 
+ "format_data": "[{\"fieldname\": \"print_heading_template\", \"fieldtype\": \"Custom HTML\", \"options\": \"<div class=\\\"print-heading\\\">\\t\\t\\t\\t<h2>Purchase Invoice<br><small>{{ doc.name }}</small>\\t\\t\\t\\t</h2></div>\"}, {\"fieldtype\": \"Section Break\", \"label\": \"\"}, {\"fieldtype\": \"Column Break\"}, {\"print_hide\": 0, \"fieldname\": \"supplier_name\", \"label\": \"Supplier Name\"}, {\"print_hide\": 0, \"fieldname\": \"due_date\", \"label\": \"Due Date\"}, {\"fieldtype\": \"Column Break\"}, {\"fieldtype\": \"Section Break\", \"label\": \"Address\"}, {\"fieldtype\": \"Column Break\"}, {\"print_hide\": 0, \"fieldname\": \"address_display\", \"label\": \"Address\"}, {\"print_hide\": 0, \"fieldname\": \"contact_display\", \"label\": \"Contact\"}, {\"print_hide\": 0, \"fieldname\": \"contact_mobile\", \"label\": \"Mobile No\"}, {\"fieldtype\": \"Column Break\"}, {\"fieldtype\": \"Section Break\", \"label\": \"\"}, {\"fieldtype\": \"Column Break\"}, {\"visible_columns\": [{\"print_hide\": 0, \"fieldname\": \"item_name\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"description\", \"print_width\": \"300px\"}, {\"print_hide\": 0, \"fieldname\": \"image\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"received_qty\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"qty\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"rejected_qty\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"discount_percentage\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"rate\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"amount\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"pricing_rule\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"weight_per_unit\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"total_weight\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"weight_uom\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"warehouse\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"rejected_warehouse\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"batch_no\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"serial_no\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"bom\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"asset\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"gst_hsn_code\", \"print_width\": \"\"}], \"print_hide\": 0, \"fieldname\": \"items\", \"label\": \"Items\"}, {\"fieldtype\": \"Section Break\", \"label\": \"\"}, {\"fieldtype\": \"Column Break\"}, {\"fieldtype\": \"Column Break\"}, {\"print_hide\": 0, \"fieldname\": \"total\", \"label\": \"Total\"}, {\"fieldtype\": \"Section Break\", \"label\": \"\"}, {\"fieldtype\": \"Column Break\"}, {\"visible_columns\": [{\"print_hide\": 0, \"fieldname\": \"category\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"add_deduct_tax\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"charge_type\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"row_id\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"included_in_print_rate\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"account_head\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"cost_center\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"description\", \"print_width\": \"300px\"}, {\"print_hide\": 0, \"fieldname\": \"rate\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"tax_amount\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"total\", \"print_width\": \"\"}], \"print_hide\": 0, \"fieldname\": \"taxes\", \"label\": \"Purchase Taxes and Charges\"}, {\"fieldtype\": \"Section Break\", \"label\": \"\"}, {\"fieldtype\": \"Column Break\"}, {\"fieldtype\": \"Column Break\"}, {\"print_hide\": 0, \"fieldname\": \"grand_total\", \"label\": \"Grand Total\"}, {\"print_hide\": 0, \"fieldname\": \"in_words\", \"label\": \"In Words\"}, {\"print_hide\": 0, \"fieldname\": \"disable_rounded_total\", \"label\": \"Disable Rounded Total\"}, {\"fieldtype\": \"Section Break\", \"label\": \"Payments\"}, {\"fieldtype\": \"Column Break\"}, {\"print_hide\": 0, \"fieldname\": \"cash_bank_account\", \"label\": \"Cash/Bank Account\"}, {\"fieldtype\": \"Column Break\"}, {\"fieldtype\": \"Section Break\", \"label\": \"\"}, {\"fieldtype\": \"Column Break\"}, {\"print_hide\": 0, \"fieldname\": \"other_charges_calculation\", \"align\": \"left\", \"label\": \"Tax Breakup\"}, {\"fieldtype\": \"Section Break\", \"label\": \"Raw\"}, {\"fieldtype\": \"Column Break\"}, {\"visible_columns\": [{\"print_hide\": 0, \"fieldname\": \"main_item_code\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"rm_item_code\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"description\", \"print_width\": \"300px\"}, {\"print_hide\": 0, \"fieldname\": \"batch_no\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"serial_no\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"required_qty\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"consumed_qty\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"stock_uom\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"rate\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"amount\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"conversion_factor\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"current_stock\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"reference_name\", \"print_width\": \"\"}, {\"print_hide\": 0, \"fieldname\": \"bom_detail_no\", \"print_width\": \"\"}], \"print_hide\": 0, \"fieldname\": \"supplied_items\", \"label\": \"Supplied Items\"}, {\"fieldtype\": \"Section Break\", \"label\": \"Terms\"}, {\"fieldtype\": \"Column Break\"}, {\"print_hide\": 0, \"fieldname\": \"terms\", \"label\": \"Terms and Conditions1\"}]", 
  "idx": 0, 
  "line_breaks": 0, 
- "modified": "2018-04-07 13:06:08.060353", 
+ "modified": "2019-03-04 13:38:47.362002", 
  "modified_by": "Administrator", 
  "module": "Accounts", 
  "name": "GST Purchase Invoice", 
diff --git a/erpnext/accounts/print_format/journal_auditing_voucher/__init__.py b/erpnext/accounts/print_format/journal_auditing_voucher/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/accounts/print_format/journal_auditing_voucher/__init__.py
diff --git a/erpnext/accounts/print_format/journal_auditing_voucher/journal_auditing_voucher.html b/erpnext/accounts/print_format/journal_auditing_voucher/journal_auditing_voucher.html
new file mode 100644
index 0000000..4565559
--- /dev/null
+++ b/erpnext/accounts/print_format/journal_auditing_voucher/journal_auditing_voucher.html
@@ -0,0 +1,76 @@
+{%- from "templates/print_formats/standard_macros.html" import add_header -%}
+<style>
+    .table-bordered td.top-bottom {border-top: none !important;border-bottom: none !important;}
+    .table-bordered td.right{border-right: none !important;}
+    .table-bordered td.left{border-left: none !important;}
+
+
+</style>
+<div class="page-break">
+    {%- if not doc.get("print_heading") and not doc.get("select_print_heading")
+        and doc.set("select_print_heading", _("Journal Entry")) -%}{%- endif -%}
+    {{ add_header(0, 1, doc, letter_head, no_letterhead, print_settings) }}
+    <div class="row margin-bottom">
+            <div class="col-sm-6">
+                <table>
+                <tr><td><strong>Voucher No: </strong></td><td>{{ doc.name }}</td></tr>
+                </table>
+            </div>
+            <div>
+                <table>
+                    <tr><td><strong>Date: </strong></td><td>{{  frappe.utils.formatdate(doc.creation)  }}</td></tr>
+                </table>
+            </div>
+    </div>
+    <div class="margin-top">
+        <table class="table table-bordered table-condensed">
+            <tr>
+                <th>Account</th>
+                <th>Party Type</th>
+                <th>Party</th>
+                <th>Amount</th>
+            </tr>
+            <tr>
+                    <td class="top-bottom" colspan="5"><strong>Credit</strong></td>
+            </tr>
+            {% set total_credit = 0 -%}
+            {% for entries in doc.gl_entries %}
+            {% if entries.debit == 0.0 %}
+            <tr>
+                <td class="right top-bottom">{{ entries.account }}</td>
+                <td class="right left top-bottom">{{ entries.party_type }}</td>
+                <td class="right left top-bottom">{{ entries.party }}</td>
+                <td class="left top-bottom">{{ entries.credit }}</td>
+                {% set total_credit = total_credit + entries.credit -%}
+            </tr>
+            <tr>
+                    <td class="right" colspan="3"><strong>Total (credit) </strong></td>
+                    <td class="left" >{{total_credit}}</td>
+            </tr>
+            {% endif %}
+            {% endfor %}
+            <tr>
+                    <td class="top-bottom" colspan="4"> </td>
+            </tr>
+            <tr>
+                    <td class="top-bottom" colspan="5"><strong>Debit</strong></td>
+            </tr>
+            {% set total_debit = 0 -%}
+            {% for entries in doc.gl_entries %}
+            {% if entries.credit == 0.0 %}
+            <tr>
+                <td class="right top-bottom">{{ entries.account }}</td>
+                <td class="right left top-bottom">{{ entries.party_type }}</td>
+                <td class="right left top-bottom">{{ entries.party }}</td>
+                {% set total_debit = total_debit + entries.debit -%}
+                <td class="left top-bottom">{{ entries.debit }}</td>
+            </tr>
+            <tr>
+                    <td class="right" colspan="3" ><strong>Total (debit) </strong></td>
+                    <td class="left" >{{total_debit}}</td>
+            </tr>
+            {% endif %}
+            {% endfor %}
+        </table>
+    <div>
+</div>
\ No newline at end of file
diff --git a/erpnext/accounts/print_format/journal_auditing_voucher/journal_auditing_voucher.json b/erpnext/accounts/print_format/journal_auditing_voucher/journal_auditing_voucher.json
new file mode 100644
index 0000000..927e818
--- /dev/null
+++ b/erpnext/accounts/print_format/journal_auditing_voucher/journal_auditing_voucher.json
@@ -0,0 +1,22 @@
+{
+ "align_labels_right": 0, 
+ "creation": "2019-02-15 14:13:05.721784", 
+ "custom_format": 0, 
+ "default_print_language": "en", 
+ "disabled": 0, 
+ "doc_type": "Journal Entry", 
+ "docstatus": 0, 
+ "doctype": "Print Format", 
+ "font": "Default", 
+ "idx": 0, 
+ "line_breaks": 0, 
+ "modified": "2019-02-15 14:13:05.721784", 
+ "modified_by": "Administrator", 
+ "module": "Accounts", 
+ "name": "Journal Auditing Voucher", 
+ "owner": "Administrator", 
+ "print_format_builder": 0, 
+ "print_format_type": "Server", 
+ "show_section_headings": 0, 
+ "standard": "Yes"
+}
\ No newline at end of file
diff --git a/erpnext/accounts/print_format/purchase_auditing_voucher/__init__.py b/erpnext/accounts/print_format/purchase_auditing_voucher/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/accounts/print_format/purchase_auditing_voucher/__init__.py
diff --git a/erpnext/accounts/print_format/purchase_auditing_voucher/purchase_auditing_voucher.html b/erpnext/accounts/print_format/purchase_auditing_voucher/purchase_auditing_voucher.html
new file mode 100644
index 0000000..35852e1
--- /dev/null
+++ b/erpnext/accounts/print_format/purchase_auditing_voucher/purchase_auditing_voucher.html
@@ -0,0 +1,99 @@
+{%- from "templates/print_formats/standard_macros.html" import add_header -%}
+<div class="page-break">
+    {%- if not doc.get("print_heading") and not doc.get("select_print_heading")
+        and doc.set("select_print_heading", _("Purchase Invoice")) -%}{%- endif -%}
+    {{ add_header(0, 1, doc, letter_head, no_letterhead, print_settings) }}
+    <div class="row margin-bottom">
+        <div class="col-sm-6">
+            <table>
+            <tr><td><strong>Supplier Name: </strong></td><td>{{ doc.supplier }}</td></tr>
+            <tr><td><strong>Due Date: </strong></td><td>{{ frappe.utils.formatdate(doc.due_date) }}</td></tr>
+            <tr><td><strong>Address: </strong></td><td>{{doc.address_display}}</td></tr>
+            <tr><td><strong>Contact: </strong></td><td>{{doc.contact_display}}</td></tr>
+            <tr><td><strong>Mobile no: </strong> </td><td>{{doc.contact_mobile}}</td></tr>
+            </table>
+        </div>
+        <div>
+            <table>
+                <tr><td><strong>Voucher No: </strong></td><td>{{ doc.name }}</td></tr>
+                <tr><td><strong>Date: </strong></td><td>{{ frappe.utils.formatdate(doc.creation) }}</td></tr>
+            </table>
+        </div>
+    </div>
+    <div class="margin-top margin-bottom">
+        <table class="table table-bordered table-condensed">
+            <tr>
+                <th>SL</th>
+                <th>Item Code</th>
+                <th>Item Name</th>
+                <th>UOM</th>
+                <th>Received Qty.</th>
+                <th>Rejected Qty</th>
+                <th>Qty</th>
+                <th>Basic Rate</th>
+                <th>Amount</th>
+            </tr>
+            {% for item in doc.items %}
+            <tr>
+                <td>{{ loop.index }}</td>
+                <td>{{ item.item_code }}</td>
+                <td>{{ item.item_name }}</td>
+                <td>{{ item.uom }}</td>
+                <td>{{ item.received_qty }}</td>
+                <td>{{ item.rejected_qty }}</td>
+                <td>{{ item.qty}}</td>
+                <td>{{ item.rate }}</td>
+                <td>{{ item.amount }}</td>
+            </tr>
+            {% endfor %}
+        </table>
+    </div>
+    <div class="row margin-bottom">
+        <div class="col-sm-6">
+            <table>
+            <tr><td><strong>Total Quantity: </strong></td><td>{{ doc.total_qty }}</td></tr>
+            <tr><td><strong>Total: </strong></td><td>{{doc.total}}</td></tr>
+            <tr><td><strong>Net Weight: </strong></td><td>{{ doc.total_net_weight }}</td></tr>
+        </table>
+    </div>
+    <div>
+        <table>
+                <tr><td><strong>Tax and Charges: </strong></td><td>{{doc.taxes_and_charges}}</td></tr>
+                {% for tax in doc.taxes %}
+                <tr><td><strong>{{ tax.account_head }}: </strong></td><td>{{ tax.tax_amount_after_discount_amount }}</td></tr>
+                {% endfor %}
+                <tr><td><strong> Taxes and Charges Added: </strong></td><td>{{ doc.taxes_and_charges_added }}</td></tr>
+                <tr><td><strong> Taxes and Charges Deducted: </strong></td><td>{{ doc.taxes_and_charges_deducted }}</td></tr>
+                <tr><td><strong> Total Taxes and Charges: </strong></td><td>{{ doc.total_taxes_and_charges }}</td></tr>
+                <tr><td><strong> Net Payable: </strong></td><td>{{ doc.grand_total }}</td></tr>
+            </table>
+        </div>
+    </div>
+    <div class="margin-top">
+        <table class='table table-bordered table-condensed'>
+            <tr>
+                <th>SL</th>
+                <th>Account</th>
+                <th>Party Type</th>
+                <th>Party</th>
+                <th>Credit Amount</th>
+                <th>Debit Amount</th>
+            </tr>
+            {% for entries in doc.gl_entries %}
+            <tr>
+                <td>{{ loop.index }}</td>
+                <td>{{ entries.account }}</td>
+                <td>{{ entries.party_type }}</td>
+                <td>{{ entries.party }}</td>
+                <td>{{ entries.credit }}</td>
+                <td>{{ entries.debit }}</td>
+            </tr>
+            {% endfor %}
+            <tr>
+                <td colspan="4"><strong>Total</strong></td>
+                <td>{{ doc.grand_total|flt }}</td>
+                <td>{{ doc.grand_total|flt }}</td>
+            </tr>
+        </table>
+    </div>
+</div>
\ No newline at end of file
diff --git a/erpnext/accounts/print_format/purchase_auditing_voucher/purchase_auditing_voucher.json b/erpnext/accounts/print_format/purchase_auditing_voucher/purchase_auditing_voucher.json
new file mode 100644
index 0000000..73779d4
--- /dev/null
+++ b/erpnext/accounts/print_format/purchase_auditing_voucher/purchase_auditing_voucher.json
@@ -0,0 +1,22 @@
+{
+ "align_labels_right": 0, 
+ "creation": "2019-02-14 14:42:35.151611", 
+ "custom_format": 0, 
+ "default_print_language": "en", 
+ "disabled": 0, 
+ "doc_type": "Purchase Invoice", 
+ "docstatus": 0, 
+ "doctype": "Print Format", 
+ "font": "Default", 
+ "idx": 0, 
+ "line_breaks": 0, 
+ "modified": "2019-02-14 14:42:35.151611", 
+ "modified_by": "Administrator", 
+ "module": "Accounts", 
+ "name": "Purchase Auditing Voucher", 
+ "owner": "Administrator", 
+ "print_format_builder": 0, 
+ "print_format_type": "Server", 
+ "show_section_headings": 0, 
+ "standard": "Yes"
+}
\ No newline at end of file
diff --git a/erpnext/accounts/print_format/sales_auditing_voucher/__init__.py b/erpnext/accounts/print_format/sales_auditing_voucher/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/accounts/print_format/sales_auditing_voucher/__init__.py
diff --git a/erpnext/accounts/print_format/sales_auditing_voucher/sales_auditing_voucher.html b/erpnext/accounts/print_format/sales_auditing_voucher/sales_auditing_voucher.html
new file mode 100644
index 0000000..04de83d
--- /dev/null
+++ b/erpnext/accounts/print_format/sales_auditing_voucher/sales_auditing_voucher.html
@@ -0,0 +1,93 @@
+{%- from "templates/print_formats/standard_macros.html" import add_header -%}
+<div class="page-break">
+    {%- if not doc.get("print_heading") and not doc.get("select_print_heading")
+        and doc.set("select_print_heading", _("Sales Invoice")) -%}{%- endif -%}
+    {{ add_header(0, 1, doc, letter_head, no_letterhead, print_settings) }}
+    <div class="row margin-bottom">
+        <div class="col-sm-6">
+            <table>
+            <tr><td><strong>Customer Name: </strong></td><td>{{ doc.customer }}</td></tr>
+            <tr><td><strong>Due Date: </strong></td><td>{{ frappe.utils.formatdate(doc.due_date) }}</td></tr>
+            <tr><td><strong>Address: </strong></td><td>{{doc.address_display}}</td></tr>
+            <tr><td><strong>Contact: </strong></td><td>{{doc.contact_display}}</td></tr>
+            <tr><td><strong>Mobile no: </strong> </td><td>{{doc.contact_mobile}}</td></tr>
+            </table>
+        </div>
+        <div>
+            <table>
+                <tr><td><strong>Voucher No: </strong></td><td>{{ doc.name }}</td></tr>
+                <tr><td><strong>Date: </strong></td><td>{{ frappe.utils.formatdate(doc.creation) }}</td></tr>
+            </table>
+        </div>
+    </div>
+    <div class="margin-top margin-bottom">
+        <table class="table table-bordered table-condensed">
+            <tr>
+                <th>SL</th>
+                <th>Item Code</th>
+                <th>Item Name</th>
+                <th>UOM</th>
+                <th>Quantity</th>
+                <th>Basic Rate</th>
+                <th>Amount</th>
+            </tr>
+            {% for item in doc.items %}
+            <tr>
+                <td>{{ loop.index }}</td>
+                <td>{{ item.item_code }}</td>
+                <td>{{ item.item_name }}</td>
+                <td>{{ item.uom }}</td>
+                <td>{{ item.qty}}</td>
+                <td>{{ item.rate }}</td>
+                <td>{{ item.amount }}</td>
+            </tr>
+            {% endfor %}
+        </table>
+    </div>
+    <div class="row margin-bottom">
+        <div class="col-sm-6">
+            <table>
+            <tr><td><strong>Total Quantity: </strong></td><td>{{ doc.total_qty }}</td></tr>
+            <tr><td><strong>Total: </strong></td><td>{{doc.total}}</td></tr>
+            <tr><td><strong>Net Weight: </strong></td><td>{{ doc.total_net_weight }}</td></tr>
+        </table>
+    </div>
+    <div>
+        <table>
+                <tr><td><strong>Tax and Charges: </strong></td><td>{{doc.taxes_and_charges}}</td></tr>
+                {% for tax in doc.taxes %}
+                <tr><td><strong>{{ tax.account_head }}: </strong></td><td>{{ tax.tax_amount_after_discount_amount }}</td></tr>
+                {% endfor %}
+                <tr><td><strong> Total Taxes and Charges: </strong></td><td>{{ doc.total_taxes_and_charges }}</td></tr>
+                <tr><td><strong> Net Payable: </strong></td><td>{{ doc.grand_total }}</td></tr>
+            </table>
+        </div>
+    </div>
+    <div class="margin-top">
+        <table class='table table-bordered table-condensed'>
+            <tr>
+                <th>SL</th>
+                <th>Account</th>
+                <th>Party Type</th>
+                <th>Party</th>
+                <th>Credit Amount</th>
+                <th>Debit Amount</th>
+            </tr>
+            {% for entries in doc.gl_entries %}
+            <tr>
+                <td>{{ loop.index }}</td>
+                <td>{{ entries.account }}</td>
+                <td>{{ entries.party_type }}</td>
+                <td>{{ entries.party }}</td>
+                <td>{{ entries.credit }}</td>
+                <td>{{ entries.debit }}</td>
+            </tr>
+            {% endfor %}
+            <tr>
+                <td colspan="4"><strong>Total</strong></td>
+                <td>{{ doc.grand_total|flt }}</td>
+                <td>{{ doc.grand_total|flt }}</td>
+            </tr>
+        </table>
+    </div>
+</div>
\ No newline at end of file
diff --git a/erpnext/accounts/print_format/sales_auditing_voucher/sales_auditing_voucher.json b/erpnext/accounts/print_format/sales_auditing_voucher/sales_auditing_voucher.json
new file mode 100644
index 0000000..0544e0b
--- /dev/null
+++ b/erpnext/accounts/print_format/sales_auditing_voucher/sales_auditing_voucher.json
@@ -0,0 +1,22 @@
+{
+ "align_labels_right": 0, 
+ "creation": "2019-02-15 15:02:51.454754", 
+ "custom_format": 0, 
+ "default_print_language": "en", 
+ "disabled": 0, 
+ "doc_type": "Sales Invoice", 
+ "docstatus": 0, 
+ "doctype": "Print Format", 
+ "font": "Default", 
+ "idx": 0, 
+ "line_breaks": 0, 
+ "modified": "2019-02-15 15:02:51.454754", 
+ "modified_by": "Administrator", 
+ "module": "Accounts", 
+ "name": "Sales Auditing Voucher", 
+ "owner": "Administrator", 
+ "print_format_builder": 0, 
+ "print_format_type": "Server", 
+ "show_section_headings": 0, 
+ "standard": "Yes"
+}
\ No newline at end of file
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 73ca8b4..8cb5ac1 100644
--- a/erpnext/accounts/report/accounts_receivable_summary/accounts_receivable_summary.py
+++ b/erpnext/accounts/report/accounts_receivable_summary/accounts_receivable_summary.py
@@ -144,9 +144,10 @@
 				row += [self.get_party_name(args.get("party_type"), party)]
 
 			row += [partywise_advance_amount.get(party, 0)]
+			paid_amt = flt(party_dict.paid_amt - partywise_advance_amount.get(party, 0))
 
 			row += [
-				party_dict.invoiced_amt, party_dict.paid_amt, party_dict.credit_amt, party_dict.outstanding_amt,
+				party_dict.invoiced_amt, paid_amt, party_dict.credit_amt, party_dict.outstanding_amt,
 				party_dict.range1, party_dict.range2, party_dict.range3, party_dict.range4,
 			]
 
@@ -205,7 +206,7 @@
 
 		cols += ["invoiced_amt", "paid_amt", "credit_amt",
 		"outstanding_amt", "age", "range1", "range2", "range3", "range4", "currency", "pdc/lc_date", "pdc/lc_ref",
-		"pdc/lc_amount", "remaining_balance"]
+		"pdc/lc_amount"]
 
 		if args.get("party_type") == "Supplier":
 			cols += ["supplier_group", "remarks"]
diff --git a/erpnext/accounts/report/customer_ledger_summary/customer_ledger_summary.py b/erpnext/accounts/report/customer_ledger_summary/customer_ledger_summary.py
index e33bd61..eceabf5 100644
--- a/erpnext/accounts/report/customer_ledger_summary/customer_ledger_summary.py
+++ b/erpnext/accounts/report/customer_ledger_summary/customer_ledger_summary.py
@@ -195,7 +195,7 @@
 		conditions = [""]
 
 		if self.filters.company:
-			conditions.append("company=%(company)s")
+			conditions.append("gle.company=%(company)s")
 
 		self.filters.company_finance_book = erpnext.get_default_finance_book(self.filters.company)
 
diff --git a/erpnext/accounts/report/financial_statements.html b/erpnext/accounts/report/financial_statements.html
index 4b3b5f2..449fb84 100644
--- a/erpnext/accounts/report/financial_statements.html
+++ b/erpnext/accounts/report/financial_statements.html
@@ -15,7 +15,7 @@
 		height: 37px;
 	}
 </style>
-{% var letterhead= filters.letter_head || (frappe.get_doc(":Company", filters.company) && frappe.get_doc(":Company", filters.company).default_letter_head) || frappe.defaults.get_default("letter_head"); %}
+{% var letterhead= filters.letter_head || (frappe.get_doc(":Company", filters.company) && frappe.get_doc(":Company", filters.company).default_letter_head) %}
 {% if(letterhead) { %}
 <div style="margin-bottom: 7px;" class="text-center">
 	{%= frappe.boot.letter_heads[letterhead].header %}
diff --git a/erpnext/accounts/report/financial_statements.py b/erpnext/accounts/report/financial_statements.py
index 09cf5b1..e9aecfb 100644
--- a/erpnext/accounts/report/financial_statements.py
+++ b/erpnext/accounts/report/financial_statements.py
@@ -126,7 +126,7 @@
 def get_data(
 		company, root_type, balance_must_be, period_list, filters=None,
 		accumulated_values=1, only_current_fiscal_year=True, ignore_closing_entries=False,
-		ignore_accumulated_values_for_fy=False):
+		ignore_accumulated_values_for_fy=False , total = True):
 
 	accounts = get_accounts(company, root_type)
 	if not accounts:
@@ -154,7 +154,7 @@
 	out = prepare_data(accounts, balance_must_be, period_list, company_currency)
 	out = filter_out_zero_value_rows(out, parent_children_map)
 
-	if out:
+	if out and total:
 		add_total_row(out, root_type, balance_must_be, period_list, company_currency)
 
 	return out
@@ -218,6 +218,9 @@
 			"year_start_date": year_start_date,
 			"year_end_date": year_end_date,
 			"currency": company_currency,
+			"include_in_gross": d.include_in_gross,
+			"account_type": d.account_type,
+			"is_group": d.is_group,
 			"opening_balance": d.get("opening_balance", 0.0) * (1 if balance_must_be=="Debit" else -1),
 			"account_name": ('%s - %s' %(_(d.account_number), _(d.account_name))
 				if d.account_number else _(d.account_name))
@@ -270,7 +273,7 @@
 			for period in period_list:
 				total_row.setdefault(period.key, 0.0)
 				total_row[period.key] += row.get(period.key, 0.0)
-				row[period.key] = 0.0
+				row[period.key] = row.get(period.key, 0.0)
 
 			total_row.setdefault("total", 0.0)
 			total_row["total"] += flt(row["total"])
@@ -285,7 +288,7 @@
 
 def get_accounts(company, root_type):
 	return frappe.db.sql("""
-		select name, account_number, parent_account, lft, rgt, root_type, report_type, account_name
+		select name, account_number, parent_account, lft, rgt, root_type, report_type, account_name, include_in_gross, account_type, is_group, lft, rgt
 		from `tabAccount`
 		where company=%s and root_type=%s order by lft""", (company, root_type), as_dict=True)
 
diff --git a/erpnext/accounts/report/general_ledger/general_ledger.py b/erpnext/accounts/report/general_ledger/general_ledger.py
index be66332..ecb18f7 100644
--- a/erpnext/accounts/report/general_ledger/general_ledger.py
+++ b/erpnext/accounts/report/general_ledger/general_ledger.py
@@ -53,7 +53,7 @@
 		frappe.throw(_("Can not filter based on Account, if grouped by Account"))
 
 	if (filters.get("voucher_no")
-		and filters.get("group_by") in [_('Group by Voucher'), _('Group by Voucher (Consolidated)')]):
+		and filters.get("group_by") in [_('Group by Voucher')]):
 		frappe.throw(_("Can not filter based on Voucher No, if grouped by Voucher"))
 
 	if filters.from_date > filters.to_date:
diff --git a/erpnext/accounts/report/gross_and_net_profit_report/__init__.py b/erpnext/accounts/report/gross_and_net_profit_report/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/accounts/report/gross_and_net_profit_report/__init__.py
diff --git a/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.html b/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.html
new file mode 100644
index 0000000..40ba20c
--- /dev/null
+++ b/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.html
@@ -0,0 +1 @@
+{% include "accounts/report/financial_statements.html" %}
\ No newline at end of file
diff --git a/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.js b/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.js
new file mode 100644
index 0000000..63ac281
--- /dev/null
+++ b/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.js
@@ -0,0 +1,51 @@
+// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
+// For license information, please see license.txt
+/* eslint-disable */
+
+frappe.query_reports["Gross and Net Profit Report"] = {
+	"filters": [
+
+	]
+}
+frappe.require("assets/erpnext/js/financial_statements.js", function() {
+	frappe.query_reports["Gross and Net Profit Report"] = $.extend({},
+		erpnext.financial_statements);
+
+	frappe.query_reports["Gross and Net Profit Report"]["filters"].push(
+		{
+			"fieldname":"project",
+			"label": __("Project"),
+			"fieldtype": "MultiSelect",
+			get_data: function() {
+				var projects = frappe.query_report.get_filter_value("project") || "";
+
+				const values = projects.split(/\s*,\s*/).filter(d => d);
+				const txt = projects.match(/[^,\s*]*$/)[0] || '';
+				let data = [];
+
+				frappe.call({
+					type: "GET",
+					method:'frappe.desk.search.search_link',
+					async: false,
+					no_spinner: true,
+					args: {
+						doctype: "Project",
+						txt: txt,
+						filters: {
+							"name": ["not in", values]
+						}
+					},
+					callback: function(r) {
+						data = r.results;
+					}
+				});
+				return data;
+			}
+		},
+		{
+			"fieldname": "accumulated_values",
+			"label": __("Accumulated Values"),
+			"fieldtype": "Check"
+		}
+	);
+});
diff --git a/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.json b/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.json
new file mode 100644
index 0000000..994b47f
--- /dev/null
+++ b/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.json
@@ -0,0 +1,30 @@
+{
+ "add_total_row": 0, 
+ "creation": "2019-02-08 10:58:55.763090", 
+ "disable_prepared_report": 0, 
+ "disabled": 0, 
+ "docstatus": 0, 
+ "doctype": "Report", 
+ "idx": 0, 
+ "is_standard": "Yes", 
+ "modified": "2019-02-08 10:58:55.763090", 
+ "modified_by": "Administrator", 
+ "module": "Accounts", 
+ "name": "Gross and Net Profit Report", 
+ "owner": "Administrator", 
+ "prepared_report": 0, 
+ "ref_doctype": "GL Entry", 
+ "report_name": "Gross and Net Profit Report", 
+ "report_type": "Script Report", 
+ "roles": [
+  {
+   "role": "Accounts User"
+  }, 
+  {
+   "role": "Accounts Manager"
+  }, 
+  {
+   "role": "Auditor"
+  }
+ ]
+}
\ No newline at end of file
diff --git a/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.py b/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.py
new file mode 100644
index 0000000..6550981
--- /dev/null
+++ b/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.py
@@ -0,0 +1,154 @@
+# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
+# For license information, please see license.txt
+
+from __future__ import unicode_literals
+import frappe
+from frappe import _
+from frappe.utils import flt
+from erpnext.accounts.report.financial_statements import (get_period_list, get_columns, get_data)
+import copy
+
+
+def execute(filters=None):
+	period_list = get_period_list(filters.from_fiscal_year, filters.to_fiscal_year,
+		filters.periodicity, filters.accumulated_values, filters.company)
+
+	columns, data = [], []
+
+	income = get_data(filters.company, "Income", "Credit", period_list, filters = filters,
+		accumulated_values=filters.accumulated_values,
+		ignore_closing_entries=True, ignore_accumulated_values_for_fy= True, total= False)
+
+	expense = get_data(filters.company, "Expense", "Debit", period_list, filters=filters,
+		accumulated_values=filters.accumulated_values,
+		ignore_closing_entries=True, ignore_accumulated_values_for_fy= True, total= False)
+
+	columns = get_columns(filters.periodicity, period_list, filters.accumulated_values, filters.company)
+
+
+	gross_income = get_revenue(income, period_list)
+
+	gross_expense = get_revenue(expense, period_list)
+
+	if(len(gross_income)==0 and len(gross_expense)== 0):
+		data.append({"account_name": "'" + _("Nothing is included in gross") + "'",
+		"account": "'" + _("Nothing is included in gross") + "'"})
+
+		return columns, data
+
+	data.append({"account_name": "'" + _("Included in Gross Profit") + "'",
+		"account": "'" + _("Included in Gross Profit") + "'"})
+
+	data.append({})
+	data.extend(gross_income or [])
+
+	data.append({})
+	data.extend(gross_expense or [])
+
+	data.append({})
+	gross_profit = get_profit(gross_income, gross_expense, period_list, filters.company, 'Gross Profit',filters.presentation_currency)
+	data.append(gross_profit)
+
+	non_gross_income = get_revenue(income, period_list, 0)
+	data.append({})
+	data.extend(non_gross_income or [])
+
+	non_gross_expense = get_revenue(expense, period_list, 0)
+	data.append({})
+	data.extend(non_gross_expense or [])
+
+	net_profit = get_net_profit(non_gross_income, gross_income, gross_expense, non_gross_expense, period_list, filters.company,filters.presentation_currency)
+	data.append({})
+	data.append(net_profit)
+
+	return columns, data
+
+def get_revenue(data, period_list, include_in_gross=1):
+	revenue = [item for item in data if item['include_in_gross']==include_in_gross or item['is_group']==1]
+
+	data_to_be_removed =True
+	while data_to_be_removed:
+		revenue, data_to_be_removed = remove_parent_with_no_child(revenue, period_list)
+	revenue = adjust_account(revenue, period_list)
+	return copy.deepcopy(revenue)
+
+def remove_parent_with_no_child(data, period_list):
+	data_to_be_removed = False
+	for parent in data:
+		if 'is_group' in parent and parent.get("is_group") == 1:
+			have_child = False
+			for child in data:
+				if 'parent_account' in child  and child.get("parent_account") == parent.get("account"):
+					have_child = True
+					break
+
+			if not have_child:
+				data_to_be_removed = True
+				data.remove(parent)
+
+	return data, data_to_be_removed
+
+def adjust_account(data, period_list, consolidated= False):
+	leaf_nodes = [item for item in data if item['is_group'] == 0]
+	totals = {}
+	for node in leaf_nodes:
+		set_total(node, node["total"], data, totals)
+	for d in data:
+		for period in period_list:
+			key = period if consolidated else period.key
+			d[key] = totals[d["account"]]
+			d['total'] = totals[d["account"]]
+	return data
+
+def set_total(node, value, complete_list, totals):
+	if not totals.get(node['account']):
+		totals[node["account"]] = 0
+	totals[node["account"]] += value
+
+	parent = node['parent_account']
+	if not parent == '':
+		return set_total(next(item for item in complete_list if item['account'] == parent), value, complete_list, totals)
+
+
+def get_profit(gross_income, gross_expense, period_list, company, profit_type, currency=None, consolidated=False):
+
+	profit_loss = {
+		"account_name": "'" + _(profit_type) + "'",
+		"account": "'" + _(profit_type) + "'",
+		"warn_if_negative": True,
+		"currency": currency or frappe.get_cached_value('Company',  company,  "default_currency")
+	}
+
+	has_value = False
+
+	for period in period_list:
+		key = period if consolidated else period.key
+		profit_loss[key] = flt(gross_income[0].get(key, 0)) - flt(gross_expense[0].get(key, 0))
+
+		if profit_loss[key]:
+			has_value=True
+
+	if has_value:
+		return profit_loss
+
+def get_net_profit(non_gross_income, gross_income, gross_expense, non_gross_expense, period_list, company, currency=None, consolidated=False):
+	profit_loss = {
+		"account_name": "'" + _("Net Profit") + "'",
+		"account": "'" + _("Net Profit") + "'",
+		"warn_if_negative": True,
+		"currency": currency or frappe.get_cached_value('Company',  company,  "default_currency")
+	}
+
+	has_value = False
+
+	for period in period_list:
+		key = period if consolidated else period.key
+		total_income = flt(gross_income[0].get(key, 0)) + flt(non_gross_income[0].get(key, 0))
+		total_expense = flt(gross_expense[0].get(key, 0)) + flt(non_gross_expense[0].get(key, 0))
+		profit_loss[key] = flt(total_income) - flt(total_expense)
+
+		if profit_loss[key]:
+			has_value=True
+
+	if has_value:
+		return profit_loss
diff --git a/erpnext/accounts/report/gross_profit/gross_profit.py b/erpnext/accounts/report/gross_profit/gross_profit.py
index 01211a9..e5aaafa 100644
--- a/erpnext/accounts/report/gross_profit/gross_profit.py
+++ b/erpnext/accounts/report/gross_profit/gross_profit.py
@@ -6,7 +6,7 @@
 from frappe import _, scrub
 from erpnext.stock.utils import get_incoming_rate
 from erpnext.controllers.queries import get_match_cond
-from frappe.utils import flt
+from frappe.utils import flt, cint
 
 
 def execute(filters=None):
@@ -106,11 +106,14 @@
 		self.grouped = {}
 		self.grouped_data = []
 
+		self.currency_precision = cint(frappe.db.get_default("currency_precision")) or 3
+		self.float_precision = cint(frappe.db.get_default("float_precision")) or 2
+
 		for row in self.si_list:
 			if self.skip_row(row, self.product_bundles):
 				continue
 
-			row.base_amount = flt(row.base_net_amount)
+			row.base_amount = flt(row.base_net_amount, self.currency_precision)
 
 			product_bundles = []
 			if row.update_stock:
@@ -122,22 +125,23 @@
 
 			# get buying amount
 			if row.item_code in product_bundles:
-				row.buying_amount = self.get_buying_amount_from_product_bundle(row,
-					product_bundles[row.item_code])
+				row.buying_amount = flt(self.get_buying_amount_from_product_bundle(row,
+					product_bundles[row.item_code]), self.currency_precision)
 			else:
-				row.buying_amount = self.get_buying_amount(row, row.item_code)
+				row.buying_amount = flt(self.get_buying_amount(row, row.item_code),
+					self.currency_precision)
 
 			# get buying rate
 			if row.qty:
-				row.buying_rate = row.buying_amount / row.qty
-				row.base_rate = row.base_amount / row.qty
+				row.buying_rate = flt(row.buying_amount / row.qty, self.float_precision)
+				row.base_rate = flt(row.base_amount / row.qty, self.float_precision)
 			else:
 				row.buying_rate, row.base_rate = 0.0, 0.0
 
 			# calculate gross profit
-			row.gross_profit = row.base_amount - row.buying_amount
+			row.gross_profit = flt(row.base_amount - row.buying_amount, self.currency_precision)
 			if row.base_amount:
-				row.gross_profit_percent = (row.gross_profit / row.base_amount) * 100.0
+				row.gross_profit_percent = flt((row.gross_profit / row.base_amount) * 100.0, self.currency_precision)
 			else:
 				row.gross_profit_percent = 0.0
 
@@ -156,8 +160,8 @@
 						new_row = row
 					else:
 						new_row.qty += row.qty
-						new_row.buying_amount += row.buying_amount
-						new_row.base_amount += row.base_amount
+						new_row.buying_amount += flt(row.buying_amount, self.currency_precision)
+						new_row.base_amount += flt(row.base_amount, self.currency_precision)
 				new_row = self.set_average_rate(new_row)
 				self.grouped_data.append(new_row)
 			else:
@@ -167,18 +171,19 @@
 						returned_item_rows = self.returned_invoices[row.parent][row.item_code]
 						for returned_item_row in returned_item_rows:
 							row.qty += returned_item_row.qty
-							row.base_amount += returned_item_row.base_amount
-						row.buying_amount = row.qty * row.buying_rate
+							row.base_amount += flt(returned_item_row.base_amount, self.currency_precision)
+						row.buying_amount = flt(row.qty * row.buying_rate, self.currency_precision)
 					if row.qty or row.base_amount:
 						row = self.set_average_rate(row)
 						self.grouped_data.append(row)
 
 	def set_average_rate(self, new_row):
-		new_row.gross_profit = new_row.base_amount - new_row.buying_amount
-		new_row.gross_profit_percent = ((new_row.gross_profit / new_row.base_amount) * 100.0) \
+		new_row.gross_profit = flt(new_row.base_amount - new_row.buying_amount, self.currency_precision)
+		new_row.gross_profit_percent = flt(((new_row.gross_profit / new_row.base_amount) * 100.0), self.currency_precision) \
 			if new_row.base_amount else 0
-		new_row.buying_rate = (new_row.buying_amount / new_row.qty) if new_row.qty else 0
-		new_row.base_rate = (new_row.base_amount / new_row.qty) if new_row.qty else 0
+		new_row.buying_rate = flt(new_row.buying_amount / new_row.qty, self.float_precision) if new_row.qty else 0
+		new_row.base_rate = flt(new_row.base_amount / new_row.qty, self.float_precision) if new_row.qty else 0
+
 		return new_row
 
 	def get_returned_invoice_items(self):
@@ -211,7 +216,7 @@
 			if packed_item.get("parent_detail_docname")==row.item_row:
 				buying_amount += self.get_buying_amount(row, packed_item.item_code)
 
-		return buying_amount
+		return flt(buying_amount, self.currency_precision)
 
 	def get_buying_amount(self, row, item_code):
 		# IMP NOTE
diff --git a/erpnext/accounts/report/supplier_ledger_summary/supplier_ledger_summary.js b/erpnext/accounts/report/supplier_ledger_summary/supplier_ledger_summary.js
index 6fd16f2..f812977 100644
--- a/erpnext/accounts/report/supplier_ledger_summary/supplier_ledger_summary.js
+++ b/erpnext/accounts/report/supplier_ledger_summary/supplier_ledger_summary.js
@@ -35,9 +35,9 @@
 		},
 		{
 			"fieldname":"party",
-			"label": __("Customer"),
+			"label": __("Supplier"),
 			"fieldtype": "Link",
-			"options": "Customer",
+			"options": "Supplier",
 			on_change: () => {
 				var party = frappe.query_report.get_filter_value('party');
 				if (party) {
diff --git a/erpnext/assets/doctype/asset/asset.py b/erpnext/assets/doctype/asset/asset.py
index a38b40b..cfacb5a 100644
--- a/erpnext/assets/doctype/asset/asset.py
+++ b/erpnext/assets/doctype/asset/asset.py
@@ -33,7 +33,7 @@
 		self.validate_in_use_date()
 		self.set_status()
 		self.update_stock_movement()
-		if not self.booked_fixed_asset:
+		if not self.booked_fixed_asset and not is_cwip_accounting_disabled():
 			self.make_gl_entries()
 
 	def on_cancel(self):
@@ -71,14 +71,15 @@
 		if not flt(self.gross_purchase_amount):
 			frappe.throw(_("Gross Purchase Amount is mandatory"), frappe.MandatoryError)
 
-		if not self.is_existing_asset and not (self.purchase_receipt or self.purchase_invoice):
-			frappe.throw(_("Please create purchase receipt or purchase invoice for the item {0}").
-				format(self.item_code))
+		if not is_cwip_accounting_disabled():
+			if not self.is_existing_asset and not (self.purchase_receipt or self.purchase_invoice):
+				frappe.throw(_("Please create purchase receipt or purchase invoice for the item {0}").
+					format(self.item_code))
 
-		if (not self.purchase_receipt and self.purchase_invoice
-			and not frappe.db.get_value('Purchase Invoice', self.purchase_invoice, 'update_stock')):
-			frappe.throw(_("Update stock must be enable for the purchase invoice {0}").
-				format(self.purchase_invoice))
+			if (not self.purchase_receipt and self.purchase_invoice
+				and not frappe.db.get_value('Purchase Invoice', self.purchase_invoice, 'update_stock')):
+				frappe.throw(_("Update stock must be enable for the purchase invoice {0}").
+					format(self.purchase_invoice))
 
 		if not self.calculate_depreciation:
 			return
@@ -255,7 +256,7 @@
 	def get_depreciation_amount(self, depreciable_value, total_number_of_depreciations, row):
 		percentage_value = 100.0 if row.depreciation_method == 'Written Down Value' else 200.0
 
-		factor = percentage_value /  total_number_of_depreciations
+		factor = percentage_value /  cint(total_number_of_depreciations)
 		depreciation_amount = flt(depreciable_value * factor / 100, 0)
 
 		value_after_depreciation = flt(depreciable_value) - depreciation_amount
@@ -275,7 +276,7 @@
 				flt(row.expected_value_after_useful_life)) / (cint(row.total_number_of_depreciations) -
 				cint(self.number_of_depreciations_booked)) * prorata_temporis
 		else:
-			depreciation_amount = self.get_depreciation_amount(depreciable_value, row)
+			depreciation_amount = self.get_depreciation_amount(depreciable_value, row.total_number_of_depreciations, row)
 
 		return depreciation_amount
 
@@ -404,6 +405,9 @@
 			asset.set_status('Out of Order')
 
 def make_post_gl_entry():
+	if is_cwip_accounting_disabled():
+		return
+
 	assets = frappe.db.sql_list(""" select name from `tabAsset`
 		where ifnull(booked_fixed_asset, 0) = 0 and available_for_use_date = %s""", nowdate())
 
@@ -551,3 +555,6 @@
 	})
 
 	return je
+
+def is_cwip_accounting_disabled():
+	return cint(frappe.db.get_single_value("Asset Settings", "disable_cwip_accounting"))
\ No newline at end of file
diff --git a/erpnext/assets/doctype/asset_settings/asset_settings.json b/erpnext/assets/doctype/asset_settings/asset_settings.json
index d6ddd33..a3fee96 100644
--- a/erpnext/assets/doctype/asset_settings/asset_settings.json
+++ b/erpnext/assets/doctype/asset_settings/asset_settings.json
@@ -1,5 +1,6 @@
 {
  "allow_copy": 0, 
+ "allow_events_in_timeline": 0, 
  "allow_guest_to_view": 0, 
  "allow_import": 0, 
  "allow_rename": 0, 
@@ -14,10 +15,12 @@
  "fields": [
   {
    "allow_bulk_edit": 0, 
+   "allow_in_quick_entry": 0, 
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "depreciation_options", 
    "fieldtype": "Section Break", 
    "hidden": 0, 
@@ -40,14 +43,17 @@
    "reqd": 0, 
    "search_index": 0, 
    "set_only_once": 0, 
+   "translatable": 0, 
    "unique": 0
   }, 
   {
    "allow_bulk_edit": 0, 
+   "allow_in_quick_entry": 0, 
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "schedule_based_on_fiscal_year", 
    "fieldtype": "Check", 
    "hidden": 0, 
@@ -70,10 +76,12 @@
    "reqd": 0, 
    "search_index": 0, 
    "set_only_once": 0, 
+   "translatable": 0, 
    "unique": 0
   }, 
   {
    "allow_bulk_edit": 0, 
+   "allow_in_quick_entry": 0, 
    "allow_on_submit": 0, 
    "bold": 0, 
    "collapsible": 0, 
@@ -81,6 +89,7 @@
    "default": "360", 
    "depends_on": "eval:doc.schedule_based_on_fiscal_year", 
    "description": "This value is used for pro-rata temporis calculation", 
+   "fetch_if_empty": 0, 
    "fieldname": "number_of_days_in_fiscal_year", 
    "fieldtype": "Data", 
    "hidden": 0, 
@@ -103,6 +112,40 @@
    "reqd": 0, 
    "search_index": 0, 
    "set_only_once": 0, 
+   "translatable": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_bulk_edit": 0, 
+   "allow_in_quick_entry": 0, 
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
+   "columns": 0, 
+   "fetch_if_empty": 0, 
+   "fieldname": "disable_cwip_accounting", 
+   "fieldtype": "Check", 
+   "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": "Disable CWIP Accounting", 
+   "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, 
+   "translatable": 0, 
    "unique": 0
   }
  ], 
@@ -116,7 +159,7 @@
  "issingle": 1, 
  "istable": 0, 
  "max_attachments": 0, 
- "modified": "2018-01-05 10:10:39.803255", 
+ "modified": "2019-03-08 10:44:41.924547", 
  "modified_by": "Administrator", 
  "module": "Assets", 
  "name": "Asset Settings", 
@@ -125,7 +168,6 @@
  "permissions": [
   {
    "amend": 0, 
-   "apply_user_permissions": 0, 
    "cancel": 0, 
    "create": 1, 
    "delete": 1, 
@@ -145,7 +187,6 @@
   }, 
   {
    "amend": 0, 
-   "apply_user_permissions": 0, 
    "cancel": 0, 
    "create": 1, 
    "delete": 1, 
@@ -171,5 +212,6 @@
  "sort_field": "modified", 
  "sort_order": "DESC", 
  "track_changes": 1, 
- "track_seen": 0
+ "track_seen": 0, 
+ "track_views": 0
 }
\ No newline at end of file
diff --git a/erpnext/buying/doctype/purchase_order/purchase_order.py b/erpnext/buying/doctype/purchase_order/purchase_order.py
index a4a636d..7201606 100644
--- a/erpnext/buying/doctype/purchase_order/purchase_order.py
+++ b/erpnext/buying/doctype/purchase_order/purchase_order.py
@@ -388,9 +388,10 @@
 
 		item = get_item_defaults(target.item_code, source_parent.company)
 		item_group = get_item_group_defaults(target.item_code, source_parent.company)
-		target.cost_center = frappe.db.get_value("Project", obj.project, "cost_center") \
-			or item.get("buying_cost_center") \
-			or item_group.get("buying_cost_center")
+		target.cost_center = (obj.cost_center
+			or frappe.db.get_value("Project", obj.project, "cost_center")
+			or item.get("buying_cost_center")
+			or item_group.get("buying_cost_center"))
 
 	doc = get_mapped_doc("Purchase Order", source_name,	{
 		"Purchase Order": {
diff --git a/erpnext/controllers/queries.py b/erpnext/controllers/queries.py
index 4c16323..f8f1e54 100644
--- a/erpnext/controllers/queries.py
+++ b/erpnext/controllers/queries.py
@@ -172,8 +172,8 @@
 				or tabItem.item_code LIKE %(txt)s
 				or tabItem.item_group LIKE %(txt)s
 				or tabItem.item_name LIKE %(txt)s
-				or tabItem.item_code IN (select parent from `tabItem Barcode` where barcode LIKE %(txt)s
-				{description_cond}))
+				or tabItem.item_code IN (select parent from `tabItem Barcode` where barcode LIKE %(txt)s)
+				{description_cond})
 			{fcond} {mcond}
 		order by
 			if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
diff --git a/erpnext/hr/doctype/additional_salary/additional_salary.py b/erpnext/hr/doctype/additional_salary/additional_salary.py
index 6f87954..968a1c4 100644
--- a/erpnext/hr/doctype/additional_salary/additional_salary.py
+++ b/erpnext/hr/doctype/additional_salary/additional_salary.py
@@ -11,16 +11,14 @@
 class AdditionalSalary(Document):
 	def validate(self):
 		self.validate_dates()
-		if self.amount <= 0:
-			frappe.throw(_("Amount should be greater than zero."))
+		if self.amount < 0:
+			frappe.throw(_("Amount should not be less than zero."))
 
 	def validate_dates(self):
  		date_of_joining, relieving_date = frappe.db.get_value("Employee", self.employee,
 			["date_of_joining", "relieving_date"])
  		if date_of_joining and getdate(self.payroll_date) < getdate(date_of_joining):
  			frappe.throw(_("Payroll date can not be less than employee's joining date"))
- 		elif relieving_date and getdate(self.payroll_date) > getdate(relieving_date):
- 			frappe.throw(_("To date can not greater than employee's relieving date"))
 
 	def get_amount(self, sal_start_date, sal_end_date):
 		start_date = getdate(sal_start_date)
diff --git a/erpnext/hr/doctype/expense_claim/expense_claim.js b/erpnext/hr/doctype/expense_claim/expense_claim.js
index 6bdab61..6da7184 100644
--- a/erpnext/hr/doctype/expense_claim/expense_claim.js
+++ b/erpnext/hr/doctype/expense_claim/expense_claim.js
@@ -35,6 +35,7 @@
 
 cur_frm.add_fetch('employee', 'company', 'company');
 cur_frm.add_fetch('employee','employee_name','employee_name');
+cur_frm.add_fetch('expense_type','description','description');
 
 cur_frm.cscript.onload = function(doc) {
 	if (doc.__islocal) {
diff --git a/erpnext/hr/doctype/expense_claim_detail/expense_claim_detail.json b/erpnext/hr/doctype/expense_claim_detail/expense_claim_detail.json
index b808990..d4e7057 100644
--- a/erpnext/hr/doctype/expense_claim_detail/expense_claim_detail.json
+++ b/erpnext/hr/doctype/expense_claim_detail/expense_claim_detail.json
@@ -1,366 +1,378 @@
 {
- "allow_copy": 0, 
- "allow_guest_to_view": 0, 
- "allow_import": 0, 
- "allow_rename": 0, 
- "beta": 0, 
- "creation": "2013-02-22 01:27:46", 
- "custom": 0, 
- "docstatus": 0, 
- "doctype": "DocType", 
- "editable_grid": 1, 
+ "allow_copy": 0,
+ "allow_events_in_timeline": 0,
+ "allow_guest_to_view": 0,
+ "allow_import": 0,
+ "allow_rename": 0,
+ "beta": 0,
+ "creation": "2013-02-22 01:27:46",
+ "custom": 0,
+ "docstatus": 0,
+ "doctype": "DocType",
+ "editable_grid": 1,
  "fields": [
   {
-   "allow_bulk_edit": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "expense_date", 
-   "fieldtype": "Date", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 1, 
-   "in_standard_filter": 0, 
-   "label": "Expense Date", 
-   "length": 0, 
-   "no_copy": 0, 
-   "oldfieldname": "expense_date", 
-   "oldfieldtype": "Date", 
-   "permlevel": 0, 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "print_width": "150px", 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
+   "allow_bulk_edit": 0,
+   "allow_in_quick_entry": 0,
+   "allow_on_submit": 0,
+   "bold": 0,
+   "collapsible": 0,
+   "columns": 0,
+   "fieldname": "expense_date",
+   "fieldtype": "Date",
+   "hidden": 0,
+   "ignore_user_permissions": 0,
+   "ignore_xss_filter": 0,
+   "in_filter": 0,
+   "in_global_search": 0,
+   "in_list_view": 1,
+   "in_standard_filter": 0,
+   "label": "Expense Date",
+   "length": 0,
+   "no_copy": 0,
+   "oldfieldname": "expense_date",
+   "oldfieldtype": "Date",
+   "permlevel": 0,
+   "print_hide": 0,
+   "print_hide_if_no_value": 0,
+   "print_width": "150px",
+   "read_only": 0,
+   "remember_last_selected_value": 0,
+   "report_hide": 0,
+   "reqd": 0,
+   "search_index": 0,
+   "set_only_once": 0,
    "translatable": 0,
-   "unique": 0, 
+   "unique": 0,
    "width": "150px"
-  }, 
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "column_break_2", 
-   "fieldtype": "Column Break", 
-   "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, 
-   "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, 
+   "allow_bulk_edit": 0,
+   "allow_in_quick_entry": 0,
+   "allow_on_submit": 0,
+   "bold": 0,
+   "collapsible": 0,
+   "columns": 0,
+   "fieldname": "column_break_2",
+   "fieldtype": "Column Break",
+   "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,
+   "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,
    "translatable": 0,
    "unique": 0
-  }, 
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "expense_type", 
-   "fieldtype": "Link", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 1, 
-   "in_standard_filter": 0, 
-   "label": "Expense Claim Type", 
-   "length": 0, 
-   "no_copy": 0, 
-   "oldfieldname": "expense_type", 
-   "oldfieldtype": "Link", 
-   "options": "Expense Claim Type", 
-   "permlevel": 0, 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "print_width": "150px", 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 1, 
-   "search_index": 0, 
-   "set_only_once": 0, 
+   "allow_bulk_edit": 0,
+   "allow_in_quick_entry": 0,
+   "allow_on_submit": 0,
+   "bold": 0,
+   "collapsible": 0,
+   "columns": 0,
+   "fieldname": "expense_type",
+   "fieldtype": "Link",
+   "hidden": 0,
+   "ignore_user_permissions": 0,
+   "ignore_xss_filter": 0,
+   "in_filter": 0,
+   "in_global_search": 0,
+   "in_list_view": 1,
+   "in_standard_filter": 0,
+   "label": "Expense Claim Type",
+   "length": 0,
+   "no_copy": 0,
+   "oldfieldname": "expense_type",
+   "oldfieldtype": "Link",
+   "options": "Expense Claim Type",
+   "permlevel": 0,
+   "print_hide": 0,
+   "print_hide_if_no_value": 0,
+   "print_width": "150px",
+   "read_only": 0,
+   "remember_last_selected_value": 0,
+   "report_hide": 0,
+   "reqd": 1,
+   "search_index": 0,
+   "set_only_once": 0,
    "translatable": 0,
-   "unique": 0, 
+   "unique": 0,
    "width": "150px"
-  }, 
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "depends_on": "expense_type", 
-   "fieldname": "default_account", 
-   "fieldtype": "Link", 
-   "hidden": 1, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 0, 
-   "in_standard_filter": 0, 
-   "label": "Default Account", 
-   "length": 0, 
-   "no_copy": 0, 
-   "options": "Account", 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 1, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
+   "allow_bulk_edit": 0,
+   "allow_in_quick_entry": 0,
+   "allow_on_submit": 0,
+   "bold": 0,
+   "collapsible": 0,
+   "columns": 0,
+   "depends_on": "expense_type",
+   "fieldname": "default_account",
+   "fieldtype": "Link",
+   "hidden": 1,
+   "ignore_user_permissions": 0,
+   "ignore_xss_filter": 0,
+   "in_filter": 0,
+   "in_global_search": 0,
+   "in_list_view": 0,
+   "in_standard_filter": 0,
+   "label": "Default Account",
+   "length": 0,
+   "no_copy": 0,
+   "options": "Account",
+   "permlevel": 0,
+   "precision": "",
+   "print_hide": 0,
+   "print_hide_if_no_value": 0,
+   "read_only": 1,
+   "remember_last_selected_value": 0,
+   "report_hide": 0,
+   "reqd": 0,
+   "search_index": 0,
+   "set_only_once": 0,
    "translatable": 0,
    "unique": 0
-  }, 
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "section_break_4", 
-   "fieldtype": "Section Break", 
-   "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, 
-   "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, 
+   "allow_bulk_edit": 0,
+   "allow_in_quick_entry": 0,
+   "allow_on_submit": 0,
+   "bold": 0,
+   "collapsible": 0,
+   "columns": 0,
+   "fieldname": "section_break_4",
+   "fieldtype": "Section Break",
+   "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,
+   "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,
    "translatable": 0,
    "unique": 0
-  }, 
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fetch_from": "expense_type.description",
-   "fieldname": "description", 
-   "fieldtype": "Text Editor", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 1, 
-   "in_standard_filter": 0, 
-   "label": "Description", 
-   "length": 0, 
-   "no_copy": 0, 
-   "oldfieldname": "description", 
-   "oldfieldtype": "Small Text", 
-   "options": "", 
-   "permlevel": 0, 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "print_width": "300px", 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
+   "allow_bulk_edit": 0,
+   "allow_in_quick_entry": 0,
+   "allow_on_submit": 0,
+   "bold": 0,
+   "collapsible": 0,
+   "columns": 0,
+   "fetch_from": "",
+   "fieldname": "description",
+   "fieldtype": "Text Editor",
+   "hidden": 0,
+   "ignore_user_permissions": 0,
+   "ignore_xss_filter": 0,
+   "in_filter": 0,
+   "in_global_search": 0,
+   "in_list_view": 1,
+   "in_standard_filter": 0,
+   "label": "Description",
+   "length": 0,
+   "no_copy": 0,
+   "oldfieldname": "description",
+   "oldfieldtype": "Small Text",
+   "options": "",
+   "permlevel": 0,
+   "print_hide": 0,
+   "print_hide_if_no_value": 0,
+   "print_width": "300px",
+   "read_only": 0,
+   "remember_last_selected_value": 0,
+   "report_hide": 0,
+   "reqd": 0,
+   "search_index": 0,
+   "set_only_once": 0,
    "translatable": 0,
-   "unique": 0, 
+   "unique": 0,
    "width": "300px"
-  }, 
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "section_break_6", 
-   "fieldtype": "Section Break", 
-   "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, 
-   "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, 
+   "allow_bulk_edit": 0,
+   "allow_in_quick_entry": 0,
+   "allow_on_submit": 0,
+   "bold": 0,
+   "collapsible": 0,
+   "columns": 0,
+   "fieldname": "section_break_6",
+   "fieldtype": "Section Break",
+   "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,
+   "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,
    "translatable": 0,
    "unique": 0
-  }, 
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "claim_amount", 
-   "fieldtype": "Currency", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 1, 
-   "in_standard_filter": 0, 
-   "label": "Claim Amount", 
-   "length": 0, 
-   "no_copy": 0, 
-   "oldfieldname": "claim_amount", 
-   "oldfieldtype": "Currency", 
-   "options": "Company:company:default_currency", 
-   "permlevel": 0, 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "print_width": "150px", 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 1, 
-   "search_index": 0, 
-   "set_only_once": 0, 
+   "allow_bulk_edit": 0,
+   "allow_in_quick_entry": 0,
+   "allow_on_submit": 0,
+   "bold": 0,
+   "collapsible": 0,
+   "columns": 0,
+   "fieldname": "claim_amount",
+   "fieldtype": "Currency",
+   "hidden": 0,
+   "ignore_user_permissions": 0,
+   "ignore_xss_filter": 0,
+   "in_filter": 0,
+   "in_global_search": 0,
+   "in_list_view": 1,
+   "in_standard_filter": 0,
+   "label": "Claim Amount",
+   "length": 0,
+   "no_copy": 0,
+   "oldfieldname": "claim_amount",
+   "oldfieldtype": "Currency",
+   "options": "Company:company:default_currency",
+   "permlevel": 0,
+   "print_hide": 0,
+   "print_hide_if_no_value": 0,
+   "print_width": "150px",
+   "read_only": 0,
+   "remember_last_selected_value": 0,
+   "report_hide": 0,
+   "reqd": 1,
+   "search_index": 0,
+   "set_only_once": 0,
    "translatable": 0,
-   "unique": 0, 
+   "unique": 0,
    "width": "150px"
-  }, 
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "column_break_8", 
-   "fieldtype": "Column Break", 
-   "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, 
-   "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, 
+   "allow_bulk_edit": 0,
+   "allow_in_quick_entry": 0,
+   "allow_on_submit": 0,
+   "bold": 0,
+   "collapsible": 0,
+   "columns": 0,
+   "fieldname": "column_break_8",
+   "fieldtype": "Column Break",
+   "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,
+   "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,
    "translatable": 0,
    "unique": 0
-  }, 
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "sanctioned_amount", 
-   "fieldtype": "Currency", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 1, 
-   "in_standard_filter": 0, 
-   "label": "Sanctioned Amount", 
-   "length": 0, 
-   "no_copy": 1, 
-   "oldfieldname": "sanctioned_amount", 
-   "oldfieldtype": "Currency", 
-   "options": "Company:company:default_currency", 
-   "permlevel": 0, 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "print_width": "150px", 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
+   "allow_bulk_edit": 0,
+   "allow_in_quick_entry": 0,
+   "allow_on_submit": 0,
+   "bold": 0,
+   "collapsible": 0,
+   "columns": 0,
+   "fieldname": "sanctioned_amount",
+   "fieldtype": "Currency",
+   "hidden": 0,
+   "ignore_user_permissions": 0,
+   "ignore_xss_filter": 0,
+   "in_filter": 0,
+   "in_global_search": 0,
+   "in_list_view": 1,
+   "in_standard_filter": 0,
+   "label": "Sanctioned Amount",
+   "length": 0,
+   "no_copy": 1,
+   "oldfieldname": "sanctioned_amount",
+   "oldfieldtype": "Currency",
+   "options": "Company:company:default_currency",
+   "permlevel": 0,
+   "print_hide": 0,
+   "print_hide_if_no_value": 0,
+   "print_width": "150px",
+   "read_only": 0,
+   "remember_last_selected_value": 0,
+   "report_hide": 0,
+   "reqd": 0,
+   "search_index": 0,
+   "set_only_once": 0,
    "translatable": 0,
-   "unique": 0, 
+   "unique": 0,
    "width": "150px"
   }
- ], 
- "has_web_view": 0, 
- "hide_heading": 0, 
- "hide_toolbar": 0, 
- "idx": 1, 
- "image_view": 0, 
- "in_create": 0, 
- "is_submittable": 0, 
- "issingle": 0, 
- "istable": 1, 
- "max_attachments": 0, 
- "modified": "2018-05-16 22:42:56.727863",
- "modified_by": "Administrator", 
- "module": "HR", 
- "name": "Expense Claim Detail", 
- "owner": "harshada@webnotestech.com", 
- "permissions": [], 
- "quick_entry": 0, 
- "read_only": 0, 
- "read_only_onload": 0, 
- "show_name_in_global_search": 0, 
- "sort_field": "modified", 
- "sort_order": "DESC", 
- "track_changes": 0, 
- "track_seen": 0
+ ],
+ "has_web_view": 0,
+ "hide_heading": 0,
+ "hide_toolbar": 0,
+ "idx": 1,
+ "image_view": 0,
+ "in_create": 0,
+ "is_submittable": 0,
+ "issingle": 0,
+ "istable": 1,
+ "max_attachments": 0,
+ "modified": "2019-02-24 08:41:36.122565",
+ "modified_by": "Administrator",
+ "module": "HR",
+ "name": "Expense Claim Detail",
+ "owner": "harshada@webnotestech.com",
+ "permissions": [],
+ "quick_entry": 0,
+ "read_only": 0,
+ "read_only_onload": 0,
+ "show_name_in_global_search": 0,
+ "sort_field": "modified",
+ "sort_order": "DESC",
+ "track_changes": 0,
+ "track_seen": 0,
+ "track_views": 0
 }
\ No newline at end of file
diff --git a/erpnext/hr/doctype/leave_application/leave_application.py b/erpnext/hr/doctype/leave_application/leave_application.py
index 6b7c0f7..692db8e 100755
--- a/erpnext/hr/doctype/leave_application/leave_application.py
+++ b/erpnext/hr/doctype/leave_application/leave_application.py
@@ -487,7 +487,6 @@
 
 	add_block_dates(events, start, end, employee, company)
 	add_holidays(events, start, end, employee, company)
-
 	return events
 
 def add_department_leaves(events, start, end, employee, company):
@@ -500,19 +499,32 @@
 	department_employees = frappe.db.sql_list("""select name from tabEmployee where department=%s
 		and company=%s""", (department, company))
 
-	match_conditions = "and employee in (\"%s\")" % '", "'.join(department_employees)
-	add_leaves(events, start, end, match_conditions=match_conditions)
+	filter_conditions = "employee in (\"%s\")" % '", "'.join(department_employees)
+	add_leaves(events, start, end, filter_conditions=filter_conditions)
 
-def add_leaves(events, start, end, match_conditions=None):
+def add_leaves(events, start, end, filter_conditions=None):
+	conditions = []
+
+
+	if not cint(frappe.db.get_value("HR Settings", None, "show_leaves_of_all_department_members_in_calendar")):
+		from frappe.desk.reportview import build_match_conditions
+		match_conditions = build_match_conditions("Leave Application")
+
+		if match_conditions:
+			conditions.append(match_conditions)
+
 	query = """select name, from_date, to_date, employee_name, half_day,
 		status, employee, docstatus
 		from `tabLeave Application` where
 		from_date <= %(end)s and to_date >= %(start)s <= to_date
 		and docstatus < 2
-		and status!="Rejected" """
+		and status!='Rejected' """
 
-	if match_conditions:
-		query += match_conditions
+	if conditions:
+		query += ' and ' + ' and '.join(conditions)
+
+	if filter_conditions:
+		query += filter_conditions
 
 	for d in frappe.db.sql(query, {"start":start, "end": end}, as_dict=True):
 		e = {
diff --git a/erpnext/hr/doctype/staffing_plan/staffing_plan.py b/erpnext/hr/doctype/staffing_plan/staffing_plan.py
index 70e185c..83e5313 100644
--- a/erpnext/hr/doctype/staffing_plan/staffing_plan.py
+++ b/erpnext/hr/doctype/staffing_plan/staffing_plan.py
@@ -20,6 +20,7 @@
 		self.total_estimated_budget = 0
 
 		for detail in self.get("staffing_details"):
+			self.set_vacancies(detail)
 			self.validate_overlap(detail)
 			self.validate_with_subsidiary_plans(detail)
 			self.validate_with_parent_plan(detail)
@@ -39,6 +40,15 @@
 			else: detail.vacancies = detail.number_of_positions = detail.total_estimated_cost = 0
 			self.total_estimated_budget += detail.total_estimated_cost
 
+	def set_vacancies(self, row):
+		if not row.vacancies:
+			current_openings = 0
+			for field in ['current_count', 'current_openings']:
+				if row.get(field):
+					current_openings += row.get(field)
+
+			row.vacancies = row.number_of_positions - current_openings
+
 	def validate_overlap(self, staffing_plan_detail):
 		# Validate if any submitted Staffing Plan exist for any Designations in this plan
 		# and spd.vacancies>0 ?
diff --git a/erpnext/hr/doctype/staffing_plan/test_staffing_plan.py b/erpnext/hr/doctype/staffing_plan/test_staffing_plan.py
index 66d9cdd..22dba99 100644
--- a/erpnext/hr/doctype/staffing_plan/test_staffing_plan.py
+++ b/erpnext/hr/doctype/staffing_plan/test_staffing_plan.py
@@ -18,7 +18,7 @@
 		if frappe.db.exists("Staffing Plan", "Test"):
 			return
 		staffing_plan = frappe.new_doc("Staffing Plan")
-		staffing_plan.company = "_Test Company 3"
+		staffing_plan.company = "_Test Company 10"
 		staffing_plan.name = "Test"
 		staffing_plan.from_date = nowdate()
 		staffing_plan.to_date = add_days(nowdate(), 10)
@@ -67,7 +67,7 @@
 		if frappe.db.exists("Staffing Plan", "Test 1"):
 			return
 		staffing_plan = frappe.new_doc("Staffing Plan")
-		staffing_plan.company = "_Test Company 3"
+		staffing_plan.company = "_Test Company 10"
 		staffing_plan.name = "Test 1"
 		staffing_plan.from_date = nowdate()
 		staffing_plan.to_date = add_days(nowdate(), 10)
@@ -85,11 +85,11 @@
 	make_company()
 
 def make_company():
-	if frappe.db.exists("Company", "_Test Company 3"):
+	if frappe.db.exists("Company", "_Test Company 10"):
 		return
 	company = frappe.new_doc("Company")
-	company.company_name = "_Test Company 3"
-	company.abbr = "_TC3"
+	company.company_name = "_Test Company 10"
+	company.abbr = "_TC10"
 	company.parent_company = "_Test Company"
 	company.default_currency = "INR"
 	company.country = "India"
diff --git a/erpnext/maintenance/doctype/maintenance_visit/maintenance_visit.py b/erpnext/maintenance/doctype/maintenance_visit/maintenance_visit.py
index 6d082bd..2f2ad00 100644
--- a/erpnext/maintenance/doctype/maintenance_visit/maintenance_visit.py
+++ b/erpnext/maintenance/doctype/maintenance_visit/maintenance_visit.py
@@ -41,12 +41,19 @@
 						work_done = nm and nm[0][3] or ''
 					else:
 						status = 'Open'
-						mntc_date = ''
-						service_person = ''
-						work_done = ''
+						mntc_date = None
+						service_person = None
+						work_done = None
 
-				frappe.db.sql("update `tabWarranty Claim` set resolution_date=%s, resolved_by=%s, resolution_details=%s, status=%s where name =%s",(mntc_date,service_person,work_done,status,d.prevdoc_docname))
+				wc_doc = frappe.get_doc('Warranty Claim', d.prevdoc_docname)
+				wc_doc.update({
+					'resolution_date': mntc_date,
+					'resolved_by': service_person,
+					'resolution_details': work_done,
+					'status': status
+				})
 
+				wc_doc.db_update()
 
 	def check_if_last_visit(self):
 		"""check if last maintenance visit against same sales order/ Warranty Claim"""
diff --git a/erpnext/manufacturing/doctype/bom/bom.py b/erpnext/manufacturing/doctype/bom/bom.py
index 88d346f..ea6b7ed 100644
--- a/erpnext/manufacturing/doctype/bom/bom.py
+++ b/erpnext/manufacturing/doctype/bom/bom.py
@@ -706,8 +706,11 @@
 
 def get_boms_in_bottom_up_order(bom_no=None):
 	def _get_parent(bom_no):
-		return frappe.db.sql_list("""select distinct parent from `tabBOM Item`
-			where bom_no = %s and docstatus=1 and parenttype='BOM'""", bom_no)
+		return frappe.db.sql_list("""
+			select distinct bom_item.parent from `tabBOM Item` bom_item
+			where bom_item.bom_no = %s and bom_item.docstatus=1 and bom_item.parenttype='BOM'
+				and exists(select bom.name from `tabBOM` bom where bom.name=bom_item.parent and bom.is_active=1)
+		""", bom_no)
 
 	count = 0
 	bom_list = []
@@ -715,9 +718,10 @@
 		bom_list.append(bom_no)
 	else:
 		# get all leaf BOMs
-		bom_list = frappe.db.sql_list("""select name from `tabBOM` bom where docstatus=1
-			and not exists(select bom_no from `tabBOM Item`
-				where parent=bom.name and ifnull(bom_no, '')!='')""")
+		bom_list = frappe.db.sql_list("""select name from `tabBOM` bom
+			where docstatus=1 and is_active=1
+				and not exists(select bom_no from `tabBOM Item`
+					where parent=bom.name and ifnull(bom_no, '')!='')""")
 
 	while(count < len(bom_list)):
 		for child_bom in _get_parent(bom_list[count]):
diff --git a/erpnext/manufacturing/doctype/bom_item/bom_item.json b/erpnext/manufacturing/doctype/bom_item/bom_item.json
index 2258360..febf315 100644
--- a/erpnext/manufacturing/doctype/bom_item/bom_item.json
+++ b/erpnext/manufacturing/doctype/bom_item/bom_item.json
@@ -85,6 +85,39 @@
    "bold": 0,
    "collapsible": 0,
    "columns": 0,
+   "fieldname": "operation",
+   "fieldtype": "Link",
+   "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": "Item operation",
+   "length": 0,
+   "no_copy": 0,
+   "options": "Operation",
+   "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,
+   "translatable": 0,
+   "unique": 0
+  },
+  {
+   "allow_bulk_edit": 0,
+   "allow_in_quick_entry": 0,
+   "allow_on_submit": 0,
+   "bold": 0,
+   "collapsible": 0,
+   "columns": 0,
    "fieldname": "column_break_3",
    "fieldtype": "Column Break",
    "hidden": 0,
@@ -900,6 +933,38 @@
    "bold": 0,
    "collapsible": 0,
    "columns": 0,
+   "fieldname": "allow_alternative_item",
+   "fieldtype": "Check",
+   "hidden": 1,
+   "ignore_user_permissions": 0,
+   "ignore_xss_filter": 0,
+   "in_filter": 0,
+   "in_global_search": 0,
+   "in_list_view": 0,
+   "in_standard_filter": 0,
+   "label": "Allow Alternative Item",
+   "length": 0,
+   "no_copy": 0,
+   "permlevel": 0,
+   "precision": "",
+   "print_hide": 0,
+   "print_hide_if_no_value": 0,
+   "read_only": 1,
+   "remember_last_selected_value": 0,
+   "report_hide": 0,
+   "reqd": 0,
+   "search_index": 0,
+   "set_only_once": 0,
+   "translatable": 0,
+   "unique": 0
+  },
+  {
+   "allow_bulk_edit": 0,
+   "allow_in_quick_entry": 0,
+   "allow_on_submit": 0,
+   "bold": 0,
+   "collapsible": 0,
+   "columns": 0,
    "fetch_from": "item_code.include_item_in_manufacturing",
    "fieldname": "include_item_in_manufacturing",
    "fieldtype": "Check",
@@ -958,71 +1023,6 @@
    "set_only_once": 0,
    "translatable": 0,
    "unique": 0
-  },
-  {
-   "allow_bulk_edit": 0,
-   "allow_in_quick_entry": 0,
-   "allow_on_submit": 0,
-   "bold": 0,
-   "collapsible": 0,
-   "columns": 0,
-   "fieldname": "operation",
-   "fieldtype": "Link",
-   "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": "Item operation",
-   "length": 0,
-   "no_copy": 0,
-   "options": "Operation",
-   "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,
-   "translatable": 0,
-   "unique": 0
-  },
-  {
-   "allow_bulk_edit": 0,
-   "allow_in_quick_entry": 0,
-   "allow_on_submit": 0,
-   "bold": 0,
-   "collapsible": 0,
-   "columns": 0,
-   "fieldname": "allow_alternative_item",
-   "fieldtype": "Check",
-   "hidden": 1,
-   "ignore_user_permissions": 0,
-   "ignore_xss_filter": 0,
-   "in_filter": 0,
-   "in_global_search": 0,
-   "in_list_view": 0,
-   "in_standard_filter": 0,
-   "label": "Allow Alternative Item",
-   "length": 0,
-   "no_copy": 0,
-   "permlevel": 0,
-   "precision": "",
-   "print_hide": 0,
-   "print_hide_if_no_value": 0,
-   "read_only": 1,
-   "remember_last_selected_value": 0,
-   "report_hide": 0,
-   "reqd": 0,
-   "search_index": 0,
-   "set_only_once": 0,
-   "translatable": 0,
-   "unique": 0
   }
  ],
  "has_web_view": 0,
@@ -1035,7 +1035,7 @@
  "issingle": 0,
  "istable": 1,
  "max_attachments": 0,
- "modified": "2018-11-23 15:05:55.187136",
+ "modified": "2019-02-21 19:19:54.872459",
  "modified_by": "Administrator",
  "module": "Manufacturing",
  "name": "BOM Item",
@@ -1050,4 +1050,4 @@
  "track_changes": 0,
  "track_seen": 0,
  "track_views": 0
-}
+}
\ No newline at end of file
diff --git a/erpnext/manufacturing/doctype/job_card/job_card.js b/erpnext/manufacturing/doctype/job_card/job_card.js
index 3fe9b8a..95549d5 100644
--- a/erpnext/manufacturing/doctype/job_card/job_card.js
+++ b/erpnext/manufacturing/doctype/job_card/job_card.js
@@ -18,20 +18,27 @@
 		}
 
 		if (frm.doc.docstatus == 0) {
-			if (!frm.doc.actual_start_date || !frm.doc.actual_end_date) {
-				frm.trigger("make_dashboard");
-			}
+			frm.trigger("make_dashboard");
 
-			if (!frm.doc.actual_start_date) {
+			if (!frm.doc.job_started) {
 				frm.add_custom_button(__("Start Job"), () => {
-					frm.set_value('actual_start_date', frappe.datetime.now_datetime());
+					let row = frappe.model.add_child(frm.doc, 'Job Card Time Log', 'time_logs');
+					row.from_time = frappe.datetime.now_datetime();
+					frm.set_value('job_started', 1);
+					frm.set_value('started_time' , row.from_time);
 					frm.save();
 				});
-			} else if (!frm.doc.actual_end_date) {
+			} else {
 				frm.add_custom_button(__("Complete Job"), () => {
-					frm.set_value('actual_end_date', frappe.datetime.now_datetime());
-					frm.save();
-					frm.savesubmit();
+					let completed_time = frappe.datetime.now_datetime();
+					frm.doc.time_logs.forEach(d => {
+						if (d.from_time && !d.to_time) {
+							d.to_time = completed_time;
+							frm.set_value('started_time' , '');
+							frm.set_value('job_started', 0);
+							frm.save();
+						}
+					})
 				});
 			}
 		}
@@ -53,8 +60,8 @@
 
 		var section = frm.dashboard.add_section(timer);
 
-		if (frm.doc.actual_start_date) {
-			let currentIncrement = moment(frappe.datetime.now_datetime()).diff(moment(frm.doc.actual_start_date),"seconds");
+		if (frm.doc.started_time) {
+			let currentIncrement = moment(frappe.datetime.now_datetime()).diff(moment(frm.doc.started_time),"seconds");
 			initialiseTimer();
 
 			function initialiseTimer() {
diff --git a/erpnext/manufacturing/doctype/job_card/job_card.json b/erpnext/manufacturing/doctype/job_card/job_card.json
index b020c89..39c5cce 100644
--- a/erpnext/manufacturing/doctype/job_card/job_card.json
+++ b/erpnext/manufacturing/doctype/job_card/job_card.json
@@ -21,6 +21,7 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "work_order", 
    "fieldtype": "Link", 
    "hidden": 0, 
@@ -54,6 +55,7 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "bom_no", 
    "fieldtype": "Link", 
    "hidden": 0, 
@@ -87,6 +89,7 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "workstation", 
    "fieldtype": "Link", 
    "hidden": 0, 
@@ -120,6 +123,7 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "operation", 
    "fieldtype": "Link", 
    "hidden": 0, 
@@ -153,6 +157,7 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "column_break_4", 
    "fieldtype": "Column Break", 
    "hidden": 0, 
@@ -185,6 +190,7 @@
    "collapsible": 0, 
    "columns": 0, 
    "default": "Today", 
+   "fetch_if_empty": 0, 
    "fieldname": "posting_date", 
    "fieldtype": "Date", 
    "hidden": 0, 
@@ -217,6 +223,7 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "company", 
    "fieldtype": "Link", 
    "hidden": 0, 
@@ -250,6 +257,7 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "for_quantity", 
    "fieldtype": "Float", 
    "hidden": 0, 
@@ -282,6 +290,7 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "wip_warehouse", 
    "fieldtype": "Link", 
    "hidden": 0, 
@@ -315,6 +324,7 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "timing_detail", 
    "fieldtype": "Section Break", 
    "hidden": 0, 
@@ -347,6 +357,7 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "employee", 
    "fieldtype": "Link", 
    "hidden": 0, 
@@ -380,7 +391,74 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
-   "fieldname": "time_in_mins", 
+   "fetch_if_empty": 0, 
+   "fieldname": "time_logs", 
+   "fieldtype": "Table", 
+   "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": "Time Logs", 
+   "length": 0, 
+   "no_copy": 0, 
+   "options": "Job Card Time Log", 
+   "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, 
+   "translatable": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_bulk_edit": 0, 
+   "allow_in_quick_entry": 0, 
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
+   "columns": 0, 
+   "fetch_if_empty": 0, 
+   "fieldname": "section_break_13", 
+   "fieldtype": "Section Break", 
+   "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, 
+   "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, 
+   "translatable": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_bulk_edit": 0, 
+   "allow_in_quick_entry": 0, 
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
+   "columns": 0, 
+   "fetch_if_empty": 0, 
+   "fieldname": "total_completed_qty", 
    "fieldtype": "Float", 
    "hidden": 0, 
    "ignore_user_permissions": 0, 
@@ -389,7 +467,7 @@
    "in_global_search": 0, 
    "in_list_view": 0, 
    "in_standard_filter": 0, 
-   "label": "Time In Mins", 
+   "label": "Total Completed Qty", 
    "length": 0, 
    "no_copy": 0, 
    "permlevel": 0, 
@@ -412,7 +490,8 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
-   "fieldname": "column_break_13", 
+   "fetch_if_empty": 0, 
+   "fieldname": "column_break_15", 
    "fieldtype": "Column Break", 
    "hidden": 0, 
    "ignore_user_permissions": 0, 
@@ -443,8 +522,9 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
-   "fieldname": "actual_start_date", 
-   "fieldtype": "Datetime", 
+   "fetch_if_empty": 0, 
+   "fieldname": "total_time_in_mins", 
+   "fieldtype": "Float", 
    "hidden": 0, 
    "ignore_user_permissions": 0, 
    "ignore_xss_filter": 0, 
@@ -452,14 +532,14 @@
    "in_global_search": 0, 
    "in_list_view": 0, 
    "in_standard_filter": 0, 
-   "label": "Actual Start Date", 
+   "label": "Total Time in Mins", 
    "length": 0, 
    "no_copy": 0, 
    "permlevel": 0, 
    "precision": "", 
    "print_hide": 0, 
    "print_hide_if_no_value": 0, 
-   "read_only": 0, 
+   "read_only": 1, 
    "remember_last_selected_value": 0, 
    "report_hide": 0, 
    "reqd": 0, 
@@ -475,38 +555,7 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
-   "fieldname": "actual_end_date", 
-   "fieldtype": "Datetime", 
-   "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": "Actual End 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, 
-   "translatable": 0, 
-   "unique": 0
-  }, 
-  {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "section_break_8", 
    "fieldtype": "Section Break", 
    "hidden": 0, 
@@ -539,6 +588,7 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "items", 
    "fieldtype": "Table", 
    "hidden": 0, 
@@ -572,6 +622,7 @@
    "bold": 0, 
    "collapsible": 1, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "more_information", 
    "fieldtype": "Section Break", 
    "hidden": 0, 
@@ -604,6 +655,7 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "operation_id", 
    "fieldtype": "Data", 
    "hidden": 1, 
@@ -637,6 +689,7 @@
    "collapsible": 0, 
    "columns": 0, 
    "default": "0", 
+   "fetch_if_empty": 0, 
    "fieldname": "transferred_qty", 
    "fieldtype": "Float", 
    "hidden": 0, 
@@ -670,6 +723,7 @@
    "collapsible": 0, 
    "columns": 0, 
    "default": "0", 
+   "fetch_if_empty": 0, 
    "fieldname": "requested_qty", 
    "fieldtype": "Float", 
    "hidden": 0, 
@@ -702,6 +756,7 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "project", 
    "fieldtype": "Link", 
    "hidden": 0, 
@@ -735,6 +790,7 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "remarks", 
    "fieldtype": "Small Text", 
    "hidden": 0, 
@@ -767,6 +823,7 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "column_break_20", 
    "fieldtype": "Column Break", 
    "hidden": 0, 
@@ -799,6 +856,7 @@
    "collapsible": 0, 
    "columns": 0, 
    "default": "Open", 
+   "fetch_if_empty": 0, 
    "fieldname": "status", 
    "fieldtype": "Select", 
    "hidden": 0, 
@@ -832,6 +890,73 @@
    "bold": 0, 
    "collapsible": 0, 
    "columns": 0, 
+   "fetch_if_empty": 0, 
+   "fieldname": "job_started", 
+   "fieldtype": "Check", 
+   "hidden": 1, 
+   "ignore_user_permissions": 0, 
+   "ignore_xss_filter": 0, 
+   "in_filter": 0, 
+   "in_global_search": 0, 
+   "in_list_view": 0, 
+   "in_standard_filter": 0, 
+   "label": "Job Started", 
+   "length": 0, 
+   "no_copy": 1, 
+   "permlevel": 0, 
+   "precision": "", 
+   "print_hide": 1, 
+   "print_hide_if_no_value": 0, 
+   "read_only": 1, 
+   "remember_last_selected_value": 0, 
+   "report_hide": 0, 
+   "reqd": 0, 
+   "search_index": 0, 
+   "set_only_once": 0, 
+   "translatable": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_bulk_edit": 0, 
+   "allow_in_quick_entry": 0, 
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
+   "columns": 0, 
+   "fetch_if_empty": 0, 
+   "fieldname": "started_time", 
+   "fieldtype": "Datetime", 
+   "hidden": 1, 
+   "ignore_user_permissions": 0, 
+   "ignore_xss_filter": 0, 
+   "in_filter": 0, 
+   "in_global_search": 0, 
+   "in_list_view": 0, 
+   "in_standard_filter": 0, 
+   "label": "Started Time", 
+   "length": 0, 
+   "no_copy": 1, 
+   "permlevel": 0, 
+   "precision": "", 
+   "print_hide": 1, 
+   "print_hide_if_no_value": 0, 
+   "read_only": 1, 
+   "remember_last_selected_value": 0, 
+   "report_hide": 0, 
+   "reqd": 0, 
+   "search_index": 0, 
+   "set_only_once": 0, 
+   "translatable": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_bulk_edit": 0, 
+   "allow_in_quick_entry": 0, 
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
+   "columns": 0, 
+   "fetch_if_empty": 0, 
    "fieldname": "amended_from", 
    "fieldtype": "Link", 
    "hidden": 0, 
@@ -868,7 +993,7 @@
  "issingle": 0, 
  "istable": 0, 
  "max_attachments": 0, 
- "modified": "2018-12-13 17:23:57.986381", 
+ "modified": "2019-03-10 17:38:37.499871", 
  "modified_by": "Administrator", 
  "module": "Manufacturing", 
  "name": "Job Card", 
diff --git a/erpnext/manufacturing/doctype/job_card/job_card.py b/erpnext/manufacturing/doctype/job_card/job_card.py
index ea9f714..23a4e51 100644
--- a/erpnext/manufacturing/doctype/job_card/job_card.py
+++ b/erpnext/manufacturing/doctype/job_card/job_card.py
@@ -11,44 +11,56 @@
 
 class JobCard(Document):
 	def validate(self):
-		self.validate_actual_dates()
-		self.set_time_in_mins()
+		self.validate_time_logs()
 		self.set_status()
 
-	def validate_actual_dates(self):
-		if get_datetime(self.actual_start_date) > get_datetime(self.actual_end_date):
-			frappe.throw(_("Actual start date must be less than actual end date"))
+	def validate_time_logs(self):
+		self.total_completed_qty = 0.0
+		self.total_time_in_mins = 0.0
 
-		if not (self.employee and self.actual_start_date and self.actual_end_date):
-			return
+		for d in self.get('time_logs'):
+			if get_datetime(d.from_time) > get_datetime(d.to_time):
+				frappe.throw(_("Row {0}: From time must be less than to time").format(d.idx))
 
-		data = frappe.db.sql(""" select name from `tabJob Card`
-			where
-				((%(actual_start_date)s > actual_start_date and %(actual_start_date)s < actual_end_date) or
-				(%(actual_end_date)s > actual_start_date and %(actual_end_date)s < actual_end_date) or
-				(%(actual_start_date)s <= actual_start_date and %(actual_end_date)s >= actual_end_date)) and
-				name != %(name)s and employee = %(employee)s and docstatus =1
-		""", {
-			'actual_start_date': self.actual_start_date,
-			'actual_end_date': self.actual_end_date,
-			'employee': self.employee,
-			'name': self.name
-		}, as_dict=1)
+			data = self.get_overlap_for(d)
+			if data:
+				frappe.throw(_("Row {0}: From Time and To Time of {1} is overlapping with {2}")
+					.format(d.idx, self.name, data.name))
 
-		if data:
-			frappe.throw(_("Start date and end date is overlapping with the job card <a href='#Form/Job Card/{0}'>{1}</a>")
-				.format(data[0].name, data[0].name))
+			if d.from_time and d.to_time:
+				d.time_in_mins = time_diff_in_hours(d.to_time, d.from_time) * 60
+				self.total_time_in_mins += d.time_in_mins
 
-	def set_time_in_mins(self):
-		if self.actual_start_date and self.actual_end_date:
-			self.time_in_mins = time_diff_in_hours(self.actual_end_date, self.actual_start_date) * 60
+			if d.completed_qty:
+				self.total_completed_qty += d.completed_qty
+
+	def get_overlap_for(self, args):
+		existing = frappe.db.sql("""select jc.name as name from
+			`tabJob Card Time Log` jctl, `tabJob Card` jc where jctl.parent = jc.name and
+			(
+				(%(from_time)s > jctl.from_time and %(from_time)s < jctl.to_time) or
+				(%(to_time)s > jctl.from_time and %(to_time)s < jctl.to_time) or
+				(%(from_time)s <= jctl.from_time and %(to_time)s >= jctl.to_time))
+			and jctl.name!=%(name)s
+			and jc.name!=%(parent)s
+			and jc.docstatus < 2
+			and jc.employee = %(employee)s """,
+			{
+				"from_time": args.from_time,
+				"to_time": args.to_time,
+				"name": args.name or "No Name",
+				"parent": args.parent or "No Name",
+				"employee": self.employee
+			}, as_dict=True)
+
+		return existing[0] if existing else None
 
 	def get_required_items(self):
 		if not self.get('work_order'):
 			return
 
 		doc = frappe.get_doc('Work Order', self.get('work_order'))
-		if doc.transfer_material_against == 'Work Order' and doc.skip_transfer:
+		if doc.transfer_material_against == 'Work Order' or doc.skip_transfer:
 			return
 
 		for d in doc.required_items:
@@ -67,36 +79,51 @@
 				})
 
 	def on_submit(self):
-		self.validate_dates()
+		self.validate_job_card()
 		self.update_work_order()
 		self.set_transferred_qty()
 
-	def validate_dates(self):
-		if not self.actual_start_date and not self.actual_end_date:
-			frappe.throw(_("Actual start date and actual end date is mandatory"))
-
 	def on_cancel(self):
 		self.update_work_order()
 		self.set_transferred_qty()
 
+	def validate_job_card(self):
+		if not self.time_logs:
+			frappe.throw(_("Time logs are required for job card {0}").format(self.name))
+
+		if self.total_completed_qty <= 0.0:
+			frappe.throw(_("Total completed qty must be greater than zero"))
+
+		if self.total_completed_qty > self.for_quantity:
+			frappe.throw(_("Total completed qty can not be greater than for quantity"))
+
 	def update_work_order(self):
 		if not self.work_order:
 			return
 
-		data = frappe.db.get_value("Job Card", {'docstatus': 1, 'operation_id': self.operation_id},
-			['sum(time_in_mins)', 'min(actual_start_date)', 'max(actual_end_date)', 'sum(for_quantity)'])
+		for_quantity, time_in_mins = 0, 0
+		from_time_list, to_time_list = [], []
 
-		if data:
-			time_in_mins, actual_start_date, actual_end_date, for_quantity = data
 
+		for d in frappe.get_all('Job Card',
+			filters = {'docstatus': 1, 'operation_id': self.operation_id}):
+			doc = frappe.get_doc('Job Card', d.name)
+
+			for_quantity += doc.total_completed_qty
+			time_in_mins += doc.total_time_in_mins
+			for time_log in doc.time_logs:
+				from_time_list.append(time_log.from_time)
+				to_time_list.append(time_log.to_time)
+
+		if for_quantity:
 			wo = frappe.get_doc('Work Order', self.work_order)
 
 			for data in wo.operations:
 				if data.name == self.operation_id:
 					data.completed_qty = for_quantity
 					data.actual_operation_time = time_in_mins
-					data.actual_start_time = actual_start_date
-					data.actual_end_time = actual_end_date
+					data.actual_start_time = min(from_time_list)
+					data.actual_end_time = max(to_time_list)
 
 			wo.flags.ignore_validate_update_after_submit = True
 			wo.update_operation_status()
@@ -132,9 +159,11 @@
 						break
 
 				if completed:
-					job_cards = frappe.get_all('Job Card', filters = {'work_order': self.work_order, 
+					job_cards = frappe.get_all('Job Card', filters = {'work_order': self.work_order,
 						'docstatus': ('!=', 2)}, fields = 'sum(transferred_qty) as qty', group_by='operation_id')
-					qty = min([d.qty for d in job_cards])
+
+					if job_cards:
+						qty = min([d.qty for d in job_cards])
 
 			doc.db_set('material_transferred_for_manufacturing', qty)
 
@@ -147,7 +176,7 @@
 			2: "Cancelled"
 		}[self.docstatus or 0]
 
-		if self.actual_start_date:
+		if self.time_logs:
 			self.status = 'Work In Progress'
 
 		if (self.docstatus == 1 and
diff --git a/erpnext/manufacturing/doctype/job_card_time_log/__init__.py b/erpnext/manufacturing/doctype/job_card_time_log/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/manufacturing/doctype/job_card_time_log/__init__.py
diff --git a/erpnext/manufacturing/doctype/job_card_time_log/job_card_time_log.json b/erpnext/manufacturing/doctype/job_card_time_log/job_card_time_log.json
new file mode 100644
index 0000000..2aab71d
--- /dev/null
+++ b/erpnext/manufacturing/doctype/job_card_time_log/job_card_time_log.json
@@ -0,0 +1,208 @@
+{
+ "allow_copy": 0, 
+ "allow_events_in_timeline": 0, 
+ "allow_guest_to_view": 0, 
+ "allow_import": 0, 
+ "allow_rename": 0, 
+ "beta": 0, 
+ "creation": "2019-03-08 23:56:43.187569", 
+ "custom": 0, 
+ "docstatus": 0, 
+ "doctype": "DocType", 
+ "document_type": "", 
+ "editable_grid": 1, 
+ "engine": "InnoDB", 
+ "fields": [
+  {
+   "allow_bulk_edit": 0, 
+   "allow_in_quick_entry": 0, 
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
+   "columns": 0, 
+   "fetch_if_empty": 0, 
+   "fieldname": "from_time", 
+   "fieldtype": "Datetime", 
+   "hidden": 0, 
+   "ignore_user_permissions": 0, 
+   "ignore_xss_filter": 0, 
+   "in_filter": 0, 
+   "in_global_search": 0, 
+   "in_list_view": 1, 
+   "in_standard_filter": 0, 
+   "label": "From Time", 
+   "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, 
+   "translatable": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_bulk_edit": 0, 
+   "allow_in_quick_entry": 0, 
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
+   "columns": 0, 
+   "fetch_if_empty": 0, 
+   "fieldname": "to_time", 
+   "fieldtype": "Datetime", 
+   "hidden": 0, 
+   "ignore_user_permissions": 0, 
+   "ignore_xss_filter": 0, 
+   "in_filter": 0, 
+   "in_global_search": 0, 
+   "in_list_view": 1, 
+   "in_standard_filter": 0, 
+   "label": "To Time", 
+   "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, 
+   "translatable": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_bulk_edit": 0, 
+   "allow_in_quick_entry": 0, 
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
+   "columns": 0, 
+   "fetch_if_empty": 0, 
+   "fieldname": "column_break_2", 
+   "fieldtype": "Column Break", 
+   "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, 
+   "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, 
+   "translatable": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_bulk_edit": 0, 
+   "allow_in_quick_entry": 0, 
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
+   "columns": 0, 
+   "fetch_if_empty": 0, 
+   "fieldname": "time_in_mins", 
+   "fieldtype": "Float", 
+   "hidden": 0, 
+   "ignore_user_permissions": 0, 
+   "ignore_xss_filter": 0, 
+   "in_filter": 0, 
+   "in_global_search": 0, 
+   "in_list_view": 1, 
+   "in_standard_filter": 0, 
+   "label": "Time In Mins", 
+   "length": 0, 
+   "no_copy": 0, 
+   "permlevel": 0, 
+   "precision": "", 
+   "print_hide": 0, 
+   "print_hide_if_no_value": 0, 
+   "read_only": 1, 
+   "remember_last_selected_value": 0, 
+   "report_hide": 0, 
+   "reqd": 0, 
+   "search_index": 0, 
+   "set_only_once": 0, 
+   "translatable": 0, 
+   "unique": 0
+  }, 
+  {
+   "allow_bulk_edit": 0, 
+   "allow_in_quick_entry": 0, 
+   "allow_on_submit": 0, 
+   "bold": 0, 
+   "collapsible": 0, 
+   "columns": 0, 
+   "default": "0", 
+   "fetch_if_empty": 0, 
+   "fieldname": "completed_qty", 
+   "fieldtype": "Float", 
+   "hidden": 0, 
+   "ignore_user_permissions": 0, 
+   "ignore_xss_filter": 0, 
+   "in_filter": 0, 
+   "in_global_search": 0, 
+   "in_list_view": 1, 
+   "in_standard_filter": 0, 
+   "label": "Completed Qty", 
+   "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": 1, 
+   "search_index": 0, 
+   "set_only_once": 0, 
+   "translatable": 0, 
+   "unique": 0
+  }
+ ], 
+ "has_web_view": 0, 
+ "hide_heading": 0, 
+ "hide_toolbar": 0, 
+ "idx": 0, 
+ "image_view": 0, 
+ "in_create": 0, 
+ "is_submittable": 0, 
+ "issingle": 0, 
+ "istable": 1, 
+ "max_attachments": 0, 
+ "modified": "2019-03-10 17:08:46.504910", 
+ "modified_by": "Administrator", 
+ "module": "Manufacturing", 
+ "name": "Job Card Time Log", 
+ "name_case": "", 
+ "owner": "Administrator", 
+ "permissions": [], 
+ "quick_entry": 1, 
+ "read_only": 0, 
+ "read_only_onload": 0, 
+ "show_name_in_global_search": 0, 
+ "sort_field": "modified", 
+ "sort_order": "ASC", 
+ "track_changes": 1, 
+ "track_seen": 0, 
+ "track_views": 0
+}
\ No newline at end of file
diff --git a/erpnext/manufacturing/doctype/job_card_time_log/job_card_time_log.py b/erpnext/manufacturing/doctype/job_card_time_log/job_card_time_log.py
new file mode 100644
index 0000000..3dc6689
--- /dev/null
+++ b/erpnext/manufacturing/doctype/job_card_time_log/job_card_time_log.py
@@ -0,0 +1,9 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and contributors
+# For license information, please see license.txt
+
+from __future__ import unicode_literals
+from frappe.model.document import Document
+
+class JobCardTimeLog(Document):
+	pass
diff --git a/erpnext/manufacturing/doctype/work_order/test_work_order.py b/erpnext/manufacturing/doctype/work_order/test_work_order.py
index 69381c5..b292047 100644
--- a/erpnext/manufacturing/doctype/work_order/test_work_order.py
+++ b/erpnext/manufacturing/doctype/work_order/test_work_order.py
@@ -302,6 +302,19 @@
 		self.assertEqual(len(ste.additional_costs), 1)
 		self.assertEqual(ste.total_additional_costs, 1000)
 
+	def test_job_card(self):
+		data = frappe.get_cached_value('BOM',
+			{'docstatus': 1, 'with_operations': 1, 'company': '_Test Company'}, ['name', 'item'])
+
+		if data:
+			bom, bom_item = data
+
+			bom_doc = frappe.get_doc('BOM', bom)
+			work_order = make_wo_order_test_record(item=bom_item, qty=1, bom_no=bom)
+
+			job_cards = frappe.get_all('Job Card', filters = {'work_order': work_order})
+			self.assertEqual(len(job_cards), len(bom_doc.operations))
+
 	def test_work_order_with_non_transfer_item(self):
 		items = {'Finished Good Transfer Item': 1, '_Test FG Item': 1, '_Test FG Item 1': 0}
 		for item, allow_transfer in items.items():
@@ -346,7 +359,7 @@
 
 	wo_order = frappe.new_doc("Work Order")
 	wo_order.production_item = args.production_item or args.item or args.item_code or "_Test FG Item"
-	wo_order.bom_no = frappe.db.get_value("BOM", {"item": wo_order.production_item,
+	wo_order.bom_no = args.bom_no or frappe.db.get_value("BOM", {"item": wo_order.production_item,
 		"is_active": 1, "is_default": 1})
 	wo_order.qty = args.qty or 10
 	wo_order.wip_warehouse = args.wip_warehouse or "_Test Warehouse - _TC"
diff --git a/erpnext/manufacturing/doctype/work_order/work_order.py b/erpnext/manufacturing/doctype/work_order/work_order.py
index 9873efa..947d693 100644
--- a/erpnext/manufacturing/doctype/work_order/work_order.py
+++ b/erpnext/manufacturing/doctype/work_order/work_order.py
@@ -282,6 +282,10 @@
 			total_bundle_qty = frappe.db.sql(""" select sum(qty) from
 				`tabProduct Bundle Item` where parent = %s""", (frappe.db.escape(self.product_bundle_item)))[0][0]
 
+			if not total_bundle_qty:
+				# product bundle is 0 (product bundle allows 0 qty for items)
+				total_bundle_qty = 1
+
 		cond = "product_bundle_item = %s" if self.product_bundle_item else "production_item = %s"
 
 		qty = frappe.db.sql(""" select sum(qty) from
diff --git a/erpnext/patches.txt b/erpnext/patches.txt
index b1a393b..7d49ad5 100755
--- a/erpnext/patches.txt
+++ b/erpnext/patches.txt
@@ -587,4 +587,5 @@
 execute:frappe.delete_doc('DocType', 'Notification Control')
 erpnext.patches.v11_0.remove_barcodes_field_from_copy_fields_to_variants
 erpnext.patches.v10_0.item_barcode_childtable_migrate # 16-02-2019
-erpnext.patches.v11_0.make_italian_localization_fields
+erpnext.patches.v11_0.make_italian_localization_fields # 01-03-2019
+erpnext.patches.v11_1.make_job_card_time_logs
\ No newline at end of file
diff --git a/erpnext/patches/v10_0/item_barcode_childtable_migrate.py b/erpnext/patches/v10_0/item_barcode_childtable_migrate.py
index bc60056..e30e0a7 100644
--- a/erpnext/patches/v10_0/item_barcode_childtable_migrate.py
+++ b/erpnext/patches/v10_0/item_barcode_childtable_migrate.py
@@ -27,5 +27,5 @@
 					'parent': item.name,
 					'parentfield': 'barcodes'
 				}).insert()
-			except frappe.DuplicateEntryError:
+			except (frappe.DuplicateEntryError, frappe.UniqueValidationError):
 				continue
diff --git a/erpnext/patches/v11_0/make_italian_localization_fields.py b/erpnext/patches/v11_0/make_italian_localization_fields.py
index fa77149..44a281f 100644
--- a/erpnext/patches/v11_0/make_italian_localization_fields.py
+++ b/erpnext/patches/v11_0/make_italian_localization_fields.py
@@ -22,7 +22,9 @@
 		condition += " when '{0}' then '{1}'".format(frappe.db.escape(state), frappe.db.escape(code))
 
 	if condition:
-		frappe.db.sql("""
-			UPDATE tabAddress set state_code = (case state {condition} end)
-			WHERE country in ('Italy', 'Italia', 'Italian Republic', 'Repubblica Italiana')
-		""".format(condition=condition))
+		condition = "state_code = (case state {0} end),".format(condition)
+
+	frappe.db.sql("""
+		UPDATE tabAddress set {condition} country_code = UPPER(ifnull((select code
+			from `tabCountry` where name = `tabAddress`.country), ''))
+	""".format(condition=condition))
diff --git a/erpnext/patches/v11_1/make_job_card_time_logs.py b/erpnext/patches/v11_1/make_job_card_time_logs.py
new file mode 100644
index 0000000..6e708df
--- /dev/null
+++ b/erpnext/patches/v11_1/make_job_card_time_logs.py
@@ -0,0 +1,29 @@
+# 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
+
+def execute():
+    frappe.reload_doc('manufacturing', 'doctype', 'job_card_time_log')
+
+    if (frappe.db.table_exists("Job Card")
+        and frappe.get_meta("Job Card").has_field("actual_start_date")):
+        time_logs = []
+        for d in frappe.get_all('Job Card',
+            fields = ["actual_start_date", "actual_end_date", "time_in_mins", "name", "for_quantity"],
+            filters = {'docstatus': ("<", 2)}):
+            if d.actual_start_date:
+                time_logs.append([d.actual_start_date, d.actual_end_date, d.time_in_mins,
+                    d.for_quantity, d.name, 'Job Card', 'time_logs', frappe.generate_hash("", 10)])
+
+        if time_logs:
+            frappe.db.sql(""" INSERT INTO
+                `tabJob Card Time Log`
+                    (from_time, to_time, time_in_mins, completed_qty, parent, parenttype, parentfield, name)
+                values {values}
+            """.format(values = ','.join(['%s'] * len(time_logs))), tuple(time_logs))
+
+        frappe.reload_doc('manufacturing', 'doctype', 'job_card')
+        frappe.db.sql(""" update `tabJob Card` set total_completed_qty = for_quantity,
+            total_time_in_mins = time_in_mins where docstatus < 2 """)
\ No newline at end of file
diff --git a/erpnext/public/js/controllers/stock_controller.js b/erpnext/public/js/controllers/stock_controller.js
index 1b8e079..1c12c35 100644
--- a/erpnext/public/js/controllers/stock_controller.js
+++ b/erpnext/public/js/controllers/stock_controller.js
@@ -73,7 +73,7 @@
 					from_date: me.frm.doc.posting_date,
 					to_date: me.frm.doc.posting_date,
 					company: me.frm.doc.company,
-					group_by: ""
+					group_by: "Group by Voucher (Consolidated)"
 				};
 				frappe.set_route("query-report", "General Ledger");
 			}, __("View"));
diff --git a/erpnext/public/js/controllers/transaction.js b/erpnext/public/js/controllers/transaction.js
index cf62af7..168a727 100644
--- a/erpnext/public/js/controllers/transaction.js
+++ b/erpnext/public/js/controllers/transaction.js
@@ -314,14 +314,21 @@
 
 				show_description(row_to_modify.idx, row_to_modify.item_code);
 
+				this.frm.from_barcode = true;
 				frappe.model.set_value(row_to_modify.doctype, row_to_modify.name, {
 					item_code: data.item_code,
 					qty: (row_to_modify.qty || 0) + 1
 				});
 
-				this.frm.refresh_field('items');
+				['serial_no', 'batch_no', 'barcode'].forEach(field => {
+					if (data[field] && frappe.meta.has_field(row_to_modify.doctype, field)) {
+						frappe.model.set_value(row_to_modify.doctype,
+							row_to_modify.name, field, data[field]);
+					}
+				});
+
+				scan_barcode_field.set_value('');
 			});
-			scan_barcode_field.set_value('');
 		}
 		return false;
 	},
@@ -384,10 +391,12 @@
 			// barcode cleared, remove item
 			d.item_code = "";
 		}
-		this.item_code(doc, cdt, cdn, true);
+
+		this.frm.from_barcode = true;
+		this.item_code(doc, cdt, cdn);
 	},
 
-	item_code: function(doc, cdt, cdn, from_barcode) {
+	item_code: function(doc, cdt, cdn) {
 		var me = this;
 		var item = frappe.get_doc(cdt, cdn);
 		var update_stock = 0, show_batch_dialog = 0;
@@ -400,9 +409,11 @@
 			show_batch_dialog = 1;
 		}
 		// clear barcode if setting item (else barcode will take priority)
-		if(!from_barcode) {
+		if(!this.frm.from_barcode) {
 			item.barcode = null;
 		}
+
+		this.frm.from_barcode = false;
 		if(item.item_code || item.barcode || item.serial_no) {
 			if(!this.validate_company_and_party()) {
 				this.frm.fields_dict["items"].grid.grid_rows[item.idx - 1].remove();
diff --git a/erpnext/public/js/utils.js b/erpnext/public/js/utils.js
index 64085a8..389e25e 100755
--- a/erpnext/public/js/utils.js
+++ b/erpnext/public/js/utils.js
@@ -255,11 +255,16 @@
 		// get valid options for tree based on user permission & locals dict
 		let unscrub_option = frappe.model.unscrub(option);
 		let user_permission = frappe.defaults.get_user_permissions();
+		let options;
+
 		if(user_permission && user_permission[unscrub_option]) {
-			return user_permission[unscrub_option].map(perm => perm.doc);
+			options = user_permission[unscrub_option].map(perm => perm.doc);
 		} else {
-			return $.map(locals[`:${unscrub_option}`], function(c) { return c.name; }).sort();
+			options = $.map(locals[`:${unscrub_option}`], function(c) { return c.name; }).sort();
 		}
+
+		// filter unique values, as there may be multiple user permissions for any value
+		return options.filter((value, index, self) => self.indexOf(value) === index);
 	},
 	get_tree_default: function(option) {
 		// set default for a field based on user permission
diff --git a/erpnext/regional/india/utils.py b/erpnext/regional/india/utils.py
index e7d0d50..9747b24 100644
--- a/erpnext/regional/india/utils.py
+++ b/erpnext/regional/india/utils.py
@@ -9,6 +9,8 @@
 from erpnext.hr.doctype.salary_structure.salary_structure import make_salary_slip
 
 def validate_gstin_for_india(doc, method):
+	if hasattr(doc, 'gst_state') and doc.gst_state:
+		doc.gst_state_number = state_numbers[doc.gst_state]
 	if not hasattr(doc, 'gstin') or not doc.gstin:
 		return
 
diff --git a/erpnext/regional/italy/e-invoice.xml b/erpnext/regional/italy/e-invoice.xml
index 34053bd..c886ee9 100644
--- a/erpnext/regional/italy/e-invoice.xml
+++ b/erpnext/regional/italy/e-invoice.xml
@@ -9,7 +9,7 @@
 {%- if address.state_code %}
 <Provincia>{{ address.state_code }}</Provincia>
 {%- endif %}
-<Nazione>{{ address.country_code|upper }}</Nazione>
+<Nazione>{{ address.country_code }}</Nazione>
 {%- endmacro %}
 
 {%- macro render_discount_or_margin(item) -%}
@@ -32,15 +32,15 @@
 {%- endmacro -%}
 
 <?xml version='1.0' encoding='UTF-8'?>
-<p:FatturaElettronica xmlns:ds="http://www.w3.org/2000/09/xmldsig#" 
-  xmlns:p="http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2" 
-  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
-  versione="{{ doc.transmission_format_code }}" 
+<p:FatturaElettronica xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
+  xmlns:p="http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2"
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  versione="{{ doc.transmission_format_code }}"
   xsi:schemaLocation="http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2 http://www.fatturapa.gov.it/export/fatturazione/sdi/fatturapa/v1.2/Schema_del_file_xml_FatturaPA_versione_1.2.xsd">
   <FatturaElettronicaHeader>
     <DatiTrasmissione>
       <IdTrasmittente>
-        <IdPaese>{{ doc.company_address_data.country_code|upper or "IT" }}</IdPaese>
+        <IdPaese>{{ doc.company_address_data.country_code }}</IdPaese>
         <IdCodice>{{ doc.company_fiscal_code or doc.company_tax_id | replace("IT","") }}</IdCodice>
       </IdTrasmittente>
       <ProgressivoInvio>{{ doc.progressive_number }}</ProgressivoInvio>
@@ -56,7 +56,7 @@
     <CedentePrestatore>
       <DatiAnagrafici>
         <IdFiscaleIVA>
-          <IdPaese>{{ doc.company_address_data.country_code|upper or "IT"}}</IdPaese>
+          <IdPaese>{{ doc.company_address_data.country_code }}</IdPaese>
           <IdCodice>{{ doc.company_tax_id | replace("IT","") }}</IdCodice>
         </IdFiscaleIVA>
         {%- if doc.company_fiscal_code %}
@@ -99,7 +99,7 @@
           <CodiceFiscale>{{ doc.customer_data.fiscal_code }}</CodiceFiscale>
           {%- else %}
           <IdFiscaleIVA>
-            <IdPaese>{{ doc.customer_address_data.country_code|upper or "IT" }}</IdPaese>
+            <IdPaese>{{ doc.customer_address_data.country_code }}</IdPaese>
             <IdCodice>{{ doc.tax_id | replace("IT","") }}</IdCodice>
           </IdFiscaleIVA>
           {%- endif %}
@@ -160,7 +160,7 @@
           <CodiceTipo>CODICE</CodiceTipo>
           <CodiceValore>{{ item.item_code }}</CodiceValore>
         </CodiceArticolo>
-        <Descrizione>{{ item.description or item.item_name }}</Descrizione>
+        <Descrizione>{{ html2text(item.description or '') or item.item_name }}</Descrizione>
         <Quantita>{{ format_float(item.qty) }}</Quantita>
         <UnitaMisura>{{ item.stock_uom }}</UnitaMisura>
         <PrezzoUnitario>{{ format_float(item.price_list_rate or item.rate) }}</PrezzoUnitario>
@@ -199,7 +199,15 @@
         <ModalitaPagamento>{{ payment_term.mode_of_payment_code.split("-")[0] }}</ModalitaPagamento>
         <DataScadenzaPagamento>{{ payment_term.due_date }}</DataScadenzaPagamento>
         <ImportoPagamento>{{ format_float(payment_term.payment_amount) }}</ImportoPagamento>
-        {%- if payment_term.bank_account_iban %}<IBAN>{{ payment_term.bank_account_iban }}</IBAN>{%- endif %}
+        <IstitutoFinanziario>{{ payment_term.bank_account_name }}</IstitutoFinanziario>
+        {%- if payment_term.bank_account_iban %}
+          <IBAN>{{ payment_term.bank_account_iban }}</IBAN>
+          <ABI>{{ payment_term.bank_account_iban[5:10] }}</ABI>
+          <CAB>{{ payment_term.bank_account_iban[10:15] }}</CAB>
+        {%- endif %}
+        {%- if payment_term.bank_account_swift_number %}
+          <BIC>{{ payment_term.bank_account_swift_number }}</BIC>
+        {%- endif %}
       </DettaglioPagamento>
       {%- endfor %}
     </DatiPagamento>
diff --git a/erpnext/regional/italy/sales_invoice.js b/erpnext/regional/italy/sales_invoice.js
new file mode 100644
index 0000000..3457f71
--- /dev/null
+++ b/erpnext/regional/italy/sales_invoice.js
@@ -0,0 +1,19 @@
+erpnext.setup_e_invoice_button = (doctype) => {
+	frappe.ui.form.on(doctype, {
+		refresh: (frm) => {
+			if(frm.doc.docstatus == 1) {
+				frm.add_custom_button('Generate E-Invoice', () => {
+					var w = window.open(
+						frappe.urllib.get_full_url(
+							"/api/method/erpnext.regional.italy.utils.generate_single_invoice?"
+							+ "docname=" + frm.doc.name
+						)
+					)
+					if (!w) {
+						frappe.msgprint(__("Please enable pop-ups")); return;
+					}
+				});
+			}
+		}
+	});
+};
diff --git a/erpnext/regional/italy/setup.py b/erpnext/regional/italy/setup.py
index a9de2d1..2b6e3af 100644
--- a/erpnext/regional/italy/setup.py
+++ b/erpnext/regional/italy/setup.py
@@ -32,12 +32,12 @@
 				fieldtype='Section Break', insert_after='date_of_establishment', print_hide=1),
 			dict(fieldname='fiscal_regime', label='Fiscal Regime',
 				fieldtype='Select', insert_after='sb_e_invoicing', print_hide=1,
-				options="\n".join(map(lambda x: x.decode('utf-8'), fiscal_regimes))),
+				options="\n".join(map(lambda x: frappe.safe_decode(x, encoding='utf-8'), fiscal_regimes))),
 			dict(fieldname='fiscal_code', label='Fiscal Code', fieldtype='Data', insert_after='fiscal_regime', print_hide=1,
 				description=_("Applicable if the company is an Individual or a Proprietorship")),
 			dict(fieldname='vat_collectability', label='VAT Collectability',
 				fieldtype='Select', insert_after='fiscal_code', print_hide=1,
-				options="\n".join(map(lambda x: x.decode('utf-8'), vat_collectability_options))),
+				options="\n".join(map(lambda x: frappe.safe_decode(x, encoding='utf-8'), vat_collectability_options))),
 			dict(fieldname='cb_e_invoicing1', fieldtype='Column Break', insert_after='vat_collectability', print_hide=1),
 			dict(fieldname='registrar_office_province', label='Province of the Registrar Office',
 				fieldtype='Data', insert_after='cb_e_invoicing1', print_hide=1, length=2),
@@ -57,7 +57,7 @@
 			dict(fieldname='tax_exemption_reason', label='Tax Exemption Reason',
 				fieldtype='Select', insert_after='included_in_print_rate', print_hide=1,
 				depends_on='eval:doc.charge_type!="Actual" && doc.rate==0.0',
-				options="\n" + "\n".join(map(lambda x: x.decode('utf-8'), tax_exemption_reasons))),
+				options="\n" + "\n".join(map(lambda x: frappe.safe_decode(x, encoding='utf-8'), tax_exemption_reasons))),
 			dict(fieldname='tax_exemption_law', label='Tax Exempt Under',
 				fieldtype='Text', insert_after='tax_exemption_reason', print_hide=1,
 				depends_on='eval:doc.charge_type!="Actual" && doc.rate==0.0')
@@ -80,30 +80,33 @@
 		'Mode of Payment': [
 			dict(fieldname='mode_of_payment_code', label='Code',
 			fieldtype='Select', insert_after='included_in_print_rate', print_hide=1,
-			options="\n".join(map(lambda x: x.decode('utf-8'), mode_of_payment_codes)))
+			options="\n".join(map(lambda x: frappe.safe_decode(x, encoding='utf-8'), mode_of_payment_codes)))
 		],
 		'Payment Schedule': [
 			dict(fieldname='mode_of_payment_code', label='Code',
 				fieldtype='Select', insert_after='mode_of_payment', print_hide=1,
-				options="\n".join(map(lambda x: x.decode('utf-8'), mode_of_payment_codes)),
+				options="\n".join(map(lambda x: frappe.safe_decode(x, encoding='utf-8'), mode_of_payment_codes)),
 				fetch_from="mode_of_payment.mode_of_payment_code", read_only=1),
 			dict(fieldname='bank_account', label='Bank Account',
 				fieldtype='Link', insert_after='mode_of_payment_code', print_hide=1,
 				options="Bank Account"),
-			dict(fieldname='bank_account_name', label='Bank Account Name',
+			dict(fieldname='bank_account_name', label='Bank Name',
 				fieldtype='Data', insert_after='bank_account', print_hide=1,
-				fetch_from="bank_account.account_name", read_only=1),
+				fetch_from="bank_account.bank", read_only=1),
 			dict(fieldname='bank_account_no', label='Bank Account No',
 				fieldtype='Data', insert_after='bank_account_name', print_hide=1,
 				fetch_from="bank_account.bank_account_no", read_only=1),
 			dict(fieldname='bank_account_iban', label='IBAN',
 				fieldtype='Data', insert_after='bank_account_name', print_hide=1,
 				fetch_from="bank_account.iban", read_only=1),
+			dict(fieldname='bank_account_swift_number', label='Swift Code (BIC)',
+				fieldtype='Data', insert_after='bank_account_iban', print_hide=1,
+				fetch_from="bank_account.swift_number", read_only=1),
 		],
 		"Sales Invoice": [
 			dict(fieldname='vat_collectability', label='VAT Collectability',
 				fieldtype='Select', insert_after='taxes_and_charges', print_hide=1,
-				options="\n".join(map(lambda x: x.decode('utf-8'), vat_collectability_options)),
+				options="\n".join(map(lambda x: frappe.safe_decode(x, encoding='utf-8'), vat_collectability_options)),
 				fetch_from="company.vat_collectability"),
 			dict(fieldname='sb_e_invoicing_reference', label='E-Invoicing',
 				fieldtype='Section Break', insert_after='pos_total_qty', print_hide=1),
@@ -132,7 +135,7 @@
 		'Supplier Quotation Item': invoice_item_fields,
 		'Address': [
 			dict(fieldname='country_code', label='Country Code',
-				fieldtype='Data', insert_after='country', print_hide=1, read_only=1,
+				fieldtype='Data', insert_after='country', print_hide=1, read_only=0,
 				fetch_from="country.code"),
 			dict(fieldname='state_code', label='State Code',
 				fieldtype='Data', insert_after='state', print_hide=1)
diff --git a/erpnext/regional/italy/utils.py b/erpnext/regional/italy/utils.py
index c86ad78..f39b144 100644
--- a/erpnext/regional/italy/utils.py
+++ b/erpnext/regional/italy/utils.py
@@ -189,7 +189,14 @@
 	if not doc.company_address:
 		frappe.throw(_("Please set an Address on the Company '%s'" % doc.company), title=_("E-Invoicing Information Missing"))
 	else:
-		validate_address(doc.company_address, "Company")
+		validate_address(doc.company_address)
+
+	company_fiscal_regime = frappe.get_cached_value("Company", doc.company, 'fiscal_regime')
+	if not company_fiscal_regime:
+		frappe.throw(_("Fiscal Regime is mandatory, kindly set the fiscal regime in the company {0}")
+			.format(doc.company))
+	else:
+		doc.company_fiscal_regime = company_fiscal_regime
 
 	if not doc.company_tax_id and not doc.company_fiscal_code:
 		frappe.throw(_("Please set either the Tax ID or Fiscal Code on Company '%s'" % doc.company), title=_("E-Invoicing Information Missing"))
@@ -210,7 +217,7 @@
 	if not doc.customer_address:
 	 	frappe.throw(_("Please set the Customer Address"), title=_("E-Invoicing Information Missing"))
 	else:
-		validate_address(doc.customer_address, "Customer")
+		validate_address(doc.customer_address)
 
 	if not len(doc.taxes):
 		frappe.throw(_("Please set at least one row in the Taxes and Charges Table"), title=_("E-Invoicing Information Missing"))
@@ -220,6 +227,10 @@
 				frappe.throw(_("Row {0}: Please set at Tax Exemption Reason in Sales Taxes and Charges".format(row.idx)),
 					title=_("E-Invoicing Information Missing"))
 
+	for schedule in doc.payment_schedule:
+		if schedule.mode_of_payment and not schedule.mode_of_payment_code:
+			schedule.mode_of_payment_code = frappe.get_cached_value('Mode of Payment',
+				schedule.mode_of_payment, 'mode_of_payment_code')
 
 #Ensure payment details are valid for e-invoice.
 def sales_invoice_on_submit(doc, method):
@@ -241,14 +252,29 @@
 
 	prepare_and_attach_invoice(doc)
 
-def prepare_and_attach_invoice(doc):
-	progressive_name, progressive_number = get_progressive_name_and_number(doc)
+def prepare_and_attach_invoice(doc, replace=False):
+	progressive_name, progressive_number = get_progressive_name_and_number(doc, replace)
 
 	invoice = prepare_invoice(doc, progressive_number)
 	invoice_xml = frappe.render_template('erpnext/regional/italy/e-invoice.xml', context={"doc": invoice}, is_path=True)
+	invoice_xml = invoice_xml.replace("&", "&amp;")
 
 	xml_filename = progressive_name + ".xml"
-	save_file(xml_filename, invoice_xml, dt=doc.doctype, dn=doc.name, is_private=True)
+	return save_file(xml_filename, invoice_xml, dt=doc.doctype, dn=doc.name, is_private=True)
+
+@frappe.whitelist()
+def generate_single_invoice(docname):
+	doc = frappe.get_doc("Sales Invoice", docname)
+
+	e_invoice = prepare_and_attach_invoice(doc, True)
+
+	content = None
+	with open(frappe.get_site_path('private', 'files', e_invoice.file_name), "r") as f:
+		content = f.read()
+
+	frappe.local.response.filename = e_invoice.file_name
+	frappe.local.response.filecontent = content
+	frappe.local.response.type = "download"
 
 #Delete e-invoice attachment on cancel.
 def sales_invoice_on_cancel(doc, method):
@@ -268,18 +294,19 @@
 	company_tax_id = invoice.company_tax_id if invoice.company_tax_id.startswith("IT") else "IT" + invoice.company_tax_id
 
 	for attachment in attachments:
-		if attachment.file_name.startswith(company_tax_id) and attachment.file_name.endswith(".xml"):
+		if attachment.file_name and attachment.file_name.startswith(company_tax_id) and attachment.file_name.endswith(".xml"):
 			out.append(attachment)
 
 	return out
 
-def validate_address(address_name, address_context):
-	pincode, city = frappe.db.get_value("Address", address_name, ["pincode", "city"])
-	if not pincode:
-		frappe.throw(_("Please set pin code on %s Address" % address_context), title=_("E-Invoicing Information Missing"))
-	if not city:
-		frappe.throw(_("Please set city on %s Address" % address_context), title=_("E-Invoicing Information Missing"))
+def validate_address(address_name):
+	fields = ["pincode", "city", "country_code"]
+	data = frappe.get_cached_value("Address", address_name, fields, as_dict=1) or {}
 
+	for field in fields:
+		if not data.get(field):
+			frappe.throw(_("Please set {0} for address {1}".format(field.replace('-',''), address_name)),
+				title=_("E-Invoicing Information Missing"))
 
 def get_unamended_name(doc):
 	attributes = ["naming_series", "amended_from"]
@@ -292,7 +319,13 @@
 	else:
 		return doc.name
 
-def get_progressive_name_and_number(doc):
+def get_progressive_name_and_number(doc, replace=False):
+	if replace:
+		for attachment in get_e_invoice_attachments(doc):
+			remove_file(attachment.name, attached_to_doctype=doc.doctype, attached_to_name=doc.name)
+			filename = attachment.file_name.split(".xml")[0]
+			return filename, filename.split("_")[1]
+
 	company_tax_id = doc.company_tax_id if doc.company_tax_id.startswith("IT") else "IT" + doc.company_tax_id
 	progressive_name = frappe.model.naming.make_autoname(company_tax_id + "_.#####")
 	progressive_number = progressive_name.split("_")[1]
@@ -300,8 +333,17 @@
 	return progressive_name, progressive_number
 
 def set_state_code(doc, method):
+	if doc.get('country_code'):
+		doc.country_code = doc.country_code.upper()
+
+	if not doc.get('state'):
+		return
+
 	if not (hasattr(doc, "state_code") and doc.country in ["Italy", "Italia", "Italian Republic", "Repubblica Italiana"]):
 		return
 
 	state_codes_lower = {key.lower():value for key,value in state_codes.items()}
-	doc.state_code = state_codes_lower.get(doc.get('state','').lower())
+
+	state = doc.get('state','').lower()
+	if state_codes_lower.get(state):
+		doc.state_code = state_codes_lower.get(state)
diff --git "a/erpnext/regional/report/fichier_des_ecritures_comptables_\133fec\135/fichier_des_ecritures_comptables_\133fec\135.py" "b/erpnext/regional/report/fichier_des_ecritures_comptables_\133fec\135/fichier_des_ecritures_comptables_\133fec\135.py"
index 5fbf700..6b8d3f0 100644
--- "a/erpnext/regional/report/fichier_des_ecritures_comptables_\133fec\135/fichier_des_ecritures_comptables_\133fec\135.py"
+++ "b/erpnext/regional/report/fichier_des_ecritures_comptables_\133fec\135/fichier_des_ecritures_comptables_\133fec\135.py"
@@ -87,8 +87,8 @@
 			left join `tabPurchase Invoice` pur on gl.voucher_no = pur.name
 			left join `tabJournal Entry` jnl on gl.voucher_no = jnl.name
 			left join `tabPayment Entry` pay on gl.voucher_no = pay.name
-			left join `tabCustomer` cus on gl.party = cus.customer_name
-			left join `tabSupplier` sup on gl.party = sup.supplier_name
+			left join `tabCustomer` cus on gl.party = cus.name
+			left join `tabSupplier` sup on gl.party = sup.name
 		where gl.company=%(company)s and gl.fiscal_year=%(fiscal_year)s
 		{group_by_condition}
 		order by GlPostDate, voucher_no"""\
diff --git a/erpnext/regional/united_arab_emirates/setup.py b/erpnext/regional/united_arab_emirates/setup.py
index 3c8328b..250659e 100644
--- a/erpnext/regional/united_arab_emirates/setup.py
+++ b/erpnext/regional/united_arab_emirates/setup.py
@@ -28,24 +28,24 @@
 	purchase_invoice_fields = [
 			dict(fieldname='company_trn', label='Company TRN',
 				fieldtype='Read Only', insert_after='shipping_address',
-				options='company.tax_id', print_hide=1),
+				fetch_from='company.tax_id', print_hide=1),
 			dict(fieldname='supplier_name_in_arabic', label='Supplier Name in Arabic',
 				fieldtype='Read Only', insert_after='supplier_name',
-				options='supplier.supplier_name_in_arabic', print_hide=1)
+				fetch_from='supplier.supplier_name_in_arabic', print_hide=1)
 		]
 
 	sales_invoice_fields = [
 			dict(fieldname='company_trn', label='Company TRN',
 				fieldtype='Read Only', insert_after='company_address',
-				options='company.tax_id', print_hide=1),
+				fetch_from='company.tax_id', print_hide=1),
 			dict(fieldname='customer_name_in_arabic', label='Customer Name in Arabic',
 				fieldtype='Read Only', insert_after='customer_name',
-				options='customer.customer_name_in_arabic', print_hide=1),
+				fetch_from='customer.customer_name_in_arabic', print_hide=1),
 		]
 
 	invoice_item_fields = [
 		dict(fieldname='tax_code', label='Tax Code',
-			fieldtype='Read Only', options='item_code.tax_code', insert_after='description',
+			fieldtype='Read Only', fetch_from='item_code.tax_code', insert_after='description',
 			allow_on_submit=1, print_hide=1),
 		dict(fieldname='tax_rate', label='Tax Rate',
 			fieldtype='Float', insert_after='tax_code',
diff --git a/erpnext/selling/doctype/sales_order/sales_order.py b/erpnext/selling/doctype/sales_order/sales_order.py
index b589cde..2345762 100755
--- a/erpnext/selling/doctype/sales_order/sales_order.py
+++ b/erpnext/selling/doctype/sales_order/sales_order.py
@@ -388,6 +388,7 @@
 						items.append(dict(
 							name= i.name,
 							item_code= i.item_code,
+							description= i.description,
 							bom = bom,
 							warehouse = i.warehouse,
 							pending_qty = pending_qty,
@@ -398,6 +399,7 @@
 						items.append(dict(
 							name= i.name,
 							item_code= i.item_code,
+							description= i.description,
 							bom = '',
 							warehouse = i.warehouse,
 							pending_qty = pending_qty,
@@ -901,7 +903,8 @@
 			sales_order=sales_order,
 			sales_order_item=i['sales_order_item'],
 			project=project,
-			fg_warehouse=i['warehouse']
+			fg_warehouse=i['warehouse'],
+			description=i['description']
 		)).insert()
 		work_order.set_work_order_operations()
 		work_order.save()
diff --git a/erpnext/selling/doctype/sales_order/test_sales_order.py b/erpnext/selling/doctype/sales_order/test_sales_order.py
index 0eb19e3..f270938 100644
--- a/erpnext/selling/doctype/sales_order/test_sales_order.py
+++ b/erpnext/selling/doctype/sales_order/test_sales_order.py
@@ -573,7 +573,8 @@
 				"item_code": item.get("item_code"),
 				"pending_qty": item.get("pending_qty"),
 				"sales_order_item": item.get("sales_order_item"),
-				"bom": item.get("bom")
+				"bom": item.get("bom"),
+				"description": item.get("description")
 			})
 			so_item_name[item.get("sales_order_item")]= item.get("pending_qty")
 		make_work_orders(json.dumps({"items":po_items}), so.name, so.company)
diff --git a/erpnext/selling/report/address_and_contacts/address_and_contacts.py b/erpnext/selling/report/address_and_contacts/address_and_contacts.py
index eb242d0..a9e4303 100644
--- a/erpnext/selling/report/address_and_contacts/address_and_contacts.py
+++ b/erpnext/selling/report/address_and_contacts/address_and_contacts.py
@@ -102,8 +102,7 @@
 	records = frappe.get_list(doctype, filters=filters, fields=fields, as_list=True)
 	for d in records:
 		details = party_details.get(d[0])
-		if details:
-			details.setdefault(frappe.scrub(doctype), []).append(d[1:])
+		details.setdefault(frappe.scrub(doctype), []).append(d[1:])
 
 	return party_details
 
diff --git a/erpnext/selling/report/sales_person_wise_transaction_summary/sales_person_wise_transaction_summary.js b/erpnext/selling/report/sales_person_wise_transaction_summary/sales_person_wise_transaction_summary.js
index 67051c8..b236151 100644
--- a/erpnext/selling/report/sales_person_wise_transaction_summary/sales_person_wise_transaction_summary.js
+++ b/erpnext/selling/report/sales_person_wise_transaction_summary/sales_person_wise_transaction_summary.js
@@ -33,7 +33,8 @@
 			label: __("Company"),
 			fieldtype: "Link",
 			options: "Company",
-			default: frappe.defaults.get_user_default("Company")
+			default: frappe.defaults.get_user_default("Company"),
+			reqd: 1
 		},
 		{
 			fieldname:"item_group",
diff --git a/erpnext/selling/report/sales_person_wise_transaction_summary/sales_person_wise_transaction_summary.py b/erpnext/selling/report/sales_person_wise_transaction_summary/sales_person_wise_transaction_summary.py
index db11ae9..41c7f76 100644
--- a/erpnext/selling/report/sales_person_wise_transaction_summary/sales_person_wise_transaction_summary.py
+++ b/erpnext/selling/report/sales_person_wise_transaction_summary/sales_person_wise_transaction_summary.py
@@ -15,7 +15,7 @@
 	item_details = get_item_details()
 	data = []
 
-	company_currency = get_company_currency(filters["company"])
+	company_currency = get_company_currency(filters.get("company"))
 
 	for d in entries:
 		if d.stock_qty > 0 or filters.get('show_return_entries', 0):
diff --git a/erpnext/setup/doctype/company/company.js b/erpnext/setup/doctype/company/company.js
index 70e047a..aff4baf 100644
--- a/erpnext/setup/doctype/company/company.js
+++ b/erpnext/setup/doctype/company/company.js
@@ -16,6 +16,12 @@
 				filters: {"is_additional_component": 1}
 			}
 		});
+
+		frm.set_query("parent_company", function() {
+			return {
+				filters: {"is_group": 1}
+			}
+		});
 	},
 
 	company_name: function(frm) {
@@ -28,6 +34,13 @@
 		}
 	},
 
+	parent_company: function(frm) {
+		var bool = frm.doc.parent_company ? true : false;
+		frm.set_value('create_chart_of_accounts_based_on', bool ? "Existing Company" : "");
+		frm.set_value('existing_company', bool ? frm.doc.parent_company : "");
+		disbale_coa_fields(frm, bool);
+	},
+
 	date_of_commencement: function(frm) {
 		if(frm.doc.date_of_commencement<frm.doc.date_of_incorporation)
 		{
@@ -39,8 +52,10 @@
 	},
 
 	refresh: function(frm) {
-		if(frm.doc.abbr && !frm.doc.__islocal) {
-			frm.set_df_property("abbr", "read_only", 1);
+		if(!frm.doc.__islocal) {
+			frm.doc.abbr && frm.set_df_property("abbr", "read_only", 1);
+			frm.set_df_property("parent_company", "read_only", 1);
+			disbale_coa_fields(frm);
 		}
 
 		frm.toggle_display('address_html', !frm.doc.__islocal);
@@ -256,3 +271,9 @@
 		}
 	});
 }
+
+var disbale_coa_fields = function(frm, bool=true) {
+	frm.set_df_property("create_chart_of_accounts_based_on", "read_only", bool);
+	frm.set_df_property("chart_of_accounts", "read_only", bool);
+	frm.set_df_property("existing_company", "read_only", bool);
+};
\ No newline at end of file
diff --git a/erpnext/setup/doctype/company/company.py b/erpnext/setup/doctype/company/company.py
index c49c264..ad9d64b 100644
--- a/erpnext/setup/doctype/company/company.py
+++ b/erpnext/setup/doctype/company/company.py
@@ -39,6 +39,7 @@
 		self.validate_coa_input()
 		self.validate_perpetual_inventory()
 		self.check_country_change()
+		self.set_chart_of_accounts()
 
 	def validate_abbr(self):
 		if not self.abbr:
@@ -141,6 +142,7 @@
 
 	def create_default_accounts(self):
 		from erpnext.accounts.doctype.account.chart_of_accounts.chart_of_accounts import create_charts
+		frappe.local.flags.ignore_root_company_validation = True
 		create_charts(self.name, self.chart_of_accounts, self.existing_company)
 
 		frappe.db.set(self, "default_receivable_account", frappe.db.get_value("Account",
@@ -173,6 +175,12 @@
 			self.country != frappe.get_cached_value('Company',  self.name,  'country'):
 			frappe.flags.country_change = True
 
+	def set_chart_of_accounts(self):
+		''' If parent company is set, chart of accounts will be based on that company '''
+		if self.parent_company:
+			self.create_chart_of_accounts_based_on = "Existing Company"
+			self.existing_company = self.parent_company
+
 	def set_default_accounts(self):
 		self._set_default_account("default_cash_account", "Cash")
 		self._set_default_account("default_bank_account", "Bank")
diff --git a/erpnext/setup/doctype/company/test_records.json b/erpnext/setup/doctype/company/test_records.json
index 7e26ca3..58d8b5c 100644
--- a/erpnext/setup/doctype/company/test_records.json
+++ b/erpnext/setup/doctype/company/test_records.json
@@ -1,32 +1,66 @@
 [
- {
-  "abbr": "_TC",
-  "company_name": "_Test Company",
-  "country": "India",
-  "default_currency": "INR",
-  "doctype": "Company",
-  "domain": "Manufacturing",
-  "chart_of_accounts": "Standard",
-  "default_holiday_list": "_Test Holiday List"
- },
- {
-  "abbr": "_TC1",
-  "company_name": "_Test Company 1",
-  "country": "United States",
-  "default_currency": "USD",
-  "doctype": "Company",
-  "domain": "Retail",
-  "chart_of_accounts": "Standard",
-  "default_holiday_list": "_Test Holiday List"
- },
- {
-  "abbr": "_TC2",
-  "company_name": "_Test Company 2",
-  "default_currency": "EUR",
-  "country": "Germany",
-  "doctype": "Company",
-  "domain": "Retail",
-  "chart_of_accounts": "Standard",
-  "default_holiday_list": "_Test Holiday List"
- }
+	{
+		"abbr": "_TC",
+		"company_name": "_Test Company",
+		"country": "India",
+		"default_currency": "INR",
+		"doctype": "Company",
+		"domain": "Manufacturing",
+		"chart_of_accounts": "Standard",
+		"default_holiday_list": "_Test Holiday List"
+	},
+	{
+		"abbr": "_TC1",
+		"company_name": "_Test Company 1",
+		"country": "United States",
+		"default_currency": "USD",
+		"doctype": "Company",
+		"domain": "Retail",
+		"chart_of_accounts": "Standard",
+		"default_holiday_list": "_Test Holiday List"
+	},
+	{
+		"abbr": "_TC2",
+		"company_name": "_Test Company 2",
+		"default_currency": "EUR",
+		"country": "Germany",
+		"doctype": "Company",
+		"domain": "Retail",
+		"chart_of_accounts": "Standard",
+		"default_holiday_list": "_Test Holiday List"
+	},
+	{
+		"abbr": "_TC3",
+		"company_name": "_Test Company 3",
+		"is_group": 1,
+		"country": "India",
+		"default_currency": "INR",
+		"doctype": "Company",
+		"domain": "Manufacturing",
+		"chart_of_accounts": "Standard",
+		"default_holiday_list": "_Test Holiday List"
+	},
+	{
+		"abbr": "_TC4",
+		"company_name": "_Test Company 4",
+		"parent_company": "_Test Company 3",
+		"is_group": 1,
+		"country": "India",
+		"default_currency": "INR",
+		"doctype": "Company",
+		"domain": "Manufacturing",
+		"chart_of_accounts": "Standard",
+		"default_holiday_list": "_Test Holiday List"
+	},
+	{
+		"abbr": "_TC5",
+		"company_name": "_Test Company 5",
+		"parent_company": "_Test Company 4",
+		"country": "India",
+		"default_currency": "INR",
+		"doctype": "Company",
+		"domain": "Manufacturing",
+		"chart_of_accounts": "Standard",
+		"default_holiday_list": "_Test Holiday List"
+	}
 ]
diff --git a/erpnext/setup/doctype/setup_progress/setup_progress.py b/erpnext/setup/doctype/setup_progress/setup_progress.py
index 9187eb7..e1402f5 100644
--- a/erpnext/setup/doctype/setup_progress/setup_progress.py
+++ b/erpnext/setup/doctype/setup_progress/setup_progress.py
@@ -16,8 +16,9 @@
 	return frappe.local.setup_progress
 
 def get_action_completed_state(action_name):
-	return [d.is_completed for d in get_setup_progress().actions
-		if d.action_name == action_name][0]
+	for d in get_setup_progress().actions:
+		if d.action_name == action_name:
+			return d.is_completed
 
 def update_action_completed_state(action_name):
 	action_table_doc = [d for d in get_setup_progress().actions
diff --git a/erpnext/startup/boot.py b/erpnext/startup/boot.py
index 62c9e7b..8a164f9 100644
--- a/erpnext/startup/boot.py
+++ b/erpnext/startup/boot.py
@@ -33,7 +33,7 @@
 				tabCompany limit 1""") and 'Yes' or 'No'
 
 		bootinfo.docs += frappe.db.sql("""select name, default_currency, cost_center, default_terms,
-			default_letter_head, default_bank_account, enable_perpetual_inventory from `tabCompany`""",
+			default_letter_head, default_bank_account, enable_perpetual_inventory, country from `tabCompany`""",
 			as_dict=1, update={"doctype":":Company"})
 
 		party_account_types = frappe.db.sql(""" select name, ifnull(account_type, '') from `tabParty Type`""")
diff --git a/erpnext/stock/doctype/delivery_note/delivery_note.py b/erpnext/stock/doctype/delivery_note/delivery_note.py
index 50996ed..1eb2b09 100644
--- a/erpnext/stock/doctype/delivery_note/delivery_note.py
+++ b/erpnext/stock/doctype/delivery_note/delivery_note.py
@@ -391,7 +391,7 @@
 
 	return invoiced_qty_map
 
-def get_returned_qty_map(sales_orders):
+def get_returned_qty_map_against_so(sales_orders):
 	"""returns a map: {so_detail: returned_qty}"""
 	returned_qty_map = {}
 
@@ -403,12 +403,25 @@
 
 	return returned_qty_map
 
+def get_returned_qty_map_against_dn(delivery_note):
+	"""returns a map: {so_detail: returned_qty}"""
+	returned_qty_map = frappe._dict(frappe.db.sql("""select dn_item.item_code, sum(abs(dn_item.qty)) as qty
+		from `tabDelivery Note Item` dn_item, `tabDelivery Note` dn
+		where dn.name = dn_item.parent
+			and dn.docstatus = 1
+			and dn.is_return = 1
+			and dn.return_against = %s
+		group by dn_item.item_code
+	""", delivery_note))
+
+	return returned_qty_map
+
 @frappe.whitelist()
 def make_sales_invoice(source_name, target_doc=None):
 	doc = frappe.get_doc('Delivery Note', source_name)
 	sales_orders = [d.against_sales_order for d in doc.items]
-	returned_qty_map = get_returned_qty_map(sales_orders)
-
+	returned_qty_map_against_so = get_returned_qty_map_against_so(sales_orders)
+	returned_qty_map_against_dn = get_returned_qty_map_against_dn(source_name)
 	invoiced_qty_map = get_invoiced_qty_map(source_name)
 
 	def set_missing_values(source, target):
@@ -428,13 +441,26 @@
 			target.update(get_fetch_values("Sales Invoice", 'company_address', target.company_address))
 
 	def update_item(source_doc, target_doc, source_parent):
-		target_doc.qty = (source_doc.qty -
-			invoiced_qty_map.get(source_doc.name, 0) - returned_qty_map.get(source_doc.so_detail, 0))
+		target_doc.qty, returned_qty = get_pending_qty(source_doc)
+		if not source_doc.so_detail:
+			returned_qty_map_against_dn[source_doc.item_code] = returned_qty
 
 		if source_doc.serial_no and source_parent.per_billed > 0:
 			target_doc.serial_no = get_delivery_note_serial_no(source_doc.item_code,
 				target_doc.qty, source_parent.name)
 
+	def get_pending_qty(item_row):
+		pending_qty = item_row.qty - invoiced_qty_map.get(item_row.name, 0) - returned_qty_map_against_so.get(item_row.so_detail, 0)
+		returned_qty = flt(returned_qty_map_against_dn.get(item_row.item_code, 0))
+		if not item_row.so_detail:
+			if returned_qty >= pending_qty:
+				pending_qty = 0
+				returned_qty -= pending_qty
+			else:
+				pending_qty -= returned_qty
+				returned_qty = 0
+		return pending_qty, returned_qty
+
 	doc = get_mapped_doc("Delivery Note", source_name, 	{
 		"Delivery Note": {
 			"doctype": "Sales Invoice",
@@ -453,7 +479,7 @@
 				"cost_center": "cost_center"
 			},
 			"postprocess": update_item,
-			"filter": lambda d: abs(d.qty) - abs(invoiced_qty_map.get(d.name, 0))<=0
+			"filter": lambda d: get_pending_qty(d)[0]<=0
 		},
 		"Sales Taxes and Charges": {
 			"doctype": "Sales Taxes and Charges",
diff --git a/erpnext/stock/doctype/delivery_note/test_delivery_note.py b/erpnext/stock/doctype/delivery_note/test_delivery_note.py
index 0c5a71c..5c03121 100644
--- a/erpnext/stock/doctype/delivery_note/test_delivery_note.py
+++ b/erpnext/stock/doctype/delivery_note/test_delivery_note.py
@@ -636,7 +636,7 @@
 			self.assertEqual(expected_values[gle.account]["cost_center"], gle.cost_center)
 
 		set_perpetual_inventory(0, company)
-	
+
 	def test_make_sales_invoice_from_dn_for_returned_qty(self):
 		from erpnext.selling.doctype.sales_order.sales_order import make_delivery_note
 		from erpnext.stock.doctype.delivery_note.delivery_note import make_sales_invoice
@@ -655,6 +655,33 @@
 		si = make_sales_invoice(dn.name)
 		self.assertEquals(si.items[0].qty, 1)
 
+	def test_make_sales_invoice_from_dn_with_returned_qty_against_dn(self):
+		from erpnext.stock.doctype.delivery_note.delivery_note import make_sales_invoice
+
+		dn = create_delivery_note(qty=8, do_not_submit=True)
+		dn.append("items", {
+			"item_code": "_Test Item",
+			"warehouse": "_Test Warehouse - _TC",
+			"qty": 1,
+			"rate": 100,
+			"conversion_factor": 1.0,
+			"expense_account": "Cost of Goods Sold - _TC",
+			"cost_center": "_Test Cost Center - _TC"
+		})
+		dn.submit()
+
+		si1 = make_sales_invoice(dn.name)
+		si1.items[0].qty = 4
+		si1.items.pop(1)
+		si1.save()
+		si1.submit()
+
+		create_delivery_note(is_return=1, return_against=dn.name, qty=-2)
+
+		si2 = make_sales_invoice(dn.name)
+		self.assertEquals(si2.items[0].qty, 2)
+		self.assertEquals(si2.items[1].qty, 1)
+
 def create_delivery_note(**args):
 	dn = frappe.new_doc("Delivery Note")
 	args = frappe._dict(args)
diff --git a/erpnext/stock/doctype/item_price/test_item_price.py b/erpnext/stock/doctype/item_price/test_item_price.py
index 455dff4..3782f54 100644
--- a/erpnext/stock/doctype/item_price/test_item_price.py
+++ b/erpnext/stock/doctype/item_price/test_item_price.py
@@ -11,7 +11,7 @@
 
 class TestItemPrice(unittest.TestCase):
 	def setUp(self):
-		frappe.db.sql("delete from `tabItem Price`")		
+		frappe.db.sql("delete from `tabItem Price`")
 		make_test_records_for_doctype("Item Price", force=True)
 
 	def test_duplicate_item(self):
diff --git a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
index f006d00..ed7f2ca 100644
--- a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
+++ b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
@@ -13,7 +13,7 @@
 from erpnext.accounts.utils import get_account_currency
 from frappe.desk.notifications import clear_doctype_notifications
 from erpnext.buying.utils import check_for_closed_status
-from erpnext.assets.doctype.asset.asset import get_asset_account
+from erpnext.assets.doctype.asset.asset import get_asset_account, is_cwip_accounting_disabled
 from six import iteritems
 
 form_grid_templates = {
@@ -125,7 +125,7 @@
 		else:
 			self.status = "Completed"
 
-		
+
 		# Updating stock ledger should always be called after updating prevdoc status,
 		# because updating ordered qty, reserved_qty_for_subcontract in bin
 		# depends upon updated ordered qty in PO
@@ -258,7 +258,8 @@
 					d.rejected_warehouse not in warehouse_with_no_account:
 						warehouse_with_no_account.append(d.warehouse)
 
-		self.get_asset_gl_entry(gl_entries)
+		if not is_cwip_accounting_disabled():
+			self.get_asset_gl_entry(gl_entries)
 		# Cost center-wise amount breakup for other charges included for valuation
 		valuation_tax = {}
 		for tax in self.get("taxes"):
@@ -311,7 +312,7 @@
 				"\n".join(warehouse_with_no_account))
 
 		return process_gl_map(gl_entries)
-		
+
 	def get_asset_gl_entry(self, gl_entries):
 		for d in self.get("items"):
 			if d.is_fixed_asset:
@@ -405,6 +406,11 @@
 @frappe.whitelist()
 def make_purchase_invoice(source_name, target_doc=None):
 	from frappe.model.mapper import get_mapped_doc
+	doc = frappe.get_doc('Purchase Receipt', source_name)
+	purchase_orders = [d.purchase_order for d in doc.items]
+	returned_qty_map_against_po = get_returned_qty_map_against_po(purchase_orders)
+	returned_qty_map_against_pr = get_returned_qty_map_against_pr(source_name)
+
 	invoiced_qty_map = get_invoiced_qty_map(source_name)
 
 	def set_missing_values(source, target):
@@ -417,7 +423,23 @@
 		doc.run_method("calculate_taxes_and_totals")
 
 	def update_item(source_doc, target_doc, source_parent):
-		target_doc.qty = source_doc.qty - invoiced_qty_map.get(source_doc.name, 0)
+		target_doc.qty, returned_qty = get_pending_qty(source_doc)
+		if not source_doc.purchase_order_item:
+			returned_qty_map_against_pr[source_doc.item_code] = returned_qty
+
+	def get_pending_qty(item_row):
+		pending_qty = item_row.qty - invoiced_qty_map.get(item_row.name, 0) \
+			- returned_qty_map_against_po.get(item_row.purchase_order_item, 0)
+		returned_qty = flt(returned_qty_map_against_pr.get(item_row.item_code, 0))
+		if not item_row.purchase_order_item:
+			if returned_qty >= pending_qty:
+				pending_qty = 0
+				returned_qty -= pending_qty
+			else:
+				pending_qty -= returned_qty
+				returned_qty = 0
+		return pending_qty, returned_qty
+
 
 	doclist = get_mapped_doc("Purchase Receipt", source_name,	{
 		"Purchase Receipt": {
@@ -440,7 +462,7 @@
 				"asset": "asset",
 			},
 			"postprocess": update_item,
-			"filter": lambda d: abs(d.qty) - abs(invoiced_qty_map.get(d.name, 0))<=0
+			"filter": lambda d: get_pending_qty(d)[0]<=0
 		},
 		"Purchase Taxes and Charges": {
 			"doctype": "Purchase Taxes and Charges",
@@ -462,6 +484,31 @@
 
 	return invoiced_qty_map
 
+def get_returned_qty_map_against_po(purchase_orders):
+	"""returns a map: {so_detail: returned_qty}"""
+	returned_qty_map = {}
+
+	for name, returned_qty in frappe.get_all('Purchase Order Item', fields = ["name", "returned_qty"],
+		filters = {'parent': ('in', purchase_orders), 'docstatus': 1}, as_list=1):
+		if not returned_qty_map.get(name):
+				returned_qty_map[name] = 0
+		returned_qty_map[name] += returned_qty
+
+	return returned_qty_map
+
+def get_returned_qty_map_against_pr(purchase_receipt):
+	"""returns a map: {so_detail: returned_qty}"""
+	returned_qty_map = frappe._dict(frappe.db.sql("""select pr_item.item_code, sum(abs(pr_item.qty)) as qty
+		from `tabPurchase Receipt Item` pr_item, `tabPurchase Receipt` pr
+		where pr.name = pr_item.parent
+			and pr.docstatus = 1
+			and pr.is_return = 1
+			and pr.return_against = %s
+		group by pr_item.item_code
+	""", purchase_receipt))
+
+	return returned_qty_map
+
 @frappe.whitelist()
 def make_purchase_return(source_name, target_doc=None):
 	from erpnext.controllers.sales_and_purchase_return import make_return_doc
diff --git a/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py b/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py
index 472083b..c5ae838 100644
--- a/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py
+++ b/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py
@@ -404,6 +404,44 @@
 
 		set_perpetual_inventory(0, pr.company)
 
+	def test_make_purchase_invoice_from_pr_for_returned_qty(self):
+		from erpnext.buying.doctype.purchase_order.test_purchase_order import create_purchase_order, create_pr_against_po
+
+		po = create_purchase_order()
+		pr = create_pr_against_po(po.name)
+
+		pr1 = make_purchase_receipt(is_return=1, return_against=pr.name, qty=-1, do_not_submit=True)
+		pr1.items[0].purchase_order = po.name
+		pr1.items[0].purchase_order_item = po.items[0].name
+		pr1.submit()
+
+		pi = make_purchase_invoice(pr.name)
+		self.assertEquals(pi.items[0].qty, 3)
+
+	def test_make_purchase_invoice_from_dn_with_returned_qty_against_dn(self):
+		pr1 = make_purchase_receipt(qty=8, do_not_submit=True)
+		pr1.append("items", {
+			"item_code": "_Test Item",
+			"warehouse": "_Test Warehouse - _TC",
+			"qty": 1,
+			"received_qty": 1,
+			"rate": 100,
+			"conversion_factor": 1.0,
+		})
+		pr1.submit()
+
+		pi1 = make_purchase_invoice(pr1.name)
+		pi1.items[0].qty = 4
+		pi1.items.pop(1)
+		pi1.save()
+		pi1.submit()
+
+		make_purchase_receipt(is_return=1, return_against=pr1.name, qty=-2)
+
+		pi2 = make_purchase_invoice(pr1.name)
+		self.assertEquals(pi2.items[0].qty, 2)
+		self.assertEquals(pi2.items[1].qty, 1)
+
 def get_gl_entries(voucher_type, voucher_no):
 	return frappe.db.sql("""select account, debit, credit, cost_center
 		from `tabGL Entry` where voucher_type=%s and voucher_no=%s
diff --git a/erpnext/stock/get_item_details.py b/erpnext/stock/get_item_details.py
index 74f3595..7f0e670 100644
--- a/erpnext/stock/get_item_details.py
+++ b/erpnext/stock/get_item_details.py
@@ -490,7 +490,7 @@
 	price_list_rate = get_item_price(item_price_args, item_code)
 	if price_list_rate:
 		desired_qty = args.get("qty")
-		if check_packing_list(price_list_rate[0][0], desired_qty, item_code):
+		if desired_qty and check_packing_list(price_list_rate[0][0], desired_qty, item_code):
 			item_price_data = price_list_rate
 	else:
 		for field in ["customer", "supplier", "min_qty"]:
@@ -521,12 +521,15 @@
 		:param qty: Derised Qt
 	"""
 
+	flag = True
 	item_price = frappe.get_doc("Item Price", price_list_rate_name)
-	if desired_qty and item_price.packing_unit:
+	if item_price.packing_unit:
 		packing_increment = desired_qty % item_price.packing_unit
 
-		if packing_increment == 0:
-			return True
+		if packing_increment != 0:
+			flag = False
+
+	return flag
 
 def validate_price_list(args):
 	if args.get("price_list"):
diff --git a/erpnext/stock/report/total_stock_summary/total_stock_summary.js b/erpnext/stock/report/total_stock_summary/total_stock_summary.js
index 223a603..b7461c4 100644
--- a/erpnext/stock/report/total_stock_summary/total_stock_summary.js
+++ b/erpnext/stock/report/total_stock_summary/total_stock_summary.js
@@ -18,7 +18,9 @@
 			"label": __("Company"),
 			"fieldtype": "Link",
 			"width": "80",
-			"options": "Company"
+			"options": "Company",
+			"default": frappe.defaults.get_user_default("Company"),
+			"reqd": 1
 		},
 	]
 }