feature(chart-of-accounts): Rebuild HSM Tree after bulk insertion (#15457)

* feature(chart-of-accounts): Rebuild HSM Tree after bulk insertion

* Update chart_of_accounts.py
diff --git a/erpnext/accounts/doctype/account/account.py b/erpnext/accounts/doctype/account/account.py
index eef85de..635a8c2 100644
--- a/erpnext/accounts/doctype/account/account.py
+++ b/erpnext/accounts/doctype/account/account.py
@@ -12,6 +12,11 @@
 
 class Account(NestedSet):
 	nsm_parent_field = 'parent_account'
+	def on_update(self):
+		if frappe.local.flags.ignore_on_update:
+			return
+		else:
+			super().on_update()
 
 	def onload(self):
 		frozen_accounts_modifier = frappe.db.get_value("Accounts Settings", "Accounts Settings",
diff --git a/erpnext/accounts/doctype/account/chart_of_accounts/chart_of_accounts.py b/erpnext/accounts/doctype/account/chart_of_accounts/chart_of_accounts.py
index f4cf6fa..9b812a8 100644
--- a/erpnext/accounts/doctype/account/chart_of_accounts/chart_of_accounts.py
+++ b/erpnext/accounts/doctype/account/chart_of_accounts/chart_of_accounts.py
@@ -6,6 +6,7 @@
 from frappe.utils import cstr
 from unidecode import unidecode
 from six import iteritems
+from frappe.utils.nestedset import rebuild_tree
 
 def create_charts(company, chart_template=None, existing_company=None):
 	chart = get_chart(chart_template, existing_company)
@@ -53,7 +54,12 @@
 
 					_import_accounts(child, account.name, root_type)
 
+		# Rebuild NestedSet HSM tree for Account Doctype
+		# after all accounts are already inserted.
+		frappe.local.flags.ignore_on_update = True
 		_import_accounts(chart, None, None, root_account=True)
+		rebuild_tree("Account", "parent_account")
+		frappe.local.flags.ignore_on_update = False
 
 def add_suffix_if_duplicate(account_name, account_number, accounts):
 	if account_number: