Merge branch 'develop' into pr-return-ux
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
index 511b682..1cf9a5b 100644
--- a/.github/CONTRIBUTING.md
+++ b/.github/CONTRIBUTING.md
@@ -23,7 +23,7 @@
 1. **Steps to Reproduce:** The bug report must have a list of steps needed to reproduce a bug. If we cannot reproduce it, then we cannot solve it.
 1. **Version Number:** Please add the version number in your report. Often a bug is fixed in the latest version
 1. **Clear Title:** Add a clear subject to your bug report like "Unable to submit Purchase Order without Basic Rate" instead of just "Cannot Submit"
-1. **Screenshots:** Screenshots are a great way of communicating the issues. Try adding annotations or using LiceCAP to take a screencast in `gif`.
+1. **Screenshots:** Screenshots are a great way of communicating issues. Try adding annotations or using LiceCAP to take a screencast in `gif`.
 
 ### Feature Request Guidelines
 
diff --git a/.github/workflows/patch.yml b/.github/workflows/patch.yml
index f8abb6c..97bccf5 100644
--- a/.github/workflows/patch.yml
+++ b/.github/workflows/patch.yml
@@ -93,7 +93,7 @@
           for version in $(seq 12 13)
           do
               echo "Updating to v$version"
-              branch_name="version-$version"
+              branch_name="version-$version-hotfix"
 
               git -C "apps/frappe" fetch --depth 1 upstream $branch_name:$branch_name
               git -C "apps/erpnext" fetch --depth 1 upstream $branch_name:$branch_name
diff --git a/README.md b/README.md
index 1105a97..9609353 100644
--- a/README.md
+++ b/README.md
@@ -8,6 +8,7 @@
 [![CI](https://github.com/frappe/erpnext/actions/workflows/server-tests.yml/badge.svg?branch=develop)](https://github.com/frappe/erpnext/actions/workflows/server-tests.yml)
 [![Open Source Helpers](https://www.codetriage.com/frappe/erpnext/badges/users.svg)](https://www.codetriage.com/frappe/erpnext)
 [![codecov](https://codecov.io/gh/frappe/erpnext/branch/develop/graph/badge.svg?token=0TwvyUg3I5)](https://codecov.io/gh/frappe/erpnext)
+[![docker pulls](https://img.shields.io/docker/pulls/frappe/erpnext-worker.svg)](https://hub.docker.com/r/frappe/erpnext-worker)
 
 [https://erpnext.com](https://erpnext.com)
 
diff --git a/erpnext/accounts/doctype/accounting_dimension_filter/accounting_dimension_filter.js b/erpnext/accounts/doctype/accounting_dimension_filter/accounting_dimension_filter.js
index 9dd882a..750e129 100644
--- a/erpnext/accounts/doctype/accounting_dimension_filter/accounting_dimension_filter.js
+++ b/erpnext/accounts/doctype/accounting_dimension_filter/accounting_dimension_filter.js
@@ -8,7 +8,7 @@
 		}
 
 		let help_content =
-			`<table class="table table-bordered" style="background-color: #f9f9f9;">
+			`<table class="table table-bordered" style="background-color: var(--scrollbar-track-color);">
 				<tr><td>
 					<p>
 						<i class="fa fa-hand-right"></i>
diff --git a/erpnext/accounts/doctype/bank_reconciliation_tool/bank_reconciliation_tool.py b/erpnext/accounts/doctype/bank_reconciliation_tool/bank_reconciliation_tool.py
index 002e312..5cbf00b 100644
--- a/erpnext/accounts/doctype/bank_reconciliation_tool/bank_reconciliation_tool.py
+++ b/erpnext/accounts/doctype/bank_reconciliation_tool/bank_reconciliation_tool.py
@@ -342,7 +342,15 @@
 
 def get_je_matching_query(amount_condition, transaction):
 	# get matching journal entry query
-	cr_or_dr = "credit" if transaction.withdrawal > 0 else "debit"
+
+	company_account = frappe.get_value("Bank Account", transaction.bank_account, "account")
+	root_type = frappe.get_value("Account", company_account, "root_type")
+
+	if root_type == "Liability":
+		cr_or_dr = "debit" if transaction.withdrawal > 0 else "credit"
+	else:
+		cr_or_dr = "credit" if transaction.withdrawal > 0 else "debit"
+
 	return f"""
 
 		SELECT
diff --git a/erpnext/accounts/doctype/loyalty_program/loyalty_program.js b/erpnext/accounts/doctype/loyalty_program/loyalty_program.js
index f90f867..6951b2a 100644
--- a/erpnext/accounts/doctype/loyalty_program/loyalty_program.js
+++ b/erpnext/accounts/doctype/loyalty_program/loyalty_program.js
@@ -6,7 +6,7 @@
 frappe.ui.form.on('Loyalty Program', {
 	setup: function(frm) {
 		var help_content =
-			`<table class="table table-bordered" style="background-color: #f9f9f9;">
+			`<table class="table table-bordered" style="background-color: var(--scrollbar-track-color);">
 				<tr><td>
 					<h4>
 						<i class="fa fa-hand-right"></i>
diff --git a/erpnext/accounts/doctype/pricing_rule/pricing_rule.js b/erpnext/accounts/doctype/pricing_rule/pricing_rule.js
index d79ad5f..8267582 100644
--- a/erpnext/accounts/doctype/pricing_rule/pricing_rule.js
+++ b/erpnext/accounts/doctype/pricing_rule/pricing_rule.js
@@ -38,7 +38,7 @@
 
 	refresh: function(frm) {
 		var help_content =
-			`<table class="table table-bordered" style="background-color: #f9f9f9;">
+			`<table class="table table-bordered" style="background-color: var(--scrollbar-track-color);">
 				<tr><td>
 					<h4>
 						<i class="fa fa-hand-right"></i>
diff --git a/erpnext/accounts/doctype/promotional_scheme/promotional_scheme.py b/erpnext/accounts/doctype/promotional_scheme/promotional_scheme.py
index e3fac07..5fbe93e 100644
--- a/erpnext/accounts/doctype/promotional_scheme/promotional_scheme.py
+++ b/erpnext/accounts/doctype/promotional_scheme/promotional_scheme.py
@@ -20,6 +20,9 @@
 product_discount_fields = ['free_item', 'free_qty', 'free_item_uom',
 	'free_item_rate', 'same_item', 'is_recursive', 'apply_multiple_pricing_rules']
 
+class TransactionExists(frappe.ValidationError):
+	pass
+
 class PromotionalScheme(Document):
 	def validate(self):
 		if not self.selling and not self.buying:
@@ -28,6 +31,40 @@
 			or self.product_discount_slabs):
 			frappe.throw(_("Price or product discount slabs are required"))
 
+		self.validate_applicable_for()
+		self.validate_pricing_rules()
+
+	def validate_applicable_for(self):
+		if self.applicable_for:
+			applicable_for = frappe.scrub(self.applicable_for)
+
+			if not self.get(applicable_for):
+				msg = (f'The field {frappe.bold(self.applicable_for)} is required')
+				frappe.throw(_(msg))
+
+	def validate_pricing_rules(self):
+		if self.is_new():
+			return
+
+		transaction_exists = False
+		docnames = []
+
+		# If user has changed applicable for
+		if self._doc_before_save.applicable_for == self.applicable_for:
+			return
+
+		docnames = frappe.get_all('Pricing Rule',
+			filters= {'promotional_scheme': self.name})
+
+		for docname in docnames:
+			if frappe.db.exists('Pricing Rule Detail',
+				{'pricing_rule': docname.name, 'docstatus': ('<', 2)}):
+				raise_for_transaction_exists(self.name)
+
+		if docnames and not transaction_exists:
+			for docname in docnames:
+				frappe.delete_doc('Pricing Rule', docname.name)
+
 	def on_update(self):
 		pricing_rules = frappe.get_all(
 			'Pricing Rule',
@@ -67,6 +104,13 @@
 			{'promotional_scheme': self.name}):
 			frappe.delete_doc('Pricing Rule', rule.name)
 
+def raise_for_transaction_exists(name):
+	msg = (f"""You can't change the {frappe.bold(_('Applicable For'))}
+		because transactions are present against the Promotional Scheme {frappe.bold(name)}. """)
+	msg += 'Kindly disable this Promotional Scheme and create new for new Applicable For.'
+
+	frappe.throw(_(msg), TransactionExists)
+
 def get_pricing_rules(doc, rules=None):
 	if rules is None:
 		rules = {}
@@ -84,45 +128,59 @@
 	new_doc = []
 	args = get_args_for_pricing_rule(doc)
 	applicable_for = frappe.scrub(doc.get('applicable_for'))
+
 	for idx, d in enumerate(doc.get(child_doc)):
 		if d.name in rules:
-			for applicable_for_value in args.get(applicable_for):
-				temp_args = args.copy()
-				docname = frappe.get_all(
-					'Pricing Rule',
-					fields = ["promotional_scheme_id", "name", applicable_for],
-					filters = {
-						'promotional_scheme_id': d.name,
-						applicable_for: applicable_for_value
-					}
-				)
-
-				if docname:
-					pr = frappe.get_doc('Pricing Rule', docname[0].get('name'))
-					temp_args[applicable_for] = applicable_for_value
-					pr = set_args(temp_args, pr, doc, child_doc, discount_fields, d)
-				else:
-					pr = frappe.new_doc("Pricing Rule")
-					pr.title = doc.name
-					temp_args[applicable_for] = applicable_for_value
-					pr = set_args(temp_args, pr, doc, child_doc, discount_fields, d)
-
+			if not args.get(applicable_for):
+				docname = get_pricing_rule_docname(d)
+				pr = prepare_pricing_rule(args, doc, child_doc, discount_fields, d, docname)
 				new_doc.append(pr)
+			else:
+				for applicable_for_value in args.get(applicable_for):
+					docname = get_pricing_rule_docname(d, applicable_for, applicable_for_value)
+					pr = prepare_pricing_rule(args, doc, child_doc, discount_fields,
+						d, docname, applicable_for, applicable_for_value)
+					new_doc.append(pr)
 
-		else:
+		elif args.get(applicable_for):
 			applicable_for_values = args.get(applicable_for) or []
 			for applicable_for_value in applicable_for_values:
-				pr = frappe.new_doc("Pricing Rule")
-				pr.title = doc.name
-				temp_args = args.copy()
-				temp_args[applicable_for] = applicable_for_value
-				pr = set_args(temp_args, pr, doc, child_doc, discount_fields, d)
+				pr = prepare_pricing_rule(args, doc, child_doc, discount_fields,
+					d, applicable_for=applicable_for, value= applicable_for_value)
+
 				new_doc.append(pr)
+		else:
+			pr = prepare_pricing_rule(args, doc, child_doc, discount_fields, d)
+			new_doc.append(pr)
 
 	return new_doc
 
+def get_pricing_rule_docname(row: dict, applicable_for: str = None, applicable_for_value: str = None) -> str:
+	fields = ['promotional_scheme_id', 'name']
+	filters = {
+		'promotional_scheme_id': row.name
+	}
 
+	if applicable_for:
+		fields.append(applicable_for)
+		filters[applicable_for] = applicable_for_value
 
+	docname = frappe.get_all('Pricing Rule', fields = fields, filters = filters)
+	return docname[0].name if docname else ''
+
+def prepare_pricing_rule(args, doc, child_doc, discount_fields, d, docname=None, applicable_for=None, value=None):
+	if docname:
+		pr = frappe.get_doc("Pricing Rule", docname)
+	else:
+		pr = frappe.new_doc("Pricing Rule")
+
+	pr.title = doc.name
+	temp_args = args.copy()
+
+	if value:
+		temp_args[applicable_for] = value
+
+	return set_args(temp_args, pr, doc, child_doc, discount_fields, d)
 
 def set_args(args, pr, doc, child_doc, discount_fields, child_doc_fields):
 	pr.update(args)
@@ -145,6 +203,7 @@
 				apply_on: d.get(apply_on),
 				'uom': d.uom
 			})
+
 	return pr
 
 def get_args_for_pricing_rule(doc):
diff --git a/erpnext/accounts/doctype/promotional_scheme/test_promotional_scheme.py b/erpnext/accounts/doctype/promotional_scheme/test_promotional_scheme.py
index e1852ae..49192a4 100644
--- a/erpnext/accounts/doctype/promotional_scheme/test_promotional_scheme.py
+++ b/erpnext/accounts/doctype/promotional_scheme/test_promotional_scheme.py
@@ -5,10 +5,17 @@
 
 import frappe
 
+from erpnext.accounts.doctype.promotional_scheme.promotional_scheme import TransactionExists
+from erpnext.selling.doctype.sales_order.test_sales_order import make_sales_order
+
 
 class TestPromotionalScheme(unittest.TestCase):
+	def setUp(self):
+		if frappe.db.exists('Promotional Scheme', '_Test Scheme'):
+			frappe.delete_doc('Promotional Scheme', '_Test Scheme')
+
 	def test_promotional_scheme(self):
-		ps = make_promotional_scheme()
+		ps = make_promotional_scheme(applicable_for='Customer', customer='_Test Customer')
 		price_rules = frappe.get_all('Pricing Rule', fields = ["promotional_scheme_id", "name", "creation"],
 			filters = {'promotional_scheme': ps.name})
 		self.assertTrue(len(price_rules),1)
@@ -39,22 +46,62 @@
 			filters = {'promotional_scheme': ps.name})
 		self.assertEqual(price_rules, [])
 
-def make_promotional_scheme():
+	def test_promotional_scheme_without_applicable_for(self):
+		ps = make_promotional_scheme()
+		price_rules = frappe.get_all('Pricing Rule', filters = {'promotional_scheme': ps.name})
+
+		self.assertTrue(len(price_rules), 1)
+		frappe.delete_doc('Promotional Scheme', ps.name)
+
+		price_rules = frappe.get_all('Pricing Rule', filters = {'promotional_scheme': ps.name})
+		self.assertEqual(price_rules, [])
+
+	def test_change_applicable_for_in_promotional_scheme(self):
+		ps = make_promotional_scheme()
+		price_rules = frappe.get_all('Pricing Rule', filters = {'promotional_scheme': ps.name})
+		self.assertTrue(len(price_rules), 1)
+
+		so = make_sales_order(qty=5, currency='USD', do_not_save=True)
+		so.set_missing_values()
+		so.save()
+		self.assertEqual(price_rules[0].name, so.pricing_rules[0].pricing_rule)
+
+		ps.applicable_for = 'Customer'
+		ps.append('customer', {
+			'customer': '_Test Customer'
+		})
+
+		self.assertRaises(TransactionExists, ps.save)
+
+		frappe.delete_doc('Sales Order', so.name)
+		frappe.delete_doc('Promotional Scheme', ps.name)
+		price_rules = frappe.get_all('Pricing Rule', filters = {'promotional_scheme': ps.name})
+		self.assertEqual(price_rules, [])
+
+def make_promotional_scheme(**args):
+	args = frappe._dict(args)
+
 	ps = frappe.new_doc('Promotional Scheme')
 	ps.name = '_Test Scheme'
 	ps.append('items',{
 		'item_code': '_Test Item'
 	})
+
 	ps.selling = 1
 	ps.append('price_discount_slabs',{
 		'min_qty': 4,
+		'validate_applied_rule': 0,
 		'discount_percentage': 20,
 		'rule_description': 'Test'
 	})
-	ps.applicable_for = 'Customer'
-	ps.append('customer',{
-		'customer': "_Test Customer"
-	})
+
+	ps.company = '_Test Company'
+	if args.applicable_for:
+		ps.applicable_for = args.applicable_for
+		ps.append(frappe.scrub(args.applicable_for), {
+			frappe.scrub(args.applicable_for): args.get(frappe.scrub(args.applicable_for))
+		})
+
 	ps.save()
 
 	return ps
diff --git a/erpnext/accounts/doctype/promotional_scheme_price_discount/promotional_scheme_price_discount.json b/erpnext/accounts/doctype/promotional_scheme_price_discount/promotional_scheme_price_discount.json
index a70d5c9..aa3696d 100644
--- a/erpnext/accounts/doctype/promotional_scheme_price_discount/promotional_scheme_price_discount.json
+++ b/erpnext/accounts/doctype/promotional_scheme_price_discount/promotional_scheme_price_discount.json
@@ -136,7 +136,7 @@
    "label": "Threshold for Suggestion"
   },
   {
-   "default": "1",
+   "default": "0",
    "fieldname": "validate_applied_rule",
    "fieldtype": "Check",
    "label": "Validate Applied Rule"
@@ -169,7 +169,7 @@
  "index_web_pages_for_search": 1,
  "istable": 1,
  "links": [],
- "modified": "2021-08-19 15:49:29.598727",
+ "modified": "2021-11-16 00:25:33.843996",
  "modified_by": "Administrator",
  "module": "Accounts",
  "name": "Promotional Scheme Price Discount",
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
index 3526e48..1a398ab 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
@@ -592,8 +592,17 @@
 		erpnext.accounts.dimensions.update_dimension(frm, frm.doctype);
 
 		if (frm.doc.company) {
-			frappe.db.get_value('Company', frm.doc.company, 'default_payable_account', (r) => {
-				frm.set_value('credit_to', r.default_payable_account);
+			frappe.call({
+				method:
+					"erpnext.accounts.party.get_party_account",
+				args: {
+					party_type: 'Supplier',
+					party: frm.doc.supplier,
+					company: frm.doc.company
+				},
+				callback: (response) => {
+					if (response) frm.set_value("credit_to", response.message);
+				},
 			});
 		}
 	},
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
index bee153b..a1f3ee4 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
@@ -15,8 +15,17 @@
 
 		let me = this;
 		if (this.frm.doc.company) {
-			frappe.db.get_value('Company', this.frm.doc.company, 'default_receivable_account', (r) => {
-				me.frm.set_value('debit_to', r.default_receivable_account);
+			frappe.call({
+				method:
+					"erpnext.accounts.party.get_party_account",
+				args: {
+					party_type: 'Customer',
+					party: this.frm.doc.customer,
+					company: this.frm.doc.company
+				},
+				callback: (response) => {
+					if (response) me.frm.set_value("debit_to", response.message);
+				},
 			});
 		}
 	}
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
index cd270f5..59d46fc 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
@@ -2029,7 +2029,7 @@
 			mpa.parent = mp.name and
 			mpa.company = %s and
 			mp.enabled = 1 and
-			mp.name in (%s)
+			mp.name in %s
 		group by
 			mp.name
 		""", (company, mode_of_payments), as_dict=1)
diff --git a/erpnext/accounts/doctype/subscription/subscription.py b/erpnext/accounts/doctype/subscription/subscription.py
index 63b714e..1dae87f 100644
--- a/erpnext/accounts/doctype/subscription/subscription.py
+++ b/erpnext/accounts/doctype/subscription/subscription.py
@@ -519,8 +519,6 @@
 		2. Change the `Subscription` status to 'Past Due Date'
 		3. Change the `Subscription` status to 'Cancelled'
 		"""
-		if getdate() > getdate(self.current_invoice_end) and self.is_prepaid_to_invoice():
-			self.update_subscription_period(add_days(self.current_invoice_end, 1))
 
 		if not self.is_current_invoice_generated(self.current_invoice_start, self.current_invoice_end) \
 			and (self.is_postpaid_to_invoice() or self.is_prepaid_to_invoice()):
@@ -528,6 +526,9 @@
 			prorate = frappe.db.get_single_value('Subscription Settings', 'prorate')
 			self.generate_invoice(prorate)
 
+		if getdate() > getdate(self.current_invoice_end) and self.is_prepaid_to_invoice():
+			self.update_subscription_period(add_days(self.current_invoice_end, 1))
+
 		if self.cancel_at_period_end and getdate() > getdate(self.current_invoice_end):
 			self.cancel_subscription_at_period_end()
 
diff --git a/erpnext/accounts/party.py b/erpnext/accounts/party.py
index 2108bc1..e904768 100644
--- a/erpnext/accounts/party.py
+++ b/erpnext/accounts/party.py
@@ -83,7 +83,8 @@
 	if party_type=="Customer":
 		party_details["sales_team"] = [{
 			"sales_person": d.sales_person,
-			"allocated_percentage": d.allocated_percentage or None
+			"allocated_percentage": d.allocated_percentage or None,
+			"commission_rate": d.commission_rate
 		} for d in party.get("sales_team")]
 
 	# supplier tax withholding category
@@ -218,7 +219,7 @@
 	return out
 
 @frappe.whitelist()
-def get_party_account(party_type, party, company=None):
+def get_party_account(party_type, party=None, company=None):
 	"""Returns the account for the given `party`.
 		Will first search in party (Customer / Supplier) record, if not found,
 		will search in group (Customer Group / Supplier Group),
@@ -226,8 +227,11 @@
 	if not company:
 		frappe.throw(_("Please select a Company"))
 
-	if not party:
-		return
+	if not party and party_type in ['Customer', 'Supplier']:
+		default_account_name = "default_receivable_account" \
+			if party_type=="Customer" else "default_payable_account"
+
+		return frappe.get_cached_value('Company',  company,  default_account_name)
 
 	account = frappe.db.get_value("Party Account",
 		{"parenttype": party_type, "parent": party, "company": company}, "account")
diff --git a/erpnext/accounts/report/financial_statements.py b/erpnext/accounts/report/financial_statements.py
index 4bb44b3..1e89b65 100644
--- a/erpnext/accounts/report/financial_statements.py
+++ b/erpnext/accounts/report/financial_statements.py
@@ -420,8 +420,7 @@
 			{additional_conditions}
 			and posting_date <= %(to_date)s
 			and is_cancelled = 0
-			{distributed_cost_center_query}
-			order by account, posting_date""".format(
+			{distributed_cost_center_query}""".format(
 				additional_conditions=additional_conditions,
 				distributed_cost_center_query=distributed_cost_center_query), gl_filters, as_dict=True) #nosec
 
diff --git a/erpnext/accounts/report/general_ledger/general_ledger.py b/erpnext/accounts/report/general_ledger/general_ledger.py
index 050403d..385c8b2 100644
--- a/erpnext/accounts/report/general_ledger/general_ledger.py
+++ b/erpnext/accounts/report/general_ledger/general_ledger.py
@@ -6,7 +6,7 @@
 
 import frappe
 from frappe import _, _dict
-from frappe.utils import cstr, flt, getdate
+from frappe.utils import cstr, getdate
 
 from erpnext import get_company_currency, get_default_company
 from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import (
@@ -17,6 +17,8 @@
 from erpnext.accounts.report.utils import convert_to_presentation_currency, get_currency
 from erpnext.accounts.utils import get_account_currency
 
+# to cache translations
+TRANSLATIONS = frappe._dict()
 
 def execute(filters=None):
 	if not filters:
@@ -42,10 +44,20 @@
 
 	columns = get_columns(filters)
 
+	update_translations()
+
 	res = get_result(filters, account_details)
 
 	return columns, res
 
+def update_translations():
+	TRANSLATIONS.update(
+		dict(
+			OPENING = _('Opening'),
+			TOTAL = _('Total'),
+			CLOSING_TOTAL = _('Closing (Opening + Total)')
+		)
+	)
 
 def validate_filters(filters, account_details):
 	if not filters.get("company"):
@@ -351,9 +363,9 @@
 			credit_in_account_currency=0.0
 		)
 	return _dict(
-		opening = _get_debit_credit_dict(_('Opening')),
-		total = _get_debit_credit_dict(_('Total')),
-		closing = _get_debit_credit_dict(_('Closing (Opening + Total)'))
+		opening = _get_debit_credit_dict(TRANSLATIONS.OPENING),
+		total = _get_debit_credit_dict(TRANSLATIONS.TOTAL),
+		closing = _get_debit_credit_dict(TRANSLATIONS.CLOSING_TOTAL)
 	)
 
 def group_by_field(group_by):
@@ -378,22 +390,23 @@
 	entries = []
 	consolidated_gle = OrderedDict()
 	group_by = group_by_field(filters.get('group_by'))
+	group_by_voucher_consolidated = filters.get("group_by") == 'Group by Voucher (Consolidated)'
 
 	if filters.get('show_net_values_in_party_account'):
 		account_type_map = get_account_type_map(filters.get('company'))
 
 	def update_value_in_dict(data, key, gle):
-		data[key].debit += flt(gle.debit)
-		data[key].credit += flt(gle.credit)
+		data[key].debit += gle.debit
+		data[key].credit += gle.credit
 
-		data[key].debit_in_account_currency += flt(gle.debit_in_account_currency)
-		data[key].credit_in_account_currency += flt(gle.credit_in_account_currency)
+		data[key].debit_in_account_currency += gle.debit_in_account_currency
+		data[key].credit_in_account_currency += gle.credit_in_account_currency
 
 		if filters.get('show_net_values_in_party_account') and \
 			account_type_map.get(data[key].account) in ('Receivable', 'Payable'):
-			net_value = flt(data[key].debit) - flt(data[key].credit)
-			net_value_in_account_currency = flt(data[key].debit_in_account_currency) \
-				- flt(data[key].credit_in_account_currency)
+			net_value = data[key].debit - data[key].credit
+			net_value_in_account_currency = data[key].debit_in_account_currency \
+				- data[key].credit_in_account_currency
 
 			if net_value < 0:
 				dr_or_cr = 'credit'
@@ -411,19 +424,29 @@
 			data[key].against_voucher += ', ' + gle.against_voucher
 
 	from_date, to_date = getdate(filters.from_date), getdate(filters.to_date)
-	for gle in gl_entries:
-		if (gle.posting_date < from_date or
-			(cstr(gle.is_opening) == "Yes" and not filters.get("show_opening_entries"))):
-			update_value_in_dict(gle_map[gle.get(group_by)].totals, 'opening', gle)
-			update_value_in_dict(totals, 'opening', gle)
+	show_opening_entries = filters.get("show_opening_entries")
 
-			update_value_in_dict(gle_map[gle.get(group_by)].totals, 'closing', gle)
+	for gle in gl_entries:
+		group_by_value = gle.get(group_by)
+
+		if (gle.posting_date < from_date or (cstr(gle.is_opening) == "Yes" and not show_opening_entries)):
+			if not group_by_voucher_consolidated:
+				update_value_in_dict(gle_map[group_by_value].totals, 'opening', gle)
+				update_value_in_dict(gle_map[group_by_value].totals, 'closing', gle)
+
+			update_value_in_dict(totals, 'opening', gle)
 			update_value_in_dict(totals, 'closing', gle)
 
 		elif gle.posting_date <= to_date:
-			if filters.get("group_by") != 'Group by Voucher (Consolidated)':
-				gle_map[gle.get(group_by)].entries.append(gle)
-			elif filters.get("group_by") == 'Group by Voucher (Consolidated)':
+			if not group_by_voucher_consolidated:
+				update_value_in_dict(gle_map[group_by_value].totals, 'total', gle)
+				update_value_in_dict(gle_map[group_by_value].totals, 'closing', gle)
+				update_value_in_dict(totals, 'total', gle)
+				update_value_in_dict(totals, 'closing', gle)
+
+				gle_map[group_by_value].entries.append(gle)
+
+			elif group_by_voucher_consolidated:
 				keylist = [gle.get("voucher_type"), gle.get("voucher_no"), gle.get("account")]
 				for dim in accounting_dimensions:
 					keylist.append(gle.get(dim))
@@ -435,9 +458,7 @@
 					update_value_in_dict(consolidated_gle, key, gle)
 
 	for key, value in consolidated_gle.items():
-		update_value_in_dict(gle_map[value.get(group_by)].totals, 'total', value)
 		update_value_in_dict(totals, 'total', value)
-		update_value_in_dict(gle_map[value.get(group_by)].totals, 'closing', value)
 		update_value_in_dict(totals, 'closing', value)
 		entries.append(value)
 
diff --git a/erpnext/buying/doctype/supplier_scorecard_criteria/supplier_scorecard_criteria.json b/erpnext/buying/doctype/supplier_scorecard_criteria/supplier_scorecard_criteria.json
index 2623585..3668b25 100644
--- a/erpnext/buying/doctype/supplier_scorecard_criteria/supplier_scorecard_criteria.json
+++ b/erpnext/buying/doctype/supplier_scorecard_criteria/supplier_scorecard_criteria.json
@@ -1,184 +1,70 @@
 {
- "allow_copy": 0, 
- "allow_guest_to_view": 0, 
- "allow_import": 0, 
- "allow_rename": 0, 
- "autoname": "field:criteria_name", 
- "beta": 0, 
- "creation": "2017-05-29 01:32:43.064891", 
- "custom": 0, 
- "docstatus": 0, 
- "doctype": "DocType", 
- "document_type": "", 
- "editable_grid": 1, 
- "engine": "InnoDB", 
+ "actions": [],
+ "allow_rename": 1,
+ "autoname": "field:criteria_name",
+ "creation": "2017-05-29 01:32:43.064891",
+ "doctype": "DocType",
+ "editable_grid": 1,
+ "engine": "InnoDB",
+ "field_order": [
+  "criteria_name",
+  "max_score",
+  "formula",
+  "weight"
+ ],
  "fields": [
   {
-   "allow_bulk_edit": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "criteria_name", 
-   "fieldtype": "Data", 
-   "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": "Criteria Name", 
-   "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, 
+   "fieldname": "criteria_name",
+   "fieldtype": "Data",
+   "label": "Criteria Name",
+   "reqd": 1,
    "unique": 1
-  }, 
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "default": "100", 
-   "fieldname": "max_score", 
-   "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": "Max Score", 
-   "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
-  }, 
+   "default": "100",
+   "fieldname": "max_score",
+   "fieldtype": "Float",
+   "in_list_view": 1,
+   "label": "Max Score",
+   "reqd": 1
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "formula", 
-   "fieldtype": "Small Text", 
-   "hidden": 0, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 1, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 1, 
-   "in_standard_filter": 0, 
-   "label": "Criteria Formula", 
-   "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
-  }, 
+   "fieldname": "formula",
+   "fieldtype": "Small Text",
+   "ignore_xss_filter": 1,
+   "in_list_view": 1,
+   "label": "Criteria Formula",
+   "reqd": 1
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "weight", 
-   "fieldtype": "Percent", 
-   "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": "Criteria Weight", 
-   "length": 0, 
-   "no_copy": 0, 
-   "permlevel": 0, 
-   "precision": "", 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 0, 
-   "search_index": 0, 
-   "set_only_once": 0, 
-   "unique": 0
+   "fieldname": "weight",
+   "fieldtype": "Percent",
+   "label": "Criteria Weight"
   }
- ], 
- "has_web_view": 0, 
- "hide_heading": 0, 
- "hide_toolbar": 0, 
- "idx": 0, 
- "image_view": 0, 
- "in_create": 0, 
- "is_submittable": 0, 
- "issingle": 0, 
- "istable": 0, 
- "max_attachments": 0, 
- "modified": "2019-01-22 10:47:00.000822", 
- "modified_by": "Administrator", 
- "module": "Buying", 
- "name": "Supplier Scorecard Criteria", 
- "name_case": "", 
- "owner": "Administrator", 
+ ],
+ "links": [],
+ "modified": "2021-11-11 18:34:58.477648",
+ "modified_by": "Administrator",
+ "module": "Buying",
+ "name": "Supplier Scorecard Criteria",
+ "naming_rule": "By fieldname",
+ "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": 0, 
+   "create": 1,
+   "delete": 1,
+   "email": 1,
+   "export": 1,
+   "print": 1,
+   "read": 1,
+   "report": 1,
+   "role": "System Manager",
+   "share": 1,
    "write": 1
   }
- ], 
- "quick_entry": 1, 
- "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
+ ],
+ "quick_entry": 1,
+ "sort_field": "modified",
+ "sort_order": "DESC",
+ "track_changes": 1
 }
\ No newline at end of file
diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index e0551a4..3190fea 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -1402,8 +1402,8 @@
 					grand_total -= self.get("total_advance")
 					base_grand_total = flt(grand_total * self.get("conversion_rate"), self.precision("base_grand_total"))
 
-			if flt(total, self.precision("grand_total")) != flt(grand_total, self.precision("grand_total")) or \
-				flt(base_total, self.precision("base_grand_total")) != flt(base_grand_total, self.precision("base_grand_total")):
+			if flt(total, self.precision("grand_total")) - flt(grand_total, self.precision("grand_total")) > 0.1 or \
+				flt(base_total, self.precision("base_grand_total")) - flt(base_grand_total, self.precision("base_grand_total")) > 0.1:
 				frappe.throw(_("Total Payment Amount in Payment Schedule must be equal to Grand / Rounded Total"))
 
 	def is_rounded_total_disabled(self):
diff --git a/erpnext/controllers/queries.py b/erpnext/controllers/queries.py
index 22e02b4..76a7d1a 100644
--- a/erpnext/controllers/queries.py
+++ b/erpnext/controllers/queries.py
@@ -210,12 +210,15 @@
 	meta = frappe.get_meta("Item", cached=True)
 	searchfields = meta.get_search_fields()
 
-	if "description" in searchfields:
-		searchfields.remove("description")
+	# these are handled separately
+	ignored_search_fields = ("item_name", "description")
+	for ignored_field in ignored_search_fields:
+		if ignored_field in searchfields:
+			searchfields.remove(ignored_field)
 
 	columns = ''
 	extra_searchfields = [field for field in searchfields
-		if not field in ["name", "item_group", "description"]]
+		if not field in ["name", "item_group", "description", "item_name"]]
 
 	if extra_searchfields:
 		columns = ", " + ", ".join(extra_searchfields)
@@ -252,10 +255,8 @@
 	if frappe.db.count('Item', cache=True) < 50000:
 		# scan description only if items are less than 50000
 		description_cond = 'or tabItem.description LIKE %(txt)s'
-	return frappe.db.sql("""select tabItem.name,
-		if(length(tabItem.item_name) > 40,
-			concat(substr(tabItem.item_name, 1, 40), "..."), item_name) as item_name,
-		tabItem.item_group,
+	return frappe.db.sql("""select
+			tabItem.name, tabItem.item_name, tabItem.item_group,
 		if(length(tabItem.description) > 40, \
 			concat(substr(tabItem.description, 1, 40), "..."), description) as description
 		{columns}
diff --git a/erpnext/crm/doctype/competitor/__init__.py b/erpnext/crm/doctype/competitor/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/crm/doctype/competitor/__init__.py
diff --git a/erpnext/crm/doctype/competitor/competitor.js b/erpnext/crm/doctype/competitor/competitor.js
new file mode 100644
index 0000000..a5b617d
--- /dev/null
+++ b/erpnext/crm/doctype/competitor/competitor.js
@@ -0,0 +1,8 @@
+// Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
+// For license information, please see license.txt
+
+frappe.ui.form.on('Competitor', {
+	// refresh: function(frm) {
+
+	// }
+});
diff --git a/erpnext/crm/doctype/competitor/competitor.json b/erpnext/crm/doctype/competitor/competitor.json
new file mode 100644
index 0000000..280441f
--- /dev/null
+++ b/erpnext/crm/doctype/competitor/competitor.json
@@ -0,0 +1,68 @@
+{
+ "actions": [],
+ "allow_rename": 1,
+ "autoname": "field:competitor_name",
+ "creation": "2021-10-21 10:28:52.071316",
+ "doctype": "DocType",
+ "editable_grid": 1,
+ "engine": "InnoDB",
+ "field_order": [
+  "competitor_name",
+  "website"
+ ],
+ "fields": [
+  {
+   "fieldname": "competitor_name",
+   "fieldtype": "Data",
+   "in_list_view": 1,
+   "label": "Competitor Name",
+   "reqd": 1,
+   "unique": 1
+  },
+  {
+   "allow_in_quick_entry": 1,
+   "fieldname": "website",
+   "fieldtype": "Data",
+   "in_list_view": 1,
+   "label": "Website",
+   "options": "URL"
+  }
+ ],
+ "index_web_pages_for_search": 1,
+ "links": [],
+ "modified": "2021-10-21 12:43:59.106807",
+ "modified_by": "Administrator",
+ "module": "CRM",
+ "name": "Competitor",
+ "naming_rule": "By fieldname",
+ "owner": "Administrator",
+ "permissions": [
+  {
+   "create": 1,
+   "delete": 1,
+   "email": 1,
+   "export": 1,
+   "print": 1,
+   "read": 1,
+   "report": 1,
+   "role": "System Manager",
+   "share": 1,
+   "write": 1
+  },
+  {
+   "create": 1,
+   "email": 1,
+   "export": 1,
+   "print": 1,
+   "read": 1,
+   "report": 1,
+   "role": "Sales User",
+   "share": 1,
+   "write": 1
+  }
+ ],
+ "quick_entry": 1,
+ "sort_field": "modified",
+ "sort_order": "DESC",
+ "track_changes": 1
+}
\ No newline at end of file
diff --git a/erpnext/crm/doctype/competitor/competitor.py b/erpnext/crm/doctype/competitor/competitor.py
new file mode 100644
index 0000000..a292e461
--- /dev/null
+++ b/erpnext/crm/doctype/competitor/competitor.py
@@ -0,0 +1,9 @@
+# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
+# For license information, please see license.txt
+
+# import frappe
+from frappe.model.document import Document
+
+
+class Competitor(Document):
+	pass
diff --git a/erpnext/crm/doctype/competitor/test_competitor.py b/erpnext/crm/doctype/competitor/test_competitor.py
new file mode 100644
index 0000000..f77d7e6
--- /dev/null
+++ b/erpnext/crm/doctype/competitor/test_competitor.py
@@ -0,0 +1,9 @@
+# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors
+# See license.txt
+
+# import frappe
+import unittest
+
+
+class TestCompetitor(unittest.TestCase):
+	pass
diff --git a/erpnext/crm/doctype/competitor_detail/__init__.py b/erpnext/crm/doctype/competitor_detail/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/crm/doctype/competitor_detail/__init__.py
diff --git a/erpnext/crm/doctype/competitor_detail/competitor_detail.json b/erpnext/crm/doctype/competitor_detail/competitor_detail.json
new file mode 100644
index 0000000..9512b22
--- /dev/null
+++ b/erpnext/crm/doctype/competitor_detail/competitor_detail.json
@@ -0,0 +1,33 @@
+{
+ "actions": [],
+ "allow_rename": 1,
+ "creation": "2021-10-21 10:34:58.841689",
+ "doctype": "DocType",
+ "editable_grid": 1,
+ "engine": "InnoDB",
+ "field_order": [
+  "competitor"
+ ],
+ "fields": [
+  {
+   "fieldname": "competitor",
+   "fieldtype": "Link",
+   "in_list_view": 1,
+   "label": "Competitor",
+   "options": "Competitor",
+   "reqd": 1
+  }
+ ],
+ "index_web_pages_for_search": 1,
+ "istable": 1,
+ "links": [],
+ "modified": "2021-10-21 10:34:58.841689",
+ "modified_by": "Administrator",
+ "module": "CRM",
+ "name": "Competitor Detail",
+ "owner": "Administrator",
+ "permissions": [],
+ "sort_field": "modified",
+ "sort_order": "DESC",
+ "track_changes": 1
+}
\ No newline at end of file
diff --git a/erpnext/crm/doctype/competitor_detail/competitor_detail.py b/erpnext/crm/doctype/competitor_detail/competitor_detail.py
new file mode 100644
index 0000000..0ef7560
--- /dev/null
+++ b/erpnext/crm/doctype/competitor_detail/competitor_detail.py
@@ -0,0 +1,9 @@
+# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
+# For license information, please see license.txt
+
+# import frappe
+from frappe.model.document import Document
+
+
+class CompetitorDetail(Document):
+	pass
diff --git a/erpnext/crm/doctype/opportunity/opportunity.json b/erpnext/crm/doctype/opportunity/opportunity.json
index dc886b5..feb6044 100644
--- a/erpnext/crm/doctype/opportunity/opportunity.json
+++ b/erpnext/crm/doctype/opportunity/opportunity.json
@@ -23,7 +23,6 @@
   "status",
   "converted_by",
   "sales_stage",
-  "order_lost_reason",
   "first_response_time",
   "expected_closing",
   "next_contact",
@@ -64,7 +63,11 @@
   "transaction_date",
   "language",
   "amended_from",
-  "lost_reasons"
+  "lost_detail_section",
+  "lost_reasons",
+  "order_lost_reason",
+  "column_break_56",
+  "competitors"
  ],
  "fields": [
   {
@@ -154,10 +157,9 @@
    "reqd": 1
   },
   {
-   "depends_on": "eval:doc.status===\"Lost\"",
    "fieldname": "order_lost_reason",
    "fieldtype": "Small Text",
-   "label": "Lost Reason",
+   "label": "Detailed Reason",
    "no_copy": 1,
    "read_only": 1
   },
@@ -409,6 +411,7 @@
    "width": "150px"
   },
   {
+   "depends_on": "eval:doc.status===\"Lost\"",
    "fieldname": "lost_reasons",
    "fieldtype": "Table MultiSelect",
    "label": "Lost Reasons",
@@ -486,15 +489,33 @@
    "label": "Grand Total",
    "options": "currency",
    "read_only": 1
+  },
+  {
+   "fieldname": "lost_detail_section",
+   "fieldtype": "Section Break",
+   "label": "Lost Reasons"
+  },
+  {
+   "fieldname": "column_break_56",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "competitors",
+   "fieldtype": "Table MultiSelect",
+   "label": "Competitors",
+   "options": "Competitor Detail",
+   "read_only": 1
   }
  ],
  "icon": "fa fa-info-sign",
  "idx": 195,
  "links": [],
- "modified": "2021-09-06 10:02:18.609136",
+ "migration_hash": "d87c646ea2579b6900197fd41e6c5c5a",
+ "modified": "2021-10-21 11:04:30.151379",
  "modified_by": "Administrator",
  "module": "CRM",
  "name": "Opportunity",
+ "naming_rule": "By \"Naming Series\" field",
  "owner": "Administrator",
  "permissions": [
   {
diff --git a/erpnext/crm/doctype/opportunity/opportunity.py b/erpnext/crm/doctype/opportunity/opportunity.py
index 90eae8d..0bef80a 100644
--- a/erpnext/crm/doctype/opportunity/opportunity.py
+++ b/erpnext/crm/doctype/opportunity/opportunity.py
@@ -116,16 +116,20 @@
 			self.party_name = lead_name
 
 	@frappe.whitelist()
-	def declare_enquiry_lost(self, lost_reasons_list, detailed_reason=None):
+	def declare_enquiry_lost(self, lost_reasons_list, competitors, detailed_reason=None):
 		if not self.has_active_quotation():
-			frappe.db.set(self, 'status', 'Lost')
+			self.status = 'Lost'
+			self.lost_reasons = self.competitors = []
 
 			if detailed_reason:
-				frappe.db.set(self, 'order_lost_reason', detailed_reason)
+				self.order_lost_reason = detailed_reason
 
 			for reason in lost_reasons_list:
 				self.append('lost_reasons', reason)
 
+			for competitor in competitors:
+				self.append('competitors', competitor)
+
 			self.save()
 
 		else:
diff --git a/erpnext/education/report/student_fee_collection/student_fee_collection.json b/erpnext/education/report/student_fee_collection/student_fee_collection.json
index 8deb865..c0229a2 100644
--- a/erpnext/education/report/student_fee_collection/student_fee_collection.json
+++ b/erpnext/education/report/student_fee_collection/student_fee_collection.json
@@ -1,5 +1,5 @@
 {
- "add_total_row": 0,
+ "add_total_row": 1,
  "creation": "2016-06-22 02:58:41.024538",
  "disable_prepared_report": 0,
  "disabled": 0,
@@ -13,7 +13,7 @@
  "name": "Student Fee Collection",
  "owner": "Administrator",
  "prepared_report": 0,
- "query": "SELECT\n student as \"Student:Link/Student:200\",\n student_name as \"Student Name::200\",\n sum(grand_total) - sum(outstanding_amount) as \"Paid Amount:Currency:150\",\n sum(outstanding_amount) as \"Outstanding Amount:Currency:150\",\n sum(grand_total) as \"Grand Total:Currency:150\"\nFROM\n `tabFees` \nGROUP BY\n student",
+ "query": "SELECT\n student as \"Student:Link/Student:200\",\n student_name as \"Student Name::200\",\n sum(grand_total) - sum(outstanding_amount) as \"Paid Amount:Currency:150\",\n sum(outstanding_amount) as \"Outstanding Amount:Currency:150\",\n sum(grand_total) as \"Grand Total:Currency:150\"\nFROM\n `tabFees` \nWHERE\n docstatus=1 \nGROUP BY\n student",
  "ref_doctype": "Fees",
  "report_name": "Student Fee Collection",
  "report_type": "Query Report",
@@ -22,4 +22,4 @@
    "role": "Academics User"
   }
  ]
-}
\ No newline at end of file
+}
diff --git a/erpnext/erpnext_integrations/connectors/woocommerce_connection.py b/erpnext/erpnext_integrations/connectors/woocommerce_connection.py
index f5f9ce3..9409485 100644
--- a/erpnext/erpnext_integrations/connectors/woocommerce_connection.py
+++ b/erpnext/erpnext_integrations/connectors/woocommerce_connection.py
@@ -19,8 +19,7 @@
 	)
 
 	if frappe.request.data and \
-		frappe.get_request_header("X-Wc-Webhook-Signature") and \
-		not sig == bytes(frappe.get_request_header("X-Wc-Webhook-Signature").encode()):
+		not sig == frappe.get_request_header("X-Wc-Webhook-Signature", "").encode():
 			frappe.throw(_("Unverified Webhook Data"))
 	frappe.set_user(woocommerce_settings.creation_user)
 
diff --git a/erpnext/erpnext_integrations/doctype/mpesa_settings/mpesa_settings.py b/erpnext/erpnext_integrations/doctype/mpesa_settings/mpesa_settings.py
index d2b6190..e7b4a30 100644
--- a/erpnext/erpnext_integrations/doctype/mpesa_settings/mpesa_settings.py
+++ b/erpnext/erpnext_integrations/doctype/mpesa_settings/mpesa_settings.py
@@ -141,6 +141,9 @@
 	transaction_response = frappe._dict(kwargs["Body"]["stkCallback"])
 
 	checkout_id = getattr(transaction_response, "CheckoutRequestID", "")
+	if not isinstance(checkout_id, str):
+		frappe.throw(_("Invalid Checkout Request ID"))
+
 	integration_request = frappe.get_doc("Integration Request", checkout_id)
 	transaction_data = frappe._dict(loads(integration_request.data))
 	total_paid = 0 # for multiple integration request made against a pos invoice
@@ -231,6 +234,9 @@
 	account_balance_response = frappe._dict(kwargs["Result"])
 
 	conversation_id = getattr(account_balance_response, "ConversationID", "")
+	if not isinstance(conversation_id, str):
+		frappe.throw(_("Invalid Conversation ID"))
+
 	request = frappe.get_doc("Integration Request", conversation_id)
 
 	if request.status == "Completed":
diff --git a/erpnext/erpnext_integrations/doctype/taxjar_settings/taxjar_settings.js b/erpnext/erpnext_integrations/doctype/taxjar_settings/taxjar_settings.js
index d495989..2925db8 100644
--- a/erpnext/erpnext_integrations/doctype/taxjar_settings/taxjar_settings.js
+++ b/erpnext/erpnext_integrations/doctype/taxjar_settings/taxjar_settings.js
@@ -7,6 +7,23 @@
 		frm.toggle_reqd("sandbox_api_key", frm.doc.is_sandbox);
 	},
 
+	on_load: (frm) => {
+		frm.set_query('shipping_account_head', function() {
+			return {
+				filters: {
+					'company': frm.doc.company
+				}
+			};
+		});
+		frm.set_query('tax_account_head', function() {
+			return {
+				filters: {
+					'company': frm.doc.company
+				}
+			};
+		});
+	},
+
 	refresh: (frm) => {
 		frm.add_custom_button(__('Update Nexus List'), function() {
 			frm.call({
diff --git a/erpnext/erpnext_integrations/doctype/taxjar_settings/taxjar_settings.json b/erpnext/erpnext_integrations/doctype/taxjar_settings/taxjar_settings.json
index 2d17f2e..23ccb7e 100644
--- a/erpnext/erpnext_integrations/doctype/taxjar_settings/taxjar_settings.json
+++ b/erpnext/erpnext_integrations/doctype/taxjar_settings/taxjar_settings.json
@@ -14,6 +14,8 @@
   "cb_keys",
   "sandbox_api_key",
   "configuration",
+  "company",
+  "column_break_10",
   "tax_account_head",
   "configuration_cb",
   "shipping_account_head",
@@ -68,10 +70,6 @@
    "label": "Sandbox API Key"
   },
   {
-   "fieldname": "configuration_cb",
-   "fieldtype": "Column Break"
-  },
-  {
    "default": "0",
    "depends_on": "taxjar_calculate_tax",
    "fieldname": "taxjar_create_transactions",
@@ -104,11 +102,25 @@
    "label": "Nexus",
    "options": "TaxJar Nexus",
    "read_only": 1
+  },
+  {
+   "fieldname": "configuration_cb",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "column_break_10",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "company",
+   "fieldtype": "Link",
+   "label": "Company",
+   "options": "Company"
   }
  ],
  "issingle": 1,
  "links": [],
- "modified": "2021-10-06 10:59:13.475442",
+ "modified": "2021-11-08 18:02:29.232090",
  "modified_by": "Administrator",
  "module": "ERPNext Integrations",
  "name": "TaxJar Settings",
diff --git a/erpnext/erpnext_integrations/doctype/taxjar_settings/taxjar_settings.py b/erpnext/erpnext_integrations/doctype/taxjar_settings/taxjar_settings.py
index bfc5e6f..b9f24b6 100644
--- a/erpnext/erpnext_integrations/doctype/taxjar_settings/taxjar_settings.py
+++ b/erpnext/erpnext_integrations/doctype/taxjar_settings/taxjar_settings.py
@@ -80,9 +80,9 @@
 			dict(fieldname='product_tax_category', fieldtype='Link', insert_after='description', options='Product Tax Category',
 				label='Product Tax Category', fetch_from='item_code.product_tax_category'),
 			dict(fieldname='tax_collectable', fieldtype='Currency', insert_after='net_amount',
-				label='Tax Collectable', read_only=1),
+				label='Tax Collectable', read_only=1, options='currency'),
 			dict(fieldname='taxable_amount', fieldtype='Currency', insert_after='tax_collectable',
-				label='Taxable Amount', read_only=1)
+				label='Taxable Amount', read_only=1, options='currency')
 		],
 		'Item': [
 			dict(fieldname='product_tax_category', fieldtype='Link', insert_after='item_group', options='Product Tax Category',
diff --git a/erpnext/erpnext_integrations/taxjar_integration.py b/erpnext/erpnext_integrations/taxjar_integration.py
index 2a7243c..a4e2157 100644
--- a/erpnext/erpnext_integrations/taxjar_integration.py
+++ b/erpnext/erpnext_integrations/taxjar_integration.py
@@ -6,7 +6,7 @@
 from frappe.contacts.doctype.address.address import get_company_address
 from frappe.utils import cint, flt
 
-from erpnext import get_default_company
+from erpnext import get_default_company, get_region
 
 TAX_ACCOUNT_HEAD = frappe.db.get_single_value("TaxJar Settings", "tax_account_head")
 SHIP_ACCOUNT_HEAD = frappe.db.get_single_value("TaxJar Settings", "shipping_account_head")
@@ -21,6 +21,7 @@
 	'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY']
 
 
+
 def get_client():
 	taxjar_settings = frappe.get_single("TaxJar Settings")
 
@@ -158,6 +159,9 @@
 	if not TAXJAR_CALCULATE_TAX:
 		return
 
+	if get_region(doc.company) != 'United States':
+		return
+
 	if not doc.items:
 		return
 
@@ -262,7 +266,7 @@
 	if doc.shipping_address_name:
 		shipping_address = frappe.get_doc("Address", doc.shipping_address_name)
 	elif doc.customer_address:
-		shipping_address = frappe.get_doc("Address", doc.customer_address_name)
+		shipping_address = frappe.get_doc("Address", doc.customer_address)
 	else:
 		shipping_address = get_company_address_details(doc)
 
diff --git a/erpnext/erpnext_integrations/utils.py b/erpnext/erpnext_integrations/utils.py
index b52c3fc..d922d87 100644
--- a/erpnext/erpnext_integrations/utils.py
+++ b/erpnext/erpnext_integrations/utils.py
@@ -23,7 +23,6 @@
 			)
 
 			if frappe.request.data and \
-				frappe.get_request_header(hmac_key) and \
 				not sig == bytes(frappe.get_request_header(hmac_key).encode()):
 					frappe.throw(_("Unverified Webhook Data"))
 			frappe.set_user(settings.modified_by)
diff --git a/erpnext/maintenance/doctype/maintenance_visit/test_maintenance_visit.py b/erpnext/maintenance/doctype/maintenance_visit/test_maintenance_visit.py
index a0c1a33..6a9e70a 100644
--- a/erpnext/maintenance/doctype/maintenance_visit/test_maintenance_visit.py
+++ b/erpnext/maintenance/doctype/maintenance_visit/test_maintenance_visit.py
@@ -3,7 +3,39 @@
 
 import unittest
 
+import frappe
+from frappe.utils.data import today
+
 # test_records = frappe.get_test_records('Maintenance Visit')
 
 class TestMaintenanceVisit(unittest.TestCase):
 	pass
+
+def make_maintenance_visit():
+	mv = frappe.new_doc("Maintenance Visit")
+	mv.company = "_Test Company"
+	mv.customer = "_Test Customer"
+	mv.mntc_date = today()
+	mv.completion_status = "Partially Completed"
+
+	sales_person = make_sales_person("Dwight Schrute")
+
+	mv.append("purposes", {
+		"item_code": "_Test Item",
+		"sales_person": "Sales Team",
+		"description": "Test Item",
+		"work_done": "Test Work Done",
+		"service_person": sales_person.name
+	})
+	mv.insert(ignore_permissions=True)
+
+	return mv
+
+def make_sales_person(name):
+	sales_person = frappe.get_doc({
+		'doctype': "Sales Person",
+		'sales_person_name': name
+	})
+	sales_person.insert(ignore_if_duplicate = True)
+
+	return sales_person
diff --git a/erpnext/manufacturing/doctype/job_card/job_card.js b/erpnext/manufacturing/doctype/job_card/job_card.js
index 35be388..f9259fb 100644
--- a/erpnext/manufacturing/doctype/job_card/job_card.js
+++ b/erpnext/manufacturing/doctype/job_card/job_card.js
@@ -23,11 +23,22 @@
 		);
 	},
 
+	onload: function(frm) {
+		if (frm.doc.scrap_items.length == 0) {
+			frm.fields_dict['scrap_items_section'].collapse();
+		}
+	},
+
 	refresh: function(frm) {
 		frappe.flags.pause_job = 0;
 		frappe.flags.resume_job = 0;
 		let has_items = frm.doc.items && frm.doc.items.length;
 
+		if (frm.doc.__onload.work_order_stopped) {
+			frm.disable_save();
+			return;
+		}
+
 		if (!frm.doc.__islocal && has_items && frm.doc.docstatus < 2) {
 			let to_request = frm.doc.for_quantity > frm.doc.transferred_qty;
 			let excess_transfer_allowed = frm.doc.__onload.job_card_excess_transfer;
diff --git a/erpnext/manufacturing/doctype/job_card/job_card.json b/erpnext/manufacturing/doctype/job_card/job_card.json
index 7dd38f4..6528199 100644
--- a/erpnext/manufacturing/doctype/job_card/job_card.json
+++ b/erpnext/manufacturing/doctype/job_card/job_card.json
@@ -396,6 +396,7 @@
    "options": "Batch"
   },
   {
+   "collapsible": 1,
    "fieldname": "scrap_items_section",
    "fieldtype": "Section Break",
    "label": "Scrap Items"
@@ -411,7 +412,7 @@
  ],
  "is_submittable": 1,
  "links": [],
- "modified": "2021-09-14 00:38:46.873105",
+ "modified": "2021-11-12 10:15:03.572401",
  "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 ff4feaa..5eea032 100644
--- a/erpnext/manufacturing/doctype/job_card/job_card.py
+++ b/erpnext/manufacturing/doctype/job_card/job_card.py
@@ -36,6 +36,7 @@
 	def onload(self):
 		excess_transfer = frappe.db.get_single_value("Manufacturing Settings", "job_card_excess_transfer")
 		self.set_onload("job_card_excess_transfer", excess_transfer)
+		self.set_onload("work_order_stopped", self.is_work_order_stopped())
 
 	def validate(self):
 		self.validate_time_logs()
@@ -44,6 +45,7 @@
 		self.validate_sequence_id()
 		self.set_sub_operations()
 		self.update_sub_operation_status()
+		self.validate_work_order()
 
 	def set_sub_operations(self):
 		if self.operation:
@@ -502,13 +504,11 @@
 			self.status = 'Work In Progress'
 
 		if (self.docstatus == 1 and
-			(self.for_quantity <= self.transferred_qty or not self.items)):
-			# consider excess transfer
-			# completed qty is checked via separate validation
+			(self.for_quantity <= self.total_completed_qty or not self.items)):
 			self.status = 'Completed'
 
 		if self.status != 'Completed':
-			if self.for_quantity == self.transferred_qty:
+			if self.for_quantity <= self.transferred_qty:
 				self.status = 'Material Transferred'
 
 		if update_status:
@@ -548,6 +548,18 @@
 				frappe.throw(_("{0}, complete the operation {1} before the operation {2}.")
 					.format(message, bold(row.operation), bold(self.operation)), OperationSequenceError)
 
+	def validate_work_order(self):
+		if self.is_work_order_stopped():
+			frappe.throw(_("You can't make any changes to Job Card since Work Order is stopped."))
+
+	def is_work_order_stopped(self):
+		if self.work_order:
+			status = frappe.get_value('Work Order', self.work_order)
+
+			if status == "Closed":
+				return True
+
+		return False
 
 @frappe.whitelist()
 def make_time_log(args):
diff --git a/erpnext/manufacturing/doctype/production_plan/production_plan.js b/erpnext/manufacturing/doctype/production_plan/production_plan.js
index 2bd02da..b171086 100644
--- a/erpnext/manufacturing/doctype/production_plan/production_plan.js
+++ b/erpnext/manufacturing/doctype/production_plan/production_plan.js
@@ -105,7 +105,7 @@
 		}
 		frm.trigger("material_requirement");
 
-		const projected_qty_formula = ` <table class="table table-bordered" style="background-color: #f9f9f9;">
+		const projected_qty_formula = ` <table class="table table-bordered" style="background-color: var(--scrollbar-track-color);">
 			<tr><td style="padding-left:25px">
 				<div>
 				<h3 style="text-decoration: underline;">
diff --git a/erpnext/manufacturing/doctype/work_order/test_work_order.py b/erpnext/manufacturing/doctype/work_order/test_work_order.py
index 85b5bfb..f4a88dc 100644
--- a/erpnext/manufacturing/doctype/work_order/test_work_order.py
+++ b/erpnext/manufacturing/doctype/work_order/test_work_order.py
@@ -12,6 +12,7 @@
 	ItemHasVariantError,
 	OverProductionError,
 	StockOverProductionError,
+	close_work_order,
 	make_stock_entry,
 	stop_unstop,
 )
@@ -800,6 +801,46 @@
 			if row.is_scrap_item:
 				self.assertEqual(row.qty, 1)
 
+	def test_close_work_order(self):
+		items = ['Test FG Item for Closed WO', 'Test RM Item 1 for Closed WO',
+			'Test RM Item 2 for Closed WO']
+
+		company = '_Test Company with perpetual inventory'
+		for item_code in items:
+			create_item(item_code = item_code, is_stock_item = 1,
+				is_purchase_item=1, opening_stock=100, valuation_rate=10, company=company, warehouse='Stores - TCP1')
+
+		item = 'Test FG Item for Closed WO'
+		raw_materials = ['Test RM Item 1 for Closed WO', 'Test RM Item 2 for Closed WO']
+		if not frappe.db.get_value('BOM', {'item': item}):
+			bom = make_bom(item=item, source_warehouse='Stores - TCP1', raw_materials=raw_materials, do_not_save=True)
+			bom.with_operations = 1
+			bom.append('operations', {
+				'operation': '_Test Operation 1',
+				'workstation': '_Test Workstation 1',
+				'hour_rate': 20,
+				'time_in_mins': 60
+			})
+
+			bom.submit()
+
+		wo_order = make_wo_order_test_record(item=item, company=company, planned_start_date=now(), qty=20, skip_transfer=1)
+		job_cards = frappe.db.get_value('Job Card', {'work_order': wo_order.name}, 'name')
+
+		if len(job_cards) == len(bom.operations):
+			for jc in job_cards:
+				job_card_doc = frappe.get_doc('Job Card', jc)
+				job_card_doc.append('time_logs', {
+					'from_time': now(),
+					'time_in_mins': 60,
+					'completed_qty': job_card_doc.for_quantity
+				})
+
+				job_card_doc.submit()
+
+			close_work_order(wo_order, "Closed")
+			self.assertEqual(wo_order.get('status'), "Closed")
+
 def update_job_card(job_card):
 	job_card_doc = frappe.get_doc('Job Card', job_card)
 	job_card_doc.set('scrap_items', [
diff --git a/erpnext/manufacturing/doctype/work_order/work_order.js b/erpnext/manufacturing/doctype/work_order/work_order.js
index 51c46f6..bfce1b8 100644
--- a/erpnext/manufacturing/doctype/work_order/work_order.js
+++ b/erpnext/manufacturing/doctype/work_order/work_order.js
@@ -135,24 +135,26 @@
 			frm.set_intro(__("Submit this Work Order for further processing."));
 		}
 
-		if (frm.doc.docstatus===1) {
-			frm.trigger('show_progress_for_items');
-			frm.trigger('show_progress_for_operations');
-		}
+		if (frm.doc.status != "Closed") {
+			if (frm.doc.docstatus===1) {
+				frm.trigger('show_progress_for_items');
+				frm.trigger('show_progress_for_operations');
+			}
 
-		if (frm.doc.docstatus === 1
-			&& frm.doc.operations && frm.doc.operations.length) {
+			if (frm.doc.docstatus === 1
+				&& frm.doc.operations && frm.doc.operations.length) {
 
-			const not_completed = frm.doc.operations.filter(d => {
-				if(d.status != 'Completed') {
-					return true;
+				const not_completed = frm.doc.operations.filter(d => {
+					if (d.status != 'Completed') {
+						return true;
+					}
+				});
+
+				if (not_completed && not_completed.length) {
+					frm.add_custom_button(__('Create Job Card'), () => {
+						frm.trigger("make_job_card");
+					}).addClass('btn-primary');
 				}
-			});
-
-			if(not_completed && not_completed.length) {
-				frm.add_custom_button(__('Create Job Card'), () => {
-					frm.trigger("make_job_card");
-				}).addClass('btn-primary');
 			}
 		}
 
@@ -517,14 +519,22 @@
 erpnext.work_order = {
 	set_custom_buttons: function(frm) {
 		var doc = frm.doc;
-		if (doc.docstatus === 1) {
+		if (doc.docstatus === 1 && doc.status != "Closed") {
+			frm.add_custom_button(__('Close'), function() {
+				frappe.confirm(__("Once the Work Order is Closed. It can't be resumed."),
+					() => {
+						erpnext.work_order.change_work_order_status(frm, "Closed");
+					}
+				);
+			}, __("Status"));
+
 			if (doc.status != 'Stopped' && doc.status != 'Completed') {
 				frm.add_custom_button(__('Stop'), function() {
-					erpnext.work_order.stop_work_order(frm, "Stopped");
+					erpnext.work_order.change_work_order_status(frm, "Stopped");
 				}, __("Status"));
 			} else if (doc.status == 'Stopped') {
 				frm.add_custom_button(__('Re-open'), function() {
-					erpnext.work_order.stop_work_order(frm, "Resumed");
+					erpnext.work_order.change_work_order_status(frm, "Resumed");
 				}, __("Status"));
 			}
 
@@ -713,9 +723,10 @@
 		});
 	},
 
-	stop_work_order: function(frm, status) {
+	change_work_order_status: function(frm, status) {
+		let method_name = status=="Closed" ? "close_work_order" : "stop_unstop";
 		frappe.call({
-			method: "erpnext.manufacturing.doctype.work_order.work_order.stop_unstop",
+			method: `erpnext.manufacturing.doctype.work_order.work_order.${method_name}`,
 			freeze: true,
 			freeze_message: __("Updating Work Order status"),
 			args: {
diff --git a/erpnext/manufacturing/doctype/work_order/work_order.json b/erpnext/manufacturing/doctype/work_order/work_order.json
index 7f8e816..df7ee53 100644
--- a/erpnext/manufacturing/doctype/work_order/work_order.json
+++ b/erpnext/manufacturing/doctype/work_order/work_order.json
@@ -99,7 +99,7 @@
    "no_copy": 1,
    "oldfieldname": "status",
    "oldfieldtype": "Select",
-   "options": "\nDraft\nSubmitted\nNot Started\nIn Process\nCompleted\nStopped\nCancelled",
+   "options": "\nDraft\nSubmitted\nNot Started\nIn Process\nCompleted\nStopped\nClosed\nCancelled",
    "read_only": 1,
    "reqd": 1,
    "search_index": 1
@@ -573,7 +573,8 @@
  "image_field": "image",
  "is_submittable": 1,
  "links": [],
- "modified": "2021-10-27 19:21:35.139888",
+ "migration_hash": "a18118963f4fcdb7f9d326de5f4063ba",
+ "modified": "2021-10-29 15:12:32.203605",
  "modified_by": "Administrator",
  "module": "Manufacturing",
  "name": "Work Order",
diff --git a/erpnext/manufacturing/doctype/work_order/work_order.py b/erpnext/manufacturing/doctype/work_order/work_order.py
index f881e1b..0090f4d 100644
--- a/erpnext/manufacturing/doctype/work_order/work_order.py
+++ b/erpnext/manufacturing/doctype/work_order/work_order.py
@@ -175,7 +175,7 @@
 
 	def update_status(self, status=None):
 		'''Update status of work order if unknown'''
-		if status != "Stopped":
+		if status != "Stopped" and status != "Closed":
 			status = self.get_status(status)
 
 		if status != self.status:
@@ -624,7 +624,6 @@
 	def validate_operation_time(self):
 		for d in self.operations:
 			if not d.time_in_mins > 0:
-				print(self.bom_no, self.production_item)
 				frappe.throw(_("Operation Time must be greater than 0 for Operation {0}").format(d.operation))
 
 	def update_required_items(self):
@@ -967,6 +966,10 @@
 		frappe.throw(_("Not permitted"), frappe.PermissionError)
 
 	pro_order = frappe.get_doc("Work Order", work_order)
+
+	if pro_order.status == "Closed":
+		frappe.throw(_("Closed Work Order can not be stopped or Re-opened"))
+
 	pro_order.update_status(status)
 	pro_order.update_planned_qty()
 	frappe.msgprint(_("Work Order has been {0}").format(status))
@@ -1001,6 +1004,29 @@
 			if row.job_card_qty > 0:
 				create_job_card(work_order, row, auto_create=True)
 
+@frappe.whitelist()
+def close_work_order(work_order, status):
+	if not frappe.has_permission("Work Order", "write"):
+		frappe.throw(_("Not permitted"), frappe.PermissionError)
+
+	work_order = frappe.get_doc("Work Order", work_order)
+	if work_order.get("operations"):
+		job_cards = frappe.get_list("Job Card",
+			filters={
+				"work_order": work_order.name,
+				"status": "Work In Progress"
+			}, pluck='name')
+
+		if job_cards:
+			job_cards = ", ".join(job_cards)
+			frappe.throw(_("Can not close Work Order. Since {0} Job Cards are in Work In Progress state.").format(job_cards))
+
+	work_order.update_status(status)
+	work_order.update_planned_qty()
+	frappe.msgprint(_("Work Order has been {0}").format(status))
+	work_order.notify_update()
+	return work_order.status
+
 def split_qty_based_on_batch_size(wo_doc, row, qty):
 	if not cint(frappe.db.get_value("Operation",
 		row.operation, "create_job_card_based_on_batch_size")):
diff --git a/erpnext/patches.txt b/erpnext/patches.txt
index 2c21ab6..e475229 100644
--- a/erpnext/patches.txt
+++ b/erpnext/patches.txt
@@ -283,8 +283,8 @@
 erpnext.patches.v13_0.einvoicing_deprecation_warning
 execute:frappe.reload_doc("erpnext_integrations", "doctype", "TaxJar Settings")
 execute:frappe.reload_doc("erpnext_integrations", "doctype", "Product Tax Category")
-erpnext.patches.v13_0.custom_fields_for_taxjar_integration
 erpnext.patches.v14_0.delete_einvoicing_doctypes
+erpnext.patches.v13_0.custom_fields_for_taxjar_integration          #08-11-2021
 erpnext.patches.v13_0.set_operation_time_based_on_operating_cost
 erpnext.patches.v13_0.validate_options_for_data_field
 erpnext.patches.v13_0.create_gst_payment_entry_fields
@@ -303,9 +303,12 @@
 erpnext.patches.v13_0.add_default_interview_notification_templates
 erpnext.patches.v13_0.enable_scheduler_job_for_item_reposting
 erpnext.patches.v13_0.requeue_failed_reposts
+erpnext.patches.v13_0.update_job_card_status
 erpnext.patches.v12_0.update_production_plan_status
 erpnext.patches.v13_0.healthcare_deprecation_warning
+erpnext.patches.v13_0.item_naming_series_not_mandatory
 erpnext.patches.v14_0.delete_healthcare_doctypes
 erpnext.patches.v13_0.update_category_in_ltds_certificate
 erpnext.patches.v13_0.create_pan_field_for_india #2
 erpnext.patches.v14_0.delete_hub_doctypes
+erpnext.patches.v13_0.create_ksa_vat_custom_fields
diff --git a/erpnext/patches/v13_0/create_ksa_vat_custom_fields.py b/erpnext/patches/v13_0/create_ksa_vat_custom_fields.py
new file mode 100644
index 0000000..f33b4b3
--- /dev/null
+++ b/erpnext/patches/v13_0/create_ksa_vat_custom_fields.py
@@ -0,0 +1,12 @@
+import frappe
+
+from erpnext.regional.saudi_arabia.setup import make_custom_fields
+
+
+def execute():
+	company = frappe.get_all('Company', filters = {'country': 'Saudi Arabia'})
+	if not company:
+		return
+
+	make_custom_fields()
+
diff --git a/erpnext/patches/v13_0/create_pan_field_for_india.py b/erpnext/patches/v13_0/create_pan_field_for_india.py
index c37651a..6df6e1e 100644
--- a/erpnext/patches/v13_0/create_pan_field_for_india.py
+++ b/erpnext/patches/v13_0/create_pan_field_for_india.py
@@ -5,6 +5,7 @@
 def execute():
 	frappe.reload_doc('buying', 'doctype', 'supplier', force=True)
 	frappe.reload_doc('selling', 'doctype', 'customer', force=True)
+	frappe.reload_doc('core', 'doctype', 'doctype', force=True)
 
 	custom_fields = {
 		'Supplier': [
diff --git a/erpnext/patches/v13_0/custom_fields_for_taxjar_integration.py b/erpnext/patches/v13_0/custom_fields_for_taxjar_integration.py
index fba9e2c..078c558 100644
--- a/erpnext/patches/v13_0/custom_fields_for_taxjar_integration.py
+++ b/erpnext/patches/v13_0/custom_fields_for_taxjar_integration.py
@@ -21,13 +21,17 @@
 			dict(fieldname='product_tax_category', fieldtype='Link', insert_after='description', options='Product Tax Category',
 				label='Product Tax Category', fetch_from='item_code.product_tax_category'),
 			dict(fieldname='tax_collectable', fieldtype='Currency', insert_after='net_amount',
-				label='Tax Collectable', read_only=1),
+				label='Tax Collectable', read_only=1, options='currency'),
 			dict(fieldname='taxable_amount', fieldtype='Currency', insert_after='tax_collectable',
-				label='Taxable Amount', read_only=1)
+				label='Taxable Amount', read_only=1, options='currency')
 		],
 		'Item': [
 			dict(fieldname='product_tax_category', fieldtype='Link', insert_after='item_group', options='Product Tax Category',
 				label='Product Tax Category')
+		],
+		'TaxJar Settings': [
+			dict(fieldname='company', fieldtype='Link', insert_after='configuration', options='Company',
+				label='Company')
 		]
 	}
 	create_custom_fields(custom_fields, update=True)
diff --git a/erpnext/patches/v13_0/item_naming_series_not_mandatory.py b/erpnext/patches/v13_0/item_naming_series_not_mandatory.py
new file mode 100644
index 0000000..5fe85a4
--- /dev/null
+++ b/erpnext/patches/v13_0/item_naming_series_not_mandatory.py
@@ -0,0 +1,11 @@
+import frappe
+
+from erpnext.setup.doctype.naming_series.naming_series import set_by_naming_series
+
+
+def execute():
+
+	stock_settings = frappe.get_doc("Stock Settings")
+
+	set_by_naming_series("Item", "item_code",
+		stock_settings.get("item_naming_by")=="Naming Series", hide_name_field=True, make_mandatory=0)
diff --git a/erpnext/patches/v13_0/update_job_card_status.py b/erpnext/patches/v13_0/update_job_card_status.py
new file mode 100644
index 0000000..797a3e2
--- /dev/null
+++ b/erpnext/patches/v13_0/update_job_card_status.py
@@ -0,0 +1,18 @@
+# Copyright (c) 2021, Frappe and Contributors
+# License: GNU General Public License v3. See license.txt
+
+import frappe
+
+
+def execute():
+
+	job_card = frappe.qb.DocType("Job Card")
+	(frappe.qb
+		.update(job_card)
+		.set(job_card.status, "Completed")
+		.where(
+			(job_card.docstatus == 1)
+			& (job_card.for_quantity <= job_card.total_completed_qty)
+			& (job_card.status.isin(["Work In Progress", "Material Transferred"]))
+		)
+	).run()
diff --git a/erpnext/payroll/report/salary_register/salary_register.py b/erpnext/payroll/report/salary_register/salary_register.py
index 13ee691..78deb22 100644
--- a/erpnext/payroll/report/salary_register/salary_register.py
+++ b/erpnext/payroll/report/salary_register/salary_register.py
@@ -134,11 +134,11 @@
 
 	ss_earning_map = {}
 	for d in ss_earnings:
-		ss_earning_map.setdefault(d.parent, frappe._dict()).setdefault(d.salary_component, [])
+		ss_earning_map.setdefault(d.parent, frappe._dict()).setdefault(d.salary_component, 0.0)
 		if currency == company_currency:
-			ss_earning_map[d.parent][d.salary_component] = flt(d.amount) * flt(d.exchange_rate if d.exchange_rate else 1)
+			ss_earning_map[d.parent][d.salary_component] += flt(d.amount) * flt(d.exchange_rate if d.exchange_rate else 1)
 		else:
-			ss_earning_map[d.parent][d.salary_component] = flt(d.amount)
+			ss_earning_map[d.parent][d.salary_component] += flt(d.amount)
 
 	return ss_earning_map
 
@@ -149,10 +149,10 @@
 
 	ss_ded_map = {}
 	for d in ss_deductions:
-		ss_ded_map.setdefault(d.parent, frappe._dict()).setdefault(d.salary_component, [])
+		ss_ded_map.setdefault(d.parent, frappe._dict()).setdefault(d.salary_component, 0.0)
 		if currency == company_currency:
-			ss_ded_map[d.parent][d.salary_component] = flt(d.amount) * flt(d.exchange_rate if d.exchange_rate else 1)
+			ss_ded_map[d.parent][d.salary_component] += flt(d.amount) * flt(d.exchange_rate if d.exchange_rate else 1)
 		else:
-			ss_ded_map[d.parent][d.salary_component] = flt(d.amount)
+			ss_ded_map[d.parent][d.salary_component] += flt(d.amount)
 
 	return ss_ded_map
diff --git a/erpnext/regional/india/setup.py b/erpnext/regional/india/setup.py
index 42ee271..316bb6b 100644
--- a/erpnext/regional/india/setup.py
+++ b/erpnext/regional/india/setup.py
@@ -12,7 +12,7 @@
 
 def setup(company=None, patch=True):
 	# Company independent fixtures should be called only once at the first company setup
-	if frappe.db.count('Company', {'country': 'India'}) <=1:
+	if patch or frappe.db.count('Company', {'country': 'India'}) <=1:
 		setup_company_independent_fixtures(patch=patch)
 
 	if not patch:
diff --git a/erpnext/regional/india/utils.py b/erpnext/regional/india/utils.py
index 9efad6d..54d592a 100644
--- a/erpnext/regional/india/utils.py
+++ b/erpnext/regional/india/utils.py
@@ -26,12 +26,13 @@
 
 	gst_category = []
 
-	if len(doc.links):
-		link_doctype = doc.links[0].get("link_doctype")
-		link_name = doc.links[0].get("link_name")
+	if hasattr(doc, 'gst_category'):
+		if len(doc.links):
+			link_doctype = doc.links[0].get("link_doctype")
+			link_name = doc.links[0].get("link_name")
 
-		if link_doctype in ["Customer", "Supplier"]:
-			gst_category = frappe.db.get_value(link_doctype, {'name': link_name}, ['gst_category'])
+			if link_doctype in ["Customer", "Supplier"]:
+				gst_category = frappe.db.get_value(link_doctype, {'name': link_name}, ['gst_category'])
 
 	doc.gstin = doc.gstin.upper().strip()
 	if not doc.gstin or doc.gstin == 'NA':
@@ -73,12 +74,11 @@
 			frappe.throw(_("Intra State tax category for GST State {0} already exists").format(doc.gst_state))
 
 def update_gst_category(doc, method):
-	for link in doc.links:
-		if link.link_doctype in ['Customer', 'Supplier']:
-			if doc.get('gstin'):
-				frappe.db.sql("""
-					UPDATE `tab{0}` SET gst_category = %s WHERE name = %s AND gst_category = 'Unregistered'
-				""".format(link.link_doctype), ("Registered Regular", link.link_name)) #nosec
+	if hasattr(doc, 'gst_category'):
+		for link in doc.links:
+			if link.link_doctype in ['Customer', 'Supplier']:
+				if doc.get('gstin'):
+					frappe.db.set_value(link.link_doctype, {'name': link.link_name, 'gst_category': 'Unregistered'}, 'gst_category', 'Registered Regular')
 
 def set_gst_state_and_state_number(doc):
 	if not doc.gst_state:
@@ -443,7 +443,7 @@
 		data = get_address_details(data, doc, company_address, billing_address, dispatch_address)
 
 		data.itemList = []
-		data.totalValue = doc.total
+		data.totalValue = doc.net_total
 
 		data = get_item_list(data, doc, hsn_wise=True)
 
diff --git a/erpnext/regional/print_format/ksa_vat_invoice/__init__.py b/erpnext/regional/print_format/ksa_vat_invoice/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/regional/print_format/ksa_vat_invoice/__init__.py
diff --git a/erpnext/regional/print_format/ksa_vat_invoice/ksa_vat_invoice.json b/erpnext/regional/print_format/ksa_vat_invoice/ksa_vat_invoice.json
new file mode 100644
index 0000000..36d6536
--- /dev/null
+++ b/erpnext/regional/print_format/ksa_vat_invoice/ksa_vat_invoice.json
@@ -0,0 +1,32 @@
+{
+ "absolute_value": 0,
+ "align_labels_right": 0,
+ "creation": "2021-10-29 22:46:26.039023",
+ "css": ".qr-code{\n    float:right;\n}\n\n.invoice-heading {\n  margin: 0;\n}\n\n.ksa-invoice-table {\n  border: 1px solid #888a8e;\n  border-collapse: collapse;\n  width: 100%;\n  margin: 20px 0;\n  color: #888a8e;\n  font-size: 16px;\n}\n\n.ksa-invoice-table.two-columns td:nth-child(2) {\n  direction: rtl;\n}\n\n.ksa-invoice-table th {\n  border: 1px solid #888a8e;\n  max-width: 50%;\n  background-color: #265e4a !important;\n  color: #fff;\n  padding: 8px;\n}\n\n.ksa-invoice-table td {\n  padding: 5px;\n  border: 1px solid #888a8e;\n  max-width: 50%;\n}\n\n.ksa-invoice-table thead,\n.ksa-invoice-table tfoot {\n  text-transform: uppercase;\n}\n\n.qr-rtl {\n  direction: rtl;\n}\n\n.qr-flex{\n    display: flex;\n    justify-content: space-between;\n}",
+ "custom_format": 1,
+ "default_print_language": "en",
+ "disabled": 0,
+ "doc_type": "Sales Invoice",
+ "docstatus": 0,
+ "doctype": "Print Format",
+ "font_size": 14,
+ "html": "<div class=\"ksa-vat-format\">\n    <div class=\"qr-flex\">\n        <div style=\"qr-flex: 1\">\n            <h2 class=\"invoice-heading\">TAX INVOICE</h2>\n            <h2 class=\"invoice-heading\">\u0641\u0627\u062a\u0648\u0631\u0629 \u0636\u0631\u064a\u0628\u064a\u0629</h2>\n        </div>\n        \n        <img class=\"qr-code\" src={{doc.qr_code}}>\n    </div>\n    {% set company = frappe.get_doc(\"Company\", doc.company)%}\n    {% if (doc.company_address) %}\n        {% set supplier_address_doc = frappe.get_doc('Address', doc.company_address) %}\n    {% endif %}\n    \n    {% if(doc.customer_address) %}\n        {% set customer_address = frappe.get_doc('Address', doc.customer_address ) %}\n    {% endif %}\n    \n    {% if(doc.shipping_address_name) %}\n        {% set customer_shipping_address = frappe.get_doc('Address', doc.shipping_address_name ) %}\n    {% endif %}  \n        \n    <table class=\"ksa-invoice-table two-columns\">\n      <thead>\n        <tr>\n          <th>{{ company.name }}</th>\n          <th style=\"text-align: right;\">{{ company.company_name_in_arabic }}</th>\n        </tr>\n      </thead>\n\n      <tbody>\n        <!-- Invoice Info -->\n        <tr>\n          <td>Invoice#: {{doc.name}}</td>\n          <td>\u0631\u0642\u0645 \u0627\u0644\u0641\u0627\u062a\u0648\u0631\u0629: {{doc.name}}</td>\n        </tr>\n        <tr>\n          <td>Invoice Date: {{doc.posting_date}}</td>\n          <td>\u062a\u0627\u0631\u064a\u062e \u0627\u0644\u0641\u0627\u062a\u0648\u0631\u0629: {{doc.posting_date}}</td>\n        </tr>\n        <tr>\n          <td>Date of Supply:{{doc.posting_date}}</td>\n          <td>\u062a\u0627\u0631\u064a\u062e \u0627\u0644\u062a\u0648\u0631\u064a\u062f: {{doc.posting_date}}</td>\n        </tr>\n        \n        <!--Supplier Info -->\n        <tr>\n          <td>Supplier:</td>\n          <td>\u0627\u0644\u0645\u0648\u0631\u062f:</td>\n        </tr>\n\t\t{% if (company.tax_id) %}\n        <tr>\n          <td>Supplier Tax Identification Number:</td>\n          <td>\u0631\u0642\u0645 \u0627\u0644\u062a\u0639\u0631\u064a\u0641 \u0627\u0644\u0636\u0631\u064a\u0628\u064a \u0644\u0644\u0645\u0648\u0631\u062f:</td>\n        </tr>\n        <tr>\n          <td>{{ company.tax_id }}</td>\n          <td>{{ company.tax_id }}</td>\n        </tr>\n        {% endif %}\n        <tr>\n          <td>{{ company.name }}</td>\n          <td>{{ company.company_name_in_arabic }} </td>\n        </tr>\n        \n        \n        {% if(supplier_address_doc) %}\n        <tr>\n          <td>{{ supplier_address_doc.address_line1}} </td>\n          <td>{{ supplier_address_doc.address_in_arabic}} </td>\n        </tr>\n        <tr>\n          <td>Phone: {{ supplier_address_doc.phone }}</td>\n          <td>\u0647\u0627\u062a\u0641: {{ supplier_address_doc.phone }}</td>\n        </tr>\n        <tr>\n          <td>Email: {{ supplier_address_doc.email_id }}</td>\n          <td>\u0628\u0631\u064a\u062f \u0627\u0644\u0643\u062a\u0631\u0648\u0646\u064a: {{ supplier_address_doc.email_id }}</td>\n        </tr>\n        {% endif %}\n        \n        <!-- Customer Info -->\n        <tr>\n          <td>CUSTOMER:</td>\n          <td>\u0639\u0645\u064a\u0644:</td>\n        </tr>\n\t\t{% set customer_tax_id = frappe.db.get_value('Customer', doc.customer, 'tax_id') %}\n\t\t{% if customer_tax_id %}\n        <tr>\n          <td>Customer Tax Identification Number:</td>\n          <td>\u0631\u0642\u0645 \u0627\u0644\u062a\u0639\u0631\u064a\u0641 \u0627\u0644\u0636\u0631\u064a\u0628\u064a \u0644\u0644\u0639\u0645\u064a\u0644:</td>\n        </tr>\n        <tr>\n          <td>{{ customer_tax_id }}</td>\n          <td>{{ customer_tax_id }}</td>\n        </tr>\n        {% endif %}\n        <tr>\n          <td> {{ doc.customer }}</td>\n          <td> {{ doc.customer_name_in_arabic }} </td>\n        </tr>\n        \n        {% if(customer_address) %}\n        <tr>\n          <td>{{ customer_address.address_line1}} </td>\n          <td>{{ customer_address.address_in_arabic}} </td>\n        </tr>\n        {% endif %}\n        \n        {% if(customer_shipping_address) %}\n        <tr>\n          <td>SHIPPING ADDRESS:</td>\n          <td>\u0639\u0646\u0648\u0627\u0646 \u0627\u0644\u0634\u062d\u0646:</td>\n        </tr>\n        \n        <tr>\n          <td>{{ customer_shipping_address.address_line1}} </td>\n          <td>{{ customer_shipping_address.address_in_arabic}} </td>\n        </tr>\n        {% endif %}\n        \n\t\t{% if(doc.po_no) %}\n        <tr>\n          <td>OTHER INFORMATION</td>\n          <td>\u0645\u0639\u0644\u0648\u0645\u0627\u062a \u0623\u062e\u0631\u0649</td>\n        </tr>\n        \n        <tr>\n          <td>Purchase Order Number: {{ doc.po_no }}</td>\n          <td>\u0631\u0642\u0645 \u0623\u0645\u0631 \u0627\u0644\u0634\u0631\u0627\u0621: {{ doc.po_no }}</td>\n        </tr>\n        {% endif %}\n        \n        <tr>\n          <td>Payment Due Date: {{  doc.due_date}} </td>\n          <td>\u062a\u0627\u0631\u064a\u062e \u0627\u0633\u062a\u062d\u0642\u0627\u0642 \u0627\u0644\u062f\u0641\u0639: {{  doc.due_date}}</td>\n        </tr>\n      </tbody>\n    </table>\n\n    <!--Dynamic Colspan for total row columns-->\n    {% set col = namespace(one = 2, two = 1) %}\n    {% set length = doc.taxes | length %}\n    {% set length = length / 2 | round %}\n    {% set col.one = col.one + length %}\n    {% set col.two = col.two + length %}\n  \n    {%- if(doc.taxes | length % 2 > 0 ) -%}\n      {% set col.two = col.two + 1 %}\n    {% endif %}\n    \n    <!-- Items -->\n    {% set total = namespace(amount = 0) %}\n    <table class=\"ksa-invoice-table\">\n      <thead>\n        <tr>\n          <th>Nature of goods or services <br />\u0637\u0628\u064a\u0639\u0629 \u0627\u0644\u0633\u0644\u0639 \u0623\u0648 \u0627\u0644\u062e\u062f\u0645\u0627\u062a</th>\n          <th>\n            Unit price <br />\n            \u0633\u0639\u0631 \u0627\u0644\u0648\u062d\u062f\u0629\n          </th>\n          <th>\n            Quantity <br />\n            \u0627\u0644\u0643\u0645\u064a\u0629\n          </th>\n          <th>\n            Taxable Amount <br />\n            \u0627\u0644\u0645\u0628\u0644\u063a \u0627\u0644\u062e\u0627\u0636\u0639 \u0644\u0644\u0636\u0631\u064a\u0628\u0629\n          </th>\n          \n          {% for row in doc.taxes %}\n            <th style=\"min-width: 130px\">{{row.description}}</th>\n          {% endfor %}\n          \n          <th>\n            Total <br />\n            \u0627\u0644\u0645\u062c\u0645\u0648\u0639\n          </th>\n        </tr>\n      </thead>\n      <tbody>\n        {%- for item in doc.items -%}\n        {% set total.amount = item.amount %}\n        <tr>\n          <td>{{ item.item_code }}</td>\n          <td>{{ item.get_formatted(\"rate\") }}</td>\n          <td>{{ item.qty }}</td>\n          <td>{{ item.get_formatted(\"amount\") }}</td>\n           {% for row in doc.taxes %}\n                {% set data_object = json.loads(row.item_wise_tax_detail) %}\n                <td>\n                   <div class=\"qr-flex\">\n                    {%- if(data_object[item.item_code][0])-%}\n                    <span>{{ frappe.format(data_object[item.item_code][0], {'fieldtype': 'Percent'}) }}</span>\n                    {%- endif -%}\n                    <span>\n                    {%- if(data_object[item.item_code][1])-%}\n                        {{ frappe.format(data_object[item.item_code][1], {'fieldtype': 'Currency'}) }}</span>\n                        {% set total.amount = total.amount + data_object[item.item_code][1] %}\n                    {%- endif -%}\n                    </div>\n                </td>\n            {% endfor %}\n          <td>{{  frappe.format(total.amount, {'fieldtype': 'Currency'}) }}</td>\n        </tr>\n        {%- endfor -%}\n      </tbody>\n      <tfoot>\n        <tr>\n          <td>\n            {{ doc.get_formatted(\"total\") }} <br />\n            {{ doc.get_formatted(\"total_taxes_and_charges\") }}\n          </td>\n          \n          <td colspan={{ col.one }} class=\"qr-rtl\">\n            \u0627\u0644\u0625\u062c\u0645\u0627\u0644\u064a \u0628\u0627\u0633\u062a\u062b\u0646\u0627\u0621 \u0636\u0631\u064a\u0628\u0629 \u0627\u0644\u0642\u064a\u0645\u0629 \u0627\u0644\u0645\u0636\u0627\u0641\u0629\n            <br />\n            \u0625\u062c\u0645\u0627\u0644\u064a \u0636\u0631\u064a\u0628\u0629 \u0627\u0644\u0642\u064a\u0645\u0629 \u0627\u0644\u0645\u0636\u0627\u0641\u0629\n          </td>\n          <td colspan={{ col.two }}>\n            Total (Excluding VAT)\n            <br />\n            Total VAT\n          </td>\n          <td>\n            {{ doc.get_formatted(\"total\") }} <br />\n            {{ doc.get_formatted(\"total_taxes_and_charges\") }}\n          </td>\n        </tr>\n        <tr>\n          <td>{{ doc.get_formatted(\"grand_total\") }}</td>\n          <td  colspan={{  col.one }} class=\"qr-rtl\">\n              \u0625\u062c\u0645\u0627\u0644\u064a \u0627\u0644\u0645\u0628\u0644\u063a \u0627\u0644\u0645\u0633\u062a\u062d\u0642</td>\n          <td  colspan={{  col.two }}>Total Amount Due</td>\n          <td>{{ doc.get_formatted(\"grand_total\") }}</td>\n        </tr>\n      </tfoot>\n    </table>\n\n\t{%- if doc.terms -%}\n    <p>\n      {{doc.terms}}\n    </p>\n\t{%- endif -%}\n</div>\n",
+ "idx": 0,
+ "line_breaks": 0,
+ "margin_bottom": 15.0,
+ "margin_left": 15.0,
+ "margin_right": 15.0,
+ "margin_top": 15.0,
+ "modified": "2021-11-08 09:19:18.660806",
+ "modified_by": "Administrator",
+ "module": "Regional",
+ "name": "KSA VAT Invoice",
+ "owner": "Administrator",
+ "page_number": "Hide",
+ "print_format_builder": 0,
+ "print_format_builder_beta": 0,
+ "print_format_type": "Jinja",
+ "raw_printing": 0,
+ "show_section_headings": 0,
+ "standard": "Yes"
+}
\ No newline at end of file
diff --git a/erpnext/regional/report/gstr_1/gstr_1.py b/erpnext/regional/report/gstr_1/gstr_1.py
index 27cfaf7..11b684d 100644
--- a/erpnext/regional/report/gstr_1/gstr_1.py
+++ b/erpnext/regional/report/gstr_1/gstr_1.py
@@ -248,18 +248,17 @@
 		""" % (self.doctype, ', '.join(['%s']*len(self.invoices))), tuple(self.invoices), as_dict=1)
 
 		for d in items:
-			if d.item_code not in self.invoice_items.get(d.parent, {}):
-				self.invoice_items.setdefault(d.parent, {}).setdefault(d.item_code, 0.0)
-				self.invoice_items[d.parent][d.item_code] += d.get('taxable_value', 0) or d.get('base_net_amount', 0)
+			self.invoice_items.setdefault(d.parent, {}).setdefault(d.item_code, 0.0)
+			self.invoice_items[d.parent][d.item_code] += d.get('taxable_value', 0) or d.get('base_net_amount', 0)
 
-				item_tax_rate = {}
+			item_tax_rate = {}
 
-				if d.item_tax_rate:
-					item_tax_rate = json.loads(d.item_tax_rate)
+			if d.item_tax_rate:
+				item_tax_rate = json.loads(d.item_tax_rate)
 
-					for account, rate in item_tax_rate.items():
-						tax_rate_dict = self.item_tax_rate.setdefault(d.parent, {}).setdefault(d.item_code, [])
-						tax_rate_dict.append(rate)
+				for account, rate in item_tax_rate.items():
+					tax_rate_dict = self.item_tax_rate.setdefault(d.parent, {}).setdefault(d.item_code, [])
+					tax_rate_dict.append(rate)
 
 	def get_items_based_on_tax_rate(self):
 		self.tax_details = frappe.db.sql("""
diff --git a/erpnext/regional/report/ksa_vat/ksa_vat.js b/erpnext/regional/report/ksa_vat/ksa_vat.js
index d46d260..59e72c3 100644
--- a/erpnext/regional/report/ksa_vat/ksa_vat.js
+++ b/erpnext/regional/report/ksa_vat/ksa_vat.js
@@ -49,7 +49,6 @@
 				value = $(`<span>${value}</span>`);
 				var $value = $(value).css("font-weight", "bold");
 				value = $value.wrap("<p></p>").parent().html();
-				console.log($value)
 				return value
 			}
 		}else{
diff --git a/erpnext/regional/report/ksa_vat/ksa_vat.py b/erpnext/regional/report/ksa_vat/ksa_vat.py
index 198b0b2..b41b2b0 100644
--- a/erpnext/regional/report/ksa_vat/ksa_vat.py
+++ b/erpnext/regional/report/ksa_vat/ksa_vat.py
@@ -118,14 +118,14 @@
 	total_taxable_adjustment_amount = 0
 	total_tax = 0
 	# Fetch All Invoices
-	invoices = frappe.get_list(doctype,
+	invoices = frappe.get_all(doctype,
 	filters ={
 		'docstatus': 1,
 		'posting_date': ['between', [from_date, to_date]]
 	}, fields =['name', 'is_return'])
 
 	for invoice in invoices:
-		invoice_items = frappe.get_list(f'{doctype} Item',
+		invoice_items = frappe.get_all(f'{doctype} Item',
 		filters ={
 			'docstatus': 1,
 			'parent': invoice.name,
diff --git a/erpnext/regional/saudi_arabia/setup.py b/erpnext/regional/saudi_arabia/setup.py
index ee25b38..38a089c 100644
--- a/erpnext/regional/saudi_arabia/setup.py
+++ b/erpnext/regional/saudi_arabia/setup.py
@@ -5,14 +5,13 @@
 from frappe.permissions import add_permission, update_permission_property
 from erpnext.regional.united_arab_emirates.setup import make_custom_fields as uae_custom_fields, add_print_formats
 from erpnext.regional.saudi_arabia.wizard.operations.setup_ksa_vat_setting import create_ksa_vat_setting
-from frappe.custom.doctype.custom_field.custom_field import create_custom_field
+from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
 
 def setup(company=None, patch=True):
 	uae_custom_fields()
 	add_print_formats()
 	add_permissions()
-	create_ksa_vat_setting(company)
-	make_qrcode_field()
+	make_custom_fields()
 
 def add_permissions():
 	"""Add Permissions for KSA VAT Setting."""
@@ -25,12 +24,40 @@
 	"""Enable KSA VAT Report"""
 	frappe.db.set_value('Report', 'KSA VAT', 'disabled', 0)
 
-def make_qrcode_field():
-	"""Created QR code Image file"""
-	qr_code_field = dict(
-		fieldname='qr_code',
-		label='QR Code',
-		fieldtype='Attach Image',
-		read_only=1, no_copy=1, hidden=1)
+def make_custom_fields():
+	"""Create Custom fields
+	- QR code Image file
+	- Company Name in Arabic
+	- Address in Arabic
+	"""
+	custom_fields = {
+		'Sales Invoice': [
+			dict(
+				fieldname='qr_code',
+				label='QR Code',
+				fieldtype='Attach Image',
+				read_only=1, no_copy=1, hidden=1
+			)
+		],
+		'Address': [
+			dict(
+				fieldname='address_in_arabic',
+				label='Address in Arabic',
+				fieldtype='Data',
+				insert_after='address_line2'
+			)
+		],
+		'Company': [
+			dict(
+				fieldname='company_name_in_arabic',
+				label='Company Name In Arabic',
+				fieldtype='Data',
+				insert_after='company_name'
+			)
+		]
+	}
 
-	create_custom_field('Sales Invoice', qr_code_field)
+	create_custom_fields(custom_fields, update=True)
+
+def update_regional_tax_settings(country, company):
+	create_ksa_vat_setting(company)
diff --git a/erpnext/regional/saudi_arabia/wizard/data/ksa_vat_settings.json b/erpnext/regional/saudi_arabia/wizard/data/ksa_vat_settings.json
index 709d65b..60951a9 100644
--- a/erpnext/regional/saudi_arabia/wizard/data/ksa_vat_settings.json
+++ b/erpnext/regional/saudi_arabia/wizard/data/ksa_vat_settings.json
@@ -15,7 +15,7 @@
             {
                 "title": "Exempted sales",
                 "item_tax_template": "KSA VAT Exempted",
-                "account": "VAT Zero"
+                "account": "VAT Exempted"
             }
         ]
     },
@@ -40,7 +40,7 @@
             {
                 "title": "Exempted purchases",
                 "item_tax_template": "KSA VAT Exempted",
-                "account": "VAT Zero"
+                "account": "VAT Exempted"
             }
         ]
     }
diff --git a/erpnext/regional/saudi_arabia/wizard/operations/setup_ksa_vat_setting.py b/erpnext/regional/saudi_arabia/wizard/operations/setup_ksa_vat_setting.py
index 3c89edd..97300dc 100644
--- a/erpnext/regional/saudi_arabia/wizard/operations/setup_ksa_vat_setting.py
+++ b/erpnext/regional/saudi_arabia/wizard/operations/setup_ksa_vat_setting.py
@@ -3,14 +3,11 @@
 
 import frappe
 
-from erpnext.setup.setup_wizard.operations.taxes_setup import setup_taxes_and_charges
-
 
 def create_ksa_vat_setting(company):
     """On creation of first company. Creates KSA VAT Setting"""
 
     company = frappe.get_doc('Company', company)
-    setup_taxes_and_charges(company.name, company.country)
 
     file_path = os.path.join(os.path.dirname(__file__), '..', 'data', 'ksa_vat_settings.json')
     with open(file_path, 'r') as json_file:
diff --git a/erpnext/selling/doctype/quotation/quotation.json b/erpnext/selling/doctype/quotation/quotation.json
index 43a4490..ad788e5 100644
--- a/erpnext/selling/doctype/quotation/quotation.json
+++ b/erpnext/selling/doctype/quotation/quotation.json
@@ -110,7 +110,8 @@
   "enq_det",
   "supplier_quotation",
   "opportunity",
-  "lost_reasons"
+  "lost_reasons",
+  "competitors"
  ],
  "fields": [
   {
@@ -946,6 +947,14 @@
    "label": "Bundle Items",
    "options": "fa fa-suitcase",
    "print_hide": 1
+  },
+  {
+   "allow_on_submit": 1,
+   "fieldname": "competitors",
+   "fieldtype": "Table MultiSelect",
+   "label": "Competitors",
+   "options": "Competitor Detail",
+   "read_only": 1
   }
  ],
  "icon": "fa fa-shopping-cart",
@@ -953,10 +962,12 @@
  "is_submittable": 1,
  "links": [],
  "max_attachments": 1,
- "modified": "2021-08-27 20:10:07.864951",
+ "migration_hash": "75a86a19f062c2257bcbc8e6e31c7f1e",
+ "modified": "2021-10-21 12:58:55.514512",
  "modified_by": "Administrator",
  "module": "Selling",
  "name": "Quotation",
+ "naming_rule": "By \"Naming Series\" field",
  "owner": "Administrator",
  "permissions": [
   {
diff --git a/erpnext/selling/doctype/quotation/quotation.py b/erpnext/selling/doctype/quotation/quotation.py
index 31b62d6..c4752ae 100644
--- a/erpnext/selling/doctype/quotation/quotation.py
+++ b/erpnext/selling/doctype/quotation/quotation.py
@@ -68,7 +68,7 @@
 		opp.set_status(status=status, update=True)
 
 	@frappe.whitelist()
-	def declare_enquiry_lost(self, lost_reasons_list, detailed_reason=None):
+	def declare_enquiry_lost(self, lost_reasons_list, competitors, detailed_reason=None):
 		if not self.has_sales_order():
 			get_lost_reasons = frappe.get_list('Quotation Lost Reason',
 			fields = ["name"])
@@ -84,6 +84,9 @@
 				else:
 					frappe.throw(_("Invalid lost reason {0}, please create a new lost reason").format(frappe.bold(reason.get('lost_reason'))))
 
+			for competitor in competitors:
+				self.append('competitors', competitor)
+
 			self.update_opportunity('Lost')
 			self.update_lead()
 			self.save()
diff --git a/erpnext/selling/doctype/sales_order/sales_order.js b/erpnext/selling/doctype/sales_order/sales_order.js
index d46c46f..79e9e17 100644
--- a/erpnext/selling/doctype/sales_order/sales_order.js
+++ b/erpnext/selling/doctype/sales_order/sales_order.js
@@ -319,7 +319,7 @@
 						title: __('Select Items to Manufacture'),
 						fields: fields,
 						primary_action: function() {
-							var data = d.get_values();
+							var data = {items: d.fields_dict.items.grid.get_selected_children()};
 							me.frm.call({
 								method: 'make_work_orders',
 								args: {
diff --git a/erpnext/selling/doctype/sales_order/sales_order.py b/erpnext/selling/doctype/sales_order/sales_order.py
index 8cb0f29..47b8ebd 100755
--- a/erpnext/selling/doctype/sales_order/sales_order.py
+++ b/erpnext/selling/doctype/sales_order/sales_order.py
@@ -223,60 +223,15 @@
 			check_credit_limit(self.customer, self.company)
 
 	def check_nextdoc_docstatus(self):
-		# Checks Delivery Note
-		submit_dn = frappe.db.sql_list("""
-			select t1.name
-			from `tabDelivery Note` t1,`tabDelivery Note Item` t2
-			where t1.name = t2.parent and t2.against_sales_order = %s and t1.docstatus = 1""", self.name)
-
-		if submit_dn:
-			submit_dn = [get_link_to_form("Delivery Note", dn) for dn in submit_dn]
-			frappe.throw(_("Delivery Notes {0} must be cancelled before cancelling this Sales Order")
-				.format(", ".join(submit_dn)))
-
-		# Checks Sales Invoice
-		submit_rv = frappe.db.sql_list("""select t1.name
+		linked_invoices = frappe.db.sql_list("""select distinct t1.name
 			from `tabSales Invoice` t1,`tabSales Invoice Item` t2
-			where t1.name = t2.parent and t2.sales_order = %s and t1.docstatus < 2""",
+			where t1.name = t2.parent and t2.sales_order = %s and t1.docstatus = 0""",
 			self.name)
 
-		if submit_rv:
-			submit_rv = [get_link_to_form("Sales Invoice", si) for si in submit_rv]
-			frappe.throw(_("Sales Invoice {0} must be cancelled before cancelling this Sales Order")
-				.format(", ".join(submit_rv)))
-
-		#check maintenance schedule
-		submit_ms = frappe.db.sql_list("""
-			select t1.name
-			from `tabMaintenance Schedule` t1, `tabMaintenance Schedule Item` t2
-			where t2.parent=t1.name and t2.sales_order = %s and t1.docstatus = 1""", self.name)
-
-		if submit_ms:
-			submit_ms = [get_link_to_form("Maintenance Schedule", ms) for ms in submit_ms]
-			frappe.throw(_("Maintenance Schedule {0} must be cancelled before cancelling this Sales Order")
-				.format(", ".join(submit_ms)))
-
-		# check maintenance visit
-		submit_mv = frappe.db.sql_list("""
-			select t1.name
-			from `tabMaintenance Visit` t1, `tabMaintenance Visit Purpose` t2
-			where t2.parent=t1.name and t2.prevdoc_docname = %s and t1.docstatus = 1""",self.name)
-
-		if submit_mv:
-			submit_mv = [get_link_to_form("Maintenance Visit", mv) for mv in submit_mv]
-			frappe.throw(_("Maintenance Visit {0} must be cancelled before cancelling this Sales Order")
-				.format(", ".join(submit_mv)))
-
-		# check work order
-		pro_order = frappe.db.sql_list("""
-			select name
-			from `tabWork Order`
-			where sales_order = %s and docstatus = 1""", self.name)
-
-		if pro_order:
-			pro_order = [get_link_to_form("Work Order", po) for po in pro_order]
-			frappe.throw(_("Work Order {0} must be cancelled before cancelling this Sales Order")
-				.format(", ".join(pro_order)))
+		if linked_invoices:
+			linked_invoices = [get_link_to_form("Sales Invoice", si) for si in linked_invoices]
+			frappe.throw(_("Sales Invoice {0} must be deleted before cancelling this Sales Order")
+				.format(", ".join(linked_invoices)))
 
 	def check_modified_date(self):
 		mod_db = frappe.db.get_value("Sales Order", self.name, "modified")
diff --git a/erpnext/selling/doctype/sales_order/test_sales_order.py b/erpnext/selling/doctype/sales_order/test_sales_order.py
index 644c0ac..2a0752e 100644
--- a/erpnext/selling/doctype/sales_order/test_sales_order.py
+++ b/erpnext/selling/doctype/sales_order/test_sales_order.py
@@ -10,6 +10,12 @@
 from frappe.utils import add_days, flt, getdate, nowdate
 
 from erpnext.controllers.accounts_controller import update_child_qty_rate
+from erpnext.maintenance.doctype.maintenance_schedule.test_maintenance_schedule import (
+	make_maintenance_schedule,
+)
+from erpnext.maintenance.doctype.maintenance_visit.test_maintenance_visit import (
+	make_maintenance_visit,
+)
 from erpnext.manufacturing.doctype.blanket_order.test_blanket_order import make_blanket_order
 from erpnext.selling.doctype.product_bundle.test_product_bundle import make_product_bundle
 from erpnext.selling.doctype.sales_order.sales_order import (
@@ -1278,6 +1284,72 @@
 
 		self.assertRaises(frappe.ValidationError, so.cancel)
 
+	def test_so_cancellation_after_si_submission(self):
+		"""
+			Test to check if Sales Order gets cancelled when linked Sales Invoice has been Submitted
+			Expected result: Sales Order should not get cancelled
+		"""
+		so = make_sales_order()
+		so.submit()
+		si = make_sales_invoice(so.name)
+		si.submit()
+
+		so.load_from_db()
+		self.assertRaises(frappe.LinkExistsError, so.cancel)
+
+	def test_so_cancellation_after_dn_submission(self):
+		"""
+			Test to check if Sales Order gets cancelled when linked Delivery Note has been Submitted
+			Expected result: Sales Order should not get cancelled
+		"""
+		so = make_sales_order()
+		so.submit()
+		dn = make_delivery_note(so.name)
+		dn.submit()
+
+		so.load_from_db()
+		self.assertRaises(frappe.LinkExistsError, so.cancel)
+
+	def test_so_cancellation_after_maintenance_schedule_submission(self):
+		"""
+			Expected result: Sales Order should not get cancelled
+		"""
+		so = make_sales_order()
+		so.submit()
+		ms = make_maintenance_schedule()
+		ms.items[0].sales_order = so.name
+		ms.submit()
+
+		so.load_from_db()
+		self.assertRaises(frappe.LinkExistsError, so.cancel)
+
+	def test_so_cancellation_after_maintenance_visit_submission(self):
+		"""
+			Expected result: Sales Order should not get cancelled
+		"""
+		so = make_sales_order()
+		so.submit()
+		mv = make_maintenance_visit()
+		mv.purposes[0].prevdoc_doctype = "Sales Order"
+		mv.purposes[0].prevdoc_docname = so.name
+		mv.submit()
+
+		so.load_from_db()
+		self.assertRaises(frappe.LinkExistsError, so.cancel)
+
+	def test_so_cancellation_after_work_order_submission(self):
+		"""
+			Expected result: Sales Order should not get cancelled
+		"""
+		from erpnext.manufacturing.doctype.work_order.test_work_order import make_wo_order_test_record
+
+		so = make_sales_order(item_code="_Test FG Item", qty=10)
+		so.submit()
+		make_wo_order_test_record(sales_order=so.name)
+
+		so.load_from_db()
+		self.assertRaises(frappe.LinkExistsError, so.cancel)
+
 	def test_payment_terms_are_fetched_when_creating_sales_invoice(self):
 		from erpnext.accounts.doctype.payment_entry.test_payment_entry import (
 			create_payment_terms_template,
diff --git a/erpnext/selling/doctype/sales_team/sales_team.json b/erpnext/selling/doctype/sales_team/sales_team.json
index 8767891..cac5b76 100644
--- a/erpnext/selling/doctype/sales_team/sales_team.json
+++ b/erpnext/selling/doctype/sales_team/sales_team.json
@@ -1,247 +1,100 @@
 {
- "allow_copy": 0, 
- "allow_guest_to_view": 0, 
- "allow_import": 0, 
- "allow_rename": 0, 
- "beta": 0, 
- "creation": "2013-04-19 13:30:51", 
- "custom": 0, 
- "docstatus": 0, 
- "doctype": "DocType", 
- "document_type": "Setup", 
- "editable_grid": 1, 
- "engine": "InnoDB", 
+ "actions": [],
+ "creation": "2013-04-19 13:30:51",
+ "doctype": "DocType",
+ "document_type": "Setup",
+ "editable_grid": 1,
+ "engine": "InnoDB",
+ "field_order": [
+  "sales_person",
+  "contact_no",
+  "allocated_percentage",
+  "allocated_amount",
+  "commission_rate",
+  "incentives"
+ ],
  "fields": [
   {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 1, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "sales_person", 
-   "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": "Sales Person", 
-   "length": 0, 
-   "no_copy": 0, 
-   "oldfieldname": "sales_person", 
-   "oldfieldtype": "Link", 
-   "options": "Sales Person", 
-   "permlevel": 0, 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "print_width": "200px", 
-   "read_only": 0, 
-   "remember_last_selected_value": 0, 
-   "report_hide": 0, 
-   "reqd": 1, 
-   "search_index": 1, 
-   "set_only_once": 0, 
-   "translatable": 0, 
-   "unique": 0, 
+   "allow_on_submit": 1,
+   "fieldname": "sales_person",
+   "fieldtype": "Link",
+   "in_list_view": 1,
+   "label": "Sales Person",
+   "oldfieldname": "sales_person",
+   "oldfieldtype": "Link",
+   "options": "Sales Person",
+   "print_width": "200px",
+   "reqd": 1,
+   "search_index": 1,
    "width": "200px"
-  }, 
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 1, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "contact_no", 
-   "fieldtype": "Data", 
-   "hidden": 1, 
-   "ignore_user_permissions": 0, 
-   "ignore_xss_filter": 0, 
-   "in_filter": 0, 
-   "in_global_search": 0, 
-   "in_list_view": 1, 
-   "in_standard_filter": 0, 
-   "label": "Contact No.", 
-   "length": 0, 
-   "no_copy": 0, 
-   "oldfieldname": "contact_no", 
-   "oldfieldtype": "Data", 
-   "permlevel": 0, 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "print_width": "100px", 
-   "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_on_submit": 1,
+   "fieldname": "contact_no",
+   "fieldtype": "Data",
+   "hidden": 1,
+   "in_list_view": 1,
+   "label": "Contact No.",
+   "oldfieldname": "contact_no",
+   "oldfieldtype": "Data",
+   "print_width": "100px",
    "width": "100px"
-  }, 
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 1, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "allocated_percentage", 
-   "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": "Contribution (%)", 
-   "length": 0, 
-   "no_copy": 0, 
-   "oldfieldname": "allocated_percentage", 
-   "oldfieldtype": "Currency", 
-   "permlevel": 0, 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "print_width": "100px", 
-   "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_on_submit": 1,
+   "fieldname": "allocated_percentage",
+   "fieldtype": "Float",
+   "in_list_view": 1,
+   "label": "Contribution (%)",
+   "oldfieldname": "allocated_percentage",
+   "oldfieldtype": "Currency",
+   "print_width": "100px",
    "width": "100px"
-  }, 
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 1, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "allocated_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": "Contribution to Net Total", 
-   "length": 0, 
-   "no_copy": 0, 
-   "oldfieldname": "allocated_amount", 
-   "oldfieldtype": "Currency", 
-   "options": "Company:company:default_currency", 
-   "permlevel": 0, 
-   "print_hide": 0, 
-   "print_hide_if_no_value": 0, 
-   "print_width": "120px", 
-   "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_on_submit": 1,
+   "fieldname": "allocated_amount",
+   "fieldtype": "Currency",
+   "in_list_view": 1,
+   "label": "Contribution to Net Total",
+   "oldfieldname": "allocated_amount",
+   "oldfieldtype": "Currency",
+   "options": "Company:company:default_currency",
+   "print_width": "120px",
+   "read_only": 1,
    "width": "120px"
-  }, 
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 0, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "commission_rate", 
-   "fieldtype": "Data", 
-   "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": "Commission Rate", 
-   "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
-  }, 
+   "fetch_from": "sales_person.commission_rate",
+   "fetch_if_empty": 1,
+   "fieldname": "commission_rate",
+   "fieldtype": "Data",
+   "in_list_view": 1,
+   "label": "Commission Rate",
+   "read_only": 1
+  },
   {
-   "allow_bulk_edit": 0, 
-   "allow_in_quick_entry": 0, 
-   "allow_on_submit": 1, 
-   "bold": 0, 
-   "collapsible": 0, 
-   "columns": 0, 
-   "fieldname": "incentives", 
-   "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": "Incentives", 
-   "length": 0, 
-   "no_copy": 0, 
-   "oldfieldname": "incentives", 
-   "oldfieldtype": "Currency", 
-   "options": "Company:company:default_currency", 
-   "permlevel": 0, 
-   "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_on_submit": 1,
+   "fieldname": "incentives",
+   "fieldtype": "Currency",
+   "in_list_view": 1,
+   "label": "Incentives",
+   "oldfieldname": "incentives",
+   "oldfieldtype": "Currency",
+   "options": "Company:company:default_currency"
   }
- ], 
- "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-09-17 13:03:14.755974", 
- "modified_by": "Administrator", 
- "module": "Selling", 
- "name": "Sales Team", 
- "owner": "Administrator", 
- "permissions": [], 
- "quick_entry": 1, 
- "read_only": 0, 
- "read_only_onload": 0, 
- "show_name_in_global_search": 0, 
- "track_changes": 1, 
- "track_seen": 0, 
- "track_views": 0
-}
+ ],
+ "idx": 1,
+ "istable": 1,
+ "links": [],
+ "modified": "2021-11-09 23:55:20.670475",
+ "modified_by": "Administrator",
+ "module": "Selling",
+ "name": "Sales Team",
+ "owner": "Administrator",
+ "permissions": [],
+ "quick_entry": 1,
+ "sort_field": "modified",
+ "sort_order": "DESC",
+ "track_changes": 1
+}
\ No newline at end of file
diff --git a/erpnext/selling/sales_common.js b/erpnext/selling/sales_common.js
index a86e604..2050478 100644
--- a/erpnext/selling/sales_common.js
+++ b/erpnext/selling/sales_common.js
@@ -474,33 +474,37 @@
 					"reqd": 1
 				},
 				{
+					"fieldtype": "Table MultiSelect",
+					"label": __("Competitors"),
+					"fieldname": "competitors",
+					"options": "Competitor Detail"
+				},
+				{
 					"fieldtype": "Text",
 					"label": __("Detailed Reason"),
 					"fieldname": "detailed_reason"
 				},
 			],
 			primary_action: function() {
-				var values = dialog.get_values();
-				var reasons = values["lost_reason"];
-				var detailed_reason = values["detailed_reason"];
+				let values = dialog.get_values();
 
 				frm.call({
 					doc: frm.doc,
 					method: 'declare_enquiry_lost',
 					args: {
-						'lost_reasons_list': reasons,
-						'detailed_reason': detailed_reason
+						'lost_reasons_list': values.lost_reason,
+						'competitors': values.competitors,
+						'detailed_reason': values.detailed_reason
 					},
 					callback: function(r) {
 						dialog.hide();
 						frm.reload_doc();
 					},
 				});
-				refresh_field("lost_reason");
 			},
 			primary_action_label: __('Declare Lost')
 		});
 
 		dialog.show();
 	}
-})
+})
\ No newline at end of file
diff --git a/erpnext/setup/doctype/item_group/item_group.py b/erpnext/setup/doctype/item_group/item_group.py
index 4c42b61..c94b346 100644
--- a/erpnext/setup/doctype/item_group/item_group.py
+++ b/erpnext/setup/doctype/item_group/item_group.py
@@ -43,7 +43,6 @@
 	def on_update(self):
 		NestedSet.on_update(self)
 		invalidate_cache_for(self)
-		self.validate_name_with_item()
 		self.validate_one_root()
 		self.delete_child_item_groups_key()
 
@@ -67,10 +66,6 @@
 		WebsiteGenerator.on_trash(self)
 		self.delete_child_item_groups_key()
 
-	def validate_name_with_item(self):
-		if frappe.db.exists("Item", self.name):
-			frappe.throw(frappe._("An item exists with same name ({0}), please change the item group name or rename the item").format(self.name), frappe.NameError)
-
 	def get_context(self, context):
 		context.show_search=True
 		context.page_length = cint(frappe.db.get_single_value('Products Settings', 'products_per_page')) or 6
diff --git a/erpnext/setup/doctype/naming_series/naming_series.py b/erpnext/setup/doctype/naming_series/naming_series.py
index 4def6eb..986b4e8 100644
--- a/erpnext/setup/doctype/naming_series/naming_series.py
+++ b/erpnext/setup/doctype/naming_series/naming_series.py
@@ -180,11 +180,11 @@
 		prefix = parse_naming_series(parts)
 		return prefix
 
-def set_by_naming_series(doctype, fieldname, naming_series, hide_name_field=True):
+def set_by_naming_series(doctype, fieldname, naming_series, hide_name_field=True, make_mandatory=1):
 	from frappe.custom.doctype.property_setter.property_setter import make_property_setter
 	if naming_series:
 		make_property_setter(doctype, "naming_series", "hidden", 0, "Check", validate_fields_for_doctype=False)
-		make_property_setter(doctype, "naming_series", "reqd", 1, "Check", validate_fields_for_doctype=False)
+		make_property_setter(doctype, "naming_series", "reqd", make_mandatory, "Check", validate_fields_for_doctype=False)
 
 		# set values for mandatory
 		try:
diff --git a/erpnext/setup/setup_wizard/data/country_wise_tax.json b/erpnext/setup/setup_wizard/data/country_wise_tax.json
index 8a13385..14b7951 100644
--- a/erpnext/setup/setup_wizard/data/country_wise_tax.json
+++ b/erpnext/setup/setup_wizard/data/country_wise_tax.json
@@ -2120,6 +2120,10 @@
 			"account_name": "VAT 15%",
 			"tax_rate": 15.00
 		},
+		"KSA VAT 5%": {
+			"account_name": "VAT 5%",
+			"tax_rate": 5.00
+		},
 		"KSA VAT Zero": {
 			"account_name": "VAT Zero",
 			"tax_rate": 0.00
diff --git a/erpnext/shopping_cart/cart.py b/erpnext/shopping_cart/cart.py
index a7d90ea..ebbe233 100644
--- a/erpnext/shopping_cart/cart.py
+++ b/erpnext/shopping_cart/cart.py
@@ -194,7 +194,9 @@
 def create_lead_for_item_inquiry(lead, subject, message):
 	lead = frappe.parse_json(lead)
 	lead_doc = frappe.new_doc('Lead')
-	lead_doc.update(lead)
+	for fieldname in ("lead_name", "company_name", "email_id", "phone"):
+		lead_doc.set(fieldname, lead.get(fieldname))
+
 	lead_doc.set('lead_owner', '')
 
 	if not frappe.db.exists('Lead Source', 'Product Inquiry'):
@@ -202,6 +204,7 @@
 			'doctype': 'Lead Source',
 			'source_name' : 'Product Inquiry'
 		}).insert(ignore_permissions=True)
+
 	lead_doc.set('source', 'Product Inquiry')
 
 	try:
diff --git a/erpnext/stock/doctype/item/item.py b/erpnext/stock/doctype/item/item.py
index fa42c7d..5daabe8 100644
--- a/erpnext/stock/doctype/item/item.py
+++ b/erpnext/stock/doctype/item/item.py
@@ -152,7 +152,6 @@
 
 	def on_update(self):
 		invalidate_cache_for_item(self)
-		self.validate_name_with_item_group()
 		self.update_variants()
 		self.update_item_price()
 		self.update_template_item()
@@ -628,12 +627,6 @@
 				where item_code = %s and is_cancelled = 0 limit 1""", self.name))
 		return self._stock_ledger_created
 
-	def validate_name_with_item_group(self):
-		# causes problem with tree build
-		if frappe.db.exists("Item Group", self.name):
-			frappe.throw(
-				_("An Item Group exists with same name, please change the item name or rename the item group"))
-
 	def update_item_price(self):
 		frappe.db.sql("""
 				UPDATE `tabItem Price`
diff --git a/erpnext/stock/doctype/landed_cost_voucher/landed_cost_voucher.js b/erpnext/stock/doctype/landed_cost_voucher/landed_cost_voucher.js
index 433f78a..9c1a809 100644
--- a/erpnext/stock/doctype/landed_cost_voucher/landed_cost_voucher.js
+++ b/erpnext/stock/doctype/landed_cost_voucher/landed_cost_voucher.js
@@ -35,7 +35,7 @@
 	refresh() {
 		var help_content =
 			`<br><br>
-			<table class="table table-bordered" style="background-color: #f9f9f9;">
+			<table class="table table-bordered" style="background-color: var(--scrollbar-track-color);">
 				<tr><td>
 					<h4>
 						<i class="fa fa-hand-right"></i>
diff --git a/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py b/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py
index 86b4b86..170aa7f 100644
--- a/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py
+++ b/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py
@@ -31,6 +31,9 @@
 			self.voucher_type = None
 			self.voucher_no = None
 
+		self.allow_negative_stock = self.allow_negative_stock or \
+				cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
+
 	def set_company(self):
 		if self.voucher_type and self.voucher_no:
 			self.company = frappe.get_cached_value(self.voucher_type, self.voucher_no, "company")
diff --git a/erpnext/stock/doctype/serial_no/serial_no.py b/erpnext/stock/doctype/serial_no/serial_no.py
index d9d1957..38291d1 100644
--- a/erpnext/stock/doctype/serial_no/serial_no.py
+++ b/erpnext/stock/doctype/serial_no/serial_no.py
@@ -342,7 +342,7 @@
 	is_stock_reco = sle.voucher_type == "Stock Reconciliation"
 	msg = None
 
-	if sr and (actual_qty < 0 or is_stock_reco) and sr.warehouse != sle.warehouse:
+	if sr and (actual_qty < 0 or is_stock_reco) and (sr.warehouse and sr.warehouse != sle.warehouse):
 		# receipt(inward) is being cancelled
 		msg = _("Cannot cancel {0} {1} as Serial No {2} does not belong to the warehouse {3}").format(
 			sle.voucher_type, doc_link, sr_link, frappe.bold(sle.warehouse))
diff --git a/erpnext/stock/doctype/stock_entry/stock_entry.py b/erpnext/stock/doctype/stock_entry/stock_entry.py
index fa2436b..46c9576 100644
--- a/erpnext/stock/doctype/stock_entry/stock_entry.py
+++ b/erpnext/stock/doctype/stock_entry/stock_entry.py
@@ -1450,7 +1450,7 @@
 				item_dict[item]["qty"] = 0
 
 		# delete items with 0 qty
-		list_of_items = item_dict.keys()
+		list_of_items = list(item_dict.keys())
 		for item in list_of_items:
 			if not item_dict[item]["qty"]:
 				del item_dict[item]
diff --git a/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py b/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
index de89b2b..48e339a 100644
--- a/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
+++ b/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
@@ -399,6 +399,34 @@
 			, do_not_submit=True)
 		self.assertRaises(frappe.ValidationError, sr.submit)
 
+	def test_serial_no_cancellation(self):
+
+		from erpnext.stock.doctype.stock_entry.test_stock_entry import make_stock_entry
+		item = create_item("Stock-Reco-Serial-Item-9", is_stock_item=1)
+		if not item.has_serial_no:
+			item.has_serial_no = 1
+			item.serial_no_series = "SRS9.####"
+			item.save()
+
+		item_code = item.name
+		warehouse = "_Test Warehouse - _TC"
+
+		se1 = make_stock_entry(item_code=item_code, target=warehouse, qty=10, basic_rate=700)
+
+		serial_nos = get_serial_nos(se1.items[0].serial_no)
+		# reduce 1 item
+		serial_nos.pop()
+		new_serial_nos = "\n".join(serial_nos)
+
+		sr = create_stock_reconciliation(item_code=item.name, warehouse=warehouse, serial_no=new_serial_nos, qty=9)
+		sr.cancel()
+
+		active_sr_no = frappe.get_all("Serial No",
+				filters={"item_code": item_code, "warehouse": warehouse, "status": "Active"})
+
+		self.assertEqual(len(active_sr_no), 10)
+
+
 def create_batch_item_with_batch(item_name, batch_id):
 	batch_item_doc = create_item(item_name, is_stock_item=1)
 	if not batch_item_doc.has_batch_no:
diff --git a/erpnext/stock/doctype/stock_settings/stock_settings.py b/erpnext/stock/doctype/stock_settings/stock_settings.py
index 2dd103d..1de48b6 100644
--- a/erpnext/stock/doctype/stock_settings/stock_settings.py
+++ b/erpnext/stock/doctype/stock_settings/stock_settings.py
@@ -20,7 +20,7 @@
 
 		from erpnext.setup.doctype.naming_series.naming_series import set_by_naming_series
 		set_by_naming_series("Item", "item_code",
-			self.get("item_naming_by")=="Naming Series", hide_name_field=True)
+			self.get("item_naming_by")=="Naming Series", hide_name_field=True, make_mandatory=0)
 
 		stock_frozen_limit = 356
 		submitted_stock_frozen = self.stock_frozen_upto_days or 0
diff --git a/erpnext/stock/report/incorrect_balance_qty_after_transaction/incorrect_balance_qty_after_transaction.py b/erpnext/stock/report/incorrect_balance_qty_after_transaction/incorrect_balance_qty_after_transaction.py
index a381820..6aa12ac 100644
--- a/erpnext/stock/report/incorrect_balance_qty_after_transaction/incorrect_balance_qty_after_transaction.py
+++ b/erpnext/stock/report/incorrect_balance_qty_after_transaction/incorrect_balance_qty_after_transaction.py
@@ -46,7 +46,7 @@
 			return row
 
 def get_stock_ledger_entries(report_filters):
-	filters = {}
+	filters = {"is_cancelled": 0}
 	fields = ['name', 'voucher_type', 'voucher_no', 'item_code', 'actual_qty',
 		'posting_date', 'posting_time', 'company', 'warehouse', 'qty_after_transaction', 'batch_no']
 
diff --git a/erpnext/stock/stock_balance.py b/erpnext/stock/stock_balance.py
index 6ac8da1..6663458 100644
--- a/erpnext/stock/stock_balance.py
+++ b/erpnext/stock/stock_balance.py
@@ -160,7 +160,7 @@
 def get_planned_qty(item_code, warehouse):
 	planned_qty = frappe.db.sql("""
 		select sum(qty - produced_qty) from `tabWork Order`
-		where production_item = %s and fg_warehouse = %s and status not in ("Stopped", "Completed")
+		where production_item = %s and fg_warehouse = %s and status not in ("Stopped", "Completed", "Closed")
 		and docstatus=1 and qty > produced_qty""", (item_code, warehouse))
 
 	return flt(planned_qty[0][0]) if planned_qty else 0
diff --git a/erpnext/support/doctype/warranty_claim/warranty_claim.json b/erpnext/support/doctype/warranty_claim/warranty_claim.json
index 88ee4a3..45485ca 100644
--- a/erpnext/support/doctype/warranty_claim/warranty_claim.json
+++ b/erpnext/support/doctype/warranty_claim/warranty_claim.json
@@ -256,6 +256,7 @@
    "fieldname": "contact_email",
    "fieldtype": "Data",
    "label": "Contact Email",
+   "options": "Email",
    "read_only": 1
   },
   {
@@ -361,7 +362,7 @@
  ],
  "icon": "fa fa-bug",
  "idx": 1,
- "modified": "2020-09-18 17:26:09.703215",
+ "modified": "2021-11-09 17:26:09.703215",
  "modified_by": "Administrator",
  "module": "Support",
  "name": "Warranty Claim",
@@ -385,4 +386,4 @@
  "sort_order": "DESC",
  "timeline_field": "customer",
  "title_field": "customer_name"
-}
\ No newline at end of file
+}