Merge pull request #18742 from rohitwaghchaure/incorrect_sequnce_between_name_and_contact

fix: sequence of customer name and contact in the AR report
diff --git a/erpnext/accounts/doctype/payment_entry/payment_entry.py b/erpnext/accounts/doctype/payment_entry/payment_entry.py
index 8c2ea73..8098329 100644
--- a/erpnext/accounts/doctype/payment_entry/payment_entry.py
+++ b/erpnext/accounts/doctype/payment_entry/payment_entry.py
@@ -648,13 +648,18 @@
 
 	orders = []
 	if voucher_type:
-		ref_field = "base_grand_total" if party_account_currency == company_currency else "grand_total"
+		if party_account_currency == company_currency:
+			grand_total_field = "base_grand_total"
+			rounded_total_field = "base_rounded_total"
+		else:
+			grand_total_field = "grand_total"
+			rounded_total_field = "rounded_total"
 
 		orders = frappe.db.sql("""
 			select
 				name as voucher_no,
-				{ref_field} as invoice_amount,
-				({ref_field} - advance_paid) as outstanding_amount,
+				if({rounded_total_field}, {rounded_total_field}, {grand_total_field}) as invoice_amount,
+				(if({rounded_total_field}, {rounded_total_field}, {grand_total_field}) - advance_paid) as outstanding_amount,
 				transaction_date as posting_date
 			from
 				`tab{voucher_type}`
@@ -663,13 +668,14 @@
 				and docstatus = 1
 				and company = %s
 				and ifnull(status, "") != "Closed"
-				and {ref_field} > advance_paid
+				and if({rounded_total_field}, {rounded_total_field}, {grand_total_field}) > advance_paid
 				and abs(100 - per_billed) > 0.01
 				{condition}
 			order by
 				transaction_date, name
 		""".format(**{
-			"ref_field": ref_field,
+			"rounded_total_field": rounded_total_field,
+			"grand_total_field": grand_total_field,
 			"voucher_type": voucher_type,
 			"party_type": scrub(party_type),
 			"condition": condition
@@ -677,8 +683,8 @@
 
 	order_list = []
 	for d in orders:
-		if not (d.outstanding_amount >= filters.get("outstanding_amt_greater_than")
-			and d.outstanding_amount <= filters.get("outstanding_amt_less_than")):
+		if not (flt(d.outstanding_amount) >= flt(filters.get("outstanding_amt_greater_than"))
+			and flt(d.outstanding_amount) <= flt(filters.get("outstanding_amt_less_than"))):
 			continue
 
 		d["voucher_type"] = voucher_type
@@ -755,9 +761,23 @@
 @frappe.whitelist()
 def get_account_details(account, date, cost_center=None):
 	frappe.has_permission('Payment Entry', throw=True)
+
+	# to check if the passed account is accessible under reference doctype Payment Entry
+	account_list = frappe.get_list('Account', {
+		'name': account
+	}, reference_doctype='Payment Entry', limit=1)
+
+	# There might be some user permissions which will allow account under certain doctypes
+	# except for Payment Entry, only in such case we should throw permission error
+	if not account_list:
+		frappe.throw(_('Account: {0} is not permitted under Payment Entry').format(account))
+
+	account_balance = get_balance_on(account, date, cost_center=cost_center,
+		ignore_account_permission=True)
+
 	return frappe._dict({
 		"account_currency": get_account_currency(account),
-		"account_balance": get_balance_on(account, date, cost_center=cost_center),
+		"account_balance": account_balance,
 		"account_type": frappe.db.get_value("Account", account, "account_type")
 	})
 
diff --git a/erpnext/accounts/utils.py b/erpnext/accounts/utils.py
index e1ed642..ac69fd3 100644
--- a/erpnext/accounts/utils.py
+++ b/erpnext/accounts/utils.py
@@ -84,7 +84,8 @@
 			throw(_("{0} '{1}' not in Fiscal Year {2}").format(label, formatdate(date), fiscal_year))
 
 @frappe.whitelist()
-def get_balance_on(account=None, date=None, party_type=None, party=None, company=None, in_account_currency=True, cost_center=None):
+def get_balance_on(account=None, date=None, party_type=None, party=None, company=None,
+	in_account_currency=True, cost_center=None, ignore_account_permission=False):
 	if not account and frappe.form_dict.get("account"):
 		account = frappe.form_dict.get("account")
 	if not date and frappe.form_dict.get("date"):
@@ -140,7 +141,8 @@
 
 	if account:
 
-		if not frappe.flags.ignore_account_permission:
+		if not (frappe.flags.ignore_account_permission
+			or ignore_account_permission):
 			acc.check_permission("read")
 
 		if report_type == 'Profit and Loss':
diff --git a/erpnext/crm/doctype/lead/lead.py b/erpnext/crm/doctype/lead/lead.py
index 9292b3a..c9216ee 100644
--- a/erpnext/crm/doctype/lead/lead.py
+++ b/erpnext/crm/doctype/lead/lead.py
@@ -146,15 +146,14 @@
 @frappe.whitelist()
 def make_opportunity(source_name, target_doc=None):
 	def set_missing_values(source, target):
-		address = frappe.db.exists('Dynamic Link', {
-			'link_doctype': target.doctype,
-			'link_name': target.name,
+		address = frappe.get_all('Dynamic Link', {
+			'link_doctype': source.doctype,
+			'link_name': source.name,
 			'parenttype': 'Address',
-			'disabled': 0
-		})
+		}, ['parent'], limit=1)
 
 		if address:
-			target.customer_address = address
+			target.customer_address = address[0].parent
 
 	target_doc = get_mapped_doc("Lead", source_name,
 		{"Lead": {
diff --git a/erpnext/crm/doctype/opportunity/opportunity.js b/erpnext/crm/doctype/opportunity/opportunity.js
index 90a12b7..ec17629 100644
--- a/erpnext/crm/doctype/opportunity/opportunity.js
+++ b/erpnext/crm/doctype/opportunity/opportunity.js
@@ -31,9 +31,9 @@
 
 	party_name: function(frm) {
 		frm.toggle_display("contact_info", frm.doc.party_name);
+		frm.trigger('set_contact_link');
 
 		if (frm.doc.opportunity_from == "Customer") {
-			frm.trigger('set_contact_link');
 			erpnext.utils.get_party_details(frm);
 		} else if (frm.doc.opportunity_from == "Lead") {
 			erpnext.utils.map_current_doc({
@@ -48,13 +48,6 @@
 		frm.get_field("items").grid.set_multiple_add("item_code", "qty");
 	},
 
-	party_name: function(frm) {
-		if (frm.doc.opportunity_from == "Customer") {
-			frm.trigger('set_contact_link');
-			erpnext.utils.get_party_details(frm);
-		}
-	},
-
 	with_items: function(frm) {
 		frm.trigger('toggle_mandatory');
 	},
diff --git a/erpnext/hr/doctype/payroll_entry/payroll_entry.js b/erpnext/hr/doctype/payroll_entry/payroll_entry.js
index e4ab680..adc0671 100644
--- a/erpnext/hr/doctype/payroll_entry/payroll_entry.js
+++ b/erpnext/hr/doctype/payroll_entry/payroll_entry.js
@@ -69,7 +69,7 @@
 	},
 
 	add_context_buttons: function(frm) {
-		if(frm.doc.salary_slips_submitted) {
+		if(frm.doc.salary_slips_submitted || (frm.doc.__onload && frm.doc.__onload.submitted_ss)) {
 			frm.events.add_bank_entry_button(frm);
 		} else if(frm.doc.salary_slips_created) {
 			frm.add_custom_button(__("Submit Salary Slip"), function() {
diff --git a/erpnext/hr/doctype/payroll_entry/payroll_entry.py b/erpnext/hr/doctype/payroll_entry/payroll_entry.py
index 8803a9a..9b988e0 100644
--- a/erpnext/hr/doctype/payroll_entry/payroll_entry.py
+++ b/erpnext/hr/doctype/payroll_entry/payroll_entry.py
@@ -18,9 +18,8 @@
 
 		# check if salary slips were manually submitted
 		entries = frappe.db.count("Salary Slip", {'payroll_entry': self.name, 'docstatus': 1}, ['name'])
-		if cint(entries) == len(self.employees) and not self.salary_slips_submitted:
-			self.db_set("salary_slips_submitted", 1)
-			self.reload()
+		if cint(entries) == len(self.employees):
+			self.set_onload("submitted_ss", True)
 
 	def on_submit(self):
 		self.create_salary_slips()
@@ -429,7 +428,6 @@
 		'start_date': start_date, 'end_date': end_date
 	})
 
-
 def get_frequency_kwargs(frequency_name):
 	frequency_dict = {
 		'monthly': {'months': 1},
diff --git a/erpnext/patches.txt b/erpnext/patches.txt
index 33d4f55..b6ea542 100644
--- a/erpnext/patches.txt
+++ b/erpnext/patches.txt
@@ -596,6 +596,7 @@
 erpnext.patches.v12_0.move_target_distribution_from_parent_to_child
 erpnext.patches.v12_0.stock_entry_enhancements
 erpnext.patches.v10_0.item_barcode_childtable_migrate # 16-02-2019 #25-06-2019
+erpnext.patches.v12_0.make_item_manufacturer
 erpnext.patches.v12_0.move_item_tax_to_item_tax_template
 erpnext.patches.v11_1.set_variant_based_on
 erpnext.patches.v11_1.woocommerce_set_creation_user
@@ -606,7 +607,6 @@
 erpnext.patches.v12_0.rename_tolerance_fields
 erpnext.patches.v12_0.make_custom_fields_for_bank_remittance #14-06-2019
 execute:frappe.delete_doc_if_exists("Page", "support-analytics")
-erpnext.patches.v12_0.make_item_manufacturer
 erpnext.patches.v12_0.remove_patient_medical_record_page
 erpnext.patches.v11_1.move_customer_lead_to_dynamic_column
 erpnext.patches.v11_1.set_default_action_for_quality_inspection
diff --git a/erpnext/quality_management/doctype/quality_procedure/quality_procedure.json b/erpnext/quality_management/doctype/quality_procedure/quality_procedure.json
index 7b241ef..472b751 100644
--- a/erpnext/quality_management/doctype/quality_procedure/quality_procedure.json
+++ b/erpnext/quality_management/doctype/quality_procedure/quality_procedure.json
@@ -1,11 +1,11 @@
 {
- "autoname": "format:PRC-{procedure}",
+ "autoname": "format:PRC-{quality_procedure_name}",
  "creation": "2018-10-06 00:06:29.756804",
  "doctype": "DocType",
  "editable_grid": 1,
  "engine": "InnoDB",
  "field_order": [
-  "procedure",
+  "quality_procedure_name",
   "parent_quality_procedure",
   "is_group",
   "sb_00",
@@ -62,14 +62,14 @@
    "options": "Quality Procedure Process"
   },
   {
-   "fieldname": "procedure",
+   "fieldname": "quality_procedure_name",
    "fieldtype": "Data",
    "in_list_view": 1,
-   "label": "Procedure",
+   "label": "Quality Procedure",
    "reqd": 1
   }
  ],
- "modified": "2019-05-26 22:11:53.771428",
+ "modified": "2019-08-05 13:09:29.945082",
  "modified_by": "Administrator",
  "module": "Quality Management",
  "name": "Quality Procedure",
diff --git a/erpnext/quality_management/doctype/quality_procedure/quality_procedure.py b/erpnext/quality_management/doctype/quality_procedure/quality_procedure.py
index 52c3320..4d3c522 100644
--- a/erpnext/quality_management/doctype/quality_procedure/quality_procedure.py
+++ b/erpnext/quality_management/doctype/quality_procedure/quality_procedure.py
@@ -36,12 +36,10 @@
 			doc.load_from_db()
 
 			for process in doc.processes:
-				if process.procedure:
-					flag_is_group = 1
+				flag_is_group = 1 if process.procedure else 0
 
-			if flag_is_group == 0:
-				doc.is_group = 0
-				doc.save(ignore_permissions=True)
+			doc.is_group = 0 if flag_is_group == 0 else 1
+			doc.save(ignore_permissions=True)
 
 	def set_parent(self):
 		for process in self.processes:
diff --git a/erpnext/quality_management/doctype/quality_procedure/quality_procedure_tree.js b/erpnext/quality_management/doctype/quality_procedure/quality_procedure_tree.js
index 15b7784..8fd785f 100644
--- a/erpnext/quality_management/doctype/quality_procedure/quality_procedure_tree.js
+++ b/erpnext/quality_management/doctype/quality_procedure/quality_procedure_tree.js
@@ -6,8 +6,8 @@
 	add_tree_node: 'erpnext.quality_management.doctype.quality_procedure.quality_procedure.add_node',
 	filters: [
 		{
-			fieldname: "Quality Procedure",
-			fieldtype:"Link",
+			fieldname: "quality_procedure",
+			fieldtype: "Link",
 			options: "Quality Procedure",
 			label: __("Quality Procedure"),
 			get_query: function() {
@@ -19,7 +19,7 @@
 	],
 	breadcrumb: "Setup",
 	root_label: "All Quality Procedures",
-	get_tree_root: false,
+	get_tree_root: true,
 	menu_items: [
 		{
 			label: __("New Quality Procedure"),
@@ -32,8 +32,4 @@
 	onload: function(treeview) {
 		treeview.make_tree();
 	},
-	onrender: function() {
-		$("button:contains('Add Child')").remove();
-		$("button:contains('New')").remove();
-	}
 };
\ No newline at end of file
diff --git a/erpnext/quality_management/doctype/quality_procedure/test_quality_procedure.py b/erpnext/quality_management/doctype/quality_procedure/test_quality_procedure.py
index 79f8771..3289bb5 100644
--- a/erpnext/quality_management/doctype/quality_procedure/test_quality_procedure.py
+++ b/erpnext/quality_management/doctype/quality_procedure/test_quality_procedure.py
@@ -18,7 +18,7 @@
 def create_procedure():
 	procedure = frappe.get_doc({
 		"doctype": "Quality Procedure",
-		"procedure": "_Test Quality Procedure",
+		"quality_procedure_name": "_Test Quality Procedure",
 		"processes": [
 			{
 				"process_description": "_Test Quality Procedure Table",
@@ -37,7 +37,7 @@
 def create_nested_procedure():
 	nested_procedure = frappe.get_doc({
 		"doctype": "Quality Procedure",
-		"procedure": "_Test Nested Quality Procedure",
+		"quality_procedure_name": "_Test Nested Quality Procedure",
 		"processes": [
 			{
 				"procedure": "PRC-_Test Quality Procedure"
diff --git a/erpnext/setup/doctype/company/company.py b/erpnext/setup/doctype/company/company.py
index da29d20..4b34dc1 100644
--- a/erpnext/setup/doctype/company/company.py
+++ b/erpnext/setup/doctype/company/company.py
@@ -252,7 +252,7 @@
 	def set_mode_of_payment_account(self):
 		cash = frappe.db.get_value('Mode of Payment', {'type': 'Cash'}, 'name')
 		if cash and self.default_cash_account \
-				and not frappe.db.get_value('Mode of Payment Account', {'company': self.name, 'parent': 'Cash'}):
+				and not frappe.db.get_value('Mode of Payment Account', {'company': self.name, 'parent': cash}):
 			mode_of_payment = frappe.get_doc('Mode of Payment', cash)
 			mode_of_payment.append('accounts', {
 				'company': self.name,
diff --git a/erpnext/stock/doctype/quality_inspection/quality_inspection.js b/erpnext/stock/doctype/quality_inspection/quality_inspection.js
index aa9854a..22f29e0 100644
--- a/erpnext/stock/doctype/quality_inspection/quality_inspection.js
+++ b/erpnext/stock/doctype/quality_inspection/quality_inspection.js
@@ -39,11 +39,12 @@
 			query: "erpnext.stock.doctype.quality_inspection.quality_inspection.item_query",
 			filters: {
 				"from": doctype,
-				"parent": doc.reference_name
+				"parent": doc.reference_name,
+				"inspection_type": doc.inspection_type
 			}
-		}
+		};
 	}
-}
+},
 
 // Serial No based on item_code
 cur_frm.fields_dict['item_serial_no'].get_query = function(doc, cdt, cdn) {
diff --git a/erpnext/stock/doctype/quality_inspection/quality_inspection.py b/erpnext/stock/doctype/quality_inspection/quality_inspection.py
index e0b7382..738c63c 100644
--- a/erpnext/stock/doctype/quality_inspection/quality_inspection.py
+++ b/erpnext/stock/doctype/quality_inspection/quality_inspection.py
@@ -63,10 +63,12 @@
 		mcond = get_match_cond(filters["from"])
 		cond, qi_condition = "", "and (quality_inspection is null or quality_inspection = '')"
 
-		if filters.get('from') in ['Purchase Invoice Item', 'Purchase Receipt Item']:
+		if filters.get('from') in ['Purchase Invoice Item', 'Purchase Receipt Item']\
+				and filters.get("inspection_type") != "In Process":
 			cond = """and item_code in (select name from `tabItem` where
 				inspection_required_before_purchase = 1)"""
-		elif filters.get('from') in ['Sales Invoice Item', 'Delivery Note Item']:
+		elif filters.get('from') in ['Sales Invoice Item', 'Delivery Note Item']\
+				and filters.get("inspection_type") != "In Process":
 			cond = """and item_code in (select name from `tabItem` where
 				inspection_required_before_delivery = 1)"""
 		elif filters.get('from') == 'Stock Entry Detail':