refactor(treewide): formatting and ruff fixes, + manually enabled F401

Signed-off-by: Akhil Narang <me@akhilnarang.dev>
diff --git a/.github/helper/documentation.py b/.github/helper/documentation.py
index 8334604..b4f9c39 100644
--- a/.github/helper/documentation.py
+++ b/.github/helper/documentation.py
@@ -1,7 +1,7 @@
 import sys
-import requests
 from urllib.parse import urlparse
 
+import requests
 
 WEBSITE_REPOS = [
 	"erpnext_com",
@@ -36,11 +36,7 @@
 
 
 def contains_documentation_link(body: str) -> bool:
-	return any(
-		is_documentation_link(word)
-		for line in body.splitlines()
-		for word in line.split()
-	)
+	return any(is_documentation_link(word) for line in body.splitlines() for word in line.split())
 
 
 def check_pull_request(number: str) -> "tuple[int, str]":
@@ -53,12 +49,7 @@
 	head_sha = (payload.get("head") or {}).get("sha")
 	body = (payload.get("body") or "").lower()
 
-	if (
-		not title.startswith("feat")
-		or not head_sha
-		or "no-docs" in body
-		or "backport" in body
-	):
+	if not title.startswith("feat") or not head_sha or "no-docs" in body or "backport" in body:
 		return 0, "Skipping documentation checks... 🏃"
 
 	if contains_documentation_link(body):
diff --git a/.github/helper/translation.py b/.github/helper/translation.py
index 9146b3b..2918f78 100644
--- a/.github/helper/translation.py
+++ b/.github/helper/translation.py
@@ -2,7 +2,9 @@
 import sys
 
 errors_encounter = 0
-pattern = re.compile(r"_\(([\"']{,3})(?P<message>((?!\1).)*)\1(\s*,\s*context\s*=\s*([\"'])(?P<py_context>((?!\5).)*)\5)*(\s*,(\s*?.*?\n*?)*(,\s*([\"'])(?P<js_context>((?!\11).)*)\11)*)*\)")
+pattern = re.compile(
+	r"_\(([\"']{,3})(?P<message>((?!\1).)*)\1(\s*,\s*context\s*=\s*([\"'])(?P<py_context>((?!\5).)*)\5)*(\s*,(\s*?.*?\n*?)*(,\s*([\"'])(?P<js_context>((?!\11).)*)\11)*)*\)"
+)
 words_pattern = re.compile(r"_{1,2}\([\"'`]{1,3}.*?[a-zA-Z]")
 start_pattern = re.compile(r"_{1,2}\([f\"'`]{1,3}")
 f_string_pattern = re.compile(r"_\(f[\"']")
@@ -10,14 +12,14 @@
 
 # skip first argument
 files = sys.argv[1:]
-files_to_scan = [_file for _file in files if _file.endswith(('.py', '.js'))]
+files_to_scan = [_file for _file in files if _file.endswith((".py", ".js"))]
 
 for _file in files_to_scan:
-	with open(_file, 'r') as f:
-		print(f'Checking: {_file}')
+	with open(_file) as f:
+		print(f"Checking: {_file}")
 		file_lines = f.readlines()
 		for line_number, line in enumerate(file_lines, 1):
-			if 'frappe-lint: disable-translate' in line:
+			if "frappe-lint: disable-translate" in line:
 				continue
 
 			start_matches = start_pattern.search(line)
@@ -28,7 +30,9 @@
 					has_f_string = f_string_pattern.search(line)
 					if has_f_string:
 						errors_encounter += 1
-						print(f'\nF-strings are not supported for translations at line number {line_number}\n{line.strip()[:100]}')
+						print(
+							f"\nF-strings are not supported for translations at line number {line_number}\n{line.strip()[:100]}"
+						)
 						continue
 					else:
 						continue
@@ -36,25 +40,29 @@
 				match = pattern.search(line)
 				error_found = False
 
-				if not match and line.endswith((',\n', '[\n')):
+				if not match and line.endswith((",\n", "[\n")):
 					# concat remaining text to validate multiline pattern
-					line = "".join(file_lines[line_number - 1:])
-					line = line[start_matches.start() + 1:]
+					line = "".join(file_lines[line_number - 1 :])
+					line = line[start_matches.start() + 1 :]
 					match = pattern.match(line)
 
 				if not match:
 					error_found = True
-					print(f'\nTranslation syntax error at line number {line_number}\n{line.strip()[:100]}')
+					print(f"\nTranslation syntax error at line number {line_number}\n{line.strip()[:100]}")
 
 				if not error_found and not words_pattern.search(line):
 					error_found = True
-					print(f'\nTranslation is useless because it has no words at line number {line_number}\n{line.strip()[:100]}')
+					print(
+						f"\nTranslation is useless because it has no words at line number {line_number}\n{line.strip()[:100]}"
+					)
 
 				if error_found:
 					errors_encounter += 1
 
 if errors_encounter > 0:
-	print('\nVisit "https://frappeframework.com/docs/user/en/translations" to learn about valid translation strings.')
+	print(
+		'\nVisit "https://frappeframework.com/docs/user/en/translations" to learn about valid translation strings.'
+	)
 	sys.exit(1)
 else:
-	print('\nGood To Go!')
+	print("\nGood To Go!")
diff --git a/erpnext/__init__.py b/erpnext/__init__.py
index 1c1c10c..7a8ff19 100644
--- a/erpnext/__init__.py
+++ b/erpnext/__init__.py
@@ -37,9 +37,7 @@
 	if not frappe.flags.company_cost_center:
 		frappe.flags.company_cost_center = {}
 	if company not in frappe.flags.company_cost_center:
-		frappe.flags.company_cost_center[company] = frappe.get_cached_value(
-			"Company", company, "cost_center"
-		)
+		frappe.flags.company_cost_center[company] = frappe.get_cached_value("Company", company, "cost_center")
 	return frappe.flags.company_cost_center[company]
 
 
diff --git a/erpnext/accounts/custom/address.py b/erpnext/accounts/custom/address.py
index 775a81f..ef57a63 100644
--- a/erpnext/accounts/custom/address.py
+++ b/erpnext/accounts/custom/address.py
@@ -11,14 +11,14 @@
 	def validate(self):
 		self.validate_reference()
 		self.update_compnay_address()
-		super(ERPNextAddress, self).validate()
+		super().validate()
 
 	def link_address(self):
 		"""Link address based on owner"""
 		if self.is_your_company_address:
 			return
 
-		return super(ERPNextAddress, self).link_address()
+		return super().link_address()
 
 	def update_compnay_address(self):
 		for link in self.get("links"):
@@ -26,11 +26,11 @@
 				self.is_your_company_address = 1
 
 	def validate_reference(self):
-		if self.is_your_company_address and not [
-			row for row in self.links if row.link_doctype == "Company"
-		]:
+		if self.is_your_company_address and not [row for row in self.links if row.link_doctype == "Company"]:
 			frappe.throw(
-				_("Address needs to be linked to a Company. Please add a row for Company in the Links table."),
+				_(
+					"Address needs to be linked to a Company. Please add a row for Company in the Links table."
+				),
 				title=_("Company Not Linked"),
 			)
 
diff --git a/erpnext/accounts/dashboard_chart_source/account_balance_timeline/account_balance_timeline.py b/erpnext/accounts/dashboard_chart_source/account_balance_timeline/account_balance_timeline.py
index f091a4f..01e6c48 100644
--- a/erpnext/accounts/dashboard_chart_source/account_balance_timeline/account_balance_timeline.py
+++ b/erpnext/accounts/dashboard_chart_source/account_balance_timeline/account_balance_timeline.py
@@ -37,7 +37,7 @@
 	filters = frappe.parse_json(filters) or frappe.parse_json(chart.filters_json)
 
 	account = filters.get("account")
-	company = filters.get("company")
+	filters.get("company")
 
 	if not account and chart_name:
 		frappe.throw(
@@ -83,7 +83,6 @@
 
 	# get balances in debit
 	for entry in gl_entries:
-
 		# entry date is after the current pointer, so move the pointer forward
 		while getdate(entry.posting_date) > result[date_index][0]:
 			date_index += 1
@@ -133,8 +132,6 @@
 
 	dates = [get_period_ending(from_date, timegrain)]
 	while getdate(dates[-1]) < getdate(to_date):
-		date = get_period_ending(
-			add_to_date(dates[-1], years=years, months=months, days=days), timegrain
-		)
+		date = get_period_ending(add_to_date(dates[-1], years=years, months=months, days=days), timegrain)
 		dates.append(date)
 	return dates
diff --git a/erpnext/accounts/deferred_revenue.py b/erpnext/accounts/deferred_revenue.py
index 367b017..3dc3e7a 100644
--- a/erpnext/accounts/deferred_revenue.py
+++ b/erpnext/accounts/deferred_revenue.py
@@ -24,14 +24,10 @@
 def validate_service_stop_date(doc):
 	"""Validates service_stop_date for Purchase Invoice and Sales Invoice"""
 
-	enable_check = (
-		"enable_deferred_revenue" if doc.doctype == "Sales Invoice" else "enable_deferred_expense"
-	)
+	enable_check = "enable_deferred_revenue" if doc.doctype == "Sales Invoice" else "enable_deferred_expense"
 
 	old_stop_dates = {}
-	old_doc = frappe.db.get_all(
-		"{0} Item".format(doc.doctype), {"parent": doc.name}, ["name", "service_stop_date"]
-	)
+	old_doc = frappe.db.get_all(f"{doc.doctype} Item", {"parent": doc.name}, ["name", "service_stop_date"])
 
 	for d in old_doc:
 		old_stop_dates[d.name] = d.service_stop_date or ""
@@ -62,16 +58,14 @@
 	)
 
 	if account:
-		conditions += "AND %s='%s'" % (deferred_account, account)
+		conditions += f"AND {deferred_account}='{account}'"
 	elif company:
 		conditions += f"AND p.company = {frappe.db.escape(company)}"
 
 	return conditions
 
 
-def convert_deferred_expense_to_expense(
-	deferred_process, start_date=None, end_date=None, conditions=""
-):
+def convert_deferred_expense_to_expense(deferred_process, start_date=None, end_date=None, conditions=""):
 	# book the expense/income on the last day, but it will be trigger on the 1st of month at 12:00 AM
 
 	if not start_date:
@@ -81,16 +75,14 @@
 
 	# check for the purchase invoice for which GL entries has to be done
 	invoices = frappe.db.sql_list(
-		"""
+		f"""
 		select distinct item.parent
 		from `tabPurchase Invoice Item` item, `tabPurchase Invoice` p
 		where item.service_start_date<=%s and item.service_end_date>=%s
 		and item.enable_deferred_expense = 1 and item.parent=p.name
 		and item.docstatus = 1 and ifnull(item.amount, 0) > 0
-		{0}
-	""".format(
-			conditions
-		),
+		{conditions}
+	""",
 		(end_date, start_date),
 	)  # nosec
 
@@ -103,9 +95,7 @@
 		send_mail(deferred_process)
 
 
-def convert_deferred_revenue_to_income(
-	deferred_process, start_date=None, end_date=None, conditions=""
-):
+def convert_deferred_revenue_to_income(deferred_process, start_date=None, end_date=None, conditions=""):
 	# book the expense/income on the last day, but it will be trigger on the 1st of month at 12:00 AM
 
 	if not start_date:
@@ -115,16 +105,14 @@
 
 	# check for the sales invoice for which GL entries has to be done
 	invoices = frappe.db.sql_list(
-		"""
+		f"""
 		select distinct item.parent
 		from `tabSales Invoice Item` item, `tabSales Invoice` p
 		where item.service_start_date<=%s and item.service_end_date>=%s
 		and item.enable_deferred_revenue = 1 and item.parent=p.name
 		and item.docstatus = 1 and ifnull(item.amount, 0) > 0
-		{0}
-	""".format(
-			conditions
-		),
+		{conditions}
+	""",
 		(end_date, start_date),
 	)  # nosec
 
@@ -243,9 +231,7 @@
 		already_booked_amount, already_booked_amount_in_account_currency = get_already_booked_amount(
 			doc, item
 		)
-		base_amount = flt(
-			item.base_net_amount - already_booked_amount, item.precision("base_net_amount")
-		)
+		base_amount = flt(item.base_net_amount - already_booked_amount, item.precision("base_net_amount"))
 		if account_currency == doc.company_currency:
 			amount = base_amount
 		else:
@@ -265,17 +251,13 @@
 		if account_currency == doc.company_currency:
 			amount = base_amount
 		else:
-			amount = flt(
-				item.net_amount * total_booking_days / flt(total_days), item.precision("net_amount")
-			)
+			amount = flt(item.net_amount * total_booking_days / flt(total_days), item.precision("net_amount"))
 	else:
 		already_booked_amount, already_booked_amount_in_account_currency = get_already_booked_amount(
 			doc, item
 		)
 
-		base_amount = flt(
-			item.base_net_amount - already_booked_amount, item.precision("base_net_amount")
-		)
+		base_amount = flt(item.base_net_amount - already_booked_amount, item.precision("base_net_amount"))
 		if account_currency == doc.company_currency:
 			amount = base_amount
 		else:
@@ -296,26 +278,22 @@
 
 	gl_entries_details = frappe.db.sql(
 		"""
-		select sum({0}) as total_credit, sum({1}) as total_credit_in_account_currency, voucher_detail_no
+		select sum({}) as total_credit, sum({}) as total_credit_in_account_currency, voucher_detail_no
 		from `tabGL Entry` where company=%s and account=%s and voucher_type=%s and voucher_no=%s and voucher_detail_no=%s
 		and is_cancelled = 0
 		group by voucher_detail_no
-	""".format(
-			total_credit_debit, total_credit_debit_currency
-		),
+	""".format(total_credit_debit, total_credit_debit_currency),
 		(doc.company, item.get(deferred_account), doc.doctype, doc.name, item.name),
 		as_dict=True,
 	)
 
 	journal_entry_details = frappe.db.sql(
 		"""
-		SELECT sum(c.{0}) as total_credit, sum(c.{1}) as total_credit_in_account_currency, reference_detail_no
+		SELECT sum(c.{}) as total_credit, sum(c.{}) as total_credit_in_account_currency, reference_detail_no
 		FROM `tabJournal Entry` p , `tabJournal Entry Account` c WHERE p.name = c.parent and
 		p.company = %s and c.account=%s and c.reference_type=%s and c.reference_name=%s and c.reference_detail_no=%s
 		and p.docstatus < 2 group by reference_detail_no
-	""".format(
-			total_credit_debit, total_credit_debit_currency
-		),
+	""".format(total_credit_debit, total_credit_debit_currency),
 		(doc.company, item.get(deferred_account), doc.doctype, doc.name, item.name),
 		as_dict=True,
 	)
@@ -337,9 +315,7 @@
 
 
 def book_deferred_income_or_expense(doc, deferred_process, posting_date=None):
-	enable_check = (
-		"enable_deferred_revenue" if doc.doctype == "Sales Invoice" else "enable_deferred_expense"
-	)
+	enable_check = "enable_deferred_revenue" if doc.doctype == "Sales Invoice" else "enable_deferred_expense"
 
 	accounts_frozen_upto = frappe.db.get_single_value("Accounts Settings", "acc_frozen_upto")
 
@@ -440,9 +416,7 @@
 	via_journal_entry = cint(
 		frappe.db.get_singles_value("Accounts Settings", "book_deferred_entries_via_journal_entry")
 	)
-	submit_journal_entry = cint(
-		frappe.db.get_singles_value("Accounts Settings", "submit_journal_entries")
-	)
+	submit_journal_entry = cint(frappe.db.get_singles_value("Accounts Settings", "submit_journal_entries"))
 	book_deferred_entries_based_on = frappe.db.get_singles_value(
 		"Accounts Settings", "book_deferred_entries_based_on"
 	)
@@ -462,9 +436,7 @@
 		posting_date = today()
 
 	if not cint(
-		frappe.db.get_singles_value(
-			"Accounts Settings", "automatically_process_deferred_accounting_entry"
-		)
+		frappe.db.get_singles_value("Accounts Settings", "automatically_process_deferred_accounting_entry")
 	):
 		return
 
@@ -587,16 +559,13 @@
 	deferred_process=None,
 	submit="No",
 ):
-
 	if amount == 0:
 		return
 
 	journal_entry = frappe.new_doc("Journal Entry")
 	journal_entry.posting_date = posting_date
 	journal_entry.company = doc.company
-	journal_entry.voucher_type = (
-		"Deferred Revenue" if doc.doctype == "Sales Invoice" else "Deferred Expense"
-	)
+	journal_entry.voucher_type = "Deferred Revenue" if doc.doctype == "Sales Invoice" else "Deferred Expense"
 	journal_entry.process_deferred_accounting = deferred_process
 
 	debit_entry = {
@@ -645,7 +614,6 @@
 
 
 def get_deferred_booking_accounts(doctype, voucher_detail_no, dr_or_cr):
-
 	if doctype == "Sales Invoice":
 		credit_account, debit_account = frappe.db.get_value(
 			"Sales Invoice Item",
diff --git a/erpnext/accounts/doctype/account/account.py b/erpnext/accounts/doctype/account/account.py
index 3f11798..db95d6c 100644
--- a/erpnext/accounts/doctype/account/account.py
+++ b/erpnext/accounts/doctype/account/account.py
@@ -88,12 +88,10 @@
 		if frappe.local.flags.ignore_update_nsm:
 			return
 		else:
-			super(Account, self).on_update()
+			super().on_update()
 
 	def onload(self):
-		frozen_accounts_modifier = frappe.db.get_single_value(
-			"Accounts Settings", "frozen_accounts_modifier"
-		)
+		frozen_accounts_modifier = frappe.db.get_single_value("Accounts Settings", "frozen_accounts_modifier")
 		if not frozen_accounts_modifier or frozen_accounts_modifier in frappe.get_roles():
 			self.set_onload("can_freeze_account", True)
 
@@ -218,9 +216,7 @@
 
 	def validate_root_company_and_sync_account_to_children(self):
 		# ignore validation while creating new compnay or while syncing to child companies
-		if (
-			frappe.local.flags.ignore_root_company_validation or self.flags.ignore_root_company_validation
-		):
+		if frappe.local.flags.ignore_root_company_validation or self.flags.ignore_root_company_validation:
 			return
 		ancestors = get_root_company(self.company)
 		if ancestors:
@@ -418,7 +414,7 @@
 		if self.check_gle_exists():
 			throw(_("Account with existing transaction can not be deleted"))
 
-		super(Account, self).on_trash(True)
+		super().on_trash(True)
 
 
 @frappe.whitelist()
@@ -426,9 +422,8 @@
 def get_parent_account(doctype, txt, searchfield, start, page_len, filters):
 	return frappe.db.sql(
 		"""select name from tabAccount
-		where is_group = 1 and docstatus != 2 and company = %s
-		and %s like %s order by name limit %s offset %s"""
-		% ("%s", searchfield, "%s", "%s", "%s"),
+		where is_group = 1 and docstatus != 2 and company = {}
+		and {} like {} order by name limit {} offset {}""".format("%s", searchfield, "%s", "%s", "%s"),
 		(filters["company"], "%%%s%%" % txt, page_len, start),
 		as_list=1,
 	)
@@ -594,7 +589,5 @@
 	if old_acc_number:
 		filters["account_number"] = old_acc_number
 
-	for d in frappe.db.get_values(
-		"Account", filters=filters, fieldname=["company", "name"], as_dict=True
-	):
+	for d in frappe.db.get_values("Account", filters=filters, fieldname=["company", "name"], as_dict=True):
 		update_account_number(d["name"], account_name, account_number, from_descendant=True)
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 05ff2a1..0ddae1b 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
@@ -31,7 +31,6 @@
 					"tax_rate",
 					"account_currency",
 				]:
-
 					account_number = cstr(child.get("account_number")).strip()
 					account_name, account_name_in_db = add_suffix_if_duplicate(
 						account_name, account_number, accounts
@@ -39,7 +38,9 @@
 
 					is_group = identify_is_group(child)
 					report_type = (
-						"Balance Sheet" if root_type in ["Asset", "Liability", "Equity"] else "Profit and Loss"
+						"Balance Sheet"
+						if root_type in ["Asset", "Liability", "Equity"]
+						else "Profit and Loss"
 					)
 
 					account = frappe.get_doc(
@@ -141,7 +142,7 @@
 			for fname in os.listdir(path):
 				fname = frappe.as_unicode(fname)
 				if fname.endswith(".json"):
-					with open(os.path.join(path, fname), "r") as f:
+					with open(os.path.join(path, fname)) as f:
 						chart = f.read()
 						if chart and json.loads(chart).get("name") == chart_template:
 							return json.loads(chart).get("tree")
@@ -173,7 +174,7 @@
 			for fname in os.listdir(path):
 				fname = frappe.as_unicode(fname)
 				if (fname.startswith(country_code) or fname.startswith(country)) and fname.endswith(".json"):
-					with open(os.path.join(path, fname), "r") as f:
+					with open(os.path.join(path, fname)) as f:
 						_get_chart_name(f.read())
 
 	# if more than one charts, returned then add the standard
@@ -249,7 +250,13 @@
 
 		def _get_account_names(account_master):
 			for account_name, child in account_master.items():
-				if account_name not in ["account_number", "account_type", "root_type", "is_group", "tax_rate"]:
+				if account_name not in [
+					"account_number",
+					"account_type",
+					"root_type",
+					"is_group",
+					"tax_rate",
+				]:
 					accounts.append(account_name)
 
 					_get_account_names(child)
diff --git a/erpnext/accounts/doctype/account/test_account.py b/erpnext/accounts/doctype/account/test_account.py
index 7d0869b..be856bc 100644
--- a/erpnext/accounts/doctype/account/test_account.py
+++ b/erpnext/accounts/doctype/account/test_account.py
@@ -261,28 +261,20 @@
 		acc.insert()
 
 		self.assertTrue(
-			frappe.db.exists(
-				"Account", {"account_name": "Test Group Account", "company": "_Test Company 4"}
-			)
+			frappe.db.exists("Account", {"account_name": "Test Group Account", "company": "_Test Company 4"})
 		)
 		self.assertTrue(
-			frappe.db.exists(
-				"Account", {"account_name": "Test Group Account", "company": "_Test Company 5"}
-			)
+			frappe.db.exists("Account", {"account_name": "Test Group Account", "company": "_Test Company 5"})
 		)
 
 		# Try renaming child company account
 		acc_tc_5 = frappe.db.get_value(
 			"Account", {"account_name": "Test Group Account", "company": "_Test Company 5"}
 		)
-		self.assertRaises(
-			frappe.ValidationError, update_account_number, acc_tc_5, "Test Modified Account"
-		)
+		self.assertRaises(frappe.ValidationError, update_account_number, acc_tc_5, "Test Modified Account")
 
 		# Rename child company account with allow_account_creation_against_child_company enabled
-		frappe.db.set_value(
-			"Company", "_Test Company 5", "allow_account_creation_against_child_company", 1
-		)
+		frappe.db.set_value("Company", "_Test Company 5", "allow_account_creation_against_child_company", 1)
 
 		update_account_number(acc_tc_5, "Test Modified Account")
 		self.assertTrue(
@@ -291,9 +283,7 @@
 			)
 		)
 
-		frappe.db.set_value(
-			"Company", "_Test Company 5", "allow_account_creation_against_child_company", 0
-		)
+		frappe.db.set_value("Company", "_Test Company 5", "allow_account_creation_against_child_company", 0)
 
 		to_delete = [
 			"Test Group Account - _TC3",
@@ -318,9 +308,7 @@
 		self.assertEqual(acc.account_currency, "INR")
 
 		# Make a JV against this account
-		make_journal_entry(
-			"Test Currency Account - _TC", "Miscellaneous Expenses - _TC", 100, submit=True
-		)
+		make_journal_entry("Test Currency Account - _TC", "Miscellaneous Expenses - _TC", 100, submit=True)
 
 		acc.account_currency = "USD"
 		self.assertRaises(frappe.ValidationError, acc.save)
diff --git a/erpnext/accounts/doctype/account_closing_balance/account_closing_balance.py b/erpnext/accounts/doctype/account_closing_balance/account_closing_balance.py
index 65933ab..82821e1 100644
--- a/erpnext/accounts/doctype/account_closing_balance/account_closing_balance.py
+++ b/erpnext/accounts/doctype/account_closing_balance/account_closing_balance.py
@@ -40,16 +40,12 @@
 def make_closing_entries(closing_entries, voucher_name, company, closing_date):
 	accounting_dimensions = get_accounting_dimensions()
 
-	previous_closing_entries = get_previous_closing_entries(
-		company, closing_date, accounting_dimensions
-	)
+	previous_closing_entries = get_previous_closing_entries(company, closing_date, accounting_dimensions)
 	combined_entries = closing_entries + previous_closing_entries
 
-	merged_entries = aggregate_with_last_account_closing_balance(
-		combined_entries, accounting_dimensions
-	)
+	merged_entries = aggregate_with_last_account_closing_balance(combined_entries, accounting_dimensions)
 
-	for key, value in merged_entries.items():
+	for _key, value in merged_entries.items():
 		cle = frappe.new_doc("Account Closing Balance")
 		cle.update(value)
 		cle.update(value["dimensions"])
diff --git a/erpnext/accounts/doctype/accounting_dimension/accounting_dimension.py b/erpnext/accounts/doctype/accounting_dimension/accounting_dimension.py
index 41af06f..db99bcd 100644
--- a/erpnext/accounts/doctype/accounting_dimension/accounting_dimension.py
+++ b/erpnext/accounts/doctype/accounting_dimension/accounting_dimension.py
@@ -40,7 +40,8 @@
 		self.set_fieldname_and_label()
 
 	def validate(self):
-		if self.document_type in core_doctypes_list + (
+		if self.document_type in (
+			*core_doctypes_list,
 			"Accounting Dimension",
 			"Project",
 			"Cost Center",
@@ -48,13 +49,10 @@
 			"Company",
 			"Account",
 		):
-
 			msg = _("Not allowed to create accounting dimension for {0}").format(self.document_type)
 			frappe.throw(msg)
 
-		exists = frappe.db.get_value(
-			"Accounting Dimension", {"document_type": self.document_type}, ["name"]
-		)
+		exists = frappe.db.get_value("Accounting Dimension", {"document_type": self.document_type}, ["name"])
 
 		if exists and self.is_new():
 			frappe.throw(_("Document Type already used as a dimension"))
@@ -113,7 +111,6 @@
 	repostable_doctypes = get_allowed_types_from_settings()
 
 	for doctype in doclist:
-
 		if (doc_count + 1) % 2 == 0:
 			insert_after_field = "dimension_col_break"
 		else:
@@ -148,7 +145,7 @@
 	df.update(
 		{
 			"insert_after": "cost_center",
-			"depends_on": "eval:doc.budget_against == '{0}'".format(doc.document_type),
+			"depends_on": f"eval:doc.budget_against == '{doc.document_type}'",
 		}
 	)
 
@@ -182,19 +179,17 @@
 	frappe.db.sql(
 		"""
 		DELETE FROM `tabCustom Field`
-		WHERE fieldname = %s
-		AND dt IN (%s)"""
-		% ("%s", ", ".join(["%s"] * len(doclist))),  # nosec
-		tuple([doc.fieldname] + doclist),
+		WHERE fieldname = {}
+		AND dt IN ({})""".format("%s", ", ".join(["%s"] * len(doclist))),  # nosec
+		tuple([doc.fieldname, *doclist]),
 	)
 
 	frappe.db.sql(
 		"""
 		DELETE FROM `tabProperty Setter`
-		WHERE field_name = %s
-		AND doc_type IN (%s)"""
-		% ("%s", ", ".join(["%s"] * len(doclist))),  # nosec
-		tuple([doc.fieldname] + doclist),
+		WHERE field_name = {}
+		AND doc_type IN ({})""".format("%s", ", ".join(["%s"] * len(doclist))),  # nosec
+		tuple([doc.fieldname, *doclist]),
 	)
 
 	budget_against_property = frappe.get_doc("Property Setter", "Budget-budget_against-options")
@@ -243,7 +238,6 @@
 
 
 def get_accounting_dimensions(as_list=True, filters=None):
-
 	if not filters:
 		filters = {"disabled": 0}
 
@@ -274,7 +268,6 @@
 
 
 def get_dimension_with_children(doctype, dimensions):
-
 	if isinstance(dimensions, str):
 		dimensions = [dimensions]
 
@@ -282,9 +275,7 @@
 
 	for dimension in dimensions:
 		lft, rgt = frappe.db.get_value(doctype, dimension, ["lft", "rgt"])
-		children = frappe.get_all(
-			doctype, filters={"lft": [">=", lft], "rgt": ["<=", rgt]}, order_by="lft"
-		)
+		children = frappe.get_all(doctype, filters={"lft": [">=", lft], "rgt": ["<=", rgt]}, order_by="lft")
 		all_dimensions += [c.name for c in children]
 
 	return all_dimensions
@@ -292,14 +283,10 @@
 
 @frappe.whitelist()
 def get_dimensions(with_cost_center_and_project=False):
-
 	c = frappe.qb.DocType("Accounting Dimension Detail")
 	p = frappe.qb.DocType("Accounting Dimension")
 	dimension_filters = (
-		frappe.qb.from_(p)
-		.select(p.label, p.fieldname, p.document_type)
-		.where(p.disabled == 0)
-		.run(as_dict=1)
+		frappe.qb.from_(p).select(p.label, p.fieldname, p.document_type).where(p.disabled == 0).run(as_dict=1)
 	)
 	default_dimensions = (
 		frappe.qb.from_(c)
diff --git a/erpnext/accounts/doctype/accounting_dimension_filter/test_accounting_dimension_filter.py b/erpnext/accounts/doctype/accounting_dimension_filter/test_accounting_dimension_filter.py
index 3a7bf80..77057c1 100644
--- a/erpnext/accounts/doctype/accounting_dimension_filter/test_accounting_dimension_filter.py
+++ b/erpnext/accounts/doctype/accounting_dimension_filter/test_accounting_dimension_filter.py
@@ -57,9 +57,7 @@
 
 
 def create_accounting_dimension_filter():
-	if not frappe.db.get_value(
-		"Accounting Dimension Filter", {"accounting_dimension": "Cost Center"}
-	):
+	if not frappe.db.get_value("Accounting Dimension Filter", {"accounting_dimension": "Cost Center"}):
 		frappe.get_doc(
 			{
 				"doctype": "Accounting Dimension Filter",
diff --git a/erpnext/accounts/doctype/accounting_period/accounting_period.py b/erpnext/accounts/doctype/accounting_period/accounting_period.py
index b32a231..172ef93 100644
--- a/erpnext/accounts/doctype/accounting_period/accounting_period.py
+++ b/erpnext/accounts/doctype/accounting_period/accounting_period.py
@@ -84,7 +84,10 @@
 			for doctype_for_closing in self.get_doctypes_for_closing():
 				self.append(
 					"closed_documents",
-					{"document_type": doctype_for_closing.document_type, "closed": doctype_for_closing.closed},
+					{
+						"document_type": doctype_for_closing.document_type,
+						"closed": doctype_for_closing.closed,
+					},
 				)
 
 
diff --git a/erpnext/accounts/doctype/accounting_period/test_accounting_period.py b/erpnext/accounts/doctype/accounting_period/test_accounting_period.py
index 41d9479..16cae96 100644
--- a/erpnext/accounts/doctype/accounting_period/test_accounting_period.py
+++ b/erpnext/accounts/doctype/accounting_period/test_accounting_period.py
@@ -34,9 +34,7 @@
 		ap1 = create_accounting_period(period_name="Test Accounting Period 2")
 		ap1.save()
 
-		doc = create_sales_invoice(
-			do_not_save=1, cost_center="_Test Company - _TC", warehouse="Stores - _TC"
-		)
+		doc = create_sales_invoice(do_not_save=1, cost_center="_Test Company - _TC", warehouse="Stores - _TC")
 		self.assertRaises(ClosedAccountingPeriod, doc.save)
 
 	def tearDown(self):
diff --git a/erpnext/accounts/doctype/bank_account/test_bank_account.py b/erpnext/accounts/doctype/bank_account/test_bank_account.py
index 8949524..0ec388d 100644
--- a/erpnext/accounts/doctype/bank_account/test_bank_account.py
+++ b/erpnext/accounts/doctype/bank_account/test_bank_account.py
@@ -37,11 +37,11 @@
 			try:
 				bank_account.validate_iban()
 			except ValidationError:
-				msg = "BankAccount.validate_iban() failed for valid IBAN {}".format(iban)
+				msg = f"BankAccount.validate_iban() failed for valid IBAN {iban}"
 				self.fail(msg=msg)
 
 		for not_iban in invalid_ibans:
 			bank_account.iban = not_iban
-			msg = "BankAccount.validate_iban() accepted invalid IBAN {}".format(not_iban)
+			msg = f"BankAccount.validate_iban() accepted invalid IBAN {not_iban}"
 			with self.assertRaises(ValidationError, msg=msg):
 				bank_account.validate_iban()
diff --git a/erpnext/accounts/doctype/bank_clearance/bank_clearance.py b/erpnext/accounts/doctype/bank_clearance/bank_clearance.py
index 8a505a8..63758a5 100644
--- a/erpnext/accounts/doctype/bank_clearance/bank_clearance.py
+++ b/erpnext/accounts/doctype/bank_clearance/bank_clearance.py
@@ -127,7 +127,7 @@
 		condition = "and (clearance_date IS NULL or clearance_date='0000-00-00')"
 
 	journal_entries = frappe.db.sql(
-		"""
+		f"""
 			select
 				"Journal Entry" as payment_document, t1.name as payment_entry,
 				t1.cheque_no as cheque_number, t1.cheque_date,
@@ -141,9 +141,7 @@
 				and ifnull(t1.is_opening, 'No') = 'No' {condition}
 			group by t2.account, t1.name
 			order by t1.posting_date ASC, t1.name DESC
-		""".format(
-			condition=condition
-		),
+		""",
 		{"account": account, "from": from_date, "to": to_date},
 		as_dict=1,
 	)
@@ -152,7 +150,7 @@
 		condition += "and bank_account = %(bank_account)s"
 
 	payment_entries = frappe.db.sql(
-		"""
+		f"""
 			select
 				"Payment Entry" as payment_document, name as payment_entry,
 				reference_no as cheque_number, reference_date as cheque_date,
@@ -167,9 +165,7 @@
 				{condition}
 			order by
 				posting_date ASC, name DESC
-		""".format(
-			condition=condition
-		),
+		""",
 		{
 			"account": account,
 			"from": from_date,
@@ -239,10 +235,7 @@
 		).run(as_dict=True)
 
 	entries = (
-		list(payment_entries)
-		+ list(journal_entries)
-		+ list(pos_sales_invoices)
-		+ list(pos_purchase_invoices)
+		list(payment_entries) + list(journal_entries) + list(pos_sales_invoices) + list(pos_purchase_invoices)
 	)
 
 	return entries
diff --git a/erpnext/accounts/doctype/bank_clearance/test_bank_clearance.py b/erpnext/accounts/doctype/bank_clearance/test_bank_clearance.py
index ace751b..d785bfb 100644
--- a/erpnext/accounts/doctype/bank_clearance/test_bank_clearance.py
+++ b/erpnext/accounts/doctype/bank_clearance/test_bank_clearance.py
@@ -68,9 +68,7 @@
 			)
 			loan.submit()
 			make_loan_disbursement_entry(loan.name, loan.loan_amount, disbursement_date=getdate())
-			repayment_entry = create_repayment_entry(
-				loan.name, "_Test Customer", getdate(), loan.loan_amount
-			)
+			repayment_entry = create_repayment_entry(loan.name, "_Test Customer", getdate(), loan.loan_amount)
 			repayment_entry.save()
 			repayment_entry.submit()
 
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 65158fc..77cb320 100644
--- a/erpnext/accounts/doctype/bank_reconciliation_tool/bank_reconciliation_tool.py
+++ b/erpnext/accounts/doctype/bank_reconciliation_tool/bank_reconciliation_tool.py
@@ -81,9 +81,7 @@
 def get_account_balance(bank_account, till_date):
 	# returns account balance till the specified date
 	account = frappe.db.get_value("Bank Account", bank_account, "account")
-	filters = frappe._dict(
-		{"account": account, "report_date": till_date, "include_pos_transactions": 1}
-	)
+	filters = frappe._dict({"account": account, "report_date": till_date, "include_pos_transactions": 1})
 	data = get_entries(filters)
 
 	balance_as_per_system = get_balance_on(filters["account"], filters["report_date"])
@@ -96,10 +94,7 @@
 	amounts_not_reflected_in_system = get_amounts_not_reflected_in_system(filters)
 
 	bank_bal = (
-		flt(balance_as_per_system)
-		- flt(total_debit)
-		+ flt(total_credit)
-		+ amounts_not_reflected_in_system
+		flt(balance_as_per_system) - flt(total_debit) + flt(total_credit) + amounts_not_reflected_in_system
 	)
 
 	return bank_bal
@@ -538,9 +533,7 @@
 	for query in queries:
 		matching_vouchers.extend(query.run(as_dict=True))
 
-	return (
-		sorted(matching_vouchers, key=lambda x: x["rank"], reverse=True) if matching_vouchers else []
-	)
+	return sorted(matching_vouchers, key=lambda x: x["rank"], reverse=True) if matching_vouchers else []
 
 
 def get_queries(
@@ -654,17 +647,13 @@
 	amount_rank = frappe.qb.terms.Case().when(amount_equality, 1).else_(0)
 	amount_condition = amount_equality if exact_match else getattr(bt, field) > 0.0
 
-	ref_rank = (
-		frappe.qb.terms.Case().when(bt.reference_number == transaction.reference_number, 1).else_(0)
-	)
+	ref_rank = frappe.qb.terms.Case().when(bt.reference_number == transaction.reference_number, 1).else_(0)
 	unallocated_rank = (
 		frappe.qb.terms.Case().when(bt.unallocated_amount == transaction.unallocated_amount, 1).else_(0)
 	)
 
 	party_condition = (
-		(bt.party_type == transaction.party_type)
-		& (bt.party == transaction.party)
-		& bt.party.isnotnull()
+		(bt.party_type == transaction.party_type) & (bt.party == transaction.party) & bt.party.isnotnull()
 	)
 	party_rank = frappe.qb.terms.Case().when(party_condition, 1).else_(0)
 
@@ -716,9 +705,7 @@
 	amount_condition = amount_equality if exact_match else pe.paid_amount > 0.0
 
 	party_condition = (
-		(pe.party_type == transaction.party_type)
-		& (pe.party == transaction.party)
-		& pe.party.isnotnull()
+		(pe.party_type == transaction.party_type) & (pe.party == transaction.party) & pe.party.isnotnull()
 	)
 	party_rank = frappe.qb.terms.Case().when(party_condition, 1).else_(0)
 
@@ -749,7 +736,7 @@
 		.orderby(pe.reference_date if cint(filter_by_reference_date) else pe.posting_date)
 	)
 
-	if frappe.flags.auto_reconcile_vouchers == True:
+	if frappe.flags.auto_reconcile_vouchers is True:
 		query = query.where(ref_condition)
 
 	return query
@@ -810,7 +797,7 @@
 		.orderby(je.cheque_date if cint(filter_by_reference_date) else je.posting_date)
 	)
 
-	if frappe.flags.auto_reconcile_vouchers == True:
+	if frappe.flags.auto_reconcile_vouchers is True:
 		query = query.where(ref_condition)
 
 	return query
diff --git a/erpnext/accounts/doctype/bank_reconciliation_tool/test_bank_reconciliation_tool.py b/erpnext/accounts/doctype/bank_reconciliation_tool/test_bank_reconciliation_tool.py
index adf5925..3813052 100644
--- a/erpnext/accounts/doctype/bank_reconciliation_tool/test_bank_reconciliation_tool.py
+++ b/erpnext/accounts/doctype/bank_reconciliation_tool/test_bank_reconciliation_tool.py
@@ -1,12 +1,11 @@
 # Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and Contributors
 # See license.txt
 
-import unittest
 
 import frappe
 from frappe import qb
-from frappe.tests.utils import FrappeTestCase, change_settings
-from frappe.utils import add_days, flt, getdate, today
+from frappe.tests.utils import FrappeTestCase
+from frappe.utils import add_days, today
 
 from erpnext.accounts.doctype.bank_reconciliation_tool.bank_reconciliation_tool import (
 	auto_reconcile_vouchers,
@@ -22,7 +21,7 @@
 		self.create_customer()
 		self.clear_old_entries()
 		bank_dt = qb.DocType("Bank")
-		q = qb.from_(bank_dt).delete().where(bank_dt.name == "HDFC").run()
+		qb.from_(bank_dt).delete().where(bank_dt.name == "HDFC").run()
 		self.create_bank_account()
 
 	def tearDown(self):
diff --git a/erpnext/accounts/doctype/bank_statement_import/bank_statement_import.py b/erpnext/accounts/doctype/bank_statement_import/bank_statement_import.py
index 6728fea..49684df 100644
--- a/erpnext/accounts/doctype/bank_statement_import/bank_statement_import.py
+++ b/erpnext/accounts/doctype/bank_statement_import/bank_statement_import.py
@@ -45,7 +45,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(BankStatementImport, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 
 	def validate(self):
 		doc_before_save = self.get_doc_before_save()
@@ -54,7 +54,6 @@
 			or (doc_before_save and doc_before_save.import_file != self.import_file)
 			or (doc_before_save and doc_before_save.google_sheets_url != self.google_sheets_url)
 		):
-
 			template_options_dict = {}
 			column_to_field_map = {}
 			bank = frappe.get_doc("Bank", self.bank)
@@ -69,7 +68,6 @@
 		self.validate_google_sheets_url()
 
 	def start_import(self):
-
 		preview = frappe.get_doc("Bank Statement Import", self.name).get_preview_from_template(
 			self.import_file, self.google_sheets_url
 		)
@@ -126,7 +124,7 @@
 def parse_data_from_template(raw_data):
 	data = []
 
-	for i, row in enumerate(raw_data):
+	for _i, row in enumerate(raw_data):
 		if all(v in INVALID_VALUES for v in row):
 			# empty row
 			continue
@@ -136,9 +134,7 @@
 	return data
 
 
-def start_import(
-	data_import, bank_account, import_file_path, google_sheets_url, bank, template_options
-):
+def start_import(data_import, bank_account, import_file_path, google_sheets_url, bank, template_options):
 	"""This method runs in background job"""
 
 	update_mapping_db(bank, template_options)
diff --git a/erpnext/accounts/doctype/bank_transaction/auto_match_party.py b/erpnext/accounts/doctype/bank_transaction/auto_match_party.py
index 04dab4c..230407b 100644
--- a/erpnext/accounts/doctype/bank_transaction/auto_match_party.py
+++ b/erpnext/accounts/doctype/bank_transaction/auto_match_party.py
@@ -1,5 +1,3 @@
-from typing import Tuple, Union
-
 import frappe
 from frappe.utils import flt
 from rapidfuzz import fuzz, process
@@ -19,7 +17,7 @@
 	def get(self, key):
 		return self.__dict__.get(key, None)
 
-	def match(self) -> Union[Tuple, None]:
+	def match(self) -> tuple | None:
 		result = None
 		result = AutoMatchbyAccountIBAN(
 			bank_party_account_number=self.bank_party_account_number,
@@ -50,7 +48,7 @@
 		result = self.match_account_in_party()
 		return result
 
-	def match_account_in_party(self) -> Union[Tuple, None]:
+	def match_account_in_party(self) -> tuple | None:
 		"""Check if there is a IBAN/Account No. match in Customer/Supplier/Employee"""
 		result = None
 		parties = get_parties_in_order(self.deposit)
@@ -97,7 +95,7 @@
 	def get(self, key):
 		return self.__dict__.get(key, None)
 
-	def match(self) -> Union[Tuple, None]:
+	def match(self) -> tuple | None:
 		# fuzzy search by customer/supplier & employee
 		if not (self.bank_party_name or self.description):
 			return None
@@ -105,7 +103,7 @@
 		result = self.match_party_name_desc_in_party()
 		return result
 
-	def match_party_name_desc_in_party(self) -> Union[Tuple, None]:
+	def match_party_name_desc_in_party(self) -> tuple | None:
 		"""Fuzzy search party name and/or description against parties in the system"""
 		result = None
 		parties = get_parties_in_order(self.deposit)
@@ -130,7 +128,7 @@
 
 		return result
 
-	def fuzzy_search_and_return_result(self, party, names, field) -> Union[Tuple, None]:
+	def fuzzy_search_and_return_result(self, party, names, field) -> tuple | None:
 		skip = False
 		result = process.extract(
 			query=self.get(field),
@@ -147,7 +145,7 @@
 			party_name,
 		), skip
 
-	def process_fuzzy_result(self, result: Union[list, None]):
+	def process_fuzzy_result(self, result: list | None):
 		"""
 		If there are multiple valid close matches return None as result may be faulty.
 		Return the result only if one accurate match stands out.
diff --git a/erpnext/accounts/doctype/bank_transaction/bank_transaction.py b/erpnext/accounts/doctype/bank_transaction/bank_transaction.py
index 4246ba5..94a66d7 100644
--- a/erpnext/accounts/doctype/bank_transaction/bank_transaction.py
+++ b/erpnext/accounts/doctype/bank_transaction/bank_transaction.py
@@ -64,7 +64,9 @@
 						_(
 							"Transaction currency: {0} cannot be different from Bank Account({1}) currency: {2}"
 						).format(
-							frappe.bold(self.currency), frappe.bold(self.bank_account), frappe.bold(account_currency)
+							frappe.bold(self.currency),
+							frappe.bold(self.bank_account),
+							frappe.bold(account_currency),
 						)
 					)
 
@@ -235,9 +237,7 @@
 	"""
 	gl_bank_account = frappe.db.get_value("Bank Account", transaction.bank_account, "account")
 	gles = get_related_bank_gl_entries(payment_entry.payment_document, payment_entry.payment_entry)
-	bt_allocations = get_total_allocated_amount(
-		payment_entry.payment_document, payment_entry.payment_entry
-	)
+	bt_allocations = get_total_allocated_amount(payment_entry.payment_document, payment_entry.payment_entry)
 
 	unallocated_amount = min(
 		transaction.unallocated_amount,
@@ -332,7 +332,6 @@
 
 def get_paid_amount(payment_entry, currency, gl_bank_account):
 	if payment_entry.payment_document in ["Payment Entry", "Sales Invoice", "Purchase Invoice"]:
-
 		paid_amount_field = "paid_amount"
 		if payment_entry.payment_document == "Payment Entry":
 			doc = frappe.get_doc("Payment Entry", payment_entry.payment_entry)
@@ -371,9 +370,7 @@
 		)
 
 	elif payment_entry.payment_document == "Loan Repayment":
-		return frappe.db.get_value(
-			payment_entry.payment_document, payment_entry.payment_entry, "amount_paid"
-		)
+		return frappe.db.get_value(payment_entry.payment_document, payment_entry.payment_entry, "amount_paid")
 
 	elif payment_entry.payment_document == "Bank Transaction":
 		dep, wth = frappe.db.get_value(
@@ -383,9 +380,7 @@
 
 	else:
 		frappe.throw(
-			"Please reconcile {0}: {1} manually".format(
-				payment_entry.payment_document, payment_entry.payment_entry
-			)
+			f"Please reconcile {payment_entry.payment_document}: {payment_entry.payment_entry} manually"
 		)
 
 
diff --git a/erpnext/accounts/doctype/bank_transaction/bank_transaction_upload.py b/erpnext/accounts/doctype/bank_transaction/bank_transaction_upload.py
index efb9d8c..a03f406 100644
--- a/erpnext/accounts/doctype/bank_transaction/bank_transaction_upload.py
+++ b/erpnext/accounts/doctype/bank_transaction/bank_transaction_upload.py
@@ -18,12 +18,12 @@
 		fcontent = frappe.local.uploaded_file
 		fname = frappe.local.uploaded_filename
 
-	if frappe.safe_encode(fname).lower().endswith("csv".encode("utf-8")):
+	if frappe.safe_encode(fname).lower().endswith(b"csv"):
 		from frappe.utils.csvutils import read_csv_content
 
 		rows = read_csv_content(fcontent, False)
 
-	elif frappe.safe_encode(fname).lower().endswith("xlsx".encode("utf-8")):
+	elif frappe.safe_encode(fname).lower().endswith(b"xlsx"):
 		from frappe.utils.xlsxutils import read_xlsx_file_from_attached_file
 
 		rows = read_xlsx_file_from_attached_file(fcontent=fcontent)
diff --git a/erpnext/accounts/doctype/bank_transaction/test_bank_transaction.py b/erpnext/accounts/doctype/bank_transaction/test_bank_transaction.py
index 1fe3608..3181a09 100644
--- a/erpnext/accounts/doctype/bank_transaction/test_bank_transaction.py
+++ b/erpnext/accounts/doctype/bank_transaction/test_bank_transaction.py
@@ -436,9 +436,7 @@
 
 	mode_of_payment = frappe.get_doc({"doctype": "Mode of Payment", "name": "Cash"})
 
-	if not frappe.db.get_value(
-		"Mode of Payment Account", {"company": "_Test Company", "parent": "Cash"}
-	):
+	if not frappe.db.get_value("Mode of Payment Account", {"company": "_Test Company", "parent": "Cash"}):
 		mode_of_payment.append("accounts", {"company": "_Test Company", "default_account": gl_account})
 		mode_of_payment.save()
 
diff --git a/erpnext/accounts/doctype/budget/budget.py b/erpnext/accounts/doctype/budget/budget.py
index aa77af6..15d51d4 100644
--- a/erpnext/accounts/doctype/budget/budget.py
+++ b/erpnext/accounts/doctype/budget/budget.py
@@ -70,10 +70,11 @@
 			select
 				b.name, ba.account from `tabBudget` b, `tabBudget Account` ba
 			where
-				ba.parent = b.name and b.docstatus < 2 and b.company = %s and %s=%s and
-				b.fiscal_year=%s and b.name != %s and ba.account in (%s) """
-			% ("%s", budget_against_field, "%s", "%s", "%s", ",".join(["%s"] * len(accounts))),
-			(self.company, budget_against, self.fiscal_year, self.name) + tuple(accounts),
+				ba.parent = b.name and b.docstatus < 2 and b.company = {} and {}={} and
+				b.fiscal_year={} and b.name != {} and ba.account in ({}) """.format(
+				"%s", budget_against_field, "%s", "%s", "%s", ",".join(["%s"] * len(accounts))
+			),
+			(self.company, budget_against, self.fiscal_year, self.name, *tuple(accounts)),
 			as_dict=1,
 		)
 
@@ -96,12 +97,14 @@
 				if account_details.is_group:
 					frappe.throw(_("Budget cannot be assigned against Group Account {0}").format(d.account))
 				elif account_details.company != self.company:
-					frappe.throw(_("Account {0} does not belongs to company {1}").format(d.account, self.company))
+					frappe.throw(
+						_("Account {0} does not belongs to company {1}").format(d.account, self.company)
+					)
 				elif account_details.report_type != "Profit and Loss":
 					frappe.throw(
-						_("Budget cannot be assigned against {0}, as it's not an Income or Expense account").format(
-							d.account
-						)
+						_(
+							"Budget cannot be assigned against {0}, as it's not an Income or Expense account"
+						).format(d.account)
 					)
 
 				if d.account in account_list:
@@ -148,9 +151,7 @@
 			"Company", args.get("company"), "exception_budget_approver_role"
 		)
 
-	if not frappe.get_cached_value(
-		"Budget", {"fiscal_year": args.fiscal_year, "company": args.company}
-	):  # nosec
+	if not frappe.get_cached_value("Budget", {"fiscal_year": args.fiscal_year, "company": args.company}):  # nosec
 		return
 
 	if not args.account:
@@ -181,30 +182,24 @@
 			and args.account
 			and (frappe.get_cached_value("Account", args.account, "root_type") == "Expense")
 		):
-
 			doctype = dimension.get("document_type")
 
 			if frappe.get_cached_value("DocType", doctype, "is_tree"):
 				lft, rgt = frappe.get_cached_value(doctype, args.get(budget_against), ["lft", "rgt"])
-				condition = """and exists(select name from `tab%s`
-					where lft<=%s and rgt>=%s and name=b.%s)""" % (
-					doctype,
-					lft,
-					rgt,
-					budget_against,
-				)  # nosec
+				condition = f"""and exists(select name from `tab{doctype}`
+					where lft<={lft} and rgt>={rgt} and name=b.{budget_against})"""  # nosec
 				args.is_tree = True
 			else:
-				condition = "and b.%s=%s" % (budget_against, frappe.db.escape(args.get(budget_against)))
+				condition = f"and b.{budget_against}={frappe.db.escape(args.get(budget_against))}"
 				args.is_tree = False
 
 			args.budget_against_field = budget_against
 			args.budget_against_doctype = doctype
 
 			budget_records = frappe.db.sql(
-				"""
+				f"""
 				select
-					b.{budget_against_field} as budget_against, ba.budget_amount, b.monthly_distribution,
+					b.{budget_against} as budget_against, ba.budget_amount, b.monthly_distribution,
 					ifnull(b.applicable_on_material_request, 0) as for_material_request,
 					ifnull(applicable_on_purchase_order, 0) as for_purchase_order,
 					ifnull(applicable_on_booking_actual_expenses,0) as for_actual_expenses,
@@ -217,9 +212,7 @@
 					b.name=ba.parent and b.fiscal_year=%s
 					and ba.account=%s and b.docstatus=1
 					{condition}
-			""".format(
-					condition=condition, budget_against_field=budget_against
-				),
+			""",
 				(args.fiscal_year, args.account),
 				as_dict=True,
 			)  # nosec
@@ -247,7 +240,12 @@
 				args["month_end_date"] = get_last_day(args.posting_date)
 
 				compare_expense_with_budget(
-					args, budget_amount, _("Accumulated Monthly"), monthly_action, budget.budget_against, amount
+					args,
+					budget_amount,
+					_("Accumulated Monthly"),
+					monthly_action,
+					budget.budget_against,
+					amount,
 				)
 
 
@@ -275,9 +273,8 @@
 			frappe.bold(fmt_money(diff, currency=currency)),
 		)
 
-		if (
-			frappe.flags.exception_approver_role
-			and frappe.flags.exception_approver_role in frappe.get_roles(frappe.session.user)
+		if frappe.flags.exception_approver_role and frappe.flags.exception_approver_role in frappe.get_roles(
+			frappe.session.user
 		):
 			action = "Warn"
 
@@ -323,10 +320,8 @@
 	data = frappe.db.sql(
 		""" select ifnull((sum(child.stock_qty - child.ordered_qty) * rate), 0) as amount
 		from `tabMaterial Request Item` child, `tabMaterial Request` parent where parent.name = child.parent and
-		child.item_code = %s and parent.docstatus = 1 and child.stock_qty > child.ordered_qty and {0} and
-		parent.material_request_type = 'Purchase' and parent.status != 'Stopped'""".format(
-			condition
-		),
+		child.item_code = %s and parent.docstatus = 1 and child.stock_qty > child.ordered_qty and {} and
+		parent.material_request_type = 'Purchase' and parent.status != 'Stopped'""".format(condition),
 		item_code,
 		as_list=1,
 	)
@@ -339,12 +334,10 @@
 	condition = get_other_condition(args, budget, "Purchase Order")
 
 	data = frappe.db.sql(
-		""" select ifnull(sum(child.amount - child.billed_amt), 0) as amount
+		f""" select ifnull(sum(child.amount - child.billed_amt), 0) as amount
 		from `tabPurchase Order Item` child, `tabPurchase Order` parent where
 		parent.name = child.parent and child.item_code = %s and parent.docstatus = 1 and child.amount > child.billed_amt
-		and parent.status != 'Closed' and {0}""".format(
-			condition
-		),
+		and parent.status != 'Closed' and {condition}""",
 		item_code,
 		as_list=1,
 	)
@@ -357,7 +350,7 @@
 	budget_against_field = args.get("budget_against_field")
 
 	if budget_against_field and args.get(budget_against_field):
-		condition += " and child.%s = '%s'" % (budget_against_field, args.get(budget_against_field))
+		condition += f" and child.{budget_against_field} = '{args.get(budget_against_field)}'"
 
 	if args.get("fiscal_year"):
 		date_field = "schedule_date" if for_doc == "Material Request" else "transaction_date"
@@ -365,12 +358,8 @@
 			"Fiscal Year", args.get("fiscal_year"), ["year_start_date", "year_end_date"]
 		)
 
-		condition += """ and parent.%s
-			between '%s' and '%s' """ % (
-			date_field,
-			start_date,
-			end_date,
-		)
+		condition += f""" and parent.{date_field}
+			between '{start_date}' and '{end_date}' """
 
 	return condition
 
@@ -392,18 +381,17 @@
 		condition2 = """and exists(select name from `tab{doctype}`
 			where lft>=%(lft)s and rgt<=%(rgt)s
 			and name=gle.{budget_against_field})""".format(
-			doctype=args.budget_against_doctype, budget_against_field=budget_against_field  # nosec
+			doctype=args.budget_against_doctype,
+			budget_against_field=budget_against_field,  # nosec
 		)
 	else:
-		condition2 = """and exists(select name from `tab{doctype}`
-		where name=gle.{budget_against} and
-		gle.{budget_against} = %({budget_against})s)""".format(
-			doctype=args.budget_against_doctype, budget_against=budget_against_field
-		)
+		condition2 = f"""and exists(select name from `tab{args.budget_against_doctype}`
+		where name=gle.{budget_against_field} and
+		gle.{budget_against_field} = %({budget_against_field})s)"""
 
 	amount = flt(
 		frappe.db.sql(
-			"""
+			f"""
 		select sum(gle.debit) - sum(gle.credit)
 		from `tabGL Entry` gle
 		where
@@ -414,9 +402,7 @@
 			and gle.company=%(company)s
 			and gle.docstatus=1
 			{condition2}
-	""".format(
-				condition1=condition1, condition2=condition2
-			),
+	""",
 			(args),
 		)[0][0]
 	)  # nosec
diff --git a/erpnext/accounts/doctype/budget/test_budget.py b/erpnext/accounts/doctype/budget/test_budget.py
index 11af9a2..6d9a6f5 100644
--- a/erpnext/accounts/doctype/budget/test_budget.py
+++ b/erpnext/accounts/doctype/budget/test_budget.py
@@ -41,9 +41,7 @@
 
 		budget = make_budget(budget_against="Cost Center")
 
-		frappe.db.set_value(
-			"Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop"
-		)
+		frappe.db.set_value("Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop")
 
 		jv = make_journal_entry(
 			"_Test Account Cost for Goods Sold - _TC",
@@ -63,9 +61,7 @@
 
 		budget = make_budget(budget_against="Cost Center")
 
-		frappe.db.set_value(
-			"Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop"
-		)
+		frappe.db.set_value("Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop")
 
 		jv = make_journal_entry(
 			"_Test Account Cost for Goods Sold - _TC",
@@ -97,9 +93,7 @@
 		)
 
 		fiscal_year = get_fiscal_year(nowdate())[0]
-		frappe.db.set_value(
-			"Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop"
-		)
+		frappe.db.set_value("Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop")
 		frappe.db.set_value("Budget", budget.name, "fiscal_year", fiscal_year)
 
 		mr = frappe.get_doc(
@@ -138,9 +132,7 @@
 		)
 
 		fiscal_year = get_fiscal_year(nowdate())[0]
-		frappe.db.set_value(
-			"Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop"
-		)
+		frappe.db.set_value("Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop")
 		frappe.db.set_value("Budget", budget.name, "fiscal_year", fiscal_year)
 
 		po = create_purchase_order(transaction_date=nowdate(), do_not_submit=True)
@@ -158,9 +150,7 @@
 
 		budget = make_budget(budget_against="Project")
 
-		frappe.db.set_value(
-			"Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop"
-		)
+		frappe.db.set_value("Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop")
 
 		project = frappe.get_value("Project", {"project_name": "_Test Project"})
 
@@ -223,7 +213,7 @@
 		if month > 9:
 			month = 9
 
-		for i in range(month + 1):
+		for _i in range(month + 1):
 			jv = make_journal_entry(
 				"_Test Account Cost for Goods Sold - _TC",
 				"_Test Bank - _TC",
@@ -237,9 +227,7 @@
 				frappe.db.get_value("GL Entry", {"voucher_type": "Journal Entry", "voucher_no": jv.name})
 			)
 
-		frappe.db.set_value(
-			"Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop"
-		)
+		frappe.db.set_value("Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop")
 
 		self.assertRaises(BudgetError, jv.cancel)
 
@@ -255,7 +243,7 @@
 			month = 9
 
 		project = frappe.get_value("Project", {"project_name": "_Test Project"})
-		for i in range(month + 1):
+		for _i in range(month + 1):
 			jv = make_journal_entry(
 				"_Test Account Cost for Goods Sold - _TC",
 				"_Test Bank - _TC",
@@ -270,9 +258,7 @@
 				frappe.db.get_value("GL Entry", {"voucher_type": "Journal Entry", "voucher_no": jv.name})
 			)
 
-		frappe.db.set_value(
-			"Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop"
-		)
+		frappe.db.set_value("Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop")
 
 		self.assertRaises(BudgetError, jv.cancel)
 
@@ -284,9 +270,7 @@
 		set_total_expense_zero(nowdate(), "cost_center", "_Test Cost Center 2 - _TC")
 
 		budget = make_budget(budget_against="Cost Center", cost_center="_Test Company - _TC")
-		frappe.db.set_value(
-			"Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop"
-		)
+		frappe.db.set_value("Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop")
 
 		jv = make_journal_entry(
 			"_Test Account Cost for Goods Sold - _TC",
@@ -316,9 +300,7 @@
 			).insert(ignore_permissions=True)
 
 		budget = make_budget(budget_against="Cost Center", cost_center=cost_center)
-		frappe.db.set_value(
-			"Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop"
-		)
+		frappe.db.set_value("Budget", budget.name, "action_if_accumulated_monthly_budget_exceeded", "Stop")
 
 		jv = make_journal_entry(
 			"_Test Account Cost for Goods Sold - _TC",
@@ -423,13 +405,11 @@
 	fiscal_year = get_fiscal_year(nowdate())[0]
 
 	if budget_against == "Project":
-		project_name = "{0}%".format("_Test Project/" + fiscal_year)
+		project_name = "{}%".format("_Test Project/" + fiscal_year)
 		budget_list = frappe.get_all("Budget", fields=["name"], filters={"name": ("like", project_name)})
 	else:
-		cost_center_name = "{0}%".format(cost_center or "_Test Cost Center - _TC/" + fiscal_year)
-		budget_list = frappe.get_all(
-			"Budget", fields=["name"], filters={"name": ("like", cost_center_name)}
-		)
+		cost_center_name = "{}%".format(cost_center or "_Test Cost Center - _TC/" + fiscal_year)
+		budget_list = frappe.get_all("Budget", fields=["name"], filters={"name": ("like", cost_center_name)})
 	for d in budget_list:
 		frappe.db.sql("delete from `tabBudget` where name = %(name)s", d)
 		frappe.db.sql("delete from `tabBudget Account` where parent = %(name)s", d)
@@ -451,24 +431,18 @@
 	budget.action_if_annual_budget_exceeded = "Stop"
 	budget.action_if_accumulated_monthly_budget_exceeded = "Ignore"
 	budget.budget_against = budget_against
-	budget.append(
-		"accounts", {"account": "_Test Account Cost for Goods Sold - _TC", "budget_amount": 200000}
-	)
+	budget.append("accounts", {"account": "_Test Account Cost for Goods Sold - _TC", "budget_amount": 200000})
 
 	if args.applicable_on_material_request:
 		budget.applicable_on_material_request = 1
-		budget.action_if_annual_budget_exceeded_on_mr = (
-			args.action_if_annual_budget_exceeded_on_mr or "Warn"
-		)
+		budget.action_if_annual_budget_exceeded_on_mr = args.action_if_annual_budget_exceeded_on_mr or "Warn"
 		budget.action_if_accumulated_monthly_budget_exceeded_on_mr = (
 			args.action_if_accumulated_monthly_budget_exceeded_on_mr or "Warn"
 		)
 
 	if args.applicable_on_purchase_order:
 		budget.applicable_on_purchase_order = 1
-		budget.action_if_annual_budget_exceeded_on_po = (
-			args.action_if_annual_budget_exceeded_on_po or "Warn"
-		)
+		budget.action_if_annual_budget_exceeded_on_po = args.action_if_annual_budget_exceeded_on_po or "Warn"
 		budget.action_if_accumulated_monthly_budget_exceeded_on_po = (
 			args.action_if_accumulated_monthly_budget_exceeded_on_po or "Warn"
 		)
diff --git a/erpnext/accounts/doctype/chart_of_accounts_importer/chart_of_accounts_importer.py b/erpnext/accounts/doctype/chart_of_accounts_importer/chart_of_accounts_importer.py
index 1c805cc..e24c7c9 100644
--- a/erpnext/accounts/doctype/chart_of_accounts_importer/chart_of_accounts_importer.py
+++ b/erpnext/accounts/doctype/chart_of_accounts_importer/chart_of_accounts_importer.py
@@ -38,9 +38,7 @@
 
 	def validate(self):
 		if self.import_file:
-			get_coa(
-				"Chart of Accounts Importer", "All Accounts", file_name=self.import_file, for_validate=1
-			)
+			get_coa("Chart of Accounts Importer", "All Accounts", file_name=self.import_file, for_validate=1)
 
 
 def validate_columns(data):
@@ -116,7 +114,7 @@
 	file_path = file_doc.get_full_path()
 
 	data = []
-	with open(file_path, "r") as in_file:
+	with open(file_path) as in_file:
 		csv_reader = list(csv.reader(in_file))
 		headers = csv_reader[0]
 		del csv_reader[0]  # delete top row and headers row
@@ -215,10 +213,10 @@
 		for row in data:
 			account_name, parent_account, account_number, parent_account_number = row[0:4]
 			if account_number:
-				account_name = "{} - {}".format(account_number, account_name)
+				account_name = f"{account_number} - {account_name}"
 			if parent_account_number:
 				parent_account_number = cstr(parent_account_number).strip()
-				parent_account = "{} - {}".format(parent_account_number, parent_account)
+				parent_account = f"{parent_account_number} - {parent_account}"
 
 			if parent_account == account_name == child:
 				return [parent_account]
@@ -230,7 +228,7 @@
 							frappe.bold(parent_account)
 						)
 					)
-				return [child] + parent_account_list
+				return [child, *parent_account_list]
 
 	charts_map, paths = {}, []
 
@@ -250,12 +248,12 @@
 		) = i
 
 		if not account_name:
-			error_messages.append("Row {0}: Please enter Account Name".format(line_no))
+			error_messages.append(f"Row {line_no}: Please enter Account Name")
 
 		name = account_name
 		if account_number:
 			account_number = cstr(account_number).strip()
-			account_name = "{} - {}".format(account_number, account_name)
+			account_name = f"{account_number} - {account_name}"
 
 		charts_map[account_name] = {}
 		charts_map[account_name]["account_name"] = name
@@ -352,9 +350,9 @@
 
 def get_sample_template(writer, company):
 	currency = frappe.db.get_value("Company", company, "default_currency")
-	with open(os.path.join(os.path.dirname(__file__), "coa_sample_template.csv"), "r") as f:
+	with open(os.path.join(os.path.dirname(__file__), "coa_sample_template.csv")) as f:
 		for row in f:
-			row = row.strip().split(",") + [currency]
+			row = [*row.strip().split(","), currency]
 			writer.writerow(row)
 
 	return writer
@@ -463,7 +461,7 @@
 		"Purchase Taxes and Charges Template",
 	]:
 		frappe.db.sql(
-			'''delete from `tab{0}` where `company`="%s"'''.format(doctype) % (company)  # nosec
+			f'''delete from `tab{doctype}` where `company`="%s"''' % (company)  # nosec
 		)
 
 
diff --git a/erpnext/accounts/doctype/cheque_print_template/cheque_print_template.py b/erpnext/accounts/doctype/cheque_print_template/cheque_print_template.py
index 205bb29..4b1394e 100644
--- a/erpnext/accounts/doctype/cheque_print_template/cheque_print_template.py
+++ b/erpnext/accounts/doctype/cheque_print_template/cheque_print_template.py
@@ -66,71 +66,71 @@
 
 	cheque_print.html = """
 <style>
-	.print-format {
+	.print-format {{
 		padding: 0px;
-	}
-	@media screen {
-		.print-format {
+	}}
+	@media screen {{
+		.print-format {{
 			padding: 0in;
-		}
-	}
+		}}
+	}}
 </style>
-<div style="position: relative; top:%(starting_position_from_top_edge)scm">
-	<div style="width:%(cheque_width)scm;height:%(cheque_height)scm;">
-		<span style="top:%(acc_pay_dist_from_top_edge)scm; left:%(acc_pay_dist_from_left_edge)scm;
+<div style="position: relative; top:{starting_position_from_top_edge}cm">
+	<div style="width:{cheque_width}cm;height:{cheque_height}cm;">
+		<span style="top:{acc_pay_dist_from_top_edge}cm; left:{acc_pay_dist_from_left_edge}cm;
 			border-bottom: solid 1px;border-top:solid 1px; width:2cm;text-align: center; position: absolute;">
-				%(message_to_show)s
+				{message_to_show}
 		</span>
-		<span style="top:%(date_dist_from_top_edge)scm; left:%(date_dist_from_left_edge)scm;
+		<span style="top:{date_dist_from_top_edge}cm; left:{date_dist_from_left_edge}cm;
 			position: absolute;">
-			{{ frappe.utils.formatdate(doc.reference_date) or '' }}
+			{{{{ frappe.utils.formatdate(doc.reference_date) or '' }}}}
 		</span>
-		<span style="top:%(acc_no_dist_from_top_edge)scm;left:%(acc_no_dist_from_left_edge)scm;
+		<span style="top:{acc_no_dist_from_top_edge}cm;left:{acc_no_dist_from_left_edge}cm;
 			position: absolute;  min-width: 6cm;">
-			{{ doc.account_no or '' }}
+			{{{{ doc.account_no or '' }}}}
 		</span>
-		<span style="top:%(payer_name_from_top_edge)scm;left: %(payer_name_from_left_edge)scm;
+		<span style="top:{payer_name_from_top_edge}cm;left: {payer_name_from_left_edge}cm;
 			position: absolute;  min-width: 6cm;">
-			{{doc.party_name}}
+			{{{{doc.party_name}}}}
 		</span>
-		<span style="top:%(amt_in_words_from_top_edge)scm; left:%(amt_in_words_from_left_edge)scm;
-			position: absolute; display: block; width: %(amt_in_word_width)scm;
-			line-height:%(amt_in_words_line_spacing)scm; word-wrap: break-word;">
-				{{frappe.utils.money_in_words(doc.base_paid_amount or doc.base_received_amount)}}
+		<span style="top:{amt_in_words_from_top_edge}cm; left:{amt_in_words_from_left_edge}cm;
+			position: absolute; display: block; width: {amt_in_word_width}cm;
+			line-height:{amt_in_words_line_spacing}cm; word-wrap: break-word;">
+				{{{{frappe.utils.money_in_words(doc.base_paid_amount or doc.base_received_amount)}}}}
 		</span>
-		<span style="top:%(amt_in_figures_from_top_edge)scm;left: %(amt_in_figures_from_left_edge)scm;
+		<span style="top:{amt_in_figures_from_top_edge}cm;left: {amt_in_figures_from_left_edge}cm;
 			position: absolute; min-width: 4cm;">
-			{{doc.get_formatted("base_paid_amount") or doc.get_formatted("base_received_amount")}}
+			{{{{doc.get_formatted("base_paid_amount") or doc.get_formatted("base_received_amount")}}}}
 		</span>
-		<span style="top:%(signatory_from_top_edge)scm;left: %(signatory_from_left_edge)scm;
+		<span style="top:{signatory_from_top_edge}cm;left: {signatory_from_left_edge}cm;
 			position: absolute;  min-width: 6cm;">
-			{{doc.company}}
+			{{{{doc.company}}}}
 		</span>
 	</div>
-</div>""" % {
-		"starting_position_from_top_edge": doc.starting_position_from_top_edge
+</div>""".format(
+		starting_position_from_top_edge=doc.starting_position_from_top_edge
 		if doc.cheque_size == "A4"
 		else 0.0,
-		"cheque_width": doc.cheque_width,
-		"cheque_height": doc.cheque_height,
-		"acc_pay_dist_from_top_edge": doc.acc_pay_dist_from_top_edge,
-		"acc_pay_dist_from_left_edge": doc.acc_pay_dist_from_left_edge,
-		"message_to_show": doc.message_to_show if doc.message_to_show else _("Account Pay Only"),
-		"date_dist_from_top_edge": doc.date_dist_from_top_edge,
-		"date_dist_from_left_edge": doc.date_dist_from_left_edge,
-		"acc_no_dist_from_top_edge": doc.acc_no_dist_from_top_edge,
-		"acc_no_dist_from_left_edge": doc.acc_no_dist_from_left_edge,
-		"payer_name_from_top_edge": doc.payer_name_from_top_edge,
-		"payer_name_from_left_edge": doc.payer_name_from_left_edge,
-		"amt_in_words_from_top_edge": doc.amt_in_words_from_top_edge,
-		"amt_in_words_from_left_edge": doc.amt_in_words_from_left_edge,
-		"amt_in_word_width": doc.amt_in_word_width,
-		"amt_in_words_line_spacing": doc.amt_in_words_line_spacing,
-		"amt_in_figures_from_top_edge": doc.amt_in_figures_from_top_edge,
-		"amt_in_figures_from_left_edge": doc.amt_in_figures_from_left_edge,
-		"signatory_from_top_edge": doc.signatory_from_top_edge,
-		"signatory_from_left_edge": doc.signatory_from_left_edge,
-	}
+		cheque_width=doc.cheque_width,
+		cheque_height=doc.cheque_height,
+		acc_pay_dist_from_top_edge=doc.acc_pay_dist_from_top_edge,
+		acc_pay_dist_from_left_edge=doc.acc_pay_dist_from_left_edge,
+		message_to_show=doc.message_to_show if doc.message_to_show else _("Account Pay Only"),
+		date_dist_from_top_edge=doc.date_dist_from_top_edge,
+		date_dist_from_left_edge=doc.date_dist_from_left_edge,
+		acc_no_dist_from_top_edge=doc.acc_no_dist_from_top_edge,
+		acc_no_dist_from_left_edge=doc.acc_no_dist_from_left_edge,
+		payer_name_from_top_edge=doc.payer_name_from_top_edge,
+		payer_name_from_left_edge=doc.payer_name_from_left_edge,
+		amt_in_words_from_top_edge=doc.amt_in_words_from_top_edge,
+		amt_in_words_from_left_edge=doc.amt_in_words_from_left_edge,
+		amt_in_word_width=doc.amt_in_word_width,
+		amt_in_words_line_spacing=doc.amt_in_words_line_spacing,
+		amt_in_figures_from_top_edge=doc.amt_in_figures_from_top_edge,
+		amt_in_figures_from_left_edge=doc.amt_in_figures_from_left_edge,
+		signatory_from_top_edge=doc.signatory_from_top_edge,
+		signatory_from_left_edge=doc.signatory_from_left_edge,
+	)
 
 	cheque_print.save(ignore_permissions=True)
 
diff --git a/erpnext/accounts/doctype/cost_center/cost_center.py b/erpnext/accounts/doctype/cost_center/cost_center.py
index f662eb1..761369c 100644
--- a/erpnext/accounts/doctype/cost_center/cost_center.py
+++ b/erpnext/accounts/doctype/cost_center/cost_center.py
@@ -34,9 +34,7 @@
 	def autoname(self):
 		from erpnext.accounts.utils import get_autoname_with_number
 
-		self.name = get_autoname_with_number(
-			self.cost_center_number, self.cost_center_name, self.company
-		)
+		self.name = get_autoname_with_number(self.cost_center_number, self.cost_center_name, self.company)
 
 	def validate(self):
 		self.validate_mandatory()
@@ -109,14 +107,14 @@
 		new_cost_center = get_name_with_abbr(newdn, self.company)
 
 		# Validate properties before merging
-		super(CostCenter, self).before_rename(olddn, new_cost_center, merge, "is_group")
+		super().before_rename(olddn, new_cost_center, merge, "is_group")
 		if not merge:
 			new_cost_center = get_name_with_number(new_cost_center, self.cost_center_number)
 
 		return new_cost_center
 
 	def after_rename(self, olddn, newdn, merge=False):
-		super(CostCenter, self).after_rename(olddn, newdn, merge)
+		super().after_rename(olddn, newdn, merge)
 
 		if not merge:
 			new_cost_center = frappe.db.get_value(
diff --git a/erpnext/accounts/doctype/cost_center/test_cost_center.py b/erpnext/accounts/doctype/cost_center/test_cost_center.py
index 2ec1609..7d01918 100644
--- a/erpnext/accounts/doctype/cost_center/test_cost_center.py
+++ b/erpnext/accounts/doctype/cost_center/test_cost_center.py
@@ -10,7 +10,6 @@
 
 class TestCostCenter(unittest.TestCase):
 	def test_cost_center_creation_against_child_node(self):
-
 		if not frappe.db.get_value("Cost Center", {"name": "_Test Cost Center 2 - _TC"}):
 			frappe.get_doc(test_records[1]).insert()
 
diff --git a/erpnext/accounts/doctype/cost_center_allocation/cost_center_allocation.py b/erpnext/accounts/doctype/cost_center_allocation/cost_center_allocation.py
index 9ed5ddf..784ad27 100644
--- a/erpnext/accounts/doctype/cost_center_allocation/cost_center_allocation.py
+++ b/erpnext/accounts/doctype/cost_center_allocation/cost_center_allocation.py
@@ -48,7 +48,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(CostCenterAllocation, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 		self._skip_from_date_validation = False
 
 	def validate(self):
@@ -63,9 +63,7 @@
 		total_percentage = sum([d.percentage for d in self.get("allocation_percentages", [])])
 
 		if total_percentage != 100:
-			frappe.throw(
-				_("Total percentage against cost centers should be 100"), WrongPercentageAllocation
-			)
+			frappe.throw(_("Total percentage against cost centers should be 100"), WrongPercentageAllocation)
 
 	def validate_from_date_based_on_existing_gle(self):
 		# Check if GLE exists against the main cost center
diff --git a/erpnext/accounts/doctype/currency_exchange_settings/currency_exchange_settings.py b/erpnext/accounts/doctype/currency_exchange_settings/currency_exchange_settings.py
index b8817c6..8cbb99e 100644
--- a/erpnext/accounts/doctype/currency_exchange_settings/currency_exchange_settings.py
+++ b/erpnext/accounts/doctype/currency_exchange_settings/currency_exchange_settings.py
@@ -43,7 +43,6 @@
 
 	def set_parameters_and_result(self):
 		if self.service_provider == "exchangerate.host":
-
 			if not self.access_key:
 				frappe.throw(
 					_("Access Key is required for Service Provider: {0}").format(
@@ -78,9 +77,7 @@
 				transaction_date=nowdate(), to_currency="INR", from_currency="USD"
 			)
 
-		api_url = self.api_endpoint.format(
-			transaction_date=nowdate(), to_currency="INR", from_currency="USD"
-		)
+		api_url = self.api_endpoint.format(transaction_date=nowdate(), to_currency="INR", from_currency="USD")
 
 		try:
 			response = requests.get(api_url, params=params)
@@ -100,14 +97,14 @@
 				]
 		except Exception:
 			frappe.throw(_("Invalid result key. Response:") + " " + response.text)
-		if not isinstance(value, (int, float)):
+		if not isinstance(value, int | float):
 			frappe.throw(_("Returned exchange rate is neither integer not float."))
 
 		self.url = response.url
 
 
 @frappe.whitelist()
-def get_api_endpoint(service_provider: str = None, use_http: bool = False):
+def get_api_endpoint(service_provider: str | None = None, use_http: bool = False):
 	if service_provider and service_provider in ["exchangerate.host", "frankfurter.app"]:
 		if service_provider == "exchangerate.host":
 			api = "api.exchangerate.host/convert"
diff --git a/erpnext/accounts/doctype/dunning/test_dunning.py b/erpnext/accounts/doctype/dunning/test_dunning.py
index b29ace2..62a0c90 100644
--- a/erpnext/accounts/doctype/dunning/test_dunning.py
+++ b/erpnext/accounts/doctype/dunning/test_dunning.py
@@ -109,9 +109,7 @@
 
 def create_dunning(overdue_days, dunning_type_name=None):
 	posting_date = add_days(today(), -1 * overdue_days)
-	sales_invoice = create_sales_invoice_against_cost_center(
-		posting_date=posting_date, qty=1, rate=100
-	)
+	sales_invoice = create_sales_invoice_against_cost_center(posting_date=posting_date, qty=1, rate=100)
 	dunning = create_dunning_from_sales_invoice(sales_invoice.name)
 
 	if dunning_type_name:
diff --git a/erpnext/accounts/doctype/exchange_rate_revaluation/exchange_rate_revaluation.py b/erpnext/accounts/doctype/exchange_rate_revaluation/exchange_rate_revaluation.py
index 29732ef..2b17779 100644
--- a/erpnext/accounts/doctype/exchange_rate_revaluation/exchange_rate_revaluation.py
+++ b/erpnext/accounts/doctype/exchange_rate_revaluation/exchange_rate_revaluation.py
@@ -268,7 +268,6 @@
 
 			# Handle Accounts with '0' balance in Account/Base Currency
 			for d in [x for x in account_details if x.zero_balance]:
-
 				if d.balance != 0:
 					current_exchange_rate = new_exchange_rate = 0
 
@@ -281,7 +280,8 @@
 					new_balance_in_account_currency = 0
 
 					current_exchange_rate = (
-						calculate_exchange_rate_using_last_gle(company, d.account, d.party_type, d.party) or 0.0
+						calculate_exchange_rate_using_last_gle(company, d.account, d.party_type, d.party)
+						or 0.0
 					)
 
 					gain_loss = new_balance_in_account_currency - (
@@ -335,9 +335,7 @@
 
 		revaluation_jv = self.make_jv_for_revaluation()
 		if revaluation_jv:
-			frappe.msgprint(
-				f"Revaluation Journal: {get_link_to_form('Journal Entry', revaluation_jv.name)}"
-			)
+			frappe.msgprint(f"Revaluation Journal: {get_link_to_form('Journal Entry', revaluation_jv.name)}")
 
 		return {
 			"revaluation_jv": revaluation_jv.name if revaluation_jv else None,
@@ -394,7 +392,8 @@
 				journal_account.update(
 					{
 						dr_or_cr: flt(
-							abs(d.get("balance_in_account_currency")), d.precision("balance_in_account_currency")
+							abs(d.get("balance_in_account_currency")),
+							d.precision("balance_in_account_currency"),
 						),
 						reverse_dr_or_cr: 0,
 						"debit": 0,
@@ -520,7 +519,9 @@
 						abs(d.get("balance_in_account_currency")), d.precision("balance_in_account_currency")
 					),
 					"cost_center": erpnext.get_default_cost_center(self.company),
-					"exchange_rate": flt(d.get("current_exchange_rate"), d.precision("current_exchange_rate")),
+					"exchange_rate": flt(
+						d.get("current_exchange_rate"), d.precision("current_exchange_rate")
+					),
 					"reference_type": "Exchange Rate Revaluation",
 					"reference_name": self.name,
 				}
@@ -598,7 +599,7 @@
 
 @frappe.whitelist()
 def get_account_details(
-	company, posting_date, account, party_type=None, party=None, rounding_loss_allowance: float = None
+	company, posting_date, account, party_type=None, party=None, rounding_loss_allowance: float | None = None
 ):
 	if not (company and posting_date):
 		frappe.throw(_("Company and Posting Date is mandatory"))
@@ -611,7 +612,7 @@
 		frappe.throw(_("Party Type and Party is mandatory for {0} account").format(account_type))
 
 	account_details = {}
-	company_currency = erpnext.get_company_currency(company)
+	erpnext.get_company_currency(company)
 
 	account_details = {
 		"account_currency": account_currency,
@@ -625,9 +626,7 @@
 		rounding_loss_allowance=rounding_loss_allowance,
 	)
 
-	if account_balance and (
-		account_balance[0].balance or account_balance[0].balance_in_account_currency
-	):
+	if account_balance and (account_balance[0].balance or account_balance[0].balance_in_account_currency):
 		if account_with_new_balance := ExchangeRateRevaluation.calculate_new_account_balance(
 			company, posting_date, account_balance
 		):
diff --git a/erpnext/accounts/doctype/exchange_rate_revaluation/test_exchange_rate_revaluation.py b/erpnext/accounts/doctype/exchange_rate_revaluation/test_exchange_rate_revaluation.py
index e520872..51053f1 100644
--- a/erpnext/accounts/doctype/exchange_rate_revaluation/test_exchange_rate_revaluation.py
+++ b/erpnext/accounts/doctype/exchange_rate_revaluation/test_exchange_rate_revaluation.py
@@ -1,21 +1,14 @@
 # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors
 # See license.txt
 
-import unittest
 
 import frappe
-from frappe import qb
 from frappe.tests.utils import FrappeTestCase, change_settings
 from frappe.utils import add_days, flt, today
 
-from erpnext import get_default_cost_center
 from erpnext.accounts.doctype.payment_entry.payment_entry import get_payment_entry
-from erpnext.accounts.doctype.payment_entry.test_payment_entry import create_payment_entry
-from erpnext.accounts.doctype.purchase_invoice.test_purchase_invoice import make_purchase_invoice
 from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice
-from erpnext.accounts.party import get_party_account
 from erpnext.accounts.test.accounts_mixin import AccountsTestMixin
-from erpnext.stock.doctype.item.test_item import create_item
 
 
 class TestExchangeRateRevaluation(AccountsTestMixin, FrappeTestCase):
@@ -73,9 +66,7 @@
 		err.extend("accounts", accounts)
 		row = err.accounts[0]
 		row.new_exchange_rate = 85
-		row.new_balance_in_base_currency = flt(
-			row.new_exchange_rate * flt(row.balance_in_account_currency)
-		)
+		row.new_balance_in_base_currency = flt(row.new_exchange_rate * flt(row.balance_in_account_currency))
 		row.gain_loss = row.new_balance_in_base_currency - flt(row.balance_in_base_currency)
 		err.set_total_gain_loss()
 		err = err.save().submit()
@@ -127,9 +118,9 @@
 		pe.save().submit()
 
 		# Cancel the auto created gain/loss JE to simulate balance only in base currency
-		je = frappe.db.get_all(
-			"Journal Entry Account", filters={"reference_name": si.name}, pluck="parent"
-		)[0]
+		je = frappe.db.get_all("Journal Entry Account", filters={"reference_name": si.name}, pluck="parent")[
+			0
+		]
 		frappe.get_doc("Journal Entry", je).cancel()
 
 		err = frappe.new_doc("Exchange Rate Revaluation")
@@ -235,9 +226,9 @@
 			self.assertEqual(flt(acc.debit, precision), 0.0)
 			self.assertEqual(flt(acc.credit, precision), 0.0)
 
-		row = [x for x in je.accounts if x.account == self.debtors_usd][0]
+		row = next(x for x in je.accounts if x.account == self.debtors_usd)
 		self.assertEqual(flt(row.credit_in_account_currency, precision), 5.0)  # in USD
-		row = [x for x in je.accounts if x.account != self.debtors_usd][0]
+		row = next(x for x in je.accounts if x.account != self.debtors_usd)
 		self.assertEqual(flt(row.debit_in_account_currency, precision), 421.06)  # in INR
 
 		# total_debit and total_credit will be 0.0, as JV is posting only to account currency fields
@@ -294,5 +285,5 @@
 			"new_balance_in_account_currency": 100.0,
 		}
 
-		for key, val in expected_data.items():
+		for key, _val in expected_data.items():
 			self.assertEqual(expected_data.get(key), account_details.get(key))
diff --git a/erpnext/accounts/doctype/fiscal_year/fiscal_year.py b/erpnext/accounts/doctype/fiscal_year/fiscal_year.py
index 85f3ffd..25aa3f3 100644
--- a/erpnext/accounts/doctype/fiscal_year/fiscal_year.py
+++ b/erpnext/accounts/doctype/fiscal_year/fiscal_year.py
@@ -108,9 +108,9 @@
 
 				if overlap:
 					frappe.throw(
-						_("Year start date or end date is overlapping with {0}. To avoid please set company").format(
-							existing.name
-						),
+						_(
+							"Year start date or end date is overlapping with {0}. To avoid please set company"
+						).format(existing.name),
 						frappe.NameError,
 					)
 
@@ -126,9 +126,9 @@
 			not frappe.flags.in_test
 		):
 			frappe.throw(
-				_("Fiscal Year Start Date and Fiscal Year End Date are already set in Fiscal Year {0}").format(
-					fiscal_year
-				)
+				_(
+					"Fiscal Year Start Date and Fiscal Year End Date are already set in Fiscal Year {0}"
+				).format(fiscal_year)
 			)
 
 
diff --git a/erpnext/accounts/doctype/gl_entry/gl_entry.py b/erpnext/accounts/doctype/gl_entry/gl_entry.py
index a6f6d4e..c494eec 100644
--- a/erpnext/accounts/doctype/gl_entry/gl_entry.py
+++ b/erpnext/accounts/doctype/gl_entry/gl_entry.py
@@ -105,13 +105,18 @@
 			]:
 				# Update outstanding amt on against voucher
 				if (
-					self.against_voucher_type in ["Journal Entry", "Sales Invoice", "Purchase Invoice", "Fees"]
+					self.against_voucher_type
+					in ["Journal Entry", "Sales Invoice", "Purchase Invoice", "Fees"]
 					and self.against_voucher
 					and self.flags.update_outstanding == "Yes"
 					and not frappe.flags.is_reverse_depr_entry
 				):
 					update_outstanding_amt(
-						self.account, self.party_type, self.party, self.against_voucher_type, self.against_voucher
+						self.account,
+						self.party_type,
+						self.party,
+						self.against_voucher_type,
+						self.against_voucher,
 					)
 
 	def check_mandatory(self):
@@ -180,9 +185,9 @@
 			):
 				if not self.get(dimension.fieldname):
 					frappe.throw(
-						_("Accounting Dimension <b>{0}</b> is required for 'Profit and Loss' account {1}.").format(
-							dimension.label, self.account
-						)
+						_(
+							"Accounting Dimension <b>{0}</b> is required for 'Profit and Loss' account {1}."
+						).format(dimension.label, self.account)
 					)
 
 			if (
@@ -193,9 +198,9 @@
 			):
 				if not self.get(dimension.fieldname):
 					frappe.throw(
-						_("Accounting Dimension <b>{0}</b> is required for 'Balance Sheet' account {1}.").format(
-							dimension.label, self.account
-						)
+						_(
+							"Accounting Dimension <b>{0}</b> is required for 'Balance Sheet' account {1}."
+						).format(dimension.label, self.account)
 					)
 
 	def check_pl_account(self):
@@ -243,9 +248,7 @@
 		if not self.cost_center:
 			return
 
-		is_group, company = frappe.get_cached_value(
-			"Cost Center", self.cost_center, ["is_group", "company"]
-		)
+		is_group, company = frappe.get_cached_value("Cost Center", self.cost_center, ["is_group", "company"])
 
 		if company != self.company:
 			frappe.throw(
@@ -314,7 +317,7 @@
 	account, party_type, party, against_voucher_type, against_voucher, on_cancel=False
 ):
 	if party_type and party:
-		party_condition = " and party_type={0} and party={1}".format(
+		party_condition = " and party_type={} and party={}".format(
 			frappe.db.escape(party_type), frappe.db.escape(party)
 		)
 	else:
@@ -322,23 +325,19 @@
 
 	if against_voucher_type == "Sales Invoice":
 		party_account = frappe.get_cached_value(against_voucher_type, against_voucher, "debit_to")
-		account_condition = "and account in ({0}, {1})".format(
-			frappe.db.escape(account), frappe.db.escape(party_account)
-		)
+		account_condition = f"and account in ({frappe.db.escape(account)}, {frappe.db.escape(party_account)})"
 	else:
-		account_condition = " and account = {0}".format(frappe.db.escape(account))
+		account_condition = f" and account = {frappe.db.escape(account)}"
 
 	# get final outstanding amt
 	bal = flt(
 		frappe.db.sql(
-			"""
+			f"""
 		select sum(debit_in_account_currency) - sum(credit_in_account_currency)
 		from `tabGL Entry`
 		where against_voucher_type=%s and against_voucher=%s
 		and voucher_type != 'Invoice Discounting'
-		{0} {1}""".format(
-				party_condition, account_condition
-			),
+		{party_condition} {account_condition}""",
 			(against_voucher_type, against_voucher),
 		)[0][0]
 		or 0.0
@@ -349,12 +348,10 @@
 	elif against_voucher_type == "Journal Entry":
 		against_voucher_amount = flt(
 			frappe.db.sql(
-				"""
+				f"""
 			select sum(debit_in_account_currency) - sum(credit_in_account_currency)
 			from `tabGL Entry` where voucher_type = 'Journal Entry' and voucher_no = %s
-			and account = %s and (against_voucher is null or against_voucher='') {0}""".format(
-					party_condition
-				),
+			and account = %s and (against_voucher is null or against_voucher='') {party_condition}""",
 				(against_voucher, account),
 			)[0][0]
 		)
@@ -373,7 +370,9 @@
 		# Validation : Outstanding can not be negative for JV
 		if bal < 0 and not on_cancel:
 			frappe.throw(
-				_("Outstanding for {0} cannot be less than zero ({1})").format(against_voucher, fmt_money(bal))
+				_("Outstanding for {0} cannot be less than zero ({1})").format(
+					against_voucher, fmt_money(bal)
+				)
 			)
 
 	if against_voucher_type in ["Sales Invoice", "Purchase Invoice", "Fees"]:
@@ -446,7 +445,7 @@
 		set_name_from_naming_options(frappe.get_meta(doctype).autoname, doc)
 		newname = doc.name
 		frappe.db.sql(
-			"UPDATE `tab{}` SET name = %s, to_rename = 0 where name = %s".format(doctype),
+			f"UPDATE `tab{doctype}` SET name = %s, to_rename = 0 where name = %s",
 			(newname, oldname),
 			auto_commit=True,
 		)
diff --git a/erpnext/accounts/doctype/gl_entry/test_gl_entry.py b/erpnext/accounts/doctype/gl_entry/test_gl_entry.py
index b188b09..3edfd67 100644
--- a/erpnext/accounts/doctype/gl_entry/test_gl_entry.py
+++ b/erpnext/accounts/doctype/gl_entry/test_gl_entry.py
@@ -14,9 +14,7 @@
 class TestGLEntry(unittest.TestCase):
 	def test_round_off_entry(self):
 		frappe.db.set_value("Company", "_Test Company", "round_off_account", "_Test Write Off - _TC")
-		frappe.db.set_value(
-			"Company", "_Test Company", "round_off_cost_center", "_Test Cost Center - _TC"
-		)
+		frappe.db.set_value("Company", "_Test Company", "round_off_cost_center", "_Test Cost Center - _TC")
 
 		jv = make_journal_entry(
 			"_Test Account Cost for Goods Sold - _TC",
@@ -73,7 +71,9 @@
 		)
 		self.assertTrue(all(entry.to_rename == 0 for entry in new_gl_entries))
 
-		self.assertTrue(all(new.name != old.name for new, old in zip(gl_entries, new_gl_entries)))
+		self.assertTrue(
+			all(new.name != old.name for new, old in zip(gl_entries, new_gl_entries, strict=False))
+		)
 
 		new_naming_series_current_value = frappe.db.sql(
 			"SELECT current from tabSeries where name = %s", naming_series
diff --git a/erpnext/accounts/doctype/invoice_discounting/invoice_discounting.py b/erpnext/accounts/doctype/invoice_discounting/invoice_discounting.py
index 76f4dad..5d3c2b9 100644
--- a/erpnext/accounts/doctype/invoice_discounting/invoice_discounting.py
+++ b/erpnext/accounts/doctype/invoice_discounting/invoice_discounting.py
@@ -83,9 +83,7 @@
 				frappe.throw(
 					_(
 						"Row({0}): Outstanding Amount cannot be greater than actual Outstanding Amount {1} in {2}"
-					).format(
-						record.idx, frappe.bold(actual_outstanding), frappe.bold(record.sales_invoice)
-					)
+					).format(record.idx, frappe.bold(actual_outstanding), frappe.bold(record.sales_invoice))
 				)
 
 	def calculate_total_amount(self):
@@ -105,7 +103,9 @@
 			self.status = status
 			self.db_set("status", status)
 			for d in self.invoices:
-				frappe.get_doc("Sales Invoice", d.sales_invoice).set_status(update=True, update_modified=False)
+				frappe.get_doc("Sales Invoice", d.sales_invoice).set_status(
+					update=True, update_modified=False
+				)
 		else:
 			self.status = "Draft"
 			if self.docstatus == 1:
diff --git a/erpnext/accounts/doctype/invoice_discounting/test_invoice_discounting.py b/erpnext/accounts/doctype/invoice_discounting/test_invoice_discounting.py
index a85fdfc..65e3c3d 100644
--- a/erpnext/accounts/doctype/invoice_discounting/test_invoice_discounting.py
+++ b/erpnext/accounts/doctype/invoice_discounting/test_invoice_discounting.py
@@ -75,7 +75,7 @@
 		gle = get_gl_entries("Invoice Discounting", inv_disc.name)
 
 		expected_gle = {inv.debit_to: [0.0, 200], self.ar_credit: [200, 0.0]}
-		for i, gle in enumerate(gle):
+		for _i, gle in enumerate(gle):
 			self.assertEqual([gle.debit, gle.credit], expected_gle.get(gle.account))
 
 	def test_loan_on_submit(self):
@@ -92,9 +92,7 @@
 			period=60,
 		)
 		self.assertEqual(inv_disc.status, "Sanctioned")
-		self.assertEqual(
-			inv_disc.loan_end_date, add_days(inv_disc.loan_start_date, inv_disc.loan_period)
-		)
+		self.assertEqual(inv_disc.loan_end_date, add_days(inv_disc.loan_start_date, inv_disc.loan_period))
 
 	def test_on_disbursed(self):
 		inv = create_sales_invoice(rate=500)
@@ -262,13 +260,9 @@
 		je_on_payment.submit()
 
 		self.assertEqual(je_on_payment.accounts[0].account, self.ar_discounted)
-		self.assertEqual(
-			je_on_payment.accounts[0].credit_in_account_currency, flt(inv.outstanding_amount)
-		)
+		self.assertEqual(je_on_payment.accounts[0].credit_in_account_currency, flt(inv.outstanding_amount))
 		self.assertEqual(je_on_payment.accounts[1].account, self.bank_account)
-		self.assertEqual(
-			je_on_payment.accounts[1].debit_in_account_currency, flt(inv.outstanding_amount)
-		)
+		self.assertEqual(je_on_payment.accounts[1].debit_in_account_currency, flt(inv.outstanding_amount))
 
 		inv.reload()
 		self.assertEqual(inv.outstanding_amount, 0)
@@ -304,13 +298,9 @@
 		je_on_payment.submit()
 
 		self.assertEqual(je_on_payment.accounts[0].account, self.ar_unpaid)
-		self.assertEqual(
-			je_on_payment.accounts[0].credit_in_account_currency, flt(inv.outstanding_amount)
-		)
+		self.assertEqual(je_on_payment.accounts[0].credit_in_account_currency, flt(inv.outstanding_amount))
 		self.assertEqual(je_on_payment.accounts[1].account, self.bank_account)
-		self.assertEqual(
-			je_on_payment.accounts[1].debit_in_account_currency, flt(inv.outstanding_amount)
-		)
+		self.assertEqual(je_on_payment.accounts[1].debit_in_account_currency, flt(inv.outstanding_amount))
 
 		inv.reload()
 		self.assertEqual(inv.outstanding_amount, 0)
diff --git a/erpnext/accounts/doctype/item_tax_template/item_tax_template.py b/erpnext/accounts/doctype/item_tax_template/item_tax_template.py
index 8d3cdc8..02b7455 100644
--- a/erpnext/accounts/doctype/item_tax_template/item_tax_template.py
+++ b/erpnext/accounts/doctype/item_tax_template/item_tax_template.py
@@ -32,7 +32,7 @@
 	def autoname(self):
 		if self.company and self.title:
 			abbr = frappe.get_cached_value("Company", self.company, "abbr")
-			self.name = "{0} - {1}".format(self.title, abbr)
+			self.name = f"{self.title} - {abbr}"
 
 	def validate_tax_accounts(self):
 		"""Check whether Tax Rate is not entered twice for same Tax Type"""
diff --git a/erpnext/accounts/doctype/journal_entry/journal_entry.py b/erpnext/accounts/doctype/journal_entry/journal_entry.py
index 835d202..048b04b 100644
--- a/erpnext/accounts/doctype/journal_entry/journal_entry.py
+++ b/erpnext/accounts/doctype/journal_entry/journal_entry.py
@@ -112,7 +112,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(JournalEntry, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 
 	def validate(self):
 		if self.voucher_type == "Opening Entry":
@@ -191,7 +191,7 @@
 
 	def on_cancel(self):
 		# References for this Journal are removed on the `on_cancel` event in accounts_controller
-		super(JournalEntry, self).on_cancel()
+		super().on_cancel()
 		self.ignore_linked_doctypes = (
 			"GL Entry",
 			"Stock Ledger Entry",
@@ -216,9 +216,9 @@
 
 	def update_advance_paid(self):
 		advance_paid = frappe._dict()
-		advance_payment_doctypes = frappe.get_hooks(
-			"advance_payment_receivable_doctypes"
-		) + frappe.get_hooks("advance_payment_payable_doctypes")
+		advance_payment_doctypes = frappe.get_hooks("advance_payment_receivable_doctypes") + frappe.get_hooks(
+			"advance_payment_payable_doctypes"
+		)
 		for d in self.get("accounts"):
 			if d.is_advance:
 				if d.reference_type in advance_payment_doctypes:
@@ -229,10 +229,7 @@
 				frappe.get_doc(voucher_type, voucher_no).set_total_advance_paid()
 
 	def validate_inter_company_accounts(self):
-		if (
-			self.voucher_type == "Inter Company Journal Entry"
-			and self.inter_company_journal_entry_reference
-		):
+		if self.voucher_type == "Inter Company Journal Entry" and self.inter_company_journal_entry_reference:
 			doc = frappe.get_doc("Journal Entry", self.inter_company_journal_entry_reference)
 			account_currency = frappe.get_cached_value("Company", self.company, "default_currency")
 			previous_account_currency = frappe.get_cached_value("Company", doc.company, "default_currency")
@@ -378,10 +375,7 @@
 				asset.set_status()
 
 	def update_inter_company_jv(self):
-		if (
-			self.voucher_type == "Inter Company Journal Entry"
-			and self.inter_company_journal_entry_reference
-		):
+		if self.voucher_type == "Inter Company Journal Entry" and self.inter_company_journal_entry_reference:
 			frappe.db.set_value(
 				"Journal Entry",
 				self.inter_company_journal_entry_reference,
@@ -409,17 +403,25 @@
 				if d.account == inv_disc_doc.short_term_loan and d.reference_name == inv_disc:
 					if self.docstatus == 1:
 						if d.credit > 0:
-							_validate_invoice_discounting_status(inv_disc, inv_disc_doc.status, "Sanctioned", d.idx)
+							_validate_invoice_discounting_status(
+								inv_disc, inv_disc_doc.status, "Sanctioned", d.idx
+							)
 							status = "Disbursed"
 						elif d.debit > 0:
-							_validate_invoice_discounting_status(inv_disc, inv_disc_doc.status, "Disbursed", d.idx)
+							_validate_invoice_discounting_status(
+								inv_disc, inv_disc_doc.status, "Disbursed", d.idx
+							)
 							status = "Settled"
 					else:
 						if d.credit > 0:
-							_validate_invoice_discounting_status(inv_disc, inv_disc_doc.status, "Disbursed", d.idx)
+							_validate_invoice_discounting_status(
+								inv_disc, inv_disc_doc.status, "Disbursed", d.idx
+							)
 							status = "Sanctioned"
 						elif d.debit > 0:
-							_validate_invoice_discounting_status(inv_disc, inv_disc_doc.status, "Settled", d.idx)
+							_validate_invoice_discounting_status(
+								inv_disc, inv_disc_doc.status, "Settled", d.idx
+							)
 							status = "Disbursed"
 					break
 			if status:
@@ -488,10 +490,7 @@
 					)
 
 	def unlink_inter_company_jv(self):
-		if (
-			self.voucher_type == "Inter Company Journal Entry"
-			and self.inter_company_journal_entry_reference
-		):
+		if self.voucher_type == "Inter Company Journal Entry" and self.inter_company_journal_entry_reference:
 			frappe.db.set_value(
 				"Journal Entry",
 				self.inter_company_journal_entry_reference,
@@ -513,9 +512,9 @@
 			if account_type in ["Receivable", "Payable"]:
 				if not (d.party_type and d.party):
 					frappe.throw(
-						_("Row {0}: Party Type and Party is required for Receivable / Payable account {1}").format(
-							d.idx, d.account
-						)
+						_(
+							"Row {0}: Party Type and Party is required for Receivable / Payable account {1}"
+						).format(d.idx, d.account)
 					)
 				elif (
 					d.party_type
@@ -580,16 +579,18 @@
 
 	def system_generated_gain_loss(self):
 		return (
-			self.voucher_type == "Exchange Gain Or Loss"
-			and self.multi_currency
-			and self.is_system_generated
+			self.voucher_type == "Exchange Gain Or Loss" and self.multi_currency and self.is_system_generated
 		)
 
 	def validate_against_jv(self):
 		for d in self.get("accounts"):
 			if d.reference_type == "Journal Entry":
 				account_root_type = frappe.get_cached_value("Account", d.account, "root_type")
-				if account_root_type == "Asset" and flt(d.debit) > 0 and not self.system_generated_gain_loss():
+				if (
+					account_root_type == "Asset"
+					and flt(d.debit) > 0
+					and not self.system_generated_gain_loss()
+				):
 					frappe.throw(
 						_(
 							"Row #{0}: For {1}, you can select reference document only if account gets credited"
@@ -671,7 +672,9 @@
 
 				if d.reference_type == "Purchase Order" and flt(d.credit) > 0:
 					frappe.throw(
-						_("Row {0}: Credit entry can not be linked with a {1}").format(d.idx, d.reference_type)
+						_("Row {0}: Credit entry can not be linked with a {1}").format(
+							d.idx, d.reference_type
+						)
 					)
 
 				# set totals
@@ -693,7 +696,10 @@
 
 				# check if party and account match
 				if d.reference_type in ("Sales Invoice", "Purchase Invoice"):
-					if self.voucher_type in ("Deferred Revenue", "Deferred Expense") and d.reference_detail_no:
+					if (
+						self.voucher_type in ("Deferred Revenue", "Deferred Expense")
+						and d.reference_detail_no
+					):
 						debit_or_credit = "Debit" if d.debit else "Credit"
 						party_account = get_deferred_booking_accounts(
 							d.reference_type, d.reference_detail_no, debit_or_credit
@@ -702,7 +708,8 @@
 					else:
 						if d.reference_type == "Sales Invoice":
 							party_account = (
-								get_party_account_based_on_invoice_discounting(d.reference_name) or against_voucher[1]
+								get_party_account_based_on_invoice_discounting(d.reference_name)
+								or against_voucher[1]
 							)
 						else:
 							party_account = against_voucher[1]
@@ -826,7 +833,9 @@
 		if not (self.voucher_type == "Exchange Gain Or Loss" and self.multi_currency):
 			if self.difference:
 				frappe.throw(
-					_("Total Debit must be equal to Total Credit. The difference is {0}").format(self.difference)
+					_("Total Debit must be equal to Total Credit. The difference is {0}").format(
+						self.difference
+					)
 				)
 
 	def set_total_debit_credit(self):
@@ -890,7 +899,6 @@
 					and self.posting_date
 				)
 			):
-
 				ignore_exchange_rate = False
 				if self.get("flags") and self.flags.get("ignore_exchange_rate"):
 					ignore_exchange_rate = True
@@ -1136,27 +1144,21 @@
 		self.validate_total_debit_and_credit()
 
 	def get_values(self):
-		cond = (
-			" and outstanding_amount <= {0}".format(self.write_off_amount)
-			if flt(self.write_off_amount) > 0
-			else ""
-		)
+		cond = f" and outstanding_amount <= {self.write_off_amount}" if flt(self.write_off_amount) > 0 else ""
 
 		if self.write_off_based_on == "Accounts Receivable":
 			return frappe.db.sql(
 				"""select name, debit_to as account, customer as party, outstanding_amount
-				from `tabSales Invoice` where docstatus = 1 and company = %s
-				and outstanding_amount > 0 %s"""
-				% ("%s", cond),
+				from `tabSales Invoice` where docstatus = 1 and company = {}
+				and outstanding_amount > 0 {}""".format("%s", cond),
 				self.company,
 				as_dict=True,
 			)
 		elif self.write_off_based_on == "Accounts Payable":
 			return frappe.db.sql(
 				"""select name, credit_to as account, supplier as party, outstanding_amount
-				from `tabPurchase Invoice` where docstatus = 1 and company = %s
-				and outstanding_amount > 0 %s"""
-				% ("%s", cond),
+				from `tabPurchase Invoice` where docstatus = 1 and company = {}
+				and outstanding_amount > 0 {}""".format("%s", cond),
 				self.company,
 				as_dict=True,
 			)
@@ -1267,7 +1269,7 @@
 			"amount_field_bank": amount_field_bank,
 			"amount": amount,
 			"debit_in_account_currency": debit_in_account_currency,
-			"remarks": "Advance Payment received against {0} {1}".format(dt, dn),
+			"remarks": f"Advance Payment received against {dt} {dn}",
 			"is_advance": "Yes",
 			"bank_account": bank_account,
 			"journal_entry": journal_entry,
@@ -1306,7 +1308,7 @@
 			"amount_field_bank": amount_field_bank,
 			"amount": amount if amount else abs(ref_doc.outstanding_amount),
 			"debit_in_account_currency": debit_in_account_currency,
-			"remarks": "Payment received against {0} {1}. {2}".format(dt, dn, ref_doc.remarks),
+			"remarks": f"Payment received against {dt} {dn}. {ref_doc.remarks}",
 			"is_advance": "No",
 			"bank_account": bank_account,
 			"journal_entry": journal_entry,
@@ -1332,9 +1334,7 @@
 		)
 
 	je = frappe.new_doc("Journal Entry")
-	je.update(
-		{"voucher_type": "Bank Entry", "company": ref_doc.company, "remark": args.get("remarks")}
-	)
+	je.update({"voucher_type": "Bank Entry", "company": ref_doc.company, "remark": args.get("remarks")})
 
 	party_row = je.append(
 		"accounts",
@@ -1357,9 +1357,7 @@
 	bank_row = je.append("accounts")
 
 	# Make it bank_details
-	bank_account = get_default_bank_cash_account(
-		ref_doc.company, "Bank", account=args.get("bank_account")
-	)
+	bank_account = get_default_bank_cash_account(ref_doc.company, "Bank", account=args.get("bank_account"))
 	if bank_account:
 		bank_row.update(bank_account)
 		# Modified to include the posting date for which the exchange rate is required.
@@ -1399,7 +1397,7 @@
 		return []
 
 	return frappe.db.sql(
-		"""
+		f"""
 		SELECT jv.name, jv.posting_date, jv.user_remark
 		FROM `tabJournal Entry` jv, `tabJournal Entry Account` jv_detail
 		WHERE jv_detail.parent = jv.name
@@ -1410,16 +1408,14 @@
 				OR jv_detail.reference_type = ''
 			)
 			AND jv.docstatus = 1
-			AND jv.`{0}` LIKE %(txt)s
+			AND jv.`{searchfield}` LIKE %(txt)s
 		ORDER BY jv.name DESC
 		LIMIT %(limit)s offset %(offset)s
-		""".format(
-			searchfield
-		),
+		""",
 		dict(
 			account=filters.get("account"),
 			party=cstr(filters.get("party")),
-			txt="%{0}%".format(txt),
+			txt=f"%{txt}%",
 			offset=start,
 			limit=page_len,
 		),
@@ -1441,19 +1437,15 @@
 		condition = " and party=%(party)s" if args.get("party") else ""
 
 		against_jv_amount = frappe.db.sql(
-			"""
+			f"""
 			select sum(debit_in_account_currency) - sum(credit_in_account_currency)
-			from `tabJournal Entry Account` where parent=%(docname)s and account=%(account)s {0}
-			and (reference_type is null or reference_type = '')""".format(
-				condition
-			),
+			from `tabJournal Entry Account` where parent=%(docname)s and account=%(account)s {condition}
+			and (reference_type is null or reference_type = '')""",
 			args,
 		)
 
 		against_jv_amount = flt(against_jv_amount[0][0]) if against_jv_amount else 0
-		amount_field = (
-			"credit_in_account_currency" if against_jv_amount > 0 else "debit_in_account_currency"
-		)
+		amount_field = "credit_in_account_currency" if against_jv_amount > 0 else "debit_in_account_currency"
 		return {amount_field: abs(against_jv_amount)}
 	elif args.get("doctype") in ("Sales Invoice", "Purchase Invoice"):
 		party_type = "Customer" if args.get("doctype") == "Sales Invoice" else "Supplier"
@@ -1466,9 +1458,7 @@
 
 		due_date = invoice.get("due_date")
 
-		exchange_rate = (
-			invoice.conversion_rate if (args.get("account_currency") != company_currency) else 1
-		)
+		exchange_rate = invoice.conversion_rate if (args.get("account_currency") != company_currency) else 1
 
 		if args["doctype"] == "Sales Invoice":
 			amount_field = (
@@ -1506,9 +1496,7 @@
 
 
 @frappe.whitelist()
-def get_account_details_and_party_type(
-	account, date, company, debit=None, credit=None, exchange_rate=None
-):
+def get_account_details_and_party_type(account, date, company, debit=None, credit=None, exchange_rate=None):
 	"""Returns dict of account details and party type to be set in Journal Entry on selection of account."""
 	if not frappe.has_permission("Account"):
 		frappe.msgprint(_("No Permission"), raise_exception=1)
diff --git a/erpnext/accounts/doctype/journal_entry/test_journal_entry.py b/erpnext/accounts/doctype/journal_entry/test_journal_entry.py
index 798d3bb..5bfb65a 100644
--- a/erpnext/accounts/doctype/journal_entry/test_journal_entry.py
+++ b/erpnext/accounts/doctype/journal_entry/test_journal_entry.py
@@ -69,10 +69,8 @@
 
 		self.assertTrue(
 			frappe.db.sql(
-				"""select name from `tabJournal Entry Account`
-			where reference_type = %s and reference_name = %s and {0}=400""".format(
-					dr_or_cr
-				),
+				f"""select name from `tabJournal Entry Account`
+			where reference_type = %s and reference_name = %s and {dr_or_cr}=400""",
 				(submitted_voucher.doctype, submitted_voucher.name),
 			)
 		)
@@ -84,9 +82,8 @@
 	def advance_paid_testcase(self, base_jv, test_voucher, dr_or_cr):
 		# Test advance paid field
 		advance_paid = frappe.db.sql(
-			"""select advance_paid from `tab%s`
-					where name=%s"""
-			% (test_voucher.doctype, "%s"),
+			"""select advance_paid from `tab{}`
+					where name={}""".format(test_voucher.doctype, "%s"),
 			(test_voucher.name),
 		)
 		payment_against_order = base_jv.get("accounts")[0].get(dr_or_cr)
@@ -159,9 +156,7 @@
 			jv.cancel()
 
 	def test_multi_currency(self):
-		jv = make_journal_entry(
-			"_Test Bank USD - _TC", "_Test Bank - _TC", 100, exchange_rate=50, save=False
-		)
+		jv = make_journal_entry("_Test Bank USD - _TC", "_Test Bank - _TC", 100, exchange_rate=50, save=False)
 
 		jv.get("accounts")[1].credit_in_account_currency = 5000
 		jv.submit()
@@ -477,9 +472,7 @@
 			query = query.select(gl[field])
 
 		query = query.where(
-			(gl.voucher_type == "Journal Entry")
-			& (gl.voucher_no == self.voucher_no)
-			& (gl.is_cancelled == 0)
+			(gl.voucher_type == "Journal Entry") & (gl.voucher_no == self.voucher_no) & (gl.is_cancelled == 0)
 		).orderby(gl.account)
 
 		gl_entries = query.run(as_dict=True)
diff --git a/erpnext/accounts/doctype/ledger_merge/test_ledger_merge.py b/erpnext/accounts/doctype/ledger_merge/test_ledger_merge.py
index 992ce9e..dccd73c 100644
--- a/erpnext/accounts/doctype/ledger_merge/test_ledger_merge.py
+++ b/erpnext/accounts/doctype/ledger_merge/test_ledger_merge.py
@@ -83,7 +83,10 @@
 				"account": "Indirect Income - _TC",
 				"merge_accounts": [
 					{"account": "Indirect Test Income - _TC", "account_name": "Indirect Test Income"},
-					{"account": "Administrative Test Income - _TC", "account_name": "Administrative Test Income"},
+					{
+						"account": "Administrative Test Income - _TC",
+						"account_name": "Administrative Test Income",
+					},
 				],
 			}
 		).insert(ignore_permissions=True)
diff --git a/erpnext/accounts/doctype/loyalty_program/loyalty_program.py b/erpnext/accounts/doctype/loyalty_program/loyalty_program.py
index 463b3cd..f3ad84b 100644
--- a/erpnext/accounts/doctype/loyalty_program/loyalty_program.py
+++ b/erpnext/accounts/doctype/loyalty_program/loyalty_program.py
@@ -52,13 +52,11 @@
 		condition += " and expiry_date>='%s' " % expiry_date
 
 	loyalty_point_details = frappe.db.sql(
-		"""select sum(loyalty_points) as loyalty_points,
+		f"""select sum(loyalty_points) as loyalty_points,
 		sum(purchase_amount) as total_spent from `tabLoyalty Point Entry`
 		where customer=%s and loyalty_program=%s and posting_date <= %s
 		{condition}
-		group by customer""".format(
-			condition=condition
-		),
+		group by customer""",
 		(customer, loyalty_program, expiry_date),
 		as_dict=1,
 	)
@@ -79,9 +77,7 @@
 	include_expired_entry=False,
 	current_transaction_amount=0,
 ):
-	lp_details = get_loyalty_program_details(
-		customer, loyalty_program, company=company, silent=silent
-	)
+	lp_details = get_loyalty_program_details(customer, loyalty_program, company=company, silent=silent)
 	loyalty_program = frappe.get_doc("Loyalty Program", loyalty_program)
 	lp_details.update(
 		get_loyalty_details(customer, loyalty_program.name, expiry_date, company, include_expired_entry)
diff --git a/erpnext/accounts/doctype/loyalty_program/test_loyalty_program.py b/erpnext/accounts/doctype/loyalty_program/test_loyalty_program.py
index cbfb17b..4d21fb6 100644
--- a/erpnext/accounts/doctype/loyalty_program/test_loyalty_program.py
+++ b/erpnext/accounts/doctype/loyalty_program/test_loyalty_program.py
@@ -19,9 +19,7 @@
 		create_records()
 
 	def test_loyalty_points_earned_single_tier(self):
-		frappe.db.set_value(
-			"Customer", "Test Loyalty Customer", "loyalty_program", "Test Single Loyalty"
-		)
+		frappe.db.set_value("Customer", "Test Loyalty Customer", "loyalty_program", "Test Single Loyalty")
 		# create a new sales invoice
 		si_original = create_sales_invoice_record()
 		si_original.insert()
@@ -69,9 +67,7 @@
 			d.cancel()
 
 	def test_loyalty_points_earned_multiple_tier(self):
-		frappe.db.set_value(
-			"Customer", "Test Loyalty Customer", "loyalty_program", "Test Multiple Loyalty"
-		)
+		frappe.db.set_value("Customer", "Test Loyalty Customer", "loyalty_program", "Test Multiple Loyalty")
 		# assign multiple tier program to the customer
 		customer = frappe.get_doc("Customer", {"customer_name": "Test Loyalty Customer"})
 		customer.loyalty_program = frappe.get_doc(
@@ -128,9 +124,7 @@
 
 	def test_cancel_sales_invoice(self):
 		"""cancelling the sales invoice should cancel the earned points"""
-		frappe.db.set_value(
-			"Customer", "Test Loyalty Customer", "loyalty_program", "Test Single Loyalty"
-		)
+		frappe.db.set_value("Customer", "Test Loyalty Customer", "loyalty_program", "Test Single Loyalty")
 		# create a new sales invoice
 		si = create_sales_invoice_record()
 		si.insert()
@@ -148,9 +142,7 @@
 		self.assertEqual(True, (lpe is None))
 
 	def test_sales_invoice_return(self):
-		frappe.db.set_value(
-			"Customer", "Test Loyalty Customer", "loyalty_program", "Test Single Loyalty"
-		)
+		frappe.db.set_value("Customer", "Test Loyalty Customer", "loyalty_program", "Test Single Loyalty")
 		# create a new sales invoice
 		si_original = create_sales_invoice_record(2)
 		si_original.conversion_rate = flt(1)
@@ -346,9 +338,7 @@
 		).insert()
 
 	# create item price
-	if not frappe.db.exists(
-		"Item Price", {"price_list": "Standard Selling", "item_code": "Loyal Item"}
-	):
+	if not frappe.db.exists("Item Price", {"price_list": "Standard Selling", "item_code": "Loyal Item"}):
 		frappe.get_doc(
 			{
 				"doctype": "Item Price",
diff --git a/erpnext/accounts/doctype/monthly_distribution/monthly_distribution.py b/erpnext/accounts/doctype/monthly_distribution/monthly_distribution.py
index 7270576..cda5f4b 100644
--- a/erpnext/accounts/doctype/monthly_distribution/monthly_distribution.py
+++ b/erpnext/accounts/doctype/monthly_distribution/monthly_distribution.py
@@ -54,9 +54,7 @@
 		total = sum(flt(d.percentage_allocation) for d in self.get("percentages"))
 
 		if flt(total, 2) != 100.0:
-			frappe.throw(
-				_("Percentage Allocation should be equal to 100%") + " ({0}%)".format(str(flt(total, 2)))
-			)
+			frappe.throw(_("Percentage Allocation should be equal to 100%") + f" ({flt(total, 2)!s}%)")
 
 
 def get_periodwise_distribution_data(distribution_id, period_list, periodicity):
diff --git a/erpnext/accounts/doctype/opening_invoice_creation_tool/test_opening_invoice_creation_tool.py b/erpnext/accounts/doctype/opening_invoice_creation_tool/test_opening_invoice_creation_tool.py
index 02c2c67..378fbde 100644
--- a/erpnext/accounts/doctype/opening_invoice_creation_tool/test_opening_invoice_creation_tool.py
+++ b/erpnext/accounts/doctype/opening_invoice_creation_tool/test_opening_invoice_creation_tool.py
@@ -83,9 +83,7 @@
 		company = "_Test Opening Invoice Company"
 		party_1, party_2 = make_customer("Customer A"), make_customer("Customer B")
 
-		old_default_receivable_account = frappe.db.get_value(
-			"Company", company, "default_receivable_account"
-		)
+		old_default_receivable_account = frappe.db.get_value("Company", company, "default_receivable_account")
 		frappe.db.set_value("Company", company, "default_receivable_account", "")
 
 		if not frappe.db.exists("Cost Center", "_Test Opening Invoice Company - _TOIC"):
@@ -121,9 +119,7 @@
 		self.assertTrue(error_log)
 
 		# teardown
-		frappe.db.set_value(
-			"Company", company, "default_receivable_account", old_default_receivable_account
-		)
+		frappe.db.set_value("Company", company, "default_receivable_account", old_default_receivable_account)
 
 	def test_renaming_of_invoice_using_invoice_number_field(self):
 		company = "_Test Opening Invoice Company"
@@ -169,7 +165,7 @@
 				{
 					"qty": 1.0,
 					"outstanding_amount": 300,
-					"party": args.get("party_1") or "_Test {0}".format(party),
+					"party": args.get("party_1") or f"_Test {party}",
 					"item_name": "Opening Item",
 					"due_date": "2016-09-10",
 					"posting_date": "2016-09-05",
@@ -179,7 +175,7 @@
 				{
 					"qty": 2.0,
 					"outstanding_amount": 250,
-					"party": args.get("party_2") or "_Test {0} 1".format(party),
+					"party": args.get("party_2") or f"_Test {party} 1",
 					"item_name": "Opening Item",
 					"due_date": "2016-09-10",
 					"posting_date": "2016-09-05",
diff --git a/erpnext/accounts/doctype/party_link/party_link.py b/erpnext/accounts/doctype/party_link/party_link.py
index d60acce..16484fc 100644
--- a/erpnext/accounts/doctype/party_link/party_link.py
+++ b/erpnext/accounts/doctype/party_link/party_link.py
@@ -38,7 +38,10 @@
 		if existing_party_link:
 			frappe.throw(
 				_("{} {} is already linked with {} {}").format(
-					self.primary_role, bold(self.primary_party), self.secondary_role, bold(self.secondary_party)
+					self.primary_role,
+					bold(self.primary_party),
+					self.secondary_role,
+					bold(self.secondary_party),
 				)
 			)
 
diff --git a/erpnext/accounts/doctype/payment_entry/payment_entry.py b/erpnext/accounts/doctype/payment_entry/payment_entry.py
index 4684aab..e2041bf 100644
--- a/erpnext/accounts/doctype/payment_entry/payment_entry.py
+++ b/erpnext/accounts/doctype/payment_entry/payment_entry.py
@@ -134,7 +134,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(PaymentEntry, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 		if not self.is_new():
 			self.setup_party_account_field()
 
@@ -247,7 +247,7 @@
 			"Unreconcile Payment",
 			"Unreconcile Payment Entries",
 		)
-		super(PaymentEntry, self).on_cancel()
+		super().on_cancel()
 		self.make_gl_entries(cancel=1)
 		self.update_outstanding_amounts()
 		self.update_advance_paid()
@@ -357,9 +357,7 @@
 				# If term based allocation is enabled, throw
 				if (
 					d.payment_term is None or d.payment_term == ""
-				) and self.term_based_allocation_enabled_for_reference(
-					d.reference_doctype, d.reference_name
-				):
+				) and self.term_based_allocation_enabled_for_reference(d.reference_doctype, d.reference_name):
 					frappe.throw(
 						_(
 							"{0} has Payment Term based allocation enabled. Select a Payment Term for Row #{1} in Payment References section"
@@ -371,7 +369,9 @@
 				# The reference has already been fully paid
 				if not latest:
 					frappe.throw(
-						_("{0} {1} has already been fully paid.").format(_(d.reference_doctype), d.reference_name)
+						_("{0} {1} has already been fully paid.").format(
+							_(d.reference_doctype), d.reference_name
+						)
 					)
 				# The reference has already been partly paid
 				elif (
@@ -395,14 +395,14 @@
 						and latest.payment_term_outstanding
 						and (flt(d.allocated_amount) > flt(latest.payment_term_outstanding))
 					)
-					and self.term_based_allocation_enabled_for_reference(d.reference_doctype, d.reference_name)
+					and self.term_based_allocation_enabled_for_reference(
+						d.reference_doctype, d.reference_name
+					)
 				):
 					frappe.throw(
 						_(
 							"Row #{0}: Allocated amount:{1} is greater than outstanding amount:{2} for Payment Term {3}"
-						).format(
-							d.idx, d.allocated_amount, latest.payment_term_outstanding, d.payment_term
-						)
+						).format(d.idx, d.allocated_amount, latest.payment_term_outstanding, d.payment_term)
 					)
 
 				if (flt(d.allocated_amount)) > 0 and flt(d.allocated_amount) > flt(latest.outstanding_amount):
@@ -445,7 +445,9 @@
 
 		if self.party:
 			if not self.contact_person:
-				set_contact_details(self, party=frappe._dict({"name": self.party}), party_type=self.party_type)
+				set_contact_details(
+					self, party=frappe._dict({"name": self.party}), party_type=self.party_type
+				)
 			else:
 				complete_contact_details(self)
 			if not self.party_balance:
@@ -527,7 +529,9 @@
 			else:
 				if ref_doc:
 					if self.paid_from_account_currency == ref_doc.currency:
-						self.source_exchange_rate = ref_doc.get("exchange_rate") or ref_doc.get("conversion_rate")
+						self.source_exchange_rate = ref_doc.get("exchange_rate") or ref_doc.get(
+							"conversion_rate"
+						)
 
 			if not self.source_exchange_rate:
 				self.source_exchange_rate = get_exchange_rate(
@@ -564,7 +568,7 @@
 			if d.reference_doctype not in valid_reference_doctypes:
 				frappe.throw(
 					_("Reference Doctype must be one of {0}").format(
-						comma_or((_(d) for d in valid_reference_doctypes))
+						comma_or(_(d) for d in valid_reference_doctypes)
 					)
 				)
 
@@ -587,7 +591,8 @@
 					if d.reference_doctype in frappe.get_hooks("invoice_doctypes"):
 						if self.party_type == "Customer":
 							ref_party_account = (
-								get_party_account_based_on_invoice_discounting(d.reference_name) or ref_doc.debit_to
+								get_party_account_based_on_invoice_discounting(d.reference_name)
+								or ref_doc.debit_to
 							)
 						elif self.party_type == "Supplier":
 							ref_party_account = ref_doc.credit_to
@@ -600,7 +605,10 @@
 						):
 							frappe.throw(
 								_("{0} {1} is associated with {2}, but Party Account is {3}").format(
-									_(d.reference_doctype), d.reference_name, ref_party_account, self.party_account
+									_(d.reference_doctype),
+									d.reference_name,
+									ref_party_account,
+									self.party_account,
 								)
 							)
 
@@ -611,7 +619,9 @@
 							)
 
 					if ref_doc.docstatus != 1:
-						frappe.throw(_("{0} {1} must be submitted").format(_(d.reference_doctype), d.reference_name))
+						frappe.throw(
+							_("{0} {1} must be submitted").format(_(d.reference_doctype), d.reference_name)
+						)
 
 	def get_valid_reference_doctypes(self):
 		if self.party_type == "Customer":
@@ -782,9 +792,7 @@
 		if not (is_single_currency and reference_is_multi_currency):
 			return allocated_amount
 
-		allocated_amount = flt(
-			allocated_amount / ref_exchange_rate, self.precision("total_allocated_amount")
-		)
+		allocated_amount = flt(allocated_amount / ref_exchange_rate, self.precision("total_allocated_amount"))
 
 		return allocated_amount
 
@@ -847,7 +855,6 @@
 		accounts = []
 		for d in self.taxes:
 			if d.account_head == tax_withholding_details.get("account_head"):
-
 				# Preserve user updated included in paid amount
 				if d.included_in_paid_amount:
 					tax_withholding_details.update({"included_in_paid_amount": d.included_in_paid_amount})
@@ -953,9 +960,9 @@
 
 	def calculate_base_allocated_amount_for_reference(self, d) -> float:
 		base_allocated_amount = 0
-		advance_payment_doctypes = frappe.get_hooks(
-			"advance_payment_receivable_doctypes"
-		) + frappe.get_hooks("advance_payment_payable_doctypes")
+		advance_payment_doctypes = frappe.get_hooks("advance_payment_receivable_doctypes") + frappe.get_hooks(
+			"advance_payment_payable_doctypes"
+		)
 		if d.reference_doctype in advance_payment_doctypes:
 			# When referencing Sales/Purchase Order, use the source/target exchange rate depending on payment type.
 			# This is so there are no Exchange Gain/Loss generated for such doctypes
@@ -970,7 +977,6 @@
 				flt(d.allocated_amount) * flt(exchange_rate), self.precision("base_paid_amount")
 			)
 		else:
-
 			# Use source/target exchange rate, so no difference amount is calculated.
 			# then update exchange gain/loss amount in reference table
 			# if there is an exchange gain/loss amount in reference table, submit a JE for that
@@ -1108,7 +1114,6 @@
 				)
 			]
 		else:
-
 			remarks = [
 				_("Amount {0} {1} {2} {3}").format(
 					_(self.party_account_currency),
@@ -1128,14 +1133,19 @@
 				if d.allocated_amount:
 					remarks.append(
 						_("Amount {0} {1} against {2} {3}").format(
-							_(self.party_account_currency), d.allocated_amount, d.reference_doctype, d.reference_name
+							_(self.party_account_currency),
+							d.allocated_amount,
+							d.reference_doctype,
+							d.reference_name,
 						)
 					)
 
 		for d in self.get("deductions"):
 			if d.amount:
 				remarks.append(
-					_("Amount {0} {1} deducted against {2}").format(_(self.company_currency), d.amount, d.account)
+					_("Amount {0} {1} deducted against {2}").format(
+						_(self.company_currency), d.amount, d.account
+					)
 				)
 
 		self.set("remarks", "\n".join(remarks))
@@ -1209,21 +1219,31 @@
 					dr_or_cr = "credit" if self.payment_type == "Receive" else "debit"
 					cost_center = self.cost_center
 					if d.reference_doctype == "Sales Invoice" and not cost_center:
-						cost_center = frappe.db.get_value(d.reference_doctype, d.reference_name, "cost_center")
+						cost_center = frappe.db.get_value(
+							d.reference_doctype, d.reference_name, "cost_center"
+						)
 
 					gle = party_gl_dict.copy()
 
-					allocated_amount_in_company_currency = self.calculate_base_allocated_amount_for_reference(d)
+					allocated_amount_in_company_currency = self.calculate_base_allocated_amount_for_reference(
+						d
+					)
 					reverse_dr_or_cr = 0
 
 					if d.reference_doctype in ["Sales Invoice", "Purchase Invoice"]:
 						is_return = frappe.db.get_value(d.reference_doctype, d.reference_name, "is_return")
 						payable_party_types = get_party_types_from_account_type("Payable")
 						receivable_party_types = get_party_types_from_account_type("Receivable")
-						if is_return and self.party_type in receivable_party_types and (self.payment_type == "Pay"):
+						if (
+							is_return
+							and self.party_type in receivable_party_types
+							and (self.payment_type == "Pay")
+						):
 							reverse_dr_or_cr = 1
 						elif (
-							is_return and self.party_type in payable_party_types and (self.payment_type == "Receive")
+							is_return
+							and self.party_type in payable_party_types
+							and (self.payment_type == "Receive")
 						):
 							reverse_dr_or_cr = 1
 
@@ -1306,9 +1326,7 @@
 		if getdate(posting_date) < getdate(self.posting_date):
 			posting_date = self.posting_date
 
-		dr_or_cr = (
-			"credit" if invoice.reference_doctype in ["Sales Invoice", "Payment Entry"] else "debit"
-		)
+		dr_or_cr = "credit" if invoice.reference_doctype in ["Sales Invoice", "Payment Entry"] else "debit"
 		args_dict["account"] = invoice.account
 		args_dict[dr_or_cr] = invoice.allocated_amount
 		args_dict[dr_or_cr + "_in_account_currency"] = invoice.allocated_amount
@@ -1694,7 +1712,8 @@
 				return []
 			elif supplier_status["hold_type"] == "Payments":
 				if (
-					not supplier_status["release_date"] or getdate(nowdate()) <= supplier_status["release_date"]
+					not supplier_status["release_date"]
+					or getdate(nowdate()) <= supplier_status["release_date"]
 				):
 					return []
 
@@ -1704,7 +1723,7 @@
 	# Get positive outstanding sales /purchase invoices
 	condition = ""
 	if args.get("voucher_type") and args.get("voucher_no"):
-		condition = " and voucher_type={0} and voucher_no={1}".format(
+		condition = " and voucher_type={} and voucher_no={}".format(
 			frappe.db.escape(args["voucher_type"]), frappe.db.escape(args["voucher_no"])
 		)
 		common_filter.append(ple.voucher_type == args["voucher_type"])
@@ -1719,7 +1738,7 @@
 	active_dimensions = get_dimensions()[0]
 	for dim in active_dimensions:
 		if args.get(dim.fieldname):
-			condition += " and {0}='{1}'".format(dim.fieldname, args.get(dim.fieldname))
+			condition += f" and {dim.fieldname}='{args.get(dim.fieldname)}'"
 			accounting_dimensions_filter.append(ple[dim.fieldname] == args.get(dim.fieldname))
 
 	date_fields_dict = {
@@ -1729,21 +1748,21 @@
 
 	for fieldname, date_fields in date_fields_dict.items():
 		if args.get(date_fields[0]) and args.get(date_fields[1]):
-			condition += " and {0} between '{1}' and '{2}'".format(
+			condition += " and {} between '{}' and '{}'".format(
 				fieldname, args.get(date_fields[0]), args.get(date_fields[1])
 			)
 			posting_and_due_date.append(ple[fieldname][args.get(date_fields[0]) : args.get(date_fields[1])])
 		elif args.get(date_fields[0]):
 			# if only from date is supplied
-			condition += " and {0} >= '{1}'".format(fieldname, args.get(date_fields[0]))
+			condition += f" and {fieldname} >= '{args.get(date_fields[0])}'"
 			posting_and_due_date.append(ple[fieldname].gte(args.get(date_fields[0])))
 		elif args.get(date_fields[1]):
 			# if only to date is supplied
-			condition += " and {0} <= '{1}'".format(fieldname, args.get(date_fields[1]))
+			condition += f" and {fieldname} <= '{args.get(date_fields[1])}'"
 			posting_and_due_date.append(ple[fieldname].lte(args.get(date_fields[1])))
 
 	if args.get("company"):
-		condition += " and company = {0}".format(frappe.db.escape(args.get("company")))
+		condition += " and company = {}".format(frappe.db.escape(args.get("company")))
 		common_filter.append(ple.company == args.get("company"))
 
 	outstanding_invoices = []
@@ -1859,12 +1878,10 @@
 	return outstanding_invoices_after_split
 
 
-def get_currency_data(outstanding_invoices: list, company: str = None) -> dict:
+def get_currency_data(outstanding_invoices: list, company: str | None = None) -> dict:
 	"""Get currency and conversion data for a list of invoices."""
 	exc_rates = frappe._dict()
-	company_currency = (
-		frappe.db.get_value("Company", company, "default_currency") if company else None
-	)
+	company_currency = frappe.db.get_value("Company", company, "default_currency") if company else None
 
 	for doctype in ["Sales Invoice", "Purchase Invoice"]:
 		invoices = [x.voucher_no for x in outstanding_invoices if x.voucher_type == doctype]
@@ -1959,7 +1976,7 @@
 	active_dimensions = get_dimensions()[0]
 	for dim in active_dimensions:
 		if filters.get(dim.fieldname):
-			condition += " and {0}='{1}'".format(dim.fieldname, filters.get(dim.fieldname))
+			condition += f" and {dim.fieldname}='{filters.get(dim.fieldname)}'"
 
 	if party_account_currency == company_currency:
 		grand_total_field = "base_grand_total"
@@ -2109,18 +2126,14 @@
 	frappe.has_permission("Payment Entry", throw=True)
 
 	# to check if the passed account is accessible under reference doctype Payment Entry
-	account_list = frappe.get_list(
-		"Account", {"name": account}, reference_doctype="Payment Entry", limit=1
-	)
+	account_list = frappe.get_list("Account", {"name": account}, reference_doctype="Payment Entry", limit=1)
 
 	# There might be some user permissions which will allow account under certain doctypes
 	# except for Payment Entry, only in such case we should throw permission error
 	if not account_list:
 		frappe.throw(_("Account: {0} is not permitted under Payment Entry").format(account))
 
-	account_balance = get_balance_on(
-		account, date, cost_center=cost_center, ignore_account_permission=True
-	)
+	account_balance = get_balance_on(account, date, cost_center=cost_center, ignore_account_permission=True)
 
 	return frappe._dict(
 		{
@@ -2167,9 +2180,7 @@
 	total_amount = outstanding_amount = exchange_rate = account = None
 
 	ref_doc = frappe.get_doc(reference_doctype, reference_name)
-	company_currency = ref_doc.get("company_currency") or erpnext.get_company_currency(
-		ref_doc.company
-	)
+	company_currency = ref_doc.get("company_currency") or erpnext.get_company_currency(ref_doc.company)
 
 	if reference_doctype == "Dunning":
 		total_amount = outstanding_amount = ref_doc.get("dunning_amount")
@@ -2178,9 +2189,7 @@
 	elif reference_doctype == "Journal Entry" and ref_doc.docstatus == 1:
 		total_amount = ref_doc.get("total_amount")
 		if ref_doc.multi_currency:
-			exchange_rate = get_exchange_rate(
-				party_account_currency, company_currency, ref_doc.posting_date
-			)
+			exchange_rate = get_exchange_rate(party_account_currency, company_currency, ref_doc.posting_date)
 		else:
 			exchange_rate = 1
 			outstanding_amount = get_outstanding_on_journal_entry(reference_name)
@@ -2250,9 +2259,7 @@
 ):
 	doc = frappe.get_doc(dt, dn)
 	over_billing_allowance = frappe.db.get_single_value("Accounts Settings", "over_billing_allowance")
-	if dt in ("Sales Order", "Purchase Order") and flt(doc.per_billed, 2) >= (
-		100.0 + over_billing_allowance
-	):
+	if dt in ("Sales Order", "Purchase Order") and flt(doc.per_billed, 2) >= (100.0 + over_billing_allowance):
 		frappe.throw(_("Can only make payment against unbilled {0}").format(_(dt)))
 
 	if not party_type:
@@ -2305,9 +2312,7 @@
 	pe.paid_from_account_currency = (
 		party_account_currency if payment_type == "Receive" else bank.account_currency
 	)
-	pe.paid_to_account_currency = (
-		party_account_currency if payment_type == "Pay" else bank.account_currency
-	)
+	pe.paid_to_account_currency = party_account_currency if payment_type == "Pay" else bank.account_currency
 	pe.paid_amount = paid_amount
 	pe.received_amount = received_amount
 	pe.letter_head = doc.get("letter_head")
@@ -2336,7 +2341,6 @@
 			doc.payment_terms_template,
 			"allocate_payment_based_on_payment_terms",
 		):
-
 			for reference in get_reference_as_per_payment_terms(
 				doc.payment_schedule, dt, dn, doc, grand_total, outstanding_amount, party_account_currency
 			):
@@ -2524,9 +2528,7 @@
 	return paid_amount, received_amount
 
 
-def apply_early_payment_discount(
-	paid_amount, received_amount, doc, party_account_currency, reference_date
-):
+def apply_early_payment_discount(paid_amount, received_amount, doc, party_account_currency, reference_date):
 	total_discount = 0
 	valid_discounts = []
 	eligible_for_payments = ["Sales Order", "Sales Invoice", "Purchase Order", "Purchase Invoice"]
@@ -2536,7 +2538,6 @@
 	if doc.doctype in eligible_for_payments and has_payment_schedule:
 		for term in doc.payment_schedule:
 			if not term.discounted_amount and term.discount and reference_date <= term.discount_date:
-
 				if term.discount_type == "Percentage":
 					grand_total = doc.get("grand_total") if is_multi_currency else doc.get("base_grand_total")
 					discount_amount = flt(grand_total) * (term.discount / 100)
@@ -2565,9 +2566,7 @@
 	return paid_amount, received_amount, total_discount, valid_discounts
 
 
-def set_pending_discount_loss(
-	pe, doc, discount_amount, base_total_discount_loss, party_account_currency
-):
+def set_pending_discount_loss(pe, doc, discount_amount, base_total_discount_loss, party_account_currency):
 	# If multi-currency, get base discount amount to adjust with base currency deductions/losses
 	if party_account_currency != doc.company_currency:
 		discount_amount = discount_amount * doc.get("conversion_rate", 1)
@@ -2587,7 +2586,8 @@
 		pe.set_gain_or_loss(
 			account_details={
 				"account": frappe.get_cached_value("Company", pe.company, account_type),
-				"cost_center": pe.cost_center or frappe.get_cached_value("Company", pe.company, "cost_center"),
+				"cost_center": pe.cost_center
+				or frappe.get_cached_value("Company", pe.company, "cost_center"),
 				"amount": discount_amount * positive_negative,
 			}
 		)
@@ -2610,9 +2610,7 @@
 def get_total_discount_percent(doc, valid_discounts) -> float:
 	"""Get total percentage and amount discount applied as a percentage."""
 	total_discount_percent = (
-		sum(
-			discount.get("discount") for discount in valid_discounts if discount.get("type") == "Percentage"
-		)
+		sum(discount.get("discount") for discount in valid_discounts if discount.get("type") == "Percentage")
 		or 0.0
 	)
 
@@ -2655,9 +2653,7 @@
 
 	# The same account head could be used more than once
 	for tax in doc.get("taxes", []):
-		base_tax_loss = tax.get("base_tax_amount_after_discount_amount") * (
-			total_discount_percentage / 100
-		)
+		base_tax_loss = tax.get("base_tax_amount_after_discount_amount") * (total_discount_percentage / 100)
 
 		account = tax.get("account_head")
 		if not tax_discount_loss.get(account):
@@ -2674,7 +2670,8 @@
 			"deductions",
 			{
 				"account": account,
-				"cost_center": pe.cost_center or frappe.get_cached_value("Company", pe.company, "cost_center"),
+				"cost_center": pe.cost_center
+				or frappe.get_cached_value("Company", pe.company, "cost_center"),
 				"amount": flt(loss, precision),
 			},
 		)
@@ -2697,7 +2694,8 @@
 		if not is_multi_currency_acc:
 			# If accounting is done in company currency for multi-currency transaction
 			payment_term_outstanding = flt(
-				payment_term_outstanding * doc.get("conversion_rate"), payment_term.precision("payment_amount")
+				payment_term_outstanding * doc.get("conversion_rate"),
+				payment_term.precision("payment_amount"),
 			)
 
 		if payment_term_outstanding:
@@ -2725,7 +2723,7 @@
 		dr_or_cr = "debit_in_account_currency - credit_in_account_currency"
 
 	paid_amount = frappe.db.sql(
-		"""
+		f"""
 		select ifnull(sum({dr_or_cr}), 0) as paid_amount
 		from `tabGL Entry`
 		where against_voucher_type = %s
@@ -2735,9 +2733,7 @@
 			and account = %s
 			and due_date = %s
 			and {dr_or_cr} > 0
-	""".format(
-			dr_or_cr=dr_or_cr
-		),
+	""",
 		(dt, dn, party_type, party, account, due_date),
 	)
 
diff --git a/erpnext/accounts/doctype/payment_entry/test_payment_entry.py b/erpnext/accounts/doctype/payment_entry/test_payment_entry.py
index 6323e4c..aaa4e49 100644
--- a/erpnext/accounts/doctype/payment_entry/test_payment_entry.py
+++ b/erpnext/accounts/doctype/payment_entry/test_payment_entry.py
@@ -1,7 +1,6 @@
 # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
 # See license.txt
 
-import unittest
 
 import frappe
 from frappe import qb
@@ -10,7 +9,6 @@
 
 from erpnext.accounts.doctype.account.test_account import create_account
 from erpnext.accounts.doctype.payment_entry.payment_entry import (
-	InvalidPaymentEntry,
 	get_outstanding_reference_documents,
 	get_payment_entry,
 	get_reference_details,
@@ -469,9 +467,7 @@
 		si.save()
 		si.submit()
 
-		pe = get_payment_entry(
-			"Sales Invoice", si.name, bank_account="_Test Bank - _TC", bank_amount=4700
-		)
+		pe = get_payment_entry("Sales Invoice", si.name, bank_account="_Test Bank - _TC", bank_amount=4700)
 		pe.reference_no = si.name
 		pe.reference_date = nowdate()
 
@@ -638,9 +634,7 @@
 		pe.set_exchange_rate()
 		pe.set_amounts()
 
-		self.assertEqual(
-			pe.source_exchange_rate, 65.1, "{0} is not equal to {1}".format(pe.source_exchange_rate, 65.1)
-		)
+		self.assertEqual(pe.source_exchange_rate, 65.1, f"{pe.source_exchange_rate} is not equal to {65.1}")
 
 	def test_internal_transfer_usd_to_inr(self):
 		pe = frappe.new_doc("Payment Entry")
@@ -896,9 +890,7 @@
 		cost_center = "_Test Cost Center for BS Account - _TC"
 		create_cost_center(cost_center_name="_Test Cost Center for BS Account", company="_Test Company")
 
-		pi = make_purchase_invoice_against_cost_center(
-			cost_center=cost_center, credit_to="Creditors - _TC"
-		)
+		pi = make_purchase_invoice_against_cost_center(cost_center=cost_center, credit_to="Creditors - _TC")
 
 		pe = get_payment_entry("Purchase Invoice", pi.name, bank_account="_Test Bank - _TC")
 		self.assertEqual(pe.cost_center, pi.cost_center)
@@ -939,9 +931,7 @@
 		si = create_sales_invoice_against_cost_center(cost_center=cost_center, debit_to="Debtors - _TC")
 
 		account_balance = get_balance_on(account="_Test Bank - _TC", cost_center=si.cost_center)
-		party_balance = get_balance_on(
-			party_type="Customer", party=si.customer, cost_center=si.cost_center
-		)
+		party_balance = get_balance_on(party_type="Customer", party=si.customer, cost_center=si.cost_center)
 		party_account_balance = get_balance_on(si.debit_to, cost_center=si.cost_center)
 
 		pe = get_payment_entry("Sales Invoice", si.name, bank_account="_Test Bank - _TC")
@@ -1203,7 +1193,7 @@
 		Overallocation validation shouldn't fire for Template without "Allocate Payment based on Payment Terms" enabled
 
 		"""
-		customer = create_customer()
+		create_customer()
 		create_payment_terms_template()
 
 		template = frappe.get_doc("Payment Terms Template", "Test Receivable Template")
@@ -1262,9 +1252,7 @@
 		create_payment_terms_template()
 
 		# SI has an earlier due date and SI2 has a later due date
-		si = create_sales_invoice(
-			qty=1, rate=100, customer=customer, posting_date=add_days(nowdate(), -4)
-		)
+		si = create_sales_invoice(qty=1, rate=100, customer=customer, posting_date=add_days(nowdate(), -4))
 		si2 = create_sales_invoice(do_not_save=1, qty=1, rate=100, customer=customer)
 		si2.payment_terms_template = "Test Receivable Template"
 		si2.submit()
@@ -1363,8 +1351,6 @@
 		self.check_gl_entries()
 
 	def test_ledger_entries_for_advance_as_liability(self):
-		from erpnext.accounts.doctype.account.test_account import create_account
-
 		company = "_Test Company"
 
 		advance_account = create_account(
@@ -1466,7 +1452,7 @@
 		self.check_pl_entries()
 
 		# Unreconcile
-		unrecon = (
+		(
 			frappe.get_doc(
 				{
 					"doctype": "Unreconcile Payment",
@@ -1554,8 +1540,6 @@
 		self.assertEqual(len(pr.payments), 0)
 
 	def test_advance_reverse_payment_reconciliation(self):
-		from erpnext.accounts.doctype.account.test_account import create_account
-
 		company = "_Test Company"
 		customer = create_customer(frappe.generate_hash(length=10), "INR")
 		advance_account = create_account(
@@ -1645,14 +1629,16 @@
 		self.check_pl_entries()
 
 		# Unreconcile
-		unrecon = (
+		(
 			frappe.get_doc(
 				{
 					"doctype": "Unreconcile Payment",
 					"company": company,
 					"voucher_type": pe.doctype,
 					"voucher_no": pe.name,
-					"allocations": [{"reference_doctype": reverse_pe.doctype, "reference_name": reverse_pe.name}],
+					"allocations": [
+						{"reference_doctype": reverse_pe.doctype, "reference_name": reverse_pe.name}
+					],
 				}
 			)
 			.save()
@@ -1703,12 +1689,11 @@
 
 
 def create_payment_terms_template():
-
 	create_payment_term("Basic Amount Receivable")
 	create_payment_term("Tax Receivable")
 
 	if not frappe.db.exists("Payment Terms Template", "Test Receivable Template"):
-		payment_term_template = frappe.get_doc(
+		frappe.get_doc(
 			{
 				"doctype": "Payment Terms Template",
 				"template_name": "Test Receivable Template",
diff --git a/erpnext/accounts/doctype/payment_ledger_entry/payment_ledger_entry.py b/erpnext/accounts/doctype/payment_ledger_entry/payment_ledger_entry.py
index 3fea325..2bc4489 100644
--- a/erpnext/accounts/doctype/payment_ledger_entry/payment_ledger_entry.py
+++ b/erpnext/accounts/doctype/payment_ledger_entry/payment_ledger_entry.py
@@ -137,9 +137,9 @@
 			):
 				if not self.get(dimension.fieldname):
 					frappe.throw(
-						_("Accounting Dimension <b>{0}</b> is required for 'Profit and Loss' account {1}.").format(
-							dimension.label, self.account
-						)
+						_(
+							"Accounting Dimension <b>{0}</b> is required for 'Profit and Loss' account {1}."
+						).format(dimension.label, self.account)
 					)
 
 			if (
@@ -150,9 +150,9 @@
 			):
 				if not self.get(dimension.fieldname):
 					frappe.throw(
-						_("Accounting Dimension <b>{0}</b> is required for 'Balance Sheet' account {1}.").format(
-							dimension.label, self.account
-						)
+						_(
+							"Accounting Dimension <b>{0}</b> is required for 'Balance Sheet' account {1}."
+						).format(dimension.label, self.account)
 					)
 
 	def validate(self):
diff --git a/erpnext/accounts/doctype/payment_ledger_entry/test_payment_ledger_entry.py b/erpnext/accounts/doctype/payment_ledger_entry/test_payment_ledger_entry.py
index ce9579e..c867e68 100644
--- a/erpnext/accounts/doctype/payment_ledger_entry/test_payment_ledger_entry.py
+++ b/erpnext/accounts/doctype/payment_ledger_entry/test_payment_ledger_entry.py
@@ -159,9 +159,7 @@
 		for doctype in doctype_list:
 			qb.from_(qb.DocType(doctype)).delete().where(qb.DocType(doctype).company == self.company).run()
 
-	def create_journal_entry(
-		self, acc1=None, acc2=None, amount=0, posting_date=None, cost_center=None
-	):
+	def create_journal_entry(self, acc1=None, acc2=None, amount=0, posting_date=None, cost_center=None):
 		je = frappe.new_doc("Journal Entry")
 		je.posting_date = posting_date or nowdate()
 		je.company = self.company
@@ -319,9 +317,7 @@
 				ple.amount,
 				ple.delinked,
 			)
-			.where(
-				(ple.against_voucher_type == cr_note1.doctype) & (ple.against_voucher_no == cr_note1.name)
-			)
+			.where((ple.against_voucher_type == cr_note1.doctype) & (ple.against_voucher_no == cr_note1.name))
 			.orderby(ple.creation)
 			.run(as_dict=True)
 		)
@@ -362,9 +358,7 @@
 		)
 		cr_note2.is_return = 1
 		cr_note2 = cr_note2.save().submit()
-		je1 = self.create_journal_entry(
-			self.debit_to, self.debit_to, amount, posting_date=transaction_date
-		)
+		je1 = self.create_journal_entry(self.debit_to, self.debit_to, amount, posting_date=transaction_date)
 		je1.get("accounts")[0].party_type = je1.get("accounts")[1].party_type = "Customer"
 		je1.get("accounts")[0].party = je1.get("accounts")[1].party = self.customer
 		je1.get("accounts")[0].reference_type = cr_note2.doctype
@@ -419,9 +413,7 @@
 				ple.amount,
 				ple.delinked,
 			)
-			.where(
-				(ple.against_voucher_type == cr_note2.doctype) & (ple.against_voucher_no == cr_note2.name)
-			)
+			.where((ple.against_voucher_type == cr_note2.doctype) & (ple.against_voucher_no == cr_note2.name))
 			.orderby(ple.creation)
 			.run(as_dict=True)
 		)
@@ -518,7 +510,7 @@
 		amount = 100
 		so = self.create_sales_order(qty=1, rate=amount, posting_date=transaction_date).save().submit()
 
-		pe = get_payment_entry(so.doctype, so.name).save().submit()
+		get_payment_entry(so.doctype, so.name).save().submit()
 
 		so.reload()
 		so.cancel()
diff --git a/erpnext/accounts/doctype/payment_order/payment_order.py b/erpnext/accounts/doctype/payment_order/payment_order.py
index 0ed26e4..a4c5962 100644
--- a/erpnext/accounts/doctype/payment_order/payment_order.py
+++ b/erpnext/accounts/doctype/payment_order/payment_order.py
@@ -90,9 +90,7 @@
 	je = frappe.new_doc("Journal Entry")
 	je.payment_order = doc.name
 	je.posting_date = nowdate()
-	mode_of_payment_type = frappe._dict(
-		frappe.get_all("Mode of Payment", fields=["name", "type"], as_list=1)
-	)
+	mode_of_payment_type = frappe._dict(frappe.get_all("Mode of Payment", fields=["name", "type"], as_list=1))
 
 	je.voucher_type = "Bank Entry"
 	if mode_of_payment and mode_of_payment_type.get(mode_of_payment) == "Cash":
diff --git a/erpnext/accounts/doctype/payment_order/test_payment_order.py b/erpnext/accounts/doctype/payment_order/test_payment_order.py
index 60f288e..7af0966 100644
--- a/erpnext/accounts/doctype/payment_order/test_payment_order.py
+++ b/erpnext/accounts/doctype/payment_order/test_payment_order.py
@@ -1,7 +1,6 @@
 # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors
 # See license.txt
 
-import unittest
 
 import frappe
 from frappe.tests.utils import FrappeTestCase
@@ -41,9 +40,7 @@
 		payment_entry.insert()
 		payment_entry.submit()
 
-		doc = create_payment_order_against_payment_entry(
-			payment_entry, "Payment Entry", self.bank_account
-		)
+		doc = create_payment_order_against_payment_entry(payment_entry, "Payment Entry", self.bank_account)
 		reference_doc = doc.get("references")[0]
 		self.assertEqual(reference_doc.reference_name, payment_entry.name)
 		self.assertEqual(reference_doc.reference_doctype, "Payment Entry")
diff --git a/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.py b/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.py
index dcb1a16..a2f355a 100644
--- a/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.py
+++ b/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.py
@@ -67,7 +67,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(PaymentReconciliation, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 		self.common_filter_conditions = []
 		self.accounting_dimension_filter_conditions = []
 		self.ple_posting_date_filter = []
@@ -286,7 +286,6 @@
 		self.return_invoices = self.return_invoices_query.run(as_dict=True)
 
 	def get_dr_or_cr_notes(self):
-
 		self.build_qb_filter_conditions(get_return_invoices=True)
 
 		ple = qb.DocType("Payment Ledger Entry")
@@ -412,9 +411,7 @@
 				payment_entry[0].get("reference_name")
 			)
 
-		new_difference_amount = self.get_difference_amount(
-			payment_entry[0], invoice[0], allocated_amount
-		)
+		new_difference_amount = self.get_difference_amount(payment_entry[0], invoice[0], allocated_amount)
 		return new_difference_amount
 
 	@frappe.whitelist()
@@ -532,9 +529,9 @@
 
 			if running_doc:
 				frappe.throw(
-					_("A Reconciliation Job {0} is running for the same filters. Cannot reconcile now").format(
-						get_link_to_form("Auto Reconcile", running_doc)
-					)
+					_(
+						"A Reconciliation Job {0} is running for the same filters. Cannot reconcile now"
+					).format(get_link_to_form("Auto Reconcile", running_doc))
 				)
 				return
 
@@ -627,9 +624,7 @@
 
 			invoice_exchange_map.update(purchase_invoice_map)
 
-		journals = [
-			d.get("invoice_number") for d in invoices if d.get("invoice_type") == "Journal Entry"
-		]
+		journals = [d.get("invoice_number") for d in invoices if d.get("invoice_type") == "Journal Entry"]
 		journals.extend(
 			[d.get("reference_name") for d in payments if d.get("reference_type") == "Journal Entry"]
 		)
@@ -721,7 +716,7 @@
 	def get_journal_filter_conditions(self):
 		conditions = []
 		je = qb.DocType("Journal Entry")
-		jea = qb.DocType("Journal Entry Account")
+		qb.DocType("Journal Entry Account")
 		conditions.append(je.company == self.company)
 
 		if self.from_payment_date:
@@ -841,7 +836,7 @@
 
 
 @frappe.whitelist()
-def get_queries_for_dimension_filters(company: str = None):
+def get_queries_for_dimension_filters(company: str | None = None):
 	dimensions_with_filters = []
 	for d in get_dimensions()[0]:
 		filters = {}
diff --git a/erpnext/accounts/doctype/payment_reconciliation/test_payment_reconciliation.py b/erpnext/accounts/doctype/payment_reconciliation/test_payment_reconciliation.py
index 1d20a5b..983cdc4 100644
--- a/erpnext/accounts/doctype/payment_reconciliation/test_payment_reconciliation.py
+++ b/erpnext/accounts/doctype/payment_reconciliation/test_payment_reconciliation.py
@@ -1,7 +1,6 @@
 # Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors
 # See license.txt
 
-import unittest
 
 import frappe
 from frappe import qb
@@ -250,9 +249,7 @@
 		pr.from_invoice_date = pr.to_invoice_date = pr.from_payment_date = pr.to_payment_date = nowdate()
 		return pr
 
-	def create_journal_entry(
-		self, acc1=None, acc2=None, amount=0, posting_date=None, cost_center=None
-	):
+	def create_journal_entry(self, acc1=None, acc2=None, amount=0, posting_date=None, cost_center=None):
 		je = frappe.new_doc("Journal Entry")
 		je.posting_date = posting_date or nowdate()
 		je.company = self.company
@@ -402,7 +399,7 @@
 		rate = 100
 		invoices = []
 		payments = []
-		for i in range(5):
+		for _i in range(5):
 			invoices.append(self.create_sales_invoice(qty=1, rate=rate, posting_date=transaction_date))
 			pe = self.create_payment_entry(amount=rate, posting_date=transaction_date).save().submit()
 			payments.append(pe)
@@ -821,9 +818,7 @@
 
 		cr_note.cancel()
 
-		pay = self.create_payment_entry(
-			amount=amount, posting_date=transaction_date, customer=self.customer3
-		)
+		pay = self.create_payment_entry(amount=amount, posting_date=transaction_date, customer=self.customer3)
 		pay.paid_from = self.debtors_eur
 		pay.paid_from_account_currency = "EUR"
 		pay.source_exchange_rate = exchange_rate
@@ -1025,9 +1020,7 @@
 		rate = 100
 
 		# 'Main - PR' Cost Center
-		si1 = self.create_sales_invoice(
-			qty=1, rate=rate, posting_date=transaction_date, do_not_submit=True
-		)
+		si1 = self.create_sales_invoice(qty=1, rate=rate, posting_date=transaction_date, do_not_submit=True)
 		si1.cost_center = self.main_cc.name
 		si1.submit()
 
@@ -1043,9 +1036,7 @@
 		je1 = je1.save().submit()
 
 		# 'Sub - PR' Cost Center
-		si2 = self.create_sales_invoice(
-			qty=1, rate=rate, posting_date=transaction_date, do_not_submit=True
-		)
+		si2 = self.create_sales_invoice(qty=1, rate=rate, posting_date=transaction_date, do_not_submit=True)
 		si2.cost_center = self.sub_cc.name
 		si2.submit()
 
diff --git a/erpnext/accounts/doctype/payment_request/payment_request.py b/erpnext/accounts/doctype/payment_request/payment_request.py
index 1649183..196838a 100644
--- a/erpnext/accounts/doctype/payment_request/payment_request.py
+++ b/erpnext/accounts/doctype/payment_request/payment_request.py
@@ -105,7 +105,7 @@
 		)
 
 		ref_doc = frappe.get_doc(self.reference_doctype, self.reference_name)
-		if not hasattr(ref_doc, "order_type") or getattr(ref_doc, "order_type") != "Shopping Cart":
+		if not hasattr(ref_doc, "order_type") or ref_doc.order_type != "Shopping Cart":
 			ref_amount = get_amount(ref_doc, self.payment_account)
 			if not ref_amount:
 				frappe.throw(_("Payment Entry is already created"))
@@ -160,7 +160,7 @@
 		ref_doc = frappe.get_doc(self.reference_doctype, self.reference_name)
 
 		if (
-			hasattr(ref_doc, "order_type") and getattr(ref_doc, "order_type") == "Shopping Cart"
+			hasattr(ref_doc, "order_type") and ref_doc.order_type == "Shopping Cart"
 		) or self.flags.mute_email:
 			send_mail = False
 
@@ -172,9 +172,9 @@
 		elif self.payment_channel == "Phone":
 			self.request_phone_payment()
 
-		advance_payment_doctypes = frappe.get_hooks(
-			"advance_payment_receivable_doctypes"
-		) + frappe.get_hooks("advance_payment_payable_doctypes")
+		advance_payment_doctypes = frappe.get_hooks("advance_payment_receivable_doctypes") + frappe.get_hooks(
+			"advance_payment_payable_doctypes"
+		)
 		if self.reference_doctype in advance_payment_doctypes:
 			# set advance payment status
 			ref_doc.set_total_advance_paid()
@@ -218,16 +218,16 @@
 		self.set_as_cancelled()
 
 		ref_doc = frappe.get_doc(self.reference_doctype, self.reference_name)
-		advance_payment_doctypes = frappe.get_hooks(
-			"advance_payment_receivable_doctypes"
-		) + frappe.get_hooks("advance_payment_payable_doctypes")
+		advance_payment_doctypes = frappe.get_hooks("advance_payment_receivable_doctypes") + frappe.get_hooks(
+			"advance_payment_payable_doctypes"
+		)
 		if self.reference_doctype in advance_payment_doctypes:
 			# set advance payment status
 			ref_doc.set_total_advance_paid()
 
 	def make_invoice(self):
 		ref_doc = frappe.get_doc(self.reference_doctype, self.reference_name)
-		if hasattr(ref_doc, "order_type") and getattr(ref_doc, "order_type") == "Shopping Cart":
+		if hasattr(ref_doc, "order_type") and ref_doc.order_type == "Shopping Cart":
 			from erpnext.selling.doctype.sales_order.sales_order import make_sales_invoice
 
 			si = make_sales_invoice(self.reference_name, ignore_permissions=True)
@@ -306,14 +306,10 @@
 		else:
 			party_account = get_party_account("Customer", ref_doc.get("customer"), ref_doc.company)
 
-		party_account_currency = ref_doc.get("party_account_currency") or get_account_currency(
-			party_account
-		)
+		party_account_currency = ref_doc.get("party_account_currency") or get_account_currency(party_account)
 
 		bank_amount = self.grand_total
-		if (
-			party_account_currency == ref_doc.company_currency and party_account_currency != self.currency
-		):
+		if party_account_currency == ref_doc.company_currency and party_account_currency != self.currency:
 			party_amount = ref_doc.get("base_rounded_total") or ref_doc.get("base_grand_total")
 		else:
 			party_amount = self.grand_total
@@ -331,7 +327,7 @@
 				"mode_of_payment": self.mode_of_payment,
 				"reference_no": self.name,
 				"reference_date": nowdate(),
-				"remarks": "Payment Entry against {0} {1} via Payment Request {2}".format(
+				"remarks": "Payment Entry against {} {} via Payment Request {}".format(
 					self.reference_doctype, self.reference_name, self.name
 				),
 			}
@@ -465,15 +461,11 @@
 		frappe.db.set_value(
 			"Sales Order", args.dn, "loyalty_points", int(args.loyalty_points), update_modified=False
 		)
-		frappe.db.set_value(
-			"Sales Order", args.dn, "loyalty_amount", loyalty_amount, update_modified=False
-		)
+		frappe.db.set_value("Sales Order", args.dn, "loyalty_amount", loyalty_amount, update_modified=False)
 		grand_total = grand_total - loyalty_amount
 
 	bank_account = (
-		get_party_bank_account(args.get("party_type"), args.get("party"))
-		if args.get("party_type")
-		else ""
+		get_party_bank_account(args.get("party_type"), args.get("party")) if args.get("party_type") else ""
 	)
 
 	draft_payment_request = frappe.db.get_value(
@@ -770,7 +762,10 @@
 			& (
 				(pe_ref.reference_name == dn)
 				| pe_ref.reference_name.isin(
-					frappe.qb.from_(inv_item).select(inv_item.parent).where(inv_item[inv_field] == dn).distinct()
+					frappe.qb.from_(inv_item)
+					.select(inv_item.parent)
+					.where(inv_item[inv_field] == dn)
+					.distinct()
 				)
 			)
 		)
diff --git a/erpnext/accounts/doctype/payment_request/test_payment_request.py b/erpnext/accounts/doctype/payment_request/test_payment_request.py
index feb2fdf..70de886 100644
--- a/erpnext/accounts/doctype/payment_request/test_payment_request.py
+++ b/erpnext/accounts/doctype/payment_request/test_payment_request.py
@@ -93,7 +93,7 @@
 			return_doc=1,
 		)
 
-		pe = pr.create_payment_entry()
+		pr.create_payment_entry()
 		pr.load_from_db()
 
 		self.assertEqual(pr.status, "Paid")
@@ -158,7 +158,7 @@
 
 		self.assertTrue(gl_entries)
 
-		for i, gle in enumerate(gl_entries):
+		for _i, gle in enumerate(gl_entries):
 			self.assertEqual(expected_gle[gle.account][0], gle.account)
 			self.assertEqual(expected_gle[gle.account][1], gle.debit)
 			self.assertEqual(expected_gle[gle.account][2], gle.credit)
diff --git a/erpnext/accounts/doctype/payment_terms_template/payment_terms_template.py b/erpnext/accounts/doctype/payment_terms_template/payment_terms_template.py
index 8f028f9..aaf8577 100644
--- a/erpnext/accounts/doctype/payment_terms_template/payment_terms_template.py
+++ b/erpnext/accounts/doctype/payment_terms_template/payment_terms_template.py
@@ -36,9 +36,7 @@
 			total_portion += flt(term.get("invoice_portion", 0))
 
 		if flt(total_portion, 2) != 100.00:
-			frappe.msgprint(
-				_("Combined invoice portion must equal 100%"), raise_exception=1, indicator="red"
-			)
+			frappe.msgprint(_("Combined invoice portion must equal 100%"), raise_exception=1, indicator="red")
 
 	def validate_terms(self):
 		terms = []
diff --git a/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.py b/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.py
index 76c0a09..e75057c 100644
--- a/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.py
+++ b/erpnext/accounts/doctype/period_closing_voucher/period_closing_voucher.py
@@ -67,7 +67,8 @@
 				enqueue_after_commit=True,
 			)
 			frappe.msgprint(
-				_("The GL Entries will be cancelled in the background, it can take a few minutes."), alert=True
+				_("The GL Entries will be cancelled in the background, it can take a few minutes."),
+				alert=True,
 			)
 		else:
 			make_reverse_gl_entries(voucher_type="Period Closing Voucher", voucher_no=self.name)
@@ -109,9 +110,7 @@
 			self.posting_date, self.fiscal_year, self.company, label=_("Posting Date"), doc=self
 		)
 
-		self.year_start_date = get_fiscal_year(
-			self.posting_date, self.fiscal_year, company=self.company
-		)[1]
+		self.year_start_date = get_fiscal_year(self.posting_date, self.fiscal_year, company=self.company)[1]
 
 		self.check_if_previous_year_closed()
 
@@ -225,7 +224,9 @@
 				"credit_in_account_currency": abs(flt(acc.bal_in_account_currency))
 				if flt(acc.bal_in_account_currency) > 0
 				else 0,
-				"credit": abs(flt(acc.bal_in_company_currency)) if flt(acc.bal_in_company_currency) > 0 else 0,
+				"credit": abs(flt(acc.bal_in_company_currency))
+				if flt(acc.bal_in_company_currency) > 0
+				else 0,
 				"is_period_closing_voucher_entry": 1,
 			},
 			item=acc,
@@ -249,7 +250,9 @@
 				"credit_in_account_currency": abs(flt(acc.bal_in_account_currency))
 				if flt(acc.bal_in_account_currency) < 0
 				else 0,
-				"credit": abs(flt(acc.bal_in_company_currency)) if flt(acc.bal_in_company_currency) < 0 else 0,
+				"credit": abs(flt(acc.bal_in_company_currency))
+				if flt(acc.bal_in_company_currency) < 0
+				else 0,
 				"is_period_closing_voucher_entry": 1,
 			},
 			item=acc,
diff --git a/erpnext/accounts/doctype/pos_closing_entry/pos_closing_entry.py b/erpnext/accounts/doctype/pos_closing_entry/pos_closing_entry.py
index 0f3a5bb..b158eda 100644
--- a/erpnext/accounts/doctype/pos_closing_entry/pos_closing_entry.py
+++ b/erpnext/accounts/doctype/pos_closing_entry/pos_closing_entry.py
@@ -70,7 +70,7 @@
 		for key, value in pos_occurences.items():
 			if len(value) > 1:
 				error_list.append(
-					_("{} is added multiple times on rows: {}".format(frappe.bold(key), frappe.bold(value)))
+					_(f"{frappe.bold(key)} is added multiple times on rows: {frappe.bold(value)}")
 				)
 
 		if error_list:
@@ -165,9 +165,7 @@
 		as_dict=1,
 	)
 
-	data = list(
-		filter(lambda d: get_datetime(start) <= get_datetime(d.timestamp) <= get_datetime(end), data)
-	)
+	data = list(filter(lambda d: get_datetime(start) <= get_datetime(d.timestamp) <= get_datetime(end), data))
 	# need to get taxes and payments so can't avoid get_doc
 	data = [frappe.get_doc("POS Invoice", d.name).as_dict() for d in data]
 
@@ -238,7 +236,11 @@
 			else:
 				payments.append(
 					frappe._dict(
-						{"mode_of_payment": p.mode_of_payment, "opening_amount": 0, "expected_amount": p.amount}
+						{
+							"mode_of_payment": p.mode_of_payment,
+							"opening_amount": 0,
+							"expected_amount": p.amount,
+						}
 					)
 				)
 
diff --git a/erpnext/accounts/doctype/pos_closing_entry/test_pos_closing_entry.py b/erpnext/accounts/doctype/pos_closing_entry/test_pos_closing_entry.py
index 62b342a..6319d5d 100644
--- a/erpnext/accounts/doctype/pos_closing_entry/test_pos_closing_entry.py
+++ b/erpnext/accounts/doctype/pos_closing_entry/test_pos_closing_entry.py
@@ -62,9 +62,7 @@
 		test_user, pos_profile = init_user_and_profile()
 		opening_entry = create_opening_entry(pos_profile, test_user.name)
 
-		pos_inv = create_pos_invoice(
-			rate=3500, do_not_submit=1, item_name="Test Item", without_item_code=1
-		)
+		pos_inv = create_pos_invoice(rate=3500, do_not_submit=1, item_name="Test Item", without_item_code=1)
 		pos_inv.append("payments", {"mode_of_payment": "Cash", "account": "Cash - _TC", "amount": 3500})
 		pos_inv.submit()
 
@@ -211,7 +209,7 @@
 		item_group="All Item Groups",
 	)
 
-	test_item_qty = [item for item in test_item_pos["items"] if item["item_code"] == "_Test Item"][
-		0
-	].get("actual_qty")
+	test_item_qty = next(item for item in test_item_pos["items"] if item["item_code"] == "_Test Item").get(
+		"actual_qty"
+	)
 	return test_item_qty
diff --git a/erpnext/accounts/doctype/pos_invoice/pos_invoice.py b/erpnext/accounts/doctype/pos_invoice/pos_invoice.py
index 8052c4c..b497279 100644
--- a/erpnext/accounts/doctype/pos_invoice/pos_invoice.py
+++ b/erpnext/accounts/doctype/pos_invoice/pos_invoice.py
@@ -183,7 +183,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(POSInvoice, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 
 	def validate(self):
 		if not cint(self.is_pos):
@@ -308,7 +308,9 @@
 				)
 
 				if paid_amt and pay.amount != paid_amt:
-					return frappe.throw(_("Payment related to {0} is not completed").format(pay.mode_of_payment))
+					return frappe.throw(
+						_("Payment related to {0} is not completed").format(pay.mode_of_payment)
+					)
 
 	def validate_stock_availablility(self):
 		if self.is_return:
@@ -328,7 +330,7 @@
 
 				available_stock, is_stock_item = get_stock_availability(d.item_code, d.warehouse)
 
-				item_code, warehouse, qty = (
+				item_code, warehouse, _qty = (
 					frappe.bold(d.item_code),
 					frappe.bold(d.warehouse),
 					frappe.bold(d.qty),
@@ -408,8 +410,7 @@
 		if (
 			self.change_amount
 			and self.account_for_change_amount
-			and frappe.get_cached_value("Account", self.account_for_change_amount, "company")
-			!= self.company
+			and frappe.get_cached_value("Account", self.account_for_change_amount, "company") != self.company
 		):
 			frappe.throw(
 				_("The selected change account {} doesn't belongs to Company {}.").format(
diff --git a/erpnext/accounts/doctype/pos_invoice/test_pos_invoice.py b/erpnext/accounts/doctype/pos_invoice/test_pos_invoice.py
index 8fab290..773ef01 100644
--- a/erpnext/accounts/doctype/pos_invoice/test_pos_invoice.py
+++ b/erpnext/accounts/doctype/pos_invoice/test_pos_invoice.py
@@ -245,7 +245,6 @@
 		self.assertEqual(pos_return.get("payments")[1].amount, -500)
 
 	def test_pos_return_for_serialized_item(self):
-		from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
 		from erpnext.stock.doctype.stock_entry.test_stock_entry import make_serialized_item
 
 		se = make_serialized_item(
@@ -287,7 +286,6 @@
 		)
 
 	def test_partial_pos_returns(self):
-		from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
 		from erpnext.stock.doctype.stock_entry.test_stock_entry import make_serialized_item
 
 		se = make_serialized_item(
@@ -359,9 +357,7 @@
 		)
 
 		pos.set("payments", [])
-		pos.append(
-			"payments", {"mode_of_payment": "Bank Draft", "account": "_Test Bank - _TC", "amount": 50}
-		)
+		pos.append("payments", {"mode_of_payment": "Bank Draft", "account": "_Test Bank - _TC", "amount": 50})
 		pos.append(
 			"payments", {"mode_of_payment": "Cash", "account": "Cash - _TC", "amount": 60, "default": 1}
 		)
@@ -379,7 +375,6 @@
 		self.assertRaises(frappe.ValidationError, inv.insert)
 
 	def test_serialized_item_transaction(self):
-		from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
 		from erpnext.stock.doctype.stock_entry.test_stock_entry import make_serialized_item
 
 		se = make_serialized_item(
@@ -434,7 +429,6 @@
 		self.assertRaises(frappe.ValidationError, pos2.submit)
 
 	def test_delivered_serialized_item_transaction(self):
-		from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
 		from erpnext.stock.doctype.stock_entry.test_stock_entry import make_serialized_item
 
 		se = make_serialized_item(
@@ -583,9 +577,7 @@
 		from erpnext.accounts.doctype.loyalty_program.test_loyalty_program import create_records
 
 		create_records()
-		frappe.db.set_value(
-			"Customer", "Test Loyalty Customer", "loyalty_program", "Test Single Loyalty"
-		)
+		frappe.db.set_value("Customer", "Test Loyalty Customer", "loyalty_program", "Test Single Loyalty")
 		before_lp_details = get_loyalty_program_details_with_points(
 			"Test Loyalty Customer", company="_Test Company", loyalty_program="Test Single Loyalty"
 		)
@@ -659,9 +651,7 @@
 		consolidate_pos_invoices()
 
 		pos_inv.load_from_db()
-		rounded_total = frappe.db.get_value(
-			"Sales Invoice", pos_inv.consolidated_invoice, "rounded_total"
-		)
+		rounded_total = frappe.db.get_value("Sales Invoice", pos_inv.consolidated_invoice, "rounded_total")
 		self.assertEqual(rounded_total, 3470)
 
 	def test_merging_into_sales_invoice_with_discount_and_inclusive_tax(self):
@@ -708,9 +698,7 @@
 		consolidate_pos_invoices()
 
 		pos_inv.load_from_db()
-		rounded_total = frappe.db.get_value(
-			"Sales Invoice", pos_inv.consolidated_invoice, "rounded_total"
-		)
+		rounded_total = frappe.db.get_value("Sales Invoice", pos_inv.consolidated_invoice, "rounded_total")
 		self.assertEqual(rounded_total, 840)
 
 	def test_merging_with_validate_selling_price(self):
@@ -762,9 +750,7 @@
 		consolidate_pos_invoices()
 
 		pos_inv2.load_from_db()
-		rounded_total = frappe.db.get_value(
-			"Sales Invoice", pos_inv2.consolidated_invoice, "rounded_total"
-		)
+		rounded_total = frappe.db.get_value("Sales Invoice", pos_inv2.consolidated_invoice, "rounded_total")
 		self.assertEqual(rounded_total, 400)
 
 	def test_pos_batch_reservation(self):
@@ -788,9 +774,7 @@
 		batch_no = get_batch_from_bundle(se.items[0].serial_and_batch_bundle)
 
 		# POS Invoice 1, for the batch without bundle
-		pos_inv1 = create_pos_invoice(
-			item="_BATCH ITEM Test For Reserve", rate=300, qty=15, do_not_save=1
-		)
+		pos_inv1 = create_pos_invoice(item="_BATCH ITEM Test For Reserve", rate=300, qty=15, do_not_save=1)
 
 		pos_inv1.items[0].batch_no = batch_no
 		pos_inv1.save()
@@ -800,9 +784,7 @@
 		self.assertFalse(pos_inv1.items[0].serial_and_batch_bundle)
 
 		batches = get_auto_batch_nos(
-			frappe._dict(
-				{"item_code": "_BATCH ITEM Test For Reserve", "warehouse": "_Test Warehouse - _TC"}
-			)
+			frappe._dict({"item_code": "_BATCH ITEM Test For Reserve", "warehouse": "_Test Warehouse - _TC"})
 		)
 
 		for batch in batches:
@@ -817,9 +799,7 @@
 		self.assertTrue(pos_inv2.items[0].serial_and_batch_bundle)
 
 		batches = get_auto_batch_nos(
-			frappe._dict(
-				{"item_code": "_BATCH ITEM Test For Reserve", "warehouse": "_Test Warehouse - _TC"}
-			)
+			frappe._dict({"item_code": "_BATCH ITEM Test For Reserve", "warehouse": "_Test Warehouse - _TC"})
 		)
 
 		for batch in batches:
@@ -896,19 +876,19 @@
 			pos_inv = create_pos_invoice(qty=1, do_not_submit=1)
 			pos_inv.items[0].rate = 300
 			pos_inv.save()
-			self.assertEquals(pos_inv.items[0].discount_percentage, 10)
+			self.assertEqual(pos_inv.items[0].discount_percentage, 10)
 			# rate shouldn't change
-			self.assertEquals(pos_inv.items[0].rate, 405)
+			self.assertEqual(pos_inv.items[0].rate, 405)
 
 			pos_inv.ignore_pricing_rule = 1
 			pos_inv.save()
-			self.assertEquals(pos_inv.ignore_pricing_rule, 1)
+			self.assertEqual(pos_inv.ignore_pricing_rule, 1)
 			# rate should reset since pricing rules are ignored
-			self.assertEquals(pos_inv.items[0].rate, 450)
+			self.assertEqual(pos_inv.items[0].rate, 450)
 
 			pos_inv.items[0].rate = 300
 			pos_inv.save()
-			self.assertEquals(pos_inv.items[0].rate, 300)
+			self.assertEqual(pos_inv.items[0].rate, 300)
 
 		finally:
 			item_price.delete()
@@ -920,7 +900,6 @@
 			init_user_and_profile,
 		)
 		from erpnext.stock.doctype.delivery_note.test_delivery_note import create_delivery_note
-		from erpnext.stock.doctype.serial_no.test_serial_no import get_serial_nos
 		from erpnext.stock.doctype.stock_entry.test_stock_entry import make_serialized_item
 
 		frappe.db.savepoint("before_test_delivered_serial_no_case")
diff --git a/erpnext/accounts/doctype/pos_invoice_merge_log/pos_invoice_merge_log.py b/erpnext/accounts/doctype/pos_invoice_merge_log/pos_invoice_merge_log.py
index cd858ca..fb91672 100644
--- a/erpnext/accounts/doctype/pos_invoice_merge_log/pos_invoice_merge_log.py
+++ b/erpnext/accounts/doctype/pos_invoice_merge_log/pos_invoice_merge_log.py
@@ -54,7 +54,7 @@
 		for key, value in pos_occurences.items():
 			if len(value) > 1:
 				error_list.append(
-					_("{} is added multiple times on rows: {}".format(frappe.bold(key), frappe.bold(value)))
+					_(f"{frappe.bold(key)} is added multiple times on rows: {frappe.bold(value)}")
 				)
 
 		if error_list:
@@ -81,7 +81,9 @@
 			bold_pos_invoice = frappe.bold(d.pos_invoice)
 			bold_status = frappe.bold(status)
 			if docstatus != 1:
-				frappe.throw(_("Row #{}: POS Invoice {} is not submitted yet").format(d.idx, bold_pos_invoice))
+				frappe.throw(
+					_("Row #{}: POS Invoice {} is not submitted yet").format(d.idx, bold_pos_invoice)
+				)
 			if status == "Consolidated":
 				frappe.throw(
 					_("Row #{}: POS Invoice {} has been {}").format(d.idx, bold_pos_invoice, bold_status)
@@ -100,15 +102,17 @@
 						d.idx, bold_return_against, bold_pos_invoice, bold_unconsolidated
 					)
 					msg += " "
-					msg += _("Original invoice should be consolidated before or along with the return invoice.")
+					msg += _(
+						"Original invoice should be consolidated before or along with the return invoice."
+					)
 					msg += "<br><br>"
-					msg += _("You can add original invoice {} manually to proceed.").format(bold_return_against)
+					msg += _("You can add original invoice {} manually to proceed.").format(
+						bold_return_against
+					)
 					frappe.throw(msg)
 
 	def on_submit(self):
-		pos_invoice_docs = [
-			frappe.get_cached_doc("POS Invoice", d.pos_invoice) for d in self.pos_invoices
-		]
+		pos_invoice_docs = [frappe.get_cached_doc("POS Invoice", d.pos_invoice) for d in self.pos_invoices]
 
 		returns = [d for d in pos_invoice_docs if d.get("is_return") == 1]
 		sales = [d for d in pos_invoice_docs if d.get("is_return") == 0]
@@ -124,9 +128,7 @@
 		self.update_pos_invoices(pos_invoice_docs, sales_invoice, credit_note)
 
 	def on_cancel(self):
-		pos_invoice_docs = [
-			frappe.get_cached_doc("POS Invoice", d.pos_invoice) for d in self.pos_invoices
-		]
+		pos_invoice_docs = [frappe.get_cached_doc("POS Invoice", d.pos_invoice) for d in self.pos_invoices]
 
 		self.update_pos_invoices(pos_invoice_docs)
 		self.cancel_linked_invoices()
@@ -217,7 +219,9 @@
 				for t in taxes:
 					if t.account_head == tax.account_head and t.cost_center == tax.cost_center:
 						t.tax_amount = flt(t.tax_amount) + flt(tax.tax_amount_after_discount_amount)
-						t.base_tax_amount = flt(t.base_tax_amount) + flt(tax.base_tax_amount_after_discount_amount)
+						t.base_tax_amount = flt(t.base_tax_amount) + flt(
+							tax.base_tax_amount_after_discount_amount
+						)
 						update_item_wise_tax_detail(t, tax)
 						found = True
 				if not found:
@@ -333,9 +337,7 @@
 		else:
 			consolidated_tax_detail.update({item_code: [tax_data[0], tax_data[1]]})
 
-	consolidate_tax_row.item_wise_tax_detail = json.dumps(
-		consolidated_tax_detail, separators=(",", ":")
-	)
+	consolidate_tax_row.item_wise_tax_detail = json.dumps(consolidated_tax_detail, separators=(",", ":"))
 
 
 def get_all_unconsolidated_invoices():
@@ -380,9 +382,7 @@
 
 	if len(invoices) >= 10 and closing_entry:
 		closing_entry.set_status(update=True, status="Queued")
-		enqueue_job(
-			create_merge_logs, invoice_by_customer=invoice_by_customer, closing_entry=closing_entry
-		)
+		enqueue_job(create_merge_logs, invoice_by_customer=invoice_by_customer, closing_entry=closing_entry)
 	else:
 		create_merge_logs(invoice_by_customer, closing_entry)
 
@@ -431,9 +431,7 @@
 			if not item.serial_no and not item.serial_and_batch_bundle:
 				continue
 
-			return_against_is_added = any(
-				d for d in _invoices if d.pos_invoice == pos_invoice.return_against
-			)
+			return_against_is_added = any(d for d in _invoices if d.pos_invoice == pos_invoice.return_against)
 			if return_against_is_added:
 				break
 
@@ -533,7 +531,7 @@
 			timeout=10000,
 			event="processing_merge_logs",
 			job_id=job_id,
-			now=frappe.conf.developer_mode or frappe.flags.in_test
+			now=frappe.conf.developer_mode or frappe.flags.in_test,
 		)
 
 		if job == create_merge_logs:
diff --git a/erpnext/accounts/doctype/pos_invoice_merge_log/test_pos_invoice_merge_log.py b/erpnext/accounts/doctype/pos_invoice_merge_log/test_pos_invoice_merge_log.py
index 0ad9131..904d8e8 100644
--- a/erpnext/accounts/doctype/pos_invoice_merge_log/test_pos_invoice_merge_log.py
+++ b/erpnext/accounts/doctype/pos_invoice_merge_log/test_pos_invoice_merge_log.py
@@ -31,15 +31,11 @@
 			pos_inv.submit()
 
 			pos_inv2 = create_pos_invoice(rate=3200, do_not_submit=1)
-			pos_inv2.append(
-				"payments", {"mode_of_payment": "Cash", "account": "Cash - _TC", "amount": 3200}
-			)
+			pos_inv2.append("payments", {"mode_of_payment": "Cash", "account": "Cash - _TC", "amount": 3200})
 			pos_inv2.submit()
 
 			pos_inv3 = create_pos_invoice(customer="_Test Customer 2", rate=2300, do_not_submit=1)
-			pos_inv3.append(
-				"payments", {"mode_of_payment": "Cash", "account": "Cash - _TC", "amount": 2300}
-			)
+			pos_inv3.append("payments", {"mode_of_payment": "Cash", "account": "Cash - _TC", "amount": 2300})
 			pos_inv3.submit()
 
 			consolidate_pos_invoices()
@@ -68,15 +64,11 @@
 			pos_inv.submit()
 
 			pos_inv2 = create_pos_invoice(rate=3200, do_not_submit=1)
-			pos_inv2.append(
-				"payments", {"mode_of_payment": "Cash", "account": "Cash - _TC", "amount": 3200}
-			)
+			pos_inv2.append("payments", {"mode_of_payment": "Cash", "account": "Cash - _TC", "amount": 3200})
 			pos_inv2.submit()
 
 			pos_inv3 = create_pos_invoice(customer="_Test Customer 2", rate=2300, do_not_submit=1)
-			pos_inv3.append(
-				"payments", {"mode_of_payment": "Cash", "account": "Cash - _TC", "amount": 2300}
-			)
+			pos_inv3.append("payments", {"mode_of_payment": "Cash", "account": "Cash - _TC", "amount": 2300})
 			pos_inv3.submit()
 
 			pos_inv_cn = make_sales_return(pos_inv.name)
@@ -312,7 +304,7 @@
 			init_user_and_profile()
 
 			item_rates = [69, 59, 29]
-			for i in [1, 2]:
+			for _i in [1, 2]:
 				inv = create_pos_invoice(is_return=1, do_not_save=1)
 				inv.items = []
 				for rate in item_rates:
@@ -406,7 +398,6 @@
 		The second and third POS Invoice should be consolidated with a single Merge Log
 		"""
 
-		from erpnext.stock.doctype.serial_no.test_serial_no import get_serial_nos
 		from erpnext.stock.doctype.stock_entry.test_stock_entry import make_serialized_item
 
 		frappe.db.sql("delete from `tabPOS Invoice`")
diff --git a/erpnext/accounts/doctype/pos_profile/pos_profile.py b/erpnext/accounts/doctype/pos_profile/pos_profile.py
index c1add57..29403ab 100644
--- a/erpnext/accounts/doctype/pos_profile/pos_profile.py
+++ b/erpnext/accounts/doctype/pos_profile/pos_profile.py
@@ -180,10 +180,8 @@
 			condition = " where pfu.default = 1 "
 
 		pos_view_users = frappe.db.sql_list(
-			"""select pfu.user
-			from `tabPOS Profile User` as pfu {0}""".format(
-				condition
-			)
+			f"""select pfu.user
+			from `tabPOS Profile User` as pfu {condition}"""
 		)
 
 		for user in pos_view_users:
@@ -210,16 +208,13 @@
 def get_child_nodes(group_type, root):
 	lft, rgt = frappe.db.get_value(group_type, root, ["lft", "rgt"])
 	return frappe.db.sql(
-		""" Select name, lft, rgt from `tab{tab}` where
-			lft >= {lft} and rgt <= {rgt} order by lft""".format(
-			tab=group_type, lft=lft, rgt=rgt
-		),
+		f""" Select name, lft, rgt from `tab{group_type}` where
+			lft >= {lft} and rgt <= {rgt} order by lft""",
 		as_dict=1,
 	)
 
 
 def required_accounting_dimensions():
-
 	p = frappe.qb.DocType("Accounting Dimension")
 	c = frappe.qb.DocType("Accounting Dimension Detail")
 
diff --git a/erpnext/accounts/doctype/pos_profile/test_pos_profile.py b/erpnext/accounts/doctype/pos_profile/test_pos_profile.py
index b468ad3..f2e3c8f 100644
--- a/erpnext/accounts/doctype/pos_profile/test_pos_profile.py
+++ b/erpnext/accounts/doctype/pos_profile/test_pos_profile.py
@@ -7,7 +7,6 @@
 
 from erpnext.accounts.doctype.pos_profile.pos_profile import (
 	get_child_nodes,
-	required_accounting_dimensions,
 )
 from erpnext.stock.get_item_details import get_pos_profile
 
@@ -55,11 +54,9 @@
 
 	return (
 		frappe.db.sql(
-			""" select name, customer_name, customer_group,
+			f""" select name, customer_name, customer_group,
 		territory, customer_pos_id from tabCustomer where disabled = 0
-		and {cond}""".format(
-				cond=cond
-			),
+		and {cond}""",
 			tuple(customer_groups),
 			as_dict=1,
 		)
@@ -78,7 +75,7 @@
 			cond = "and i.item_group in (%s)" % (", ".join(["%s"] * len(args_list)))
 
 	return frappe.db.sql(
-		"""
+		f"""
 		select
 			i.name, i.item_code, i.item_name, i.description, i.item_group, i.has_batch_no,
 			i.has_serial_no, i.is_stock_item, i.brand, i.stock_uom, i.image,
@@ -91,10 +88,8 @@
 		where
 			i.disabled = 0 and i.has_variants = 0 and i.is_sales_item = 1 and i.is_fixed_asset = 0
 			{cond}
-		""".format(
-			cond=cond
-		),
-		tuple([company] + args_list),
+		""",
+		tuple([company, *args_list]),
 		as_dict=1,
 	)
 
diff --git a/erpnext/accounts/doctype/pricing_rule/pricing_rule.py b/erpnext/accounts/doctype/pricing_rule/pricing_rule.py
index 300692f..11529ef 100644
--- a/erpnext/accounts/doctype/pricing_rule/pricing_rule.py
+++ b/erpnext/accounts/doctype/pricing_rule/pricing_rule.py
@@ -186,9 +186,9 @@
 
 			if self.priority and cint(self.priority) == 1:
 				throw(
-					_("As the field {0} is enabled, the value of the field {1} should be more than 1.").format(
-						frappe.bold("Apply Discount on Discounted Rate"), frappe.bold("Priority")
-					)
+					_(
+						"As the field {0} is enabled, the value of the field {1} should be more than 1."
+					).format(frappe.bold("Apply Discount on Discounted Rate"), frappe.bold("Priority"))
 				)
 
 	def validate_applicable_for_selling_or_buying(self):
@@ -458,9 +458,11 @@
 				)
 
 				if pricing_rule.apply_rule_on_other_items:
-					item_details["apply_rule_on_other_items"] = json.dumps(pricing_rule.apply_rule_on_other_items)
+					item_details["apply_rule_on_other_items"] = json.dumps(
+						pricing_rule.apply_rule_on_other_items
+					)
 
-			if pricing_rule.coupon_code_based == 1 and args.coupon_code == None:
+			if pricing_rule.coupon_code_based == 1 and args.coupon_code is None:
 				return item_details
 
 			if not pricing_rule.validate_applied_rule:
@@ -504,7 +506,6 @@
 
 	if args.transaction_type == "selling":
 		if args.customer and not (args.customer_group and args.territory):
-
 			if args.quotation_to and args.quotation_to != "Customer":
 				customer = frappe._dict()
 			else:
@@ -535,9 +536,9 @@
 def apply_price_discount_rule(pricing_rule, item_details, args):
 	item_details.pricing_rule_for = pricing_rule.rate_or_discount
 
-	if (
-		pricing_rule.margin_type in ["Amount", "Percentage"] and pricing_rule.currency == args.currency
-	) or (pricing_rule.margin_type == "Percentage"):
+	if (pricing_rule.margin_type in ["Amount", "Percentage"] and pricing_rule.currency == args.currency) or (
+		pricing_rule.margin_type == "Percentage"
+	):
 		item_details.margin_type = pricing_rule.margin_type
 		item_details.has_margin = True
 
@@ -685,7 +686,7 @@
 
 	return frappe.get_all(
 		"UOM Conversion Detail",
-		filters={"parent": ("in", items), "uom": ("like", "{0}%".format(txt))},
+		filters={"parent": ("in", items), "uom": ("like", f"{txt}%")},
 		fields=["distinct uom"],
 		as_list=1,
 	)
diff --git a/erpnext/accounts/doctype/pricing_rule/test_pricing_rule.py b/erpnext/accounts/doctype/pricing_rule/test_pricing_rule.py
index 5bb366a..046a599 100644
--- a/erpnext/accounts/doctype/pricing_rule/test_pricing_rule.py
+++ b/erpnext/accounts/doctype/pricing_rule/test_pricing_rule.py
@@ -103,8 +103,6 @@
 		self.assertEqual(details.get("discount_percentage"), 15)
 
 	def test_pricing_rule_for_margin(self):
-		from frappe import MandatoryError
-
 		from erpnext.stock.get_item_details import get_item_details
 
 		test_record = {
@@ -205,8 +203,6 @@
 		self.assertEqual(details.get("discount_percentage"), 10)
 
 	def test_pricing_rule_for_variants(self):
-		from frappe import MandatoryError
-
 		from erpnext.stock.get_item_details import get_item_details
 
 		if not frappe.db.exists("Item", "Test Variant PRT"):
@@ -1181,8 +1177,7 @@
 		"Pricing Rule Item Group",
 		"Pricing Rule Brand",
 	]:
-
-		frappe.db.sql("delete from `tab{0}`".format(doctype))
+		frappe.db.sql(f"delete from `tab{doctype}`")
 
 
 def make_item_price(item, price_list_name, item_price):
diff --git a/erpnext/accounts/doctype/pricing_rule/utils.py b/erpnext/accounts/doctype/pricing_rule/utils.py
index 73c5d59..2144233 100644
--- a/erpnext/accounts/doctype/pricing_rule/utils.py
+++ b/erpnext/accounts/doctype/pricing_rule/utils.py
@@ -101,14 +101,12 @@
 	if not args.get(apply_on_field):
 		return []
 
-	child_doc = "`tabPricing Rule {0}`".format(apply_on)
+	child_doc = f"`tabPricing Rule {apply_on}`"
 
 	conditions = item_variant_condition = item_conditions = ""
 	values[apply_on_field] = args.get(apply_on_field)
 	if apply_on_field in ["item_code", "brand"]:
-		item_conditions = "{child_doc}.{apply_on_field}= %({apply_on_field})s".format(
-			child_doc=child_doc, apply_on_field=apply_on_field
-		)
+		item_conditions = f"{child_doc}.{apply_on_field}= %({apply_on_field})s"
 
 		if apply_on_field == "item_code":
 			if args.get("uom", None):
@@ -121,23 +119,19 @@
 				args.variant_of = frappe.get_cached_value("Item", args.item_code, "variant_of")
 
 			if args.variant_of:
-				item_variant_condition = " or {child_doc}.item_code=%(variant_of)s ".format(
-					child_doc=child_doc
-				)
+				item_variant_condition = f" or {child_doc}.item_code=%(variant_of)s "
 				values["variant_of"] = args.variant_of
 	elif apply_on_field == "item_group":
 		item_conditions = _get_tree_conditions(args, "Item Group", child_doc, False)
 		if args.get("uom", None):
-			item_conditions += (
-				" and ({child_doc}.uom='{item_uom}' or IFNULL({child_doc}.uom, '')='')".format(
-					child_doc=child_doc, item_uom=args.get("uom")
-				)
+			item_conditions += " and ({child_doc}.uom='{item_uom}' or IFNULL({child_doc}.uom, '')='')".format(
+				child_doc=child_doc, item_uom=args.get("uom")
 			)
 
 	conditions += get_other_conditions(conditions, values, args)
 	warehouse_conditions = _get_tree_conditions(args, "Warehouse", "`tabPricing Rule`")
 	if warehouse_conditions:
-		warehouse_conditions = " and {0}".format(warehouse_conditions)
+		warehouse_conditions = f" and {warehouse_conditions}"
 
 	if not args.price_list:
 		args.price_list = None
@@ -163,7 +157,7 @@
 				item_variant_condition=item_variant_condition,
 				transaction_type=args.transaction_type,
 				warehouse_cond=warehouse_conditions,
-				apply_on_other_field="other_{0}".format(apply_on_field),
+				apply_on_other_field=f"other_{apply_on_field}",
 				conditions=conditions,
 			),
 			values,
@@ -202,14 +196,13 @@
 			frappe.throw(_("Invalid {0}").format(args.get(field)))
 
 		parent_groups = frappe.db.sql_list(
-			"""select name from `tab%s`
-			where lft<=%s and rgt>=%s"""
-			% (parenttype, "%s", "%s"),
+			"""select name from `tab{}`
+			where lft<={} and rgt>={}""".format(parenttype, "%s", "%s"),
 			(lft, rgt),
 		)
 
 		if parenttype in ["Customer Group", "Item Group", "Territory"]:
-			parent_field = "parent_{0}".format(frappe.scrub(parenttype))
+			parent_field = f"parent_{frappe.scrub(parenttype)}"
 			root_name = frappe.db.get_list(
 				parenttype,
 				{"is_group": 1, parent_field: ("is", "not set")},
@@ -235,10 +228,10 @@
 def get_other_conditions(conditions, values, args):
 	for field in ["company", "customer", "supplier", "campaign", "sales_partner"]:
 		if args.get(field):
-			conditions += " and ifnull(`tabPricing Rule`.{0}, '') in (%({1})s, '')".format(field, field)
+			conditions += f" and ifnull(`tabPricing Rule`.{field}, '') in (%({field})s, '')"
 			values[field] = args.get(field)
 		else:
-			conditions += " and ifnull(`tabPricing Rule`.{0}, '') = ''".format(field)
+			conditions += f" and ifnull(`tabPricing Rule`.{field}, '') = ''"
 
 	for parenttype in ["Customer Group", "Territory", "Supplier Group"]:
 		group_condition = _get_tree_conditions(args, parenttype, "`tabPricing Rule`")
@@ -510,7 +503,7 @@
 		"transaction_date" if frappe.get_meta(doctype).has_field("transaction_date") else "posting_date"
 	)
 
-	child_doctype = "{0} Item".format(doctype)
+	child_doctype = f"{doctype} Item"
 	apply_on = frappe.scrub(pr_doc.get("apply_on"))
 
 	values = [pr_doc.valid_from, pr_doc.valid_upto]
@@ -520,9 +513,7 @@
 		warehouses = get_child_warehouses(pr_doc.warehouse)
 
 		condition += """ and `tab{child_doc}`.warehouse in ({warehouses})
-			""".format(
-			child_doc=child_doctype, warehouses=",".join(["%s"] * len(warehouses))
-		)
+			""".format(child_doc=child_doctype, warehouses=",".join(["%s"] * len(warehouses)))
 
 		values.extend(warehouses)
 
@@ -534,16 +525,14 @@
 		values.extend(items)
 
 	data_set = frappe.db.sql(
-		""" SELECT `tab{child_doc}`.stock_qty,
-			`tab{child_doc}`.amount
-		FROM `tab{child_doc}`, `tab{parent_doc}`
+		f""" SELECT `tab{child_doctype}`.stock_qty,
+			`tab{child_doctype}`.amount
+		FROM `tab{child_doctype}`, `tab{doctype}`
 		WHERE
-			`tab{child_doc}`.parent = `tab{parent_doc}`.name and `tab{parent_doc}`.{date_field}
-			between %s and %s and `tab{parent_doc}`.docstatus = 1
-			{condition} group by `tab{child_doc}`.name
-	""".format(
-			parent_doc=doctype, child_doc=child_doctype, condition=condition, date_field=date_field
-		),
+			`tab{child_doctype}`.parent = `tab{doctype}`.name and `tab{doctype}`.{date_field}
+			between %s and %s and `tab{doctype}`.docstatus = 1
+			{condition} group by `tab{child_doctype}`.name
+	""",
 		tuple(values),
 		as_dict=1,
 	)
@@ -562,11 +551,9 @@
 	conditions = get_other_conditions(conditions, values, doc)
 
 	pricing_rules = frappe.db.sql(
-		""" Select `tabPricing Rule`.* from `tabPricing Rule`
+		f""" Select `tabPricing Rule`.* from `tabPricing Rule`
 		where  {conditions} and `tabPricing Rule`.disable = 0
-	""".format(
-			conditions=conditions
-		),
+	""",
 		values,
 		as_dict=1,
 	)
@@ -591,7 +578,9 @@
 						continue
 
 					if (
-						d.validate_applied_rule and doc.get(field) is not None and doc.get(field) < d.get(pr_field)
+						d.validate_applied_rule
+						and doc.get(field) is not None
+						and doc.get(field) < d.get(pr_field)
 					):
 						frappe.msgprint(_("User has not applied rule on the invoice {0}").format(doc.name))
 					else:
@@ -660,9 +649,7 @@
 
 	qty = pricing_rule.free_qty or 1
 	if pricing_rule.is_recursive:
-		transaction_qty = (
-			args.get("qty") if args else doc.total_qty
-		) - pricing_rule.apply_recursion_over
+		transaction_qty = (args.get("qty") if args else doc.total_qty) - pricing_rule.apply_recursion_over
 		if transaction_qty:
 			qty = flt(transaction_qty) * qty / pricing_rule.recurse_for
 			if pricing_rule.round_free_qty:
diff --git a/erpnext/accounts/doctype/process_deferred_accounting/test_process_deferred_accounting.py b/erpnext/accounts/doctype/process_deferred_accounting/test_process_deferred_accounting.py
index 263621d..fddd9f8 100644
--- a/erpnext/accounts/doctype/process_deferred_accounting/test_process_deferred_accounting.py
+++ b/erpnext/accounts/doctype/process_deferred_accounting/test_process_deferred_accounting.py
@@ -40,7 +40,7 @@
 		si.save()
 		si.submit()
 
-		process_deferred_accounting = doc = frappe.get_doc(
+		process_deferred_accounting = frappe.get_doc(
 			dict(
 				doctype="Process Deferred Accounting",
 				posting_date="2023-07-01",
diff --git a/erpnext/accounts/doctype/process_payment_reconciliation/process_payment_reconciliation.py b/erpnext/accounts/doctype/process_payment_reconciliation/process_payment_reconciliation.py
index 761c2bc..5ae6f64 100644
--- a/erpnext/accounts/doctype/process_payment_reconciliation/process_payment_reconciliation.py
+++ b/erpnext/accounts/doctype/process_payment_reconciliation/process_payment_reconciliation.py
@@ -66,9 +66,7 @@
 
 	def on_cancel(self):
 		self.db_set("status", "Cancelled")
-		log = frappe.db.get_value(
-			"Process Payment Reconciliation Log", filters={"process_pr": self.name}
-		)
+		log = frappe.db.get_value("Process Payment Reconciliation Log", filters={"process_pr": self.name})
 		if log:
 			frappe.db.set_value("Process Payment Reconciliation Log", log, "status", "Cancelled")
 
@@ -416,7 +414,6 @@
 					# If Payment Entry, update details only for newly linked references
 					# This is for performance
 					if allocations[0].reference_type == "Payment Entry":
-
 						references = [(x.invoice_type, x.invoice_number) for x in allocations]
 						pe = frappe.get_doc(allocations[0].reference_type, allocations[0].reference_name)
 						pe.flags.ignore_validate_update_after_submit = True
@@ -430,13 +427,14 @@
 
 					# Update reconciled count
 					reconciled_count = frappe.db.count(
-						"Process Payment Reconciliation Log Allocations", filters={"parent": log, "reconciled": True}
+						"Process Payment Reconciliation Log Allocations",
+						filters={"parent": log, "reconciled": True},
 					)
 					frappe.db.set_value(
 						"Process Payment Reconciliation Log", log, "reconciled_entries", reconciled_count
 					)
 
-				except Exception as err:
+				except Exception:
 					# Update the parent doc about the exception
 					frappe.db.rollback()
 
@@ -474,15 +472,12 @@
 						frappe.db.set_value("Process Payment Reconciliation Log", log, "reconciled", True)
 						frappe.db.set_value("Process Payment Reconciliation", doc, "status", "Completed")
 					else:
-
 						if frappe.db.get_value("Process Payment Reconciliation", doc, "status") != "Paused":
 							# trigger next batch in job
 							# generate reconcile job name
 							allocation = get_next_allocation(log)
 							if allocation:
-								reconcile_job_name = (
-									f"process_{doc}_reconcile_allocation_{allocation[0].idx}_{allocation[-1].idx}"
-								)
+								reconcile_job_name = f"process_{doc}_reconcile_allocation_{allocation[0].idx}_{allocation[-1].idx}"
 							else:
 								reconcile_job_name = f"process_{doc}_reconcile"
 
diff --git a/erpnext/accounts/doctype/process_payment_reconciliation_log/process_payment_reconciliation_log.py b/erpnext/accounts/doctype/process_payment_reconciliation_log/process_payment_reconciliation_log.py
index 153fffc..80337e1 100644
--- a/erpnext/accounts/doctype/process_payment_reconciliation_log/process_payment_reconciliation_log.py
+++ b/erpnext/accounts/doctype/process_payment_reconciliation_log/process_payment_reconciliation_log.py
@@ -24,9 +24,7 @@
 		process_pr: DF.Link
 		reconciled: DF.Check
 		reconciled_entries: DF.Int
-		status: DF.Literal[
-			"Running", "Paused", "Reconciled", "Partially Reconciled", "Failed", "Cancelled"
-		]
+		status: DF.Literal["Running", "Paused", "Reconciled", "Partially Reconciled", "Failed", "Cancelled"]
 		total_allocations: DF.Int
 	# end: auto-generated types
 
diff --git a/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.py b/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.py
index f9d6136..c73c13e 100644
--- a/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.py
+++ b/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.py
@@ -46,9 +46,7 @@
 		company: DF.Link
 		cost_center: DF.TableMultiSelect[PSOACostCenter]
 		currency: DF.Link | None
-		customer_collection: DF.Literal[
-			"", "Customer Group", "Territory", "Sales Partner", "Sales Person"
-		]
+		customer_collection: DF.Literal["", "Customer Group", "Territory", "Sales Partner", "Sales Person"]
 		customers: DF.Table[ProcessStatementOfAccountsCustomer]
 		enable_auto_email: DF.Check
 		filter_duration: DF.Int
@@ -406,9 +404,7 @@
 			{mcond}
 		ORDER BY
 			contact.creation desc
-		""".format(
-			mcond=get_match_cond("Contact")
-		),
+		""".format(mcond=get_match_cond("Contact")),
 		customer_name,
 	)
 
@@ -481,9 +477,7 @@
 			else:
 				new_to_date = add_months(new_to_date, 1 if doc.frequency == "Monthly" else 3)
 			new_from_date = add_months(new_to_date, -1 * doc.filter_duration)
-			doc.add_comment(
-				"Comment", "Emails sent on: " + frappe.utils.format_datetime(frappe.utils.now())
-			)
+			doc.add_comment("Comment", "Emails sent on: " + frappe.utils.format_datetime(frappe.utils.now()))
 			if doc.report == "General Ledger":
 				doc.db_set("to_date", new_to_date, commit=True)
 				doc.db_set("from_date", new_from_date, commit=True)
diff --git a/erpnext/accounts/doctype/process_statement_of_accounts/test_process_statement_of_accounts.py b/erpnext/accounts/doctype/process_statement_of_accounts/test_process_statement_of_accounts.py
index a3a74df..92dbb5e 100644
--- a/erpnext/accounts/doctype/process_statement_of_accounts/test_process_statement_of_accounts.py
+++ b/erpnext/accounts/doctype/process_statement_of_accounts/test_process_statement_of_accounts.py
@@ -1,7 +1,6 @@
 # Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and Contributors
 # See license.txt
 
-import unittest
 
 import frappe
 from frappe.tests.utils import FrappeTestCase
diff --git a/erpnext/accounts/doctype/process_subscription/process_subscription.py b/erpnext/accounts/doctype/process_subscription/process_subscription.py
index b271e7c..f0a2244 100644
--- a/erpnext/accounts/doctype/process_subscription/process_subscription.py
+++ b/erpnext/accounts/doctype/process_subscription/process_subscription.py
@@ -2,7 +2,6 @@
 # For license information, please see license.txt
 
 from datetime import datetime
-from typing import Union
 
 import frappe
 from frappe.model.document import Document
@@ -30,7 +29,7 @@
 
 
 def create_subscription_process(
-	subscription: str | None = None, posting_date: Union[str, datetime.date] | None = None
+	subscription: str | None = None, posting_date: str | datetime.date | None = None
 ):
 	"""Create a new Process Subscription document"""
 	doc = frappe.new_doc("Process Subscription")
diff --git a/erpnext/accounts/doctype/promotional_scheme/promotional_scheme.py b/erpnext/accounts/doctype/promotional_scheme/promotional_scheme.py
index a9c1900..ed4e3d2 100644
--- a/erpnext/accounts/doctype/promotional_scheme/promotional_scheme.py
+++ b/erpnext/accounts/doctype/promotional_scheme/promotional_scheme.py
@@ -169,9 +169,7 @@
 		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)}
-			):
+			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:
@@ -246,7 +244,7 @@
 	args = get_args_for_pricing_rule(doc)
 	applicable_for = frappe.scrub(doc.get("applicable_for"))
 
-	for idx, d in enumerate(doc.get(child_doc)):
+	for _idx, d in enumerate(doc.get(child_doc)):
 		if d.name in rules:
 			if not args.get(applicable_for):
 				docname = get_pricing_rule_docname(d)
@@ -256,7 +254,14 @@
 				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
+						args,
+						doc,
+						child_doc,
+						discount_fields,
+						d,
+						docname,
+						applicable_for,
+						applicable_for_value,
 					)
 					new_doc.append(pr)
 
@@ -282,7 +287,7 @@
 
 
 def get_pricing_rule_docname(
-	row: dict, applicable_for: str = None, applicable_for_value: str = None
+	row: dict, applicable_for: str | None = None, applicable_for_value: str | None = None
 ) -> str:
 	fields = ["promotional_scheme_id", "name"]
 	filters = {"promotional_scheme_id": row.name}
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
index 4b5b456..e224b59 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
@@ -227,7 +227,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(PurchaseInvoice, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 		self.status_updater = [
 			{
 				"source_dt": "Purchase Invoice Item",
@@ -244,7 +244,7 @@
 		]
 
 	def onload(self):
-		super(PurchaseInvoice, self).onload()
+		super().onload()
 		supplier_tds = frappe.db.get_value("Supplier", self.supplier, "tax_withholding_category")
 		self.set_onload("supplier_tds", supplier_tds)
 
@@ -264,7 +264,7 @@
 
 		self.validate_posting_time()
 
-		super(PurchaseInvoice, self).validate()
+		super().validate()
 
 		if not self.is_return:
 			self.po_required()
@@ -324,7 +324,6 @@
 		if flt(self.paid_amount) + flt(self.write_off_amount) - flt(
 			self.get("rounded_total") or self.grand_total
 		) > 1 / (10 ** (self.precision("base_grand_total") + 1)):
-
 			frappe.throw(_("""Paid amount + Write Off Amount can not be greater than Grand Total"""))
 
 	def create_remarks(self):
@@ -353,7 +352,7 @@
 			self.tax_withholding_category = tds_category
 			self.set_onload("supplier_tds", tds_category)
 
-		super(PurchaseInvoice, self).set_missing_values(for_validate)
+		super().set_missing_values(for_validate)
 
 	def validate_credit_to_acc(self):
 		if not self.credit_to:
@@ -392,7 +391,7 @@
 				check_on_hold_or_closed_status("Purchase Order", d.purchase_order)
 
 	def validate_with_previous_doc(self):
-		super(PurchaseInvoice, self).validate_with_previous_doc(
+		super().validate_with_previous_doc(
 			{
 				"Purchase Order": {
 					"ref_dn_field": "purchase_order",
@@ -440,7 +439,7 @@
 						exc=WarehouseMissingError,
 					)
 
-		super(PurchaseInvoice, self).validate_warehouse()
+		super().validate_warehouse()
 
 	def validate_item_code(self):
 		for d in self.get("items"):
@@ -476,7 +475,6 @@
 					or not frappe.db.get_value("Purchase Order Item", item.po_detail, "delivered_by_supplier")
 				)
 			):
-
 				if self.update_stock and item.warehouse and (not item.from_warehouse):
 					if (
 						for_validate
@@ -504,12 +502,16 @@
 
 						if negative_expense_booked_in_pr:
 							if (
-								for_validate and item.expense_account and item.expense_account != stock_not_billed_account
+								for_validate
+								and item.expense_account
+								and item.expense_account != stock_not_billed_account
 							):
 								msg = _(
 									"Row {0}: Expense Head changed to {1} because expense is booked against this account in Purchase Receipt {2}"
 								).format(
-									item.idx, frappe.bold(stock_not_billed_account), frappe.bold(item.purchase_receipt)
+									item.idx,
+									frappe.bold(stock_not_billed_account),
+									frappe.bold(item.purchase_receipt),
 								)
 								frappe.msgprint(msg, title=_("Expense Head Changed"))
 
@@ -518,7 +520,9 @@
 						# If no purchase receipt present then book expense in 'Stock Received But Not Billed'
 						# This is done in cases when Purchase Invoice is created before Purchase Receipt
 						if (
-							for_validate and item.expense_account and item.expense_account != stock_not_billed_account
+							for_validate
+							and item.expense_account
+							and item.expense_account != stock_not_billed_account
 						):
 							msg = _(
 								"Row {0}: Expense Head changed to {1} as no Purchase Receipt is created against Item {2}."
@@ -569,7 +573,6 @@
 
 	def po_required(self):
 		if frappe.db.get_single_value("Buying Settings", "po_required") == "Yes":
-
 			if frappe.get_value(
 				"Supplier", self.supplier, "allow_purchase_invoice_creation_without_purchase_order"
 			):
@@ -579,7 +582,9 @@
 				if not d.purchase_order:
 					msg = _("Purchase Order Required for item {}").format(frappe.bold(d.item_code))
 					msg += "<br><br>"
-					msg += _("To submit the invoice without purchase order please set {0} as {1} in {2}").format(
+					msg += _(
+						"To submit the invoice without purchase order please set {0} as {1} in {2}"
+					).format(
 						frappe.bold(_("Purchase Order Required")),
 						frappe.bold("No"),
 						get_link_to_form("Buying Settings", "Buying Settings", "Buying Settings"),
@@ -589,7 +594,6 @@
 	def pr_required(self):
 		stock_items = self.get_stock_items()
 		if frappe.db.get_single_value("Buying Settings", "pr_required") == "Yes":
-
 			if frappe.get_value(
 				"Supplier", self.supplier, "allow_purchase_invoice_creation_without_purchase_receipt"
 			):
@@ -622,7 +626,8 @@
 					frappe.throw(_("Purchase Order {0} is not submitted").format(d.purchase_order))
 			if d.purchase_receipt:
 				submitted = frappe.db.sql(
-					"select name from `tabPurchase Receipt` where docstatus = 1 and name = %s", d.purchase_receipt
+					"select name from `tabPurchase Receipt` where docstatus = 1 and name = %s",
+					d.purchase_receipt,
 				)
 				if not submitted:
 					frappe.throw(_("Purchase Receipt {0} is not submitted").format(d.purchase_receipt))
@@ -670,7 +675,9 @@
 			for item in self.get("items"):
 				if item.purchase_receipt:
 					frappe.throw(
-						_("Stock cannot be updated against Purchase Receipt {0}").format(item.purchase_receipt)
+						_("Stock cannot be updated against Purchase Receipt {0}").format(
+							item.purchase_receipt
+						)
 					)
 
 	def validate_for_repost(self):
@@ -680,7 +687,7 @@
 		validate_docs_for_deferred_accounting([], [self.name])
 
 	def on_submit(self):
-		super(PurchaseInvoice, self).on_submit()
+		super().on_submit()
 
 		self.check_prev_docstatus()
 
@@ -717,9 +724,7 @@
 		if self.update_stock == 1:
 			self.repost_future_sle_and_gle()
 
-		if (
-			frappe.db.get_single_value("Buying Settings", "project_update_frequency") == "Each Transaction"
-		):
+		if frappe.db.get_single_value("Buying Settings", "project_update_frequency") == "Each Transaction":
 			self.update_project()
 
 		update_linked_doc(self.doctype, self.name, self.inter_company_invoice_reference)
@@ -911,7 +916,7 @@
 			if flt(item.base_net_amount):
 				account_currency = get_account_currency(item.expense_account)
 				if item.item_code:
-					asset_category = frappe.get_cached_value("Item", item.item_code, "asset_category")
+					frappe.get_cached_value("Item", item.item_code, "asset_category")
 
 				if (
 					self.update_stock
@@ -1016,7 +1021,9 @@
 					if flt(item.rm_supp_cost):
 						supplier_warehouse_account = warehouse_account[self.supplier_warehouse]["account"]
 						if not supplier_warehouse_account:
-							frappe.throw(_("Please set account in Warehouse {0}").format(self.supplier_warehouse))
+							frappe.throw(
+								_("Please set account in Warehouse {0}").format(self.supplier_warehouse)
+							)
 						gl_entries.append(
 							self.get_gl_dict(
 								{
@@ -1066,10 +1073,9 @@
 								and self.conversion_rate != exchange_rate_map[item.purchase_receipt]
 								and item.net_rate == net_rate_map[item.pr_detail]
 							):
-
-								discrepancy_caused_by_exchange_rate_difference = (item.qty * item.net_rate) * (
-									exchange_rate_map[item.purchase_receipt] - self.conversion_rate
-								)
+								discrepancy_caused_by_exchange_rate_difference = (
+									item.qty * item.net_rate
+								) * (exchange_rate_map[item.purchase_receipt] - self.conversion_rate)
 
 								gl_entries.append(
 									self.get_gl_dict(
@@ -1111,7 +1117,7 @@
 						(item.purchase_receipt, valuation_tax_accounts),
 					)
 
-					stock_rbnb = (
+					(
 						self.get_company_default("asset_received_but_not_billed")
 						if item.is_fixed_asset
 						else self.stock_received_but_not_billed
@@ -1150,7 +1156,9 @@
 		default_provisional_account = self.get_company_default("default_provisional_account")
 		provisional_accounts = set(
 			[
-				d.provisional_expense_account if d.provisional_expense_account else default_provisional_account
+				d.provisional_expense_account
+				if d.provisional_expense_account
+				else default_provisional_account
 				for d in pr_items
 			]
 		)
@@ -1207,9 +1215,7 @@
 				},
 			)
 
-	def make_stock_adjustment_entry(
-		self, gl_entries, item, voucher_wise_stock_value, account_currency
-	):
+	def make_stock_adjustment_entry(self, gl_entries, item, voucher_wise_stock_value, account_currency):
 		net_amt_precision = item.precision("base_net_amount")
 		val_rate_db_precision = 6 if cint(item.precision("valuation_rate")) <= 6 else 9
 
@@ -1225,7 +1231,6 @@
 			and warehouse_debit_amount
 			!= flt(voucher_wise_stock_value.get((item.name, item.warehouse)), net_amt_precision)
 		):
-
 			cost_of_goods_sold_account = self.get_company_default("default_expense_account")
 			stock_amount = flt(voucher_wise_stock_value.get((item.name, item.warehouse)), net_amt_precision)
 			stock_adjustment_amt = warehouse_debit_amount - stock_amount
@@ -1448,9 +1453,7 @@
 		# base_rounding_adjustment may become zero due to small precision
 		# eg: rounding_adjustment = 0.01 and exchange rate = 0.05 and precision of base_rounding_adjustment is 2
 		# 	then base_rounding_adjustment becomes zero and error is thrown in GL Entry
-		if (
-			not self.is_internal_transfer() and self.rounding_adjustment and self.base_rounding_adjustment
-		):
+		if not self.is_internal_transfer() and self.rounding_adjustment and self.base_rounding_adjustment:
 			round_off_account, round_off_cost_center = get_round_off_account_and_cost_center(
 				self.company, "Purchase Invoice", self.name, self.use_company_roundoff_cost_center
 			)
@@ -1473,7 +1476,7 @@
 	def on_cancel(self):
 		check_if_return_invoice_linked_with_payment_entry(self)
 
-		super(PurchaseInvoice, self).on_cancel()
+		super().on_cancel()
 
 		self.check_on_hold_or_closed_status()
 
@@ -1504,9 +1507,7 @@
 		if self.update_stock == 1:
 			self.repost_future_sle_and_gle()
 
-		if (
-			frappe.db.get_single_value("Buying Settings", "project_update_frequency") == "Each Transaction"
-		):
+		if frappe.db.get_single_value("Buying Settings", "project_update_frequency") == "Each Transaction":
 			self.update_project()
 		self.db_set("status", "Cancelled")
 
@@ -1538,9 +1539,7 @@
 
 		pj = frappe.qb.DocType("Project")
 		for proj, value in projects.items():
-			res = (
-				frappe.qb.from_(pj).select(pj.total_purchase_cost).where(pj.name == proj).for_update().run()
-			)
+			res = frappe.qb.from_(pj).select(pj.total_purchase_cost).where(pj.name == proj).for_update().run()
 			current_purchase_cost = res and res[0][0] or 0
 			frappe.db.set_value("Project", proj, "total_purchase_cost", current_purchase_cost + value)
 
@@ -1808,9 +1807,7 @@
 	)
 
 	net_rate_map = frappe._dict(
-		frappe.get_all(
-			child_doctype, filters={"name": ("in", items)}, fields=["name", "net_rate"], as_list=1
-		)
+		frappe.get_all(child_doctype, filters={"name": ("in", items)}, fields=["name", "net_rate"], as_list=1)
 	)
 
 	return exchange_rate_map, net_rate_map
diff --git a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
index 2ef0275..879aa21 100644
--- a/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/test_purchase_invoice.py
@@ -2,8 +2,6 @@
 # License: GNU General Public License v3. See license.txt
 
 
-import unittest
-
 import frappe
 from frappe.tests.utils import FrappeTestCase, change_settings
 from frappe.utils import add_days, cint, flt, getdate, nowdate, today
@@ -267,7 +265,6 @@
 		self.assertEqual(pi.on_hold, 0)
 
 	def test_gl_entries_with_perpetual_inventory_against_pr(self):
-
 		pr = make_purchase_receipt(
 			company="_Test Company with perpetual inventory",
 			supplier_warehouse="Work In Progress - TCP1",
@@ -318,7 +315,7 @@
 			]
 		)
 
-		for i, gle in enumerate(gl_entries):
+		for _i, gle in enumerate(gl_entries):
 			self.assertEqual(expected_values[gle.account][0], gle.account)
 			self.assertEqual(expected_values[gle.account][1], gle.debit)
 			self.assertEqual(expected_values[gle.account][2], gle.credit)
@@ -342,9 +339,7 @@
 		pi.submit()
 
 		# Get exchnage gain and loss account
-		exchange_gain_loss_account = frappe.db.get_value(
-			"Company", pi.company, "exchange_gain_loss_account"
-		)
+		exchange_gain_loss_account = frappe.db.get_value("Company", pi.company, "exchange_gain_loss_account")
 
 		# fetching the latest GL Entry with exchange gain and loss account account
 		amount = frappe.db.get_value(
@@ -560,12 +555,10 @@
 			project = frappe.get_doc("Project", {"project_name": "_Test Project for Purchase"})
 
 		existing_purchase_cost = frappe.db.sql(
-			"""select sum(base_net_amount)
+			f"""select sum(base_net_amount)
 			from `tabPurchase Invoice Item`
-			where project = '{0}'
-			and docstatus=1""".format(
-				project.name
-			)
+			where project = '{project.name}'
+			and docstatus=1"""
 		)
 		existing_purchase_cost = existing_purchase_cost and existing_purchase_cost[0][0] or 0
 
@@ -740,7 +733,7 @@
 			"credit",
 			"credit_in_account_currency",
 		):
-			for i, gle in enumerate(gl_entries):
+			for _i, gle in enumerate(gl_entries):
 				self.assertEqual(expected_values[gle.account][field], gle[field])
 
 		# Check for valid currency
@@ -762,7 +755,6 @@
 		self.assertFalse(gle)
 
 	def test_purchase_invoice_update_stock_gl_entry_with_perpetual_inventory(self):
-
 		pi = make_purchase_invoice(
 			update_stock=1,
 			posting_date=frappe.utils.nowdate(),
@@ -791,13 +783,12 @@
 			(d[0], d) for d in [[pi.credit_to, 0.0, 250.0], [stock_in_hand_account, 250.0, 0.0]]
 		)
 
-		for i, gle in enumerate(gl_entries):
+		for _i, gle in enumerate(gl_entries):
 			self.assertEqual(expected_gl_entries[gle.account][0], gle.account)
 			self.assertEqual(expected_gl_entries[gle.account][1], gle.debit)
 			self.assertEqual(expected_gl_entries[gle.account][2], gle.credit)
 
 	def test_purchase_invoice_for_is_paid_and_update_stock_gl_entry_with_perpetual_inventory(self):
-
 		pi = make_purchase_invoice(
 			update_stock=1,
 			posting_date=frappe.utils.nowdate(),
@@ -832,7 +823,7 @@
 			]
 		)
 
-		for i, gle in enumerate(gl_entries):
+		for _i, gle in enumerate(gl_entries):
 			self.assertEqual(expected_gl_entries[gle.account][0], gle.account)
 			self.assertEqual(expected_gl_entries[gle.account][1], gle.debit)
 			self.assertEqual(expected_gl_entries[gle.account][2], gle.credit)
@@ -904,9 +895,9 @@
 		pi.load_from_db()
 
 		serial_no = get_serial_nos_from_bundle(pi.get("items")[0].serial_and_batch_bundle)[0]
-		rejected_serial_no = get_serial_nos_from_bundle(
-			pi.get("items")[0].rejected_serial_and_batch_bundle
-		)[0]
+		rejected_serial_no = get_serial_nos_from_bundle(pi.get("items")[0].rejected_serial_and_batch_bundle)[
+			0
+		]
 
 		self.assertEqual(
 			frappe.db.get_value("Serial No", serial_no, "warehouse"),
@@ -1036,12 +1027,8 @@
 
 	def test_duplicate_due_date_in_terms(self):
 		pi = make_purchase_invoice(do_not_save=1)
-		pi.append(
-			"payment_schedule", dict(due_date="2017-01-01", invoice_portion=50.00, payment_amount=50)
-		)
-		pi.append(
-			"payment_schedule", dict(due_date="2017-01-01", invoice_portion=50.00, payment_amount=50)
-		)
+		pi.append("payment_schedule", dict(due_date="2017-01-01", invoice_portion=50.00, payment_amount=50))
+		pi.append("payment_schedule", dict(due_date="2017-01-01", invoice_portion=50.00, payment_amount=50))
 
 		self.assertRaises(frappe.ValidationError, pi.insert)
 
@@ -1079,9 +1066,7 @@
 		cost_center = "_Test Cost Center for BS Account - _TC"
 		create_cost_center(cost_center_name="_Test Cost Center for BS Account", company="_Test Company")
 
-		pi = make_purchase_invoice_against_cost_center(
-			cost_center=cost_center, credit_to="Creditors - _TC"
-		)
+		pi = make_purchase_invoice_against_cost_center(cost_center=cost_center, credit_to="Creditors - _TC")
 		self.assertEqual(pi.cost_center, cost_center)
 
 		expected_values = {
@@ -1541,9 +1526,7 @@
 	def test_provisional_accounting_entry(self):
 		setup_provisional_accounting()
 
-		pr = make_purchase_receipt(
-			item_code="_Test Non Stock Item", posting_date=add_days(nowdate(), -2)
-		)
+		pr = make_purchase_receipt(item_code="_Test Non Stock Item", posting_date=add_days(nowdate(), -2))
 
 		pi = create_purchase_invoice_from_receipt(pr.name)
 		pi.set_posting_time = 1
@@ -1552,7 +1535,7 @@
 		pi.save()
 		pi.submit()
 
-		self.assertEquals(pr.items[0].provisional_expense_account, "Provision Account - _TC")
+		self.assertEqual(pr.items[0].provisional_expense_account, "Provision Account - _TC")
 
 		# Check GLE for Purchase Invoice
 		expected_gle = [
@@ -1579,9 +1562,7 @@
 			["_Test Account Cost for Goods Sold - _TC", 250, 0, pi.posting_date],
 		]
 
-		check_gl_entries(
-			self, pr.name, expected_gle_for_purchase_receipt_post_pi_cancel, pr.posting_date
-		)
+		check_gl_entries(self, pr.name, expected_gle_for_purchase_receipt_post_pi_cancel, pr.posting_date)
 
 		toggle_provisional_accounting_setting()
 
@@ -1630,9 +1611,7 @@
 			["_Test Account Cost for Goods Sold - _TC", 5000, 0, pi.posting_date],
 		]
 
-		check_gl_entries(
-			self, pr.name, expected_gle_for_purchase_receipt_post_pi_cancel, pr.posting_date
-		)
+		check_gl_entries(self, pr.name, expected_gle_for_purchase_receipt_post_pi_cancel, pr.posting_date)
 
 		toggle_provisional_accounting_setting()
 
@@ -1678,9 +1657,7 @@
 	def test_adjust_incoming_rate(self):
 		frappe.db.set_single_value("Buying Settings", "maintain_same_rate", 0)
 
-		frappe.db.set_single_value(
-			"Buying Settings", "set_landed_cost_based_on_purchase_invoice_rate", 1
-		)
+		frappe.db.set_single_value("Buying Settings", "set_landed_cost_based_on_purchase_invoice_rate", 1)
 
 		# Increase the cost of the item
 
@@ -1732,9 +1709,7 @@
 		)
 		self.assertEqual(stock_value_difference, 50)
 
-		frappe.db.set_single_value(
-			"Buying Settings", "set_landed_cost_based_on_purchase_invoice_rate", 0
-		)
+		frappe.db.set_single_value("Buying Settings", "set_landed_cost_based_on_purchase_invoice_rate", 0)
 
 		# Don't adjust incoming rate
 
@@ -1764,7 +1739,6 @@
 		frappe.db.set_single_value("Buying Settings", "maintain_same_rate", 1)
 
 	def test_item_less_defaults(self):
-
 		pi = frappe.new_doc("Purchase Invoice")
 		pi.supplier = "_Test Supplier"
 		pi.company = "_Test Company"
@@ -2301,7 +2275,7 @@
 	pi.cost_center = args.parent_cost_center
 
 	bundle_id = None
-	if not args.use_serial_batch_fields and ((args.get("batch_no") or args.get("serial_no"))):
+	if not args.use_serial_batch_fields and (args.get("batch_no") or args.get("serial_no")):
 		batches = {}
 		qty = args.qty if args.qty is not None else 5
 		item_code = args.item or args.item_code or "_Test Item"
@@ -2450,9 +2424,7 @@
 		parent_account=args.parent_account or "Current Liabilities - _TC",
 		company=company,
 	)
-	toggle_provisional_accounting_setting(
-		enable=1, company=company, provisional_account=provisional_account
-	)
+	toggle_provisional_accounting_setting(enable=1, company=company, provisional_account=provisional_account)
 
 
 def toggle_provisional_accounting_setting(**args):
diff --git a/erpnext/accounts/doctype/purchase_taxes_and_charges_template/purchase_taxes_and_charges_template.py b/erpnext/accounts/doctype/purchase_taxes_and_charges_template/purchase_taxes_and_charges_template.py
index 16c30c5..4c8504b 100644
--- a/erpnext/accounts/doctype/purchase_taxes_and_charges_template/purchase_taxes_and_charges_template.py
+++ b/erpnext/accounts/doctype/purchase_taxes_and_charges_template/purchase_taxes_and_charges_template.py
@@ -37,4 +37,4 @@
 	def autoname(self):
 		if self.company and self.title:
 			abbr = frappe.get_cached_value("Company", self.company, "abbr")
-			self.name = "{0} - {1}".format(self.title, abbr)
+			self.name = f"{self.title} - {abbr}"
diff --git a/erpnext/accounts/doctype/repost_accounting_ledger/repost_accounting_ledger.py b/erpnext/accounts/doctype/repost_accounting_ledger/repost_accounting_ledger.py
index b050bc8..6bc1922 100644
--- a/erpnext/accounts/doctype/repost_accounting_ledger/repost_accounting_ledger.py
+++ b/erpnext/accounts/doctype/repost_accounting_ledger/repost_accounting_ledger.py
@@ -27,7 +27,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(RepostAccountingLedger, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 		self._allowed_types = get_allowed_types_from_settings()
 
 	def validate(self):
@@ -154,7 +154,9 @@
 				doc = frappe.get_doc(x.voucher_type, x.voucher_no)
 
 				if repost_doc.delete_cancelled_entries:
-					frappe.db.delete("GL Entry", filters={"voucher_type": doc.doctype, "voucher_no": doc.name})
+					frappe.db.delete(
+						"GL Entry", filters={"voucher_type": doc.doctype, "voucher_no": doc.name}
+					)
 					frappe.db.delete(
 						"Payment Ledger Entry", filters={"voucher_type": doc.doctype, "voucher_no": doc.name}
 					)
@@ -200,7 +202,9 @@
 	if docs_with_deferred_revenue or docs_with_deferred_expense:
 		frappe.throw(
 			_("Documents: {0} have deferred revenue/expense enabled for them. Cannot repost.").format(
-				frappe.bold(comma_and([x[0] for x in docs_with_deferred_expense + docs_with_deferred_revenue]))
+				frappe.bold(
+					comma_and([x[0] for x in docs_with_deferred_expense + docs_with_deferred_revenue])
+				)
 			)
 		)
 
diff --git a/erpnext/accounts/doctype/repost_accounting_ledger/test_repost_accounting_ledger.py b/erpnext/accounts/doctype/repost_accounting_ledger/test_repost_accounting_ledger.py
index d6f7096..f631ef4 100644
--- a/erpnext/accounts/doctype/repost_accounting_ledger/test_repost_accounting_ledger.py
+++ b/erpnext/accounts/doctype/repost_accounting_ledger/test_repost_accounting_ledger.py
@@ -9,7 +9,6 @@
 
 from erpnext.accounts.doctype.payment_entry.payment_entry import get_payment_entry
 from erpnext.accounts.doctype.payment_request.payment_request import make_payment_request
-from erpnext.accounts.doctype.repost_accounting_ledger.repost_accounting_ledger import start_repost
 from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice
 from erpnext.accounts.test.accounts_mixin import AccountsTestMixin
 from erpnext.accounts.utils import get_fiscal_year
diff --git a/erpnext/accounts/doctype/repost_payment_ledger/repost_payment_ledger.py b/erpnext/accounts/doctype/repost_payment_ledger/repost_payment_ledger.py
index 2d10f7c..6b90300 100644
--- a/erpnext/accounts/doctype/repost_payment_ledger/repost_payment_ledger.py
+++ b/erpnext/accounts/doctype/repost_payment_ledger/repost_payment_ledger.py
@@ -40,7 +40,7 @@
 
 				frappe.db.set_value(repost_doc.doctype, repost_doc.name, "repost_error_log", "")
 				frappe.db.set_value(repost_doc.doctype, repost_doc.name, "repost_status", "Completed")
-			except Exception as e:
+			except Exception:
 				frappe.db.rollback()
 
 				traceback = frappe.get_traceback(with_context=True)
@@ -75,7 +75,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(RepostPaymentLedger, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 		self.vouchers = []
 
 	def before_validate(self):
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
index 6be6a9b..3ccaba9 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
@@ -235,7 +235,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(SalesInvoice, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 		self.status_updater = [
 			{
 				"source_dt": "Sales Invoice Item",
@@ -272,7 +272,7 @@
 			self.indicator_title = _("Paid")
 
 	def validate(self):
-		super(SalesInvoice, self).validate()
+		super().validate()
 		self.validate_auto_set_posting_time()
 
 		if not (self.is_pos or self.is_debit_note):
@@ -475,9 +475,7 @@
 
 		self.update_time_sheet(self.name)
 
-		if (
-			frappe.db.get_single_value("Selling Settings", "sales_update_frequency") == "Each Transaction"
-		):
+		if frappe.db.get_single_value("Selling Settings", "sales_update_frequency") == "Each Transaction":
 			update_company_current_month_sales(self.company)
 			self.update_project()
 		update_linked_doc(self.doctype, self.name, self.inter_company_invoice_reference)
@@ -493,9 +491,7 @@
 			and not self.dont_create_loyalty_points
 		):
 			self.make_loyalty_point_entry()
-		elif (
-			self.is_return and self.return_against and not self.is_consolidated and self.loyalty_program
-		):
+		elif self.is_return and self.return_against and not self.is_consolidated and self.loyalty_program:
 			against_si_doc = frappe.get_doc("Sales Invoice", self.return_against)
 			against_si_doc.delete_loyalty_point_entry()
 			against_si_doc.make_loyalty_point_entry()
@@ -524,11 +520,11 @@
 	def check_if_consolidated_invoice(self):
 		# since POS Invoice extends Sales Invoice, we explicitly check if doctype is Sales Invoice
 		if self.doctype == "Sales Invoice" and self.is_consolidated:
-			invoice_or_credit_note = (
-				"consolidated_credit_note" if self.is_return else "consolidated_invoice"
-			)
+			invoice_or_credit_note = "consolidated_credit_note" if self.is_return else "consolidated_invoice"
 			pos_closing_entry = frappe.get_all(
-				"POS Invoice Merge Log", filters={invoice_or_credit_note: self.name}, pluck="pos_closing_entry"
+				"POS Invoice Merge Log",
+				filters={invoice_or_credit_note: self.name},
+				pluck="pos_closing_entry",
 			)
 			if pos_closing_entry and pos_closing_entry[0]:
 				msg = _("To cancel a {} you need to cancel the POS Closing Entry {}.").format(
@@ -540,13 +536,13 @@
 	def before_cancel(self):
 		self.check_if_consolidated_invoice()
 
-		super(SalesInvoice, self).before_cancel()
+		super().before_cancel()
 		self.update_time_sheet(None)
 
 	def on_cancel(self):
 		check_if_return_invoice_linked_with_payment_entry(self)
 
-		super(SalesInvoice, self).on_cancel()
+		super().on_cancel()
 
 		self.check_sales_order_on_hold_or_close("sales_order")
 
@@ -578,16 +574,12 @@
 		if self.coupon_code:
 			update_coupon_code_count(self.coupon_code, "cancelled")
 
-		if (
-			frappe.db.get_single_value("Selling Settings", "sales_update_frequency") == "Each Transaction"
-		):
+		if frappe.db.get_single_value("Selling Settings", "sales_update_frequency") == "Each Transaction":
 			update_company_current_month_sales(self.company)
 			self.update_project()
 		if not self.is_return and not self.is_consolidated and self.loyalty_program:
 			self.delete_loyalty_point_entry()
-		elif (
-			self.is_return and self.return_against and not self.is_consolidated and self.loyalty_program
-		):
+		elif self.is_return and self.return_against and not self.is_consolidated and self.loyalty_program:
 			against_si_doc = frappe.get_doc("Sales Invoice", self.return_against)
 			against_si_doc.delete_loyalty_point_entry()
 			against_si_doc.make_loyalty_point_entry()
@@ -694,7 +686,7 @@
 		if not self.due_date and self.customer:
 			self.due_date = get_due_date(self.posting_date, "Customer", self.customer, self.company)
 
-		super(SalesInvoice, self).set_missing_values(for_validate)
+		super().set_missing_values(for_validate)
 
 		print_format = pos.get("print_format") if pos else None
 		if not print_format and not cint(frappe.db.get_value("Print Format", "POS Invoice", "disabled")):
@@ -885,7 +877,8 @@
 
 		if account.report_type != "Balance Sheet":
 			msg = (
-				_("Please ensure {} account is a Balance Sheet account.").format(frappe.bold("Debit To")) + " "
+				_("Please ensure {} account is a Balance Sheet account.").format(frappe.bold("Debit To"))
+				+ " "
 			)
 			msg += _(
 				"You can change the parent account to a Balance Sheet account or select a different account."
@@ -914,11 +907,16 @@
 		)
 
 	def validate_with_previous_doc(self):
-		super(SalesInvoice, self).validate_with_previous_doc(
+		super().validate_with_previous_doc(
 			{
 				"Sales Order": {
 					"ref_dn_field": "sales_order",
-					"compare_fields": [["customer", "="], ["company", "="], ["project", "="], ["currency", "="]],
+					"compare_fields": [
+						["customer", "="],
+						["company", "="],
+						["project", "="],
+						["currency", "="],
+					],
 				},
 				"Sales Order Item": {
 					"ref_dn_field": "so_detail",
@@ -928,7 +926,12 @@
 				},
 				"Delivery Note": {
 					"ref_dn_field": "delivery_note",
-					"compare_fields": [["customer", "="], ["company", "="], ["project", "="], ["currency", "="]],
+					"compare_fields": [
+						["customer", "="],
+						["company", "="],
+						["project", "="],
+						["currency", "="],
+					],
 				},
 				"Delivery Note Item": {
 					"ref_dn_field": "dn_detail",
@@ -983,13 +986,14 @@
 		}
 		for key, value in prev_doc_field_map.items():
 			if frappe.db.get_single_value("Selling Settings", value[0]) == "Yes":
-
 				if frappe.get_value("Customer", self.customer, value[0]):
 					continue
 
 				for d in self.get("items"):
 					if d.item_code and not d.get(key.lower().replace(" ", "_")) and not self.get(value[1]):
-						msgprint(_("{0} is mandatory for Item {1}").format(key, d.item_code), raise_exception=1)
+						msgprint(
+							_("{0} is mandatory for Item {1}").format(key, d.item_code), raise_exception=1
+						)
 
 	def validate_proj_cust(self):
 		"""check for does customer belong to same project as entered.."""
@@ -1011,7 +1015,7 @@
 				frappe.throw(_("Paid amount + Write Off Amount can not be greater than Grand Total"))
 
 	def validate_warehouse(self):
-		super(SalesInvoice, self).validate_warehouse()
+		super().validate_warehouse()
 
 		for d in self.get_item_list():
 			if (
@@ -1331,7 +1335,9 @@
 						add_asset_activity(asset.name, _("Asset returned"))
 
 						if asset.calculate_depreciation:
-							posting_date = frappe.db.get_value("Sales Invoice", self.return_against, "posting_date")
+							posting_date = frappe.db.get_value(
+								"Sales Invoice", self.return_against, "posting_date"
+							)
 							reverse_depreciation_entry_made_after_disposal(asset, posting_date)
 							notes = _(
 								"This schedule was created when Asset {0} was returned through Sales Invoice {1}."
@@ -1379,7 +1385,9 @@
 							else item.deferred_revenue_account
 						)
 
-						amount, base_amount = self.get_amount_and_base_amount(item, enable_discount_accounting)
+						amount, base_amount = self.get_amount_and_base_amount(
+							item, enable_discount_accounting
+						)
 
 						account_currency = get_account_currency(income_account)
 						gl_entries.append(
@@ -1403,7 +1411,7 @@
 
 		# expense account gl entries
 		if cint(self.update_stock) and erpnext.is_perpetual_inventory_enabled(self.company):
-			gl_entries += super(SalesInvoice, self).get_gl_entries()
+			gl_entries += super().get_gl_entries()
 
 	def get_asset(self, item):
 		if item.get("asset"):
@@ -1466,7 +1474,6 @@
 
 	def make_pos_gl_entries(self, gl_entries):
 		if cint(self.is_pos):
-
 			skip_change_gl_entries = not cint(
 				frappe.db.get_single_value("Accounts Settings", "post_change_gl_entries")
 			)
@@ -1624,7 +1631,9 @@
 						"credit_in_account_currency": flt(
 							self.rounding_adjustment, self.precision("rounding_adjustment")
 						),
-						"credit": flt(self.base_rounding_adjustment, self.precision("base_rounding_adjustment")),
+						"credit": flt(
+							self.base_rounding_adjustment, self.precision("base_rounding_adjustment")
+						),
 						"cost_center": round_off_cost_center
 						if self.use_company_roundoff_cost_center
 						else (self.cost_center or round_off_cost_center),
@@ -1646,7 +1655,11 @@
 				)
 				billed_amt = billed_amt and billed_amt[0][0] or 0
 				frappe.db.set_value(
-					"Delivery Note Item", d.dn_detail, "billed_amt", billed_amt, update_modified=update_modified
+					"Delivery Note Item",
+					d.dn_detail,
+					"billed_amt",
+					billed_amt,
+					update_modified=update_modified,
 				)
 				updated_delivery_notes.append(d.delivery_note)
 			elif d.so_detail:
@@ -1701,7 +1714,6 @@
 			and getdate(lp_details.from_date) <= getdate(self.posting_date)
 			and (not lp_details.to_date or getdate(lp_details.to_date) >= getdate(self.posting_date))
 		):
-
 			collection_factor = lp_details.collection_factor if lp_details.collection_factor else 1.0
 			points_earned = cint(eligible_amount / collection_factor)
 
@@ -1961,7 +1973,6 @@
 
 
 def update_linked_doc(doctype, name, inter_company_reference):
-
 	if doctype in ["Sales Invoice", "Purchase Invoice"]:
 		ref_field = "inter_company_invoice_reference"
 	else:
@@ -1972,7 +1983,6 @@
 
 
 def unlink_inter_company_doc(doctype, name, inter_company_reference):
-
 	if doctype in ["Sales Invoice", "Purchase Invoice"]:
 		ref_doc = "Purchase Invoice" if doctype == "Sales Invoice" else "Sales Invoice"
 		ref_field = "inter_company_invoice_reference"
@@ -2147,16 +2157,13 @@
 
 
 def validate_inter_company_transaction(doc, doctype):
-
 	details = get_inter_company_details(doc, doctype)
 	price_list = (
 		doc.selling_price_list
 		if doctype in ["Sales Invoice", "Sales Order", "Delivery Note"]
 		else doc.buying_price_list
 	)
-	valid_price_list = frappe.db.get_value(
-		"Price List", {"name": price_list, "buying": 1, "selling": 1}
-	)
+	valid_price_list = frappe.db.get_value("Price List", {"name": price_list, "buying": 1, "selling": 1})
 	if not valid_price_list and not doc.is_internal_transfer():
 		frappe.throw(_("Selected Price List should have buying and selling fields checked."))
 
@@ -2417,9 +2424,7 @@
 	for item in doc.get("items"):
 		item.warehouse = warehouse_map.get(sales_item_map.get(item.delivery_note_item))
 		if not item.warehouse and item.get("purchase_order") and item.get("purchase_order_item"):
-			item.warehouse = frappe.db.get_value(
-				"Purchase Order Item", item.purchase_order_item, "warehouse"
-			)
+			item.warehouse = frappe.db.get_value("Purchase Order Item", item.purchase_order_item, "warehouse")
 
 
 def get_delivery_note_details(internal_reference):
@@ -2665,9 +2670,7 @@
 	# If a Return invoice is linked with payment entry along with other invoices,
 	# the cancellation of the Return causes allocated amount to be greater than paid
 
-	if not frappe.db.get_single_value(
-		"Accounts Settings", "unlink_payment_on_cancellation_of_invoice"
-	):
+	if not frappe.db.get_single_value("Accounts Settings", "unlink_payment_on_cancellation_of_invoice"):
 		return
 
 	payment_entries = []
diff --git a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
index 7e3eec5..2c937cd 100644
--- a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
@@ -2,7 +2,6 @@
 # License: GNU General Public License v3. See license.txt
 
 import copy
-import unittest
 
 import frappe
 from frappe.model.dynamic_links import get_dynamic_link_map
@@ -925,7 +924,7 @@
 			]
 		)
 
-		for i, gle in enumerate(gl_entries):
+		for _i, gle in enumerate(gl_entries):
 			self.assertEqual(expected_values[gle.account][0], gle.account)
 			self.assertEqual(expected_values[gle.account][1], gle.debit)
 			self.assertEqual(expected_values[gle.account][2], gle.credit)
@@ -951,7 +950,7 @@
 			write_off_account="_Test Write Off - TCP1",
 		)
 
-		pr = make_purchase_receipt(
+		make_purchase_receipt(
 			company="_Test Company with perpetual inventory",
 			item_code="_Test FG Item",
 			warehouse="Stores - TCP1",
@@ -1332,7 +1331,7 @@
 		expected_values = dict(
 			(d[0], d) for d in [["Debtors - TCP1", 100.0, 0.0], ["Sales - TCP1", 0.0, 100.0]]
 		)
-		for i, gle in enumerate(gl_entries):
+		for _i, gle in enumerate(gl_entries):
 			self.assertEqual(expected_values[gle.account][0], gle.account)
 			self.assertEqual(expected_values[gle.account][1], gle.debit)
 			self.assertEqual(expected_values[gle.account][2], gle.credit)
@@ -1356,7 +1355,7 @@
 				[test_records[1]["items"][0]["income_account"], 0.0, 100.0],
 			]
 		)
-		for i, gle in enumerate(gl_entries):
+		for _i, gle in enumerate(gl_entries):
 			self.assertEqual(expected_values[gle.account][0], gle.account)
 			self.assertEqual(expected_values[gle.account][1], gle.debit)
 			self.assertEqual(expected_values[gle.account][2], gle.credit)
@@ -1431,7 +1430,6 @@
 		si.cancel()
 
 	def test_serialized(self):
-		from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
 		from erpnext.stock.doctype.stock_entry.test_stock_entry import make_serialized_item
 
 		se = make_serialized_item()
@@ -1771,7 +1769,7 @@
 			"credit",
 			"credit_in_account_currency",
 		):
-			for i, gle in enumerate(gl_entries):
+			for _i, gle in enumerate(gl_entries):
 				self.assertEqual(expected_values[gle.account][field], gle[field])
 
 		# cancel
@@ -2315,12 +2313,8 @@
 
 	def test_duplicate_due_date_in_terms(self):
 		si = create_sales_invoice(do_not_save=1)
-		si.append(
-			"payment_schedule", dict(due_date="2017-01-01", invoice_portion=50.00, payment_amount=50)
-		)
-		si.append(
-			"payment_schedule", dict(due_date="2017-01-01", invoice_portion=50.00, payment_amount=50)
-		)
+		si.append("payment_schedule", dict(due_date="2017-01-01", invoice_portion=50.00, payment_amount=50))
+		si.append("payment_schedule", dict(due_date="2017-01-01", invoice_portion=50.00, payment_amount=50))
 
 		self.assertRaises(frappe.ValidationError, si.insert)
 
@@ -2514,9 +2508,7 @@
 		item.no_of_months = 12
 		item.save()
 
-		si = create_sales_invoice(
-			item=item.name, posting_date="2019-01-16", rate=50000, do_not_submit=True
-		)
+		si = create_sales_invoice(item=item.name, posting_date="2019-01-16", rate=50000, do_not_submit=True)
 		si.items[0].enable_deferred_revenue = 1
 		si.items[0].service_start_date = "2019-01-16"
 		si.items[0].service_end_date = "2019-03-31"
@@ -2837,21 +2829,16 @@
 		item.save()
 
 		sales_invoice = create_sales_invoice(item="T Shirt", rate=700, do_not_submit=True)
-		self.assertEqual(
-			sales_invoice.items[0].item_tax_template, "_Test Account Excise Duty @ 12 - _TC"
-		)
+		self.assertEqual(sales_invoice.items[0].item_tax_template, "_Test Account Excise Duty @ 12 - _TC")
 
 		# Apply discount
 		sales_invoice.apply_discount_on = "Net Total"
 		sales_invoice.discount_amount = 300
 		sales_invoice.save()
-		self.assertEqual(
-			sales_invoice.items[0].item_tax_template, "_Test Account Excise Duty @ 10 - _TC"
-		)
+		self.assertEqual(sales_invoice.items[0].item_tax_template, "_Test Account Excise Duty @ 10 - _TC")
 
 	@change_settings("Selling Settings", {"enable_discount_accounting": 1})
 	def test_sales_invoice_with_discount_accounting_enabled(self):
-
 		discount_account = create_account(
 			account_name="Discount Account",
 			parent_account="Indirect Expenses - _TC",
@@ -2869,7 +2856,6 @@
 
 	@change_settings("Selling Settings", {"enable_discount_accounting": 1})
 	def test_additional_discount_for_sales_invoice_with_discount_accounting_enabled(self):
-
 		from erpnext.accounts.doctype.repost_accounting_ledger.test_repost_accounting_ledger import (
 			update_repost_settings,
 		)
@@ -2882,7 +2868,7 @@
 			company="_Test Company",
 		)
 
-		tds_payable_account = create_account(
+		create_account(
 			account_name="TDS Payable",
 			account_type="Tax",
 			parent_account="Duties and Taxes - _TC",
@@ -3204,9 +3190,7 @@
 		"""
 		from erpnext.stock.doctype.delivery_note.test_delivery_note import create_delivery_note
 
-		over_billing_allowance = frappe.db.get_single_value(
-			"Accounts Settings", "over_billing_allowance"
-		)
+		over_billing_allowance = frappe.db.get_single_value("Accounts Settings", "over_billing_allowance")
 		frappe.db.set_single_value("Accounts Settings", "over_billing_allowance", 0)
 
 		dn = create_delivery_note()
@@ -3398,7 +3382,7 @@
 		self.assertEqual(len(journals), 1)
 		je_type = frappe.get_cached_value("Journal Entry", journals[0], "voucher_type")
 		self.assertEqual(je_type, "Exchange Gain Or Loss")
-		ledger_outstanding = frappe.db.get_all(
+		frappe.db.get_all(
 			"Payment Ledger Entry",
 			filters={"against_voucher_no": si.name, "delinked": 0},
 			fields=["sum(amount), sum(amount_in_account_currency)"],
diff --git a/erpnext/accounts/doctype/sales_taxes_and_charges_template/sales_taxes_and_charges_template.py b/erpnext/accounts/doctype/sales_taxes_and_charges_template/sales_taxes_and_charges_template.py
index ce3eda9..e0b4258 100644
--- a/erpnext/accounts/doctype/sales_taxes_and_charges_template/sales_taxes_and_charges_template.py
+++ b/erpnext/accounts/doctype/sales_taxes_and_charges_template/sales_taxes_and_charges_template.py
@@ -42,7 +42,7 @@
 	def autoname(self):
 		if self.company and self.title:
 			abbr = frappe.get_cached_value("Company", self.company, "abbr")
-			self.name = "{0} - {1}".format(self.title, abbr)
+			self.name = f"{self.title} - {abbr}"
 
 	def set_missing_values(self):
 		for data in self.taxes:
@@ -57,10 +57,8 @@
 
 	if doc.is_default == 1:
 		frappe.db.sql(
-			"""update `tab{0}` set is_default = 0
-			where is_default = 1 and name != %s and company = %s""".format(
-				doc.doctype
-			),
+			f"""update `tab{doc.doctype}` set is_default = 0
+			where is_default = 1 and name != %s and company = %s""",
 			(doc.name, doc.company),
 		)
 
diff --git a/erpnext/accounts/doctype/share_transfer/share_transfer.py b/erpnext/accounts/doctype/share_transfer/share_transfer.py
index 6a3ff7c..bc86594 100644
--- a/erpnext/accounts/doctype/share_transfer/share_transfer.py
+++ b/erpnext/accounts/doctype/share_transfer/share_transfer.py
@@ -205,7 +205,9 @@
 		doc = self.get_shareholder_doc(shareholder)
 		for entry in doc.share_balance:
 			if (
-				entry.share_type != self.share_type or entry.from_no > self.to_no or entry.to_no < self.from_no
+				entry.share_type != self.share_type
+				or entry.from_no > self.to_no
+				or entry.to_no < self.from_no
 			):
 				continue  # since query lies outside bounds
 			elif entry.from_no <= self.from_no and entry.to_no >= self.to_no:  # both inside
@@ -257,7 +259,9 @@
 		for entry in current_entries:
 			# use spaceage logic here
 			if (
-				entry.share_type != self.share_type or entry.from_no > self.to_no or entry.to_no < self.from_no
+				entry.share_type != self.share_type
+				or entry.from_no > self.to_no
+				or entry.to_no < self.from_no
 			):
 				new_entries.append(entry)
 				continue  # since query lies outside bounds
@@ -267,7 +271,9 @@
 					if entry.to_no == self.to_no:
 						pass  # nothing to append
 					else:
-						new_entries.append(self.return_share_balance_entry(self.to_no + 1, entry.to_no, entry.rate))
+						new_entries.append(
+							self.return_share_balance_entry(self.to_no + 1, entry.to_no, entry.rate)
+						)
 				else:
 					if entry.to_no == self.to_no:
 						new_entries.append(
@@ -277,7 +283,9 @@
 						new_entries.append(
 							self.return_share_balance_entry(entry.from_no, self.from_no - 1, entry.rate)
 						)
-						new_entries.append(self.return_share_balance_entry(self.to_no + 1, entry.to_no, entry.rate))
+						new_entries.append(
+							self.return_share_balance_entry(self.to_no + 1, entry.to_no, entry.rate)
+						)
 			elif entry.from_no >= self.from_no and entry.to_no <= self.to_no:
 				# split and check
 				pass  # nothing to append
@@ -309,7 +317,7 @@
 	def get_shareholder_doc(self, shareholder):
 		# Get Shareholder doc based on the Shareholder name
 		if shareholder:
-			query_filters = {"name": shareholder}
+			pass
 
 		name = frappe.db.get_value("Shareholder", {"name": shareholder}, "name")
 
diff --git a/erpnext/accounts/doctype/shipping_rule/shipping_rule.py b/erpnext/accounts/doctype/shipping_rule/shipping_rule.py
index 6877a74..d9b7b0a 100644
--- a/erpnext/accounts/doctype/shipping_rule/shipping_rule.py
+++ b/erpnext/accounts/doctype/shipping_rule/shipping_rule.py
@@ -71,7 +71,8 @@
 				zero_to_values.append(d)
 			elif d.from_value >= d.to_value:
 				throw(
-					_("From value must be less than to value in row {0}").format(d.idx), FromGreaterThanToError
+					_("From value must be less than to value in row {0}").format(d.idx),
+					FromGreaterThanToError,
 				)
 
 		# check if more than two or more rows has To Value = 0
@@ -114,9 +115,7 @@
 
 	def get_shipping_amount_from_rules(self, value):
 		for condition in self.get("conditions"):
-			if not condition.to_value or (
-				flt(condition.from_value) <= flt(value) <= flt(condition.to_value)
-			):
+			if not condition.to_value or (flt(condition.from_value) <= flt(value) <= flt(condition.to_value)):
 				return condition.shipping_amount
 
 		return 0.0
@@ -131,7 +130,9 @@
 				)
 			if shipping_country not in [d.country for d in self.countries]:
 				frappe.throw(
-					_("Shipping rule not applicable for country {0} in Shipping Address").format(shipping_country)
+					_("Shipping rule not applicable for country {0} in Shipping Address").format(
+						shipping_country
+					)
 				)
 
 	def add_shipping_rule_to_tax_table(self, doc, shipping_amount):
@@ -199,11 +200,9 @@
 			messages = []
 			for d1, d2 in overlaps:
 				messages.append(
-					"%s-%s = %s "
-					% (d1.from_value, d1.to_value, fmt_money(d1.shipping_amount, currency=company_currency))
+					f"{d1.from_value}-{d1.to_value} = {fmt_money(d1.shipping_amount, currency=company_currency)} "
 					+ _("and")
-					+ " %s-%s = %s"
-					% (d2.from_value, d2.to_value, fmt_money(d2.shipping_amount, currency=company_currency))
+					+ f" {d2.from_value}-{d2.to_value} = {fmt_money(d2.shipping_amount, currency=company_currency)}"
 				)
 
 			msgprint("\n".join(messages), raise_exception=OverlappingConditionError)
diff --git a/erpnext/accounts/doctype/shipping_rule/test_shipping_rule.py b/erpnext/accounts/doctype/shipping_rule/test_shipping_rule.py
index a24e834..a5a0ada 100644
--- a/erpnext/accounts/doctype/shipping_rule/test_shipping_rule.py
+++ b/erpnext/accounts/doctype/shipping_rule/test_shipping_rule.py
@@ -45,7 +45,6 @@
 
 
 def create_shipping_rule(shipping_rule_type, shipping_rule_name):
-
 	if frappe.db.exists("Shipping Rule", shipping_rule_name):
 		return frappe.get_doc("Shipping Rule", shipping_rule_name)
 
diff --git a/erpnext/accounts/doctype/subscription/subscription.py b/erpnext/accounts/doctype/subscription/subscription.py
index 1a79103..a241e82 100644
--- a/erpnext/accounts/doctype/subscription/subscription.py
+++ b/erpnext/accounts/doctype/subscription/subscription.py
@@ -3,7 +3,7 @@
 
 
 from datetime import datetime
-from typing import Dict, List, Optional, Union
+from typing import Optional, Union
 
 import frappe
 from frappe import _
@@ -105,9 +105,7 @@
 
 		return _current_invoice_start, _current_invoice_end
 
-	def get_current_invoice_start(
-		self, date: Optional["DateTimeLikeObject"] = None
-	) -> Union[datetime.date, str]:
+	def get_current_invoice_start(self, date: Optional["DateTimeLikeObject"] = None) -> datetime.date | str:
 		"""
 		This returns the date of the beginning of the current billing period.
 		If the `date` parameter is not given , it will be automatically set as today's
@@ -130,9 +128,7 @@
 
 		return _current_invoice_start
 
-	def get_current_invoice_end(
-		self, date: Optional["DateTimeLikeObject"] = None
-	) -> Union[datetime.date, str]:
+	def get_current_invoice_end(self, date: Optional["DateTimeLikeObject"] = None) -> datetime.date | str:
 		"""
 		This returns the date of the end of the current billing period.
 		If the subscription is in trial period, it will be set as the end of the
@@ -174,7 +170,7 @@
 		return _current_invoice_end
 
 	@staticmethod
-	def validate_plans_billing_cycle(billing_cycle_data: List[Dict[str, str]]) -> None:
+	def validate_plans_billing_cycle(billing_cycle_data: list[dict[str, str]]) -> None:
 		"""
 		Makes sure that all `Subscription Plan` in the `Subscription` have the
 		same billing interval
@@ -182,7 +178,7 @@
 		if billing_cycle_data and len(billing_cycle_data) != 1:
 			frappe.throw(_("You can only have Plans with the same billing cycle in a Subscription"))
 
-	def get_billing_cycle_and_interval(self) -> List[Dict[str, str]]:
+	def get_billing_cycle_and_interval(self) -> list[dict[str, str]]:
 		"""
 		Returns a dict representing the billing interval and cycle for this `Subscription`.
 		You shouldn't need to call this directly. Use `get_billing_cycle` instead.
@@ -199,7 +195,7 @@
 
 		return billing_info
 
-	def get_billing_cycle_data(self) -> Dict[str, int]:
+	def get_billing_cycle_data(self) -> dict[str, int]:
 		"""
 		Returns dict contain the billing cycle data.
 		You shouldn't need to call this directly. Use `get_billing_cycle` instead.
@@ -232,9 +228,7 @@
 		"""
 		if self.is_trialling():
 			self.status = "Trialing"
-		elif (
-			self.status == "Active" and self.end_date and getdate(posting_date) > getdate(self.end_date)
-		):
+		elif self.status == "Active" and self.end_date and getdate(posting_date) > getdate(self.end_date):
 			self.status = "Completed"
 		elif self.is_past_grace_period():
 			self.status = self.get_status_for_past_grace_period()
@@ -252,7 +246,7 @@
 
 	@staticmethod
 	def period_has_passed(
-		end_date: Union[str, datetime.date], posting_date: Optional["DateTimeLikeObject"] = None
+		end_date: str | datetime.date, posting_date: Optional["DateTimeLikeObject"] = None
 	) -> bool:
 		"""
 		Returns true if the given `end_date` has passed
@@ -282,9 +276,7 @@
 		grace_period = cint(frappe.get_value("Subscription Settings", None, "grace_period"))
 		return getdate(posting_date) >= getdate(add_days(self.current_invoice.due_date, grace_period))
 
-	def current_invoice_is_past_due(
-		self, posting_date: Optional["DateTimeLikeObject"] = None
-	) -> bool:
+	def current_invoice_is_past_due(self, posting_date: Optional["DateTimeLikeObject"] = None) -> bool:
 		"""
 		Returns `True` if the current generated invoice is overdue
 		"""
@@ -334,14 +326,15 @@
 			unsupported_plans = []
 			for x in subscription_plan_currencies:
 				if x.currency != party_billing_currency:
-					unsupported_plans.append("{0}".format(get_link_to_form("Subscription Plan", x.name)))
+					unsupported_plans.append("{}".format(get_link_to_form("Subscription Plan", x.name)))
 
 			if unsupported_plans:
 				unsupported_plans = [
 					_(
 						"Below Subscription Plans are of different currency to the party default billing currency/Company currency: {0}"
-					).format(frappe.bold(party_billing_currency))
-				] + unsupported_plans
+					).format(frappe.bold(party_billing_currency)),
+					*unsupported_plans,
+				]
 
 				frappe.throw(
 					unsupported_plans, frappe.ValidationError, "Unsupported Subscription Plans", as_list=True
@@ -384,9 +377,9 @@
 
 	def generate_invoice(
 		self,
-		from_date: Optional[Union[str, datetime.date]] = None,
-		to_date: Optional[Union[str, datetime.date]] = None,
-		posting_date: Optional[Union[str, datetime.date]] = None,
+		from_date: str | datetime.date | None = None,
+		to_date: str | datetime.date | None = None,
+		posting_date: str | datetime.date | None = None,
 	) -> Document:
 		"""
 		Creates a `Invoice` for the `Subscription`, updates `self.invoices` and
@@ -397,9 +390,9 @@
 
 	def create_invoice(
 		self,
-		from_date: Optional[Union[str, datetime.date]] = None,
-		to_date: Optional[Union[str, datetime.date]] = None,
-		posting_date: Optional[Union[str, datetime.date]] = None,
+		from_date: str | datetime.date | None = None,
+		to_date: str | datetime.date | None = None,
+		posting_date: str | datetime.date | None = None,
 	) -> Document:
 		"""
 		Creates a `Invoice`, submits it and returns it
@@ -503,9 +496,7 @@
 
 		return invoice
 
-	def get_items_from_plans(
-		self, plans: List[Dict[str, str]], prorate: Optional[bool] = None
-	) -> List[Dict]:
+	def get_items_from_plans(self, plans: list[dict[str, str]], prorate: bool | None = None) -> list[dict]:
 		"""
 		Returns the `Item`s linked to `Subscription Plan`
 		"""
@@ -628,8 +619,8 @@
 
 	def is_current_invoice_generated(
 		self,
-		_current_start_date: Union[datetime.date, str] = None,
-		_current_end_date: Union[datetime.date, str] = None,
+		_current_start_date: datetime.date | str | None = None,
+		_current_end_date: datetime.date | str | None = None,
 	) -> bool:
 		if not (_current_start_date and _current_end_date):
 			_current_start_date, _current_end_date = self._get_subscription_period(
@@ -644,13 +635,13 @@
 		return False
 
 	@property
-	def current_invoice(self) -> Union[Document, None]:
+	def current_invoice(self) -> Document | None:
 		"""
 		Adds property for accessing the current_invoice
 		"""
 		return self.get_current_invoice()
 
-	def get_current_invoice(self) -> Union[Document, None]:
+	def get_current_invoice(self) -> Document | None:
 		"""
 		Returns the most recent generated invoice.
 		"""
@@ -675,7 +666,7 @@
 		self.cancelation_date = nowdate()
 
 	@property
-	def invoices(self) -> List[Dict]:
+	def invoices(self) -> list[dict]:
 		return frappe.get_all(
 			self.invoice_document_type,
 			filters={"subscription": self.name},
@@ -745,10 +736,10 @@
 
 
 def get_prorata_factor(
-	period_end: Union[datetime.date, str],
-	period_start: Union[datetime.date, str],
-	is_prepaid: Optional[int] = None,
-) -> Union[int, float]:
+	period_end: datetime.date | str,
+	period_start: datetime.date | str,
+	is_prepaid: int | None = None,
+) -> int | float:
 	if is_prepaid:
 		return 1
 
@@ -757,9 +748,7 @@
 	return diff / plan_days
 
 
-def process_all(
-	subscription: str | None = None, posting_date: Optional["DateTimeLikeObject"] = None
-) -> None:
+def process_all(subscription: str | None = None, posting_date: Optional["DateTimeLikeObject"] = None) -> None:
 	"""
 	Task to updates the status of all `Subscription` apart from those that are cancelled
 	"""
diff --git a/erpnext/accounts/doctype/subscription/test_subscription.py b/erpnext/accounts/doctype/subscription/test_subscription.py
index 89be543..13c6a52 100644
--- a/erpnext/accounts/doctype/subscription/test_subscription.py
+++ b/erpnext/accounts/doctype/subscription/test_subscription.py
@@ -1,7 +1,6 @@
 # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contributors
 # See license.txt
 
-import unittest
 
 import frappe
 from frappe.tests.utils import FrappeTestCase
@@ -201,9 +200,7 @@
 
 		invoice = subscription.get_current_invoice()
 		diff = flt(date_diff(nowdate(), subscription.current_invoice_start) + 1)
-		plan_days = flt(
-			date_diff(subscription.current_invoice_end, subscription.current_invoice_start) + 1
-		)
+		plan_days = flt(date_diff(subscription.current_invoice_end, subscription.current_invoice_start) + 1)
 		prorate_factor = flt(diff / plan_days)
 
 		self.assertEqual(
@@ -249,9 +246,7 @@
 
 		invoice = subscription.get_current_invoice()
 		diff = flt(date_diff(nowdate(), subscription.current_invoice_start) + 1)
-		plan_days = flt(
-			date_diff(subscription.current_invoice_end, subscription.current_invoice_start) + 1
-		)
+		plan_days = flt(date_diff(subscription.current_invoice_end, subscription.current_invoice_start) + 1)
 		prorate_factor = flt(diff / plan_days)
 
 		self.assertEqual(flt(invoice.grand_total, 2), flt(prorate_factor * 900, 2))
@@ -385,9 +380,7 @@
 		settings.prorate = 1
 		settings.save()
 
-		subscription = create_subscription(
-			generate_invoice_at="Beginning of the current subscription period"
-		)
+		subscription = create_subscription(generate_invoice_at="Beginning of the current subscription period")
 		subscription.process()
 		subscription.cancel_subscription()
 
@@ -546,9 +539,7 @@
 		billing_interval_count=3,
 		currency="INR",
 	)
-	create_plan(
-		plan_name="_Test Plan Multicurrency", cost=50, billing_interval="Month", currency="USD"
-	)
+	create_plan(plan_name="_Test Plan Multicurrency", cost=50, billing_interval="Month", currency="USD")
 
 
 def create_plan(**kwargs):
@@ -575,9 +566,7 @@
 		customer = frappe.new_doc("Customer")
 		customer.customer_name = "_Test Subscription Customer"
 		customer.billing_currency = "USD"
-		customer.append(
-			"accounts", {"company": "_Test Company", "account": "_Test Receivable USD - _TC"}
-		)
+		customer.append("accounts", {"company": "_Test Company", "account": "_Test Receivable USD - _TC"})
 		customer.insert()
 
 
@@ -600,9 +589,7 @@
 	subscription.additional_discount_percentage = kwargs.get("additional_discount_percentage")
 	subscription.additional_discount_amount = kwargs.get("additional_discount_amount")
 	subscription.follow_calendar_months = kwargs.get("follow_calendar_months")
-	subscription.generate_new_invoices_past_due_date = kwargs.get(
-		"generate_new_invoices_past_due_date"
-	)
+	subscription.generate_new_invoices_past_due_date = kwargs.get("generate_new_invoices_past_due_date")
 	subscription.submit_invoice = kwargs.get("submit_invoice")
 	subscription.days_until_due = kwargs.get("days_until_due")
 	subscription.number_of_days = kwargs.get("number_of_days")
diff --git a/erpnext/accounts/doctype/tax_rule/tax_rule.py b/erpnext/accounts/doctype/tax_rule/tax_rule.py
index 9ff530b..ed623c6 100644
--- a/erpnext/accounts/doctype/tax_rule/tax_rule.py
+++ b/erpnext/accounts/doctype/tax_rule/tax_rule.py
@@ -112,27 +112,23 @@
 		for d in filters:
 			if conds:
 				conds += " and "
-			conds += """ifnull({0}, '') = {1}""".format(d, frappe.db.escape(cstr(filters[d])))
+			conds += f"""ifnull({d}, '') = {frappe.db.escape(cstr(filters[d]))}"""
 
 		if self.from_date and self.to_date:
-			conds += """ and ((from_date > '{from_date}' and from_date < '{to_date}') or
-					(to_date > '{from_date}' and to_date < '{to_date}') or
-					('{from_date}' > from_date and '{from_date}' < to_date) or
-					('{from_date}' = from_date and '{to_date}' = to_date))""".format(
-				from_date=self.from_date, to_date=self.to_date
-			)
+			conds += f""" and ((from_date > '{self.from_date}' and from_date < '{self.to_date}') or
+					(to_date > '{self.from_date}' and to_date < '{self.to_date}') or
+					('{self.from_date}' > from_date and '{self.from_date}' < to_date) or
+					('{self.from_date}' = from_date and '{self.to_date}' = to_date))"""
 
 		elif self.from_date and not self.to_date:
-			conds += """ and to_date > '{from_date}'""".format(from_date=self.from_date)
+			conds += f""" and to_date > '{self.from_date}'"""
 
 		elif self.to_date and not self.from_date:
-			conds += """ and from_date < '{to_date}'""".format(to_date=self.to_date)
+			conds += f""" and from_date < '{self.to_date}'"""
 
 		tax_rule = frappe.db.sql(
-			"select name, priority \
-			from `tabTax Rule` where {0} and name != '{1}'".format(
-				conds, self.name
-			),
+			f"select name, priority \
+			from `tabTax Rule` where {conds} and name != '{self.name}'",
 			as_dict=1,
 		)
 
@@ -189,27 +185,25 @@
 		conditions.append("(from_date is null) and (to_date is null)")
 
 	conditions.append(
-		"ifnull(tax_category, '') = {0}".format(frappe.db.escape(cstr(args.get("tax_category"))))
+		"ifnull(tax_category, '') = {}".format(frappe.db.escape(cstr(args.get("tax_category"))))
 	)
 	if "tax_category" in args.keys():
 		del args["tax_category"]
 
 	for key, value in args.items():
 		if key == "use_for_shopping_cart":
-			conditions.append("use_for_shopping_cart = {0}".format(1 if value else 0))
+			conditions.append(f"use_for_shopping_cart = {1 if value else 0}")
 		elif key == "customer_group":
 			if not value:
 				value = get_root_of("Customer Group")
 			customer_group_condition = get_customer_group_condition(value)
-			conditions.append("ifnull({0}, '') in ('', {1})".format(key, customer_group_condition))
+			conditions.append(f"ifnull({key}, '') in ('', {customer_group_condition})")
 		else:
-			conditions.append("ifnull({0}, '') in ('', {1})".format(key, frappe.db.escape(cstr(value))))
+			conditions.append(f"ifnull({key}, '') in ('', {frappe.db.escape(cstr(value))})")
 
 	tax_rule = frappe.db.sql(
 		"""select * from `tabTax Rule`
-		where {0}""".format(
-			" and ".join(conditions)
-		),
+		where {}""".format(" and ".join(conditions)),
 		as_dict=True,
 	)
 
@@ -234,7 +228,7 @@
 	)[0]
 
 	tax_template = rule.sales_tax_template or rule.purchase_tax_template
-	doctype = "{0} Taxes and Charges Template".format(rule.tax_type)
+	doctype = f"{rule.tax_type} Taxes and Charges Template"
 
 	if frappe.db.get_value(doctype, tax_template, "disabled") == 1:
 		return None
@@ -244,9 +238,7 @@
 
 def get_customer_group_condition(customer_group):
 	condition = ""
-	customer_groups = [
-		"%s" % (frappe.db.escape(d.name)) for d in get_parent_customer_groups(customer_group)
-	]
+	customer_groups = ["%s" % (frappe.db.escape(d.name)) for d in get_parent_customer_groups(customer_group)]
 	if customer_groups:
 		condition = ",".join(["%s"] * len(customer_groups)) % (tuple(customer_groups))
 	return condition
diff --git a/erpnext/accounts/doctype/tax_withholding_category/tax_withholding_category.py b/erpnext/accounts/doctype/tax_withholding_category/tax_withholding_category.py
index 405f587..b043f9a 100644
--- a/erpnext/accounts/doctype/tax_withholding_category/tax_withholding_category.py
+++ b/erpnext/accounts/doctype/tax_withholding_category/tax_withholding_category.py
@@ -57,13 +57,11 @@
 
 	def validate_thresholds(self):
 		for d in self.get("rates"):
-			if (
-				d.cumulative_threshold and d.single_threshold and d.cumulative_threshold < d.single_threshold
-			):
+			if d.cumulative_threshold and d.single_threshold and d.cumulative_threshold < d.single_threshold:
 				frappe.throw(
-					_("Row #{0}: Cumulative threshold cannot be less than Single Transaction threshold").format(
-						d.idx
-					)
+					_(
+						"Row #{0}: Cumulative threshold cannot be less than Single Transaction threshold"
+					).format(d.idx)
 				)
 
 
@@ -319,9 +317,7 @@
 def get_invoice_vouchers(parties, tax_details, company, party_type="Supplier"):
 	doctype = "Purchase Invoice" if party_type == "Supplier" else "Sales Invoice"
 	field = (
-		"base_tax_withholding_net_total as base_net_total"
-		if party_type == "Supplier"
-		else "base_net_total"
+		"base_tax_withholding_net_total as base_net_total" if party_type == "Supplier" else "base_net_total"
 	)
 	voucher_wise_amount = {}
 	vouchers = []
@@ -375,9 +371,7 @@
 	return vouchers, voucher_wise_amount
 
 
-def get_advance_vouchers(
-	parties, company=None, from_date=None, to_date=None, party_type="Supplier"
-):
+def get_advance_vouchers(parties, company=None, from_date=None, to_date=None, party_type="Supplier"):
 	"""
 	Use Payment Ledger to fetch unallocated Advance Payments
 	"""
@@ -398,9 +392,7 @@
 	if from_date and to_date:
 		conditions.append(ple.posting_date[from_date:to_date])
 
-	advances = (
-		qb.from_(ple).select(ple.voucher_no).distinct().where(Criterion.all(conditions)).run(as_list=1)
-	)
+	advances = qb.from_(ple).select(ple.voucher_no).distinct().where(Criterion.all(conditions)).run(as_list=1)
 	if advances:
 		advances = [x[0] for x in advances]
 
@@ -566,9 +558,7 @@
 	conditions.append(ple.voucher_no == ple.against_voucher_no)
 	conditions.append(ple.company == inv.company)
 
-	advances = (
-		qb.from_(ple).select(Abs(Sum(ple.amount))).where(Criterion.all(conditions)).run(as_list=1)
-	)
+	qb.from_(ple).select(Abs(Sum(ple.amount))).where(Criterion.all(conditions)).run(as_list=1)
 
 	advance_amt = (
 		qb.from_(ple).select(Abs(Sum(ple.amount))).where(Criterion.all(conditions)).run()[0][0] or 0.0
@@ -627,9 +617,7 @@
 	return limit_consumed
 
 
-def get_lower_deduction_amount(
-	current_amount, limit_consumed, certificate_limit, rate, tax_details
-):
+def get_lower_deduction_amount(current_amount, limit_consumed, certificate_limit, rate, tax_details):
 	if certificate_limit - flt(limit_consumed) - flt(current_amount) >= 0:
 		return current_amount * rate / 100
 	else:
@@ -641,9 +629,7 @@
 
 def is_valid_certificate(ldc, posting_date, limit_consumed):
 	available_amount = flt(ldc.certificate_limit) - flt(limit_consumed)
-	if (
-		getdate(ldc.valid_from) <= getdate(posting_date) <= getdate(ldc.valid_upto)
-	) and available_amount > 0:
+	if (getdate(ldc.valid_from) <= getdate(posting_date) <= getdate(ldc.valid_upto)) and available_amount > 0:
 		return True
 
 	return False
diff --git a/erpnext/accounts/doctype/tax_withholding_category/test_tax_withholding_category.py b/erpnext/accounts/doctype/tax_withholding_category/test_tax_withholding_category.py
index 0fbaf23..087e0d0 100644
--- a/erpnext/accounts/doctype/tax_withholding_category/test_tax_withholding_category.py
+++ b/erpnext/accounts/doctype/tax_withholding_category/test_tax_withholding_category.py
@@ -95,9 +95,7 @@
 
 	def test_tax_withholding_category_checks(self):
 		invoices = []
-		frappe.db.set_value(
-			"Supplier", "Test TDS Supplier3", "tax_withholding_category", "New TDS Category"
-		)
+		frappe.db.set_value("Supplier", "Test TDS Supplier3", "tax_withholding_category", "New TDS Category")
 
 		# First Invoice with no tds check
 		pi = create_purchase_invoice(supplier="Test TDS Supplier3", rate=20000, do_not_save=True)
@@ -448,7 +446,7 @@
 		pe3.save()
 		pe3.submit()
 
-		self.assertEquals(pe3.get("taxes")[0].tax_amount, 1200)
+		self.assertEqual(pe3.get("taxes")[0].tax_amount, 1200)
 		pe1.cancel()
 		pe2.cancel()
 		pe3.cancel()
@@ -845,9 +843,7 @@
 		).insert()
 
 
-def create_lower_deduction_certificate(
-	supplier, tax_withholding_category, tax_rate, certificate_no, limit
-):
+def create_lower_deduction_certificate(supplier, tax_withholding_category, tax_rate, certificate_no, limit):
 	fiscal_year = get_fiscal_year(today(), company="_Test Company")
 	if not frappe.db.exists("Lower Deduction Certificate", certificate_no):
 		frappe.get_doc(
diff --git a/erpnext/accounts/doctype/unreconcile_payment/test_unreconcile_payment.py b/erpnext/accounts/doctype/unreconcile_payment/test_unreconcile_payment.py
index 57f66dd..882dd1d 100644
--- a/erpnext/accounts/doctype/unreconcile_payment/test_unreconcile_payment.py
+++ b/erpnext/accounts/doctype/unreconcile_payment/test_unreconcile_payment.py
@@ -93,7 +93,7 @@
 		unreconcile.add_references()
 		self.assertEqual(len(unreconcile.allocations), 2)
 		allocations = [x.reference_name for x in unreconcile.allocations]
-		self.assertEquals([si1.name, si2.name], allocations)
+		self.assertEqual([si1.name, si2.name], allocations)
 		# unreconcile si1
 		for x in unreconcile.allocations:
 			if x.reference_name != si1.name:
@@ -158,7 +158,7 @@
 		unreconcile.add_references()
 		self.assertEqual(len(unreconcile.allocations), 2)
 		allocations = [x.reference_name for x in unreconcile.allocations]
-		self.assertEquals([si1.name, si2.name], allocations)
+		self.assertEqual([si1.name, si2.name], allocations)
 		# unreconcile si1 from pe2
 		for x in unreconcile.allocations:
 			if x.reference_name != si1.name:
@@ -216,7 +216,7 @@
 		unreconcile.add_references()
 		self.assertEqual(len(unreconcile.allocations), 2)
 		allocations = [x.reference_name for x in unreconcile.allocations]
-		self.assertEquals([si1.name, si2.name], allocations)
+		self.assertEqual([si1.name, si2.name], allocations)
 		# unreconcile si1 from pe
 		for x in unreconcile.allocations:
 			if x.reference_name != si1.name:
@@ -301,7 +301,7 @@
 		unreconcile.add_references()
 		self.assertEqual(len(unreconcile.allocations), 2)
 		allocations = [x.reference_name for x in unreconcile.allocations]
-		self.assertEquals([si1.name, si2.name], allocations)
+		self.assertEqual([si1.name, si2.name], allocations)
 		# unreconcile si1 from pe2
 		for x in unreconcile.allocations:
 			if x.reference_name != si1.name:
@@ -353,7 +353,7 @@
 		unreconcile.add_references()
 		self.assertEqual(len(unreconcile.allocations), 1)
 		allocations = [x.reference_name for x in unreconcile.allocations]
-		self.assertEquals([so.name], allocations)
+		self.assertEqual([so.name], allocations)
 		# unreconcile so
 		unreconcile.save().submit()
 
diff --git a/erpnext/accounts/doctype/unreconcile_payment/unreconcile_payment.py b/erpnext/accounts/doctype/unreconcile_payment/unreconcile_payment.py
index 664622f..29eb270 100644
--- a/erpnext/accounts/doctype/unreconcile_payment/unreconcile_payment.py
+++ b/erpnext/accounts/doctype/unreconcile_payment/unreconcile_payment.py
@@ -91,7 +91,7 @@
 
 
 @frappe.whitelist()
-def doc_has_references(doctype: str = None, docname: str = None):
+def doc_has_references(doctype: str | None = None, docname: str | None = None):
 	if doctype in ["Sales Invoice", "Purchase Invoice"]:
 		return frappe.db.count(
 			"Payment Ledger Entry",
@@ -106,7 +106,7 @@
 
 @frappe.whitelist()
 def get_linked_payments_for_doc(
-	company: str = None, doctype: str = None, docname: str = None
+	company: str | None = None, doctype: str | None = None, docname: str | None = None
 ) -> list:
 	if company and doctype and docname:
 		_dt = doctype
diff --git a/erpnext/accounts/general_ledger.py b/erpnext/accounts/general_ledger.py
index 825a01e..700d777 100644
--- a/erpnext/accounts/general_ledger.py
+++ b/erpnext/accounts/general_ledger.py
@@ -78,7 +78,7 @@
 					"credit": credit,
 					"debit_in_account_currency": debit,
 					"credit_in_account_currency": credit,
-					"remarks": _("Offsetting for Accounting Dimension") + " - {0}".format(dimension.name),
+					"remarks": _("Offsetting for Accounting Dimension") + f" - {dimension.name}",
 					"against_voucher": None,
 				}
 			)
@@ -179,9 +179,7 @@
 
 
 def distribute_gl_based_on_cost_center_allocation(gl_map, precision=None):
-	cost_center_allocation = get_cost_center_allocation_data(
-		gl_map[0]["company"], gl_map[0]["posting_date"]
-	)
+	cost_center_allocation = get_cost_center_allocation_data(gl_map[0]["company"], gl_map[0]["posting_date"])
 	if not cost_center_allocation:
 		return gl_map
 
@@ -190,9 +188,7 @@
 		cost_center = d.get("cost_center")
 
 		# Validate budget against main cost center
-		validate_expense_against_budget(
-			d, expense_amount=flt(d.debit, precision) - flt(d.credit, precision)
-		)
+		validate_expense_against_budget(d, expense_amount=flt(d.debit, precision) - flt(d.credit, precision))
 
 		if cost_center and cost_center_allocation.get(cost_center):
 			for sub_cost_center, percentage in cost_center_allocation.get(cost_center, {}).items():
@@ -224,9 +220,7 @@
 
 	cc_allocation = frappe._dict()
 	for d in records:
-		cc_allocation.setdefault(d.main_cost_center, frappe._dict()).setdefault(
-			d.cost_center, d.percentage
-		)
+		cc_allocation.setdefault(d.main_cost_center, frappe._dict()).setdefault(d.cost_center, d.percentage)
 
 	return cc_allocation
 
@@ -541,9 +535,7 @@
 			round_off_gle[dimension] = dimension_values.get(dimension)
 
 
-def get_round_off_account_and_cost_center(
-	company, voucher_type, voucher_no, use_company_default=False
-):
+def get_round_off_account_and_cost_center(company, voucher_type, voucher_no, use_company_default=False):
 	round_off_account, round_off_cost_center = frappe.get_cached_value(
 		"Company", company, ["round_off_account", "round_off_cost_center"]
 	) or [None, None]
@@ -678,9 +670,7 @@
 
 
 def validate_against_pcv(is_opening, posting_date, company):
-	if is_opening and frappe.db.exists(
-		"Period Closing Voucher", {"docstatus": 1, "company": company}
-	):
+	if is_opening and frappe.db.exists("Period Closing Voucher", {"docstatus": 1, "company": company}):
 		frappe.throw(
 			_("Opening Entry can not be created after Period Closing Voucher is created."),
 			title=_("Invalid Opening Entry"),
@@ -691,9 +681,7 @@
 	)
 
 	if last_pcv_date and getdate(posting_date) <= getdate(last_pcv_date):
-		message = _("Books have been closed till the period ending on {0}").format(
-			formatdate(last_pcv_date)
-		)
+		message = _("Books have been closed till the period ending on {0}").format(formatdate(last_pcv_date))
 		message += "</br >"
 		message += _("You cannot create/amend any accounting entries till this date.")
 		frappe.throw(message, title=_("Period Closed"))
diff --git a/erpnext/accounts/party.py b/erpnext/accounts/party.py
index 4b3f0c8..85fe605 100644
--- a/erpnext/accounts/party.py
+++ b/erpnext/accounts/party.py
@@ -2,8 +2,6 @@
 # License: GNU General Public License v3. See license.txt
 
 
-from typing import Optional
-
 import frappe
 from frappe import _, msgprint, qb, scrub
 from frappe.contacts.doctype.address.address import get_company_address, get_default_address
@@ -69,7 +67,6 @@
 	shipping_address=None,
 	pos_profile=None,
 ):
-
 	if not party:
 		return {}
 	if not frappe.db.exists(party_type, party):
@@ -153,9 +150,7 @@
 		party_details["taxes_and_charges"] = tax_template
 
 	if cint(fetch_payment_terms_template):
-		party_details["payment_terms_template"] = get_payment_terms_template(
-			party.name, party_type, company
-		)
+		party_details["payment_terms_template"] = get_payment_terms_template(party.name, party_type, company)
 
 	if not party_details.get("currency"):
 		party_details["currency"] = currency
@@ -173,9 +168,7 @@
 
 	# supplier tax withholding category
 	if party_type == "Supplier" and party:
-		party_details["supplier_tds"] = frappe.get_value(
-			party_type, party.name, "tax_withholding_category"
-		)
+		party_details["supplier_tds"] = frappe.get_value(party_type, party.name, "tax_withholding_category")
 
 	if not party_details.get("tax_category") and pos_profile:
 		party_details["tax_category"] = frappe.get_value("POS Profile", pos_profile, "tax_category")
@@ -195,12 +188,8 @@
 	*,
 	ignore_permissions=False,
 ):
-	billing_address_field = (
-		"customer_address" if party_type == "Lead" else party_type.lower() + "_address"
-	)
-	party_details[billing_address_field] = party_address or get_default_address(
-		party_type, party.name
-	)
+	billing_address_field = "customer_address" if party_type == "Lead" else party_type.lower() + "_address"
+	party_details[billing_address_field] = party_address or get_default_address(party_type, party.name)
 	if doctype:
 		party_details.update(
 			get_fetch_values(doctype, billing_address_field, party_details[billing_address_field])
@@ -306,9 +295,7 @@
 			"department as contact_department",
 		]
 
-		contact_details = frappe.db.get_value(
-			"Contact", party_details.contact_person, fields, as_dict=True
-		)
+		contact_details = frappe.db.get_value("Contact", party_details.contact_person, fields, as_dict=True)
 
 		party_details.update(contact_details)
 
@@ -328,9 +315,7 @@
 		party_details[f] = party.get(f)
 
 	# fields prepended with default in Customer doctype
-	for f in ["currency"] + (
-		["sales_partner", "commission_rate"] if party_type == "Customer" else []
-	):
+	for f in ["currency"] + (["sales_partner", "commission_rate"] if party_type == "Customer" else []):
 		if party.get("default_" + f):
 			party_details[f] = party.get("default_" + f)
 
@@ -367,14 +352,10 @@
 			"Price List", price_list, "currency", cache=True
 		)
 
-	party_details[
-		"selling_price_list" if party.doctype == "Customer" else "buying_price_list"
-	] = price_list
+	party_details["selling_price_list" if party.doctype == "Customer" else "buying_price_list"] = price_list
 
 
-def set_account_and_due_date(
-	party, account, party_type, company, posting_date, bill_date, doctype
-):
+def set_account_and_due_date(party, account, party_type, company, posting_date, bill_date, doctype):
 	if doctype not in ["POS Invoice", "Sales Invoice", "Purchase Invoice"]:
 		# not an invoice
 		return {party_type.lower(): party}
@@ -462,9 +443,7 @@
 
 	if not account:
 		account_name = (
-			"default_advance_received_account"
-			if party_type == "Customer"
-			else "default_advance_paid_account"
+			"default_advance_received_account" if party_type == "Customer" else "default_advance_paid_account"
 		)
 		account = frappe.get_cached_value("Company", company, account_name)
 
@@ -473,9 +452,7 @@
 
 @frappe.whitelist()
 def get_party_bank_account(party_type, party):
-	return frappe.db.get_value(
-		"Bank Account", {"party_type": party_type, "party": party, "is_default": 1}
-	)
+	return frappe.db.get_value("Bank Account", {"party_type": party_type, "party": party, "is_default": 1})
 
 
 def get_party_account_currency(party_type, party, company):
@@ -567,9 +544,7 @@
 				"Company", frappe.db.get_default("Company"), "default_currency"
 			)
 		else:
-			company_default_currency = frappe.get_cached_value(
-				"Company", account.company, "default_currency"
-			)
+			company_default_currency = frappe.get_cached_value("Company", account.company, "default_currency")
 
 		validate_party_gle_currency(doc.doctype, doc.name, account.company, party_account_currency)
 
@@ -600,9 +575,7 @@
 		template_name = get_payment_terms_template(party, party_type, company)
 
 		if template_name:
-			due_date = get_due_date_from_template(template_name, posting_date, bill_date).strftime(
-				"%Y-%m-%d"
-			)
+			due_date = get_due_date_from_template(template_name, posting_date, bill_date).strftime("%Y-%m-%d")
 		else:
 			if party_type == "Supplier":
 				supplier_group = frappe.get_cached_value(party_type, party, "supplier_group")
@@ -761,7 +734,6 @@
 
 
 def validate_party_frozen_disabled(party_type, party_name):
-
 	if frappe.flags.ignore_party_validation:
 		return
 
@@ -897,9 +869,7 @@
 		party_account_currency = get_party_account_currency(party_type, party, d.company)
 
 		if party_account_currency == company_default_currency:
-			billing_this_year = flt(
-				company_wise_billing_this_year.get(d.company, {}).get("base_grand_total")
-			)
+			billing_this_year = flt(company_wise_billing_this_year.get(d.company, {}).get("base_grand_total"))
 		else:
 			billing_this_year = flt(company_wise_billing_this_year.get(d.company, {}).get("grand_total"))
 
@@ -925,7 +895,7 @@
 	return company_wise_info
 
 
-def get_party_shipping_address(doctype: str, name: str) -> Optional[str]:
+def get_party_shipping_address(doctype: str, name: str) -> str | None:
 	"""
 	Returns an Address name (best guess) for the given doctype and name for which `address_type == 'Shipping'` is true.
 	and/or `is_shipping_address = 1`.
@@ -991,7 +961,7 @@
 		return frappe._dict(data)
 
 
-def get_default_contact(doctype: str, name: str) -> Optional[str]:
+def get_default_contact(doctype: str, name: str) -> str | None:
 	"""
 	Returns contact name only if there is a primary contact for given doctype and name.
 
diff --git a/erpnext/accounts/report/account_balance/account_balance.py b/erpnext/accounts/report/account_balance/account_balance.py
index b3e80a7..628aca5 100644
--- a/erpnext/accounts/report/account_balance/account_balance.py
+++ b/erpnext/accounts/report/account_balance/account_balance.py
@@ -61,7 +61,6 @@
 
 
 def get_data(filters):
-
 	data = []
 	conditions = get_conditions(filters)
 	accounts = frappe.db.get_all(
diff --git a/erpnext/accounts/report/accounts_payable/test_accounts_payable.py b/erpnext/accounts/report/accounts_payable/test_accounts_payable.py
index b4cb25f..f5c9d16 100644
--- a/erpnext/accounts/report/accounts_payable/test_accounts_payable.py
+++ b/erpnext/accounts/report/accounts_payable/test_accounts_payable.py
@@ -1,16 +1,10 @@
-import unittest
-
 import frappe
-from frappe.tests.utils import FrappeTestCase, change_settings
-from frappe.utils import add_days, flt, getdate, today
+from frappe.tests.utils import FrappeTestCase
+from frappe.utils import today
 
-from erpnext import get_default_cost_center
-from erpnext.accounts.doctype.payment_entry.payment_entry import get_payment_entry
 from erpnext.accounts.doctype.purchase_invoice.test_purchase_invoice import make_purchase_invoice
-from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice
 from erpnext.accounts.report.accounts_payable.accounts_payable import execute
 from erpnext.accounts.test.accounts_mixin import AccountsTestMixin
-from erpnext.selling.doctype.sales_order.test_sales_order import make_sales_order
 
 
 class TestAccountsReceivable(AccountsTestMixin, FrappeTestCase):
diff --git a/erpnext/accounts/report/accounts_receivable/accounts_receivable.py b/erpnext/accounts/report/accounts_receivable/accounts_receivable.py
index 38723e9..c7862c1 100644
--- a/erpnext/accounts/report/accounts_receivable/accounts_receivable.py
+++ b/erpnext/accounts/report/accounts_receivable/accounts_receivable.py
@@ -40,24 +40,20 @@
 	return ReceivablePayableReport(filters).run(args)
 
 
-class ReceivablePayableReport(object):
+class ReceivablePayableReport:
 	def __init__(self, filters=None):
 		self.filters = frappe._dict(filters or {})
 		self.qb_selection_filter = []
 		self.ple = qb.DocType("Payment Ledger Entry")
 		self.filters.report_date = getdate(self.filters.report_date or nowdate())
 		self.age_as_on = (
-			getdate(nowdate())
-			if self.filters.report_date > getdate(nowdate())
-			else self.filters.report_date
+			getdate(nowdate()) if self.filters.report_date > getdate(nowdate()) else self.filters.report_date
 		)
 
 	def run(self, args):
 		self.filters.update(args)
 		self.set_defaults()
-		self.party_naming_by = frappe.db.get_single_value(
-			args.get("naming_by")[0], args.get("naming_by")[1]
-		)
+		self.party_naming_by = frappe.db.get_single_value(args.get("naming_by")[0], args.get("naming_by")[1])
 		self.get_columns()
 		self.get_data()
 		self.get_chart_data()
@@ -279,7 +275,7 @@
 	def build_data(self):
 		# set outstanding for all the accumulated balances
 		# as we can use this to filter out invoices without outstanding
-		for key, row in self.voucher_balance.items():
+		for _key, row in self.voucher_balance.items():
 			row.outstanding = flt(row.invoiced - row.paid - row.credit_note, self.currency_precision)
 			row.outstanding_in_account_currency = flt(
 				row.invoiced_in_account_currency
@@ -293,7 +289,7 @@
 			must_consider = False
 			if self.filters.get("for_revaluation_journals"):
 				if (abs(row.outstanding) > 0.0 / 10**self.currency_precision) or (
-					(abs(row.outstanding_in_account_currency) > 0.0 / 10**self.currency_precision)
+					abs(row.outstanding_in_account_currency) > 0.0 / 10**self.currency_precision
 				):
 					must_consider = True
 			else:
@@ -479,19 +475,17 @@
 	def get_payment_terms(self, row):
 		# build payment_terms for row
 		payment_terms_details = frappe.db.sql(
-			"""
+			f"""
 			select
 				si.name, si.party_account_currency, si.currency, si.conversion_rate,
 				si.total_advance, ps.due_date, ps.payment_term, ps.payment_amount, ps.base_payment_amount,
 				ps.description, ps.paid_amount, ps.discounted_amount
-			from `tab{0}` si, `tabPayment Schedule` ps
+			from `tab{row.voucher_type}` si, `tabPayment Schedule` ps
 			where
 				si.name = ps.parent and
 				si.name = %s
 			order by ps.paid_amount desc, due_date
-		""".format(
-				row.voucher_type
-			),
+		""",
 			row.voucher_no,
 			as_dict=1,
 		)
@@ -735,9 +729,7 @@
 		row.age = (getdate(self.age_as_on) - getdate(entry_date)).days or 0
 		index = None
 
-		if not (
-			self.filters.range1 and self.filters.range2 and self.filters.range3 and self.filters.range4
-		):
+		if not (self.filters.range1 and self.filters.range2 and self.filters.range3 and self.filters.range4):
 			self.filters.range1, self.filters.range2, self.filters.range3, self.filters.range4 = (
 				30,
 				60,
@@ -763,12 +755,10 @@
 
 		if self.filters.show_future_payments:
 			self.qb_selection_filter.append(
-				(
-					self.ple.posting_date.lte(self.filters.report_date)
-					| (
-						(self.ple.voucher_no == self.ple.against_voucher_no)
-						& (Date(self.ple.creation).lte(self.filters.report_date))
-					)
+				self.ple.posting_date.lte(self.filters.report_date)
+				| (
+					(self.ple.voucher_no == self.ple.against_voucher_no)
+					& (Date(self.ple.creation).lte(self.filters.report_date))
 				)
 			)
 		else:
@@ -836,7 +826,7 @@
 		self.qb_selection_filter = []
 		self.or_filters = []
 
-		for party_type in self.party_type:
+		for _party_type in self.party_type:
 			self.add_common_filters()
 
 			if self.account_type == "Receivable":
diff --git a/erpnext/accounts/report/accounts_receivable/test_accounts_receivable.py b/erpnext/accounts/report/accounts_receivable/test_accounts_receivable.py
index de49139..83d95de 100644
--- a/erpnext/accounts/report/accounts_receivable/test_accounts_receivable.py
+++ b/erpnext/accounts/report/accounts_receivable/test_accounts_receivable.py
@@ -1,11 +1,8 @@
-import unittest
-
 import frappe
 from frappe import qb
 from frappe.tests.utils import FrappeTestCase, change_settings
 from frappe.utils import add_days, flt, getdate, today
 
-from erpnext import get_default_cost_center
 from erpnext.accounts.doctype.payment_entry.payment_entry import get_payment_entry
 from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice
 from erpnext.accounts.report.accounts_receivable.accounts_receivable import execute
@@ -126,7 +123,6 @@
 
 		# check invoice grand total and invoiced column's value for 3 payment terms
 		si = self.create_sales_invoice()
-		name = si.name
 
 		report = execute(filters)
 
@@ -218,7 +214,7 @@
 			[0, 0, 100.0, 0.0, -100.0, cr_note.name],
 		]
 		self.assertEqual(len(report[1]), 2)
-		si_row = [
+		si_row = next(
 			[
 				row.invoice_grand_total,
 				row.invoiced,
@@ -229,9 +225,9 @@
 			]
 			for row in report[1]
 			if row.voucher_no == si.name
-		][0]
+		)
 
-		cr_note_row = [
+		cr_note_row = next(
 			[
 				row.invoice_grand_total,
 				row.invoiced,
@@ -242,7 +238,7 @@
 			]
 			for row in report[1]
 			if row.voucher_no == cr_note.name
-		][0]
+		)
 		self.assertEqual(expected_data_after_credit_note[0], si_row)
 		self.assertEqual(expected_data_after_credit_note[1], cr_note_row)
 
@@ -317,9 +313,7 @@
 		err.extend("accounts", accounts)
 		err.accounts[0].new_exchange_rate = 85
 		row = err.accounts[0]
-		row.new_balance_in_base_currency = flt(
-			row.new_exchange_rate * flt(row.balance_in_account_currency)
-		)
+		row.new_balance_in_base_currency = flt(row.new_exchange_rate * flt(row.balance_in_account_currency))
 		row.gain_loss = row.new_balance_in_base_currency - flt(row.balance_in_base_currency)
 		err.set_total_gain_loss()
 		err = err.save().submit()
@@ -340,7 +334,7 @@
 		report = execute(filters)
 
 		expected_data_for_err = [0, -500, 0, 500]
-		row = [x for x in report[1] if x.voucher_type == je.doctype and x.voucher_no == je.name][0]
+		row = next(x for x in report[1] if x.voucher_type == je.doctype and x.voucher_no == je.name)
 		self.assertEqual(
 			expected_data_for_err,
 			[
@@ -551,7 +545,7 @@
 		self.assertEqual(expected_data, [row.invoiced, row.outstanding, row.sales_person])
 
 	def test_cost_center_filter(self):
-		si = self.create_sales_invoice()
+		self.create_sales_invoice()
 		filters = {
 			"company": self.company,
 			"report_date": today(),
@@ -568,7 +562,7 @@
 		self.assertEqual(expected_data, [row.invoiced, row.outstanding, row.cost_center])
 
 	def test_customer_group_filter(self):
-		si = self.create_sales_invoice()
+		self.create_sales_invoice()
 		cus_group = frappe.db.get_value("Customer", self.customer, "customer_group")
 		filters = {
 			"company": self.company,
@@ -590,7 +584,7 @@
 		self.assertEqual(len(report), 0)
 
 	def test_multi_customer_group_filter(self):
-		si = self.create_sales_invoice()
+		self.create_sales_invoice()
 		cus_group = frappe.db.get_value("Customer", self.customer, "customer_group")
 		# Create a list of customer groups, e.g., ["Group1", "Group2"]
 		cus_groups_list = [cus_group, "_Test Customer Group 1"]
@@ -703,7 +697,6 @@
 		si.conversion_rate = 80
 		si.debit_to = self.debtors_usd
 		si.save().submit()
-		name = si.name
 
 		# check invoice grand total and invoiced column's value for 3 payment terms
 		report = execute(filters)
@@ -763,9 +756,7 @@
 
 	def test_report_output_if_party_is_missing(self):
 		acc_name = "Additional Debtors"
-		if not frappe.db.get_value(
-			"Account", filters={"account_name": acc_name, "company": self.company}
-		):
+		if not frappe.db.get_value("Account", filters={"account_name": acc_name, "company": self.company}):
 			additional_receivable_acc = frappe.get_doc(
 				{
 					"doctype": "Account",
diff --git a/erpnext/accounts/report/accounts_receivable_summary/accounts_receivable_summary.py b/erpnext/accounts/report/accounts_receivable_summary/accounts_receivable_summary.py
index 0947cff..1aab7f7 100644
--- a/erpnext/accounts/report/accounts_receivable_summary/accounts_receivable_summary.py
+++ b/erpnext/accounts/report/accounts_receivable_summary/accounts_receivable_summary.py
@@ -24,9 +24,7 @@
 	def run(self, args):
 		self.account_type = args.get("account_type")
 		self.party_type = get_party_types_from_account_type(self.account_type)
-		self.party_naming_by = frappe.db.get_single_value(
-			args.get("naming_by")[0], args.get("naming_by")[1]
-		)
+		self.party_naming_by = frappe.db.get_single_value(args.get("naming_by")[0], args.get("naming_by")[1])
 		self.get_columns()
 		self.get_data(args)
 		return self.columns, self.data
diff --git a/erpnext/accounts/report/accounts_receivable_summary/test_accounts_receivable_summary.py b/erpnext/accounts/report/accounts_receivable_summary/test_accounts_receivable_summary.py
index 3ee35a1..4ef607b 100644
--- a/erpnext/accounts/report/accounts_receivable_summary/test_accounts_receivable_summary.py
+++ b/erpnext/accounts/report/accounts_receivable_summary/test_accounts_receivable_summary.py
@@ -1,5 +1,3 @@
-import unittest
-
 import frappe
 from frappe.tests.utils import FrappeTestCase, change_settings
 from frappe.utils import today
diff --git a/erpnext/accounts/report/asset_depreciations_and_balances/asset_depreciations_and_balances.py b/erpnext/accounts/report/asset_depreciations_and_balances/asset_depreciations_and_balances.py
index 48da17a..4fa485f 100644
--- a/erpnext/accounts/report/asset_depreciations_and_balances/asset_depreciations_and_balances.py
+++ b/erpnext/accounts/report/asset_depreciations_and_balances/asset_depreciations_and_balances.py
@@ -70,7 +70,7 @@
 	if filters.get("asset_category"):
 		condition += " and asset_category = %(asset_category)s"
 	return frappe.db.sql(
-		"""
+		f"""
 		SELECT asset_category,
 			   ifnull(sum(case when purchase_date < %(from_date)s then
 							   case when ifnull(disposal_date, 0) = 0 or disposal_date >= %(from_date)s then
@@ -109,11 +109,9 @@
 								0
 						   end), 0) as cost_of_scrapped_asset
 		from `tabAsset`
-		where docstatus=1 and company=%(company)s and purchase_date <= %(to_date)s {}
+		where docstatus=1 and company=%(company)s and purchase_date <= %(to_date)s {condition}
 		group by asset_category
-	""".format(
-			condition
-		),
+	""",
 		{
 			"to_date": filters.to_date,
 			"from_date": filters.from_date,
@@ -129,7 +127,7 @@
 	if filters.get("asset"):
 		condition += " and name = %(asset)s"
 	return frappe.db.sql(
-		"""
+		f"""
 		SELECT name,
 			   ifnull(sum(case when purchase_date < %(from_date)s then
 							   case when ifnull(disposal_date, 0) = 0 or disposal_date >= %(from_date)s then
@@ -168,11 +166,9 @@
 								0
 						   end), 0) as cost_of_scrapped_asset
 		from `tabAsset`
-		where docstatus=1 and company=%(company)s and purchase_date <= %(to_date)s {}
+		where docstatus=1 and company=%(company)s and purchase_date <= %(to_date)s {condition}
 		group by name
-	""".format(
-			condition
-		),
+	""",
 		{
 			"to_date": filters.to_date,
 			"from_date": filters.from_date,
@@ -276,9 +272,7 @@
 			where a.docstatus=1 and a.company=%(company)s and a.purchase_date <= %(to_date)s {0}
 			group by a.asset_category) as results
 		group by results.asset_category
-		""".format(
-			condition
-		),
+		""".format(condition),
 		{"to_date": filters.to_date, "from_date": filters.from_date, "company": filters.company},
 		as_dict=1,
 	)
@@ -338,9 +332,7 @@
 			where a.docstatus=1 and a.company=%(company)s and a.purchase_date <= %(to_date)s {0}
 			group by a.name) as results
 		group by results.name
-		""".format(
-			condition
-		),
+		""".format(condition),
 		{"to_date": filters.to_date, "from_date": filters.from_date, "company": filters.company},
 		as_dict=1,
 	)
diff --git a/erpnext/accounts/report/balance_sheet/balance_sheet.py b/erpnext/accounts/report/balance_sheet/balance_sheet.py
index d45dc07..b2e55b6 100644
--- a/erpnext/accounts/report/balance_sheet/balance_sheet.py
+++ b/erpnext/accounts/report/balance_sheet/balance_sheet.py
@@ -180,7 +180,6 @@
 	filters,
 	consolidated=False,
 ):
-
 	net_asset, net_liability, net_equity, net_provisional_profit_loss = 0.0, 0.0, 0.0, 0.0
 
 	if filters.get("accumulated_values"):
diff --git a/erpnext/accounts/report/bank_clearance_summary/bank_clearance_summary.py b/erpnext/accounts/report/bank_clearance_summary/bank_clearance_summary.py
index 7e0bdea..ae67567 100644
--- a/erpnext/accounts/report/bank_clearance_summary/bank_clearance_summary.py
+++ b/erpnext/accounts/report/bank_clearance_summary/bank_clearance_summary.py
@@ -83,31 +83,27 @@
 	conditions = get_conditions(filters)
 
 	journal_entries = frappe.db.sql(
-		"""SELECT
+		f"""SELECT
 			"Journal Entry", jv.name, jv.posting_date, jv.cheque_no,
 			jv.clearance_date, jvd.against_account, jvd.debit - jvd.credit
 		FROM
 			`tabJournal Entry Account` jvd, `tabJournal Entry` jv
 		WHERE
-			jvd.parent = jv.name and jv.docstatus=1 and jvd.account = %(account)s {0}
-			order by posting_date DESC, jv.name DESC""".format(
-			conditions
-		),
+			jvd.parent = jv.name and jv.docstatus=1 and jvd.account = %(account)s {conditions}
+			order by posting_date DESC, jv.name DESC""",
 		filters,
 		as_list=1,
 	)
 
 	payment_entries = frappe.db.sql(
-		"""SELECT
+		f"""SELECT
 			"Payment Entry", name, posting_date, reference_no, clearance_date, party,
 			if(paid_from=%(account)s, ((paid_amount * -1) - total_taxes_and_charges) , received_amount)
 		FROM
 			`tabPayment Entry`
 		WHERE
-			docstatus=1 and (paid_from = %(account)s or paid_to = %(account)s) {0}
-			order by posting_date DESC, name DESC""".format(
-			conditions
-		),
+			docstatus=1 and (paid_from = %(account)s or paid_to = %(account)s) {conditions}
+			order by posting_date DESC, name DESC""",
 		filters,
 		as_list=1,
 	)
diff --git a/erpnext/accounts/report/bank_reconciliation_statement/bank_reconciliation_statement.py b/erpnext/accounts/report/bank_reconciliation_statement/bank_reconciliation_statement.py
index 206654c..8a8e3a5 100644
--- a/erpnext/accounts/report/bank_reconciliation_statement/bank_reconciliation_statement.py
+++ b/erpnext/accounts/report/bank_reconciliation_statement/bank_reconciliation_statement.py
@@ -32,10 +32,7 @@
 	amounts_not_reflected_in_system = get_amounts_not_reflected_in_system(filters)
 
 	bank_bal = (
-		flt(balance_as_per_system)
-		- flt(total_debit)
-		+ flt(total_credit)
-		+ amounts_not_reflected_in_system
+		flt(balance_as_per_system) - flt(total_debit) + flt(total_credit) + amounts_not_reflected_in_system
 	)
 
 	data += [
diff --git a/erpnext/accounts/report/billed_items_to_be_received/billed_items_to_be_received.py b/erpnext/accounts/report/billed_items_to_be_received/billed_items_to_be_received.py
index 62bee82..f6efc8a 100644
--- a/erpnext/accounts/report/billed_items_to_be_received/billed_items_to_be_received.py
+++ b/erpnext/accounts/report/billed_items_to_be_received/billed_items_to_be_received.py
@@ -30,9 +30,7 @@
 	]
 
 	if report_filters.get("purchase_invoice"):
-		filters.append(
-			["Purchase Invoice", "per_received", "in", [report_filters.get("purchase_invoice")]]
-		)
+		filters.append(["Purchase Invoice", "per_received", "in", [report_filters.get("purchase_invoice")]])
 
 	return filters
 
@@ -40,10 +38,10 @@
 def get_report_fields():
 	fields = []
 	for p_field in ["name", "supplier", "company", "posting_date", "currency"]:
-		fields.append("`tabPurchase Invoice`.`{}`".format(p_field))
+		fields.append(f"`tabPurchase Invoice`.`{p_field}`")
 
 	for c_field in ["item_code", "item_name", "uom", "qty", "received_qty", "rate", "amount"]:
-		fields.append("`tabPurchase Invoice Item`.`{}`".format(c_field))
+		fields.append(f"`tabPurchase Invoice Item`.`{c_field}`")
 
 	return fields
 
diff --git a/erpnext/accounts/report/budget_variance_report/budget_variance_report.py b/erpnext/accounts/report/budget_variance_report/budget_variance_report.py
index 96cfab9..e540aa9 100644
--- a/erpnext/accounts/report/budget_variance_report/budget_variance_report.py
+++ b/erpnext/accounts/report/budget_variance_report/budget_variance_report.py
@@ -112,7 +112,9 @@
 				]:
 					if group_months:
 						label = label % (
-							formatdate(from_date, format_string="MMM") + "-" + formatdate(to_date, format_string="MMM")
+							formatdate(from_date, format_string="MMM")
+							+ "-"
+							+ formatdate(to_date, format_string="MMM")
 						)
 					else:
 						label = label % formatdate(from_date, format_string="MMM")
@@ -147,9 +149,7 @@
 				where
 					company = %s
 				{order_by}
-			""".format(
-				tab=filters.get("budget_against"), order_by=order_by
-			),
+			""".format(tab=filters.get("budget_against"), order_by=order_by),
 			filters.get("company"),
 		)
 	else:
@@ -159,9 +159,7 @@
 					name
 				from
 					`tab{tab}`
-			""".format(
-				tab=filters.get("budget_against")
-			)
+			""".format(tab=filters.get("budget_against"))
 		)  # nosec
 
 
@@ -170,12 +168,12 @@
 	budget_against = frappe.scrub(filters.get("budget_against"))
 	cond = ""
 	if filters.get("budget_against_filter"):
-		cond += """ and b.{budget_against} in (%s)""".format(budget_against=budget_against) % ", ".join(
+		cond += f""" and b.{budget_against} in (%s)""" % ", ".join(
 			["%s"] * len(filters.get("budget_against_filter"))
 		)
 
 	return frappe.db.sql(
-		"""
+		f"""
 			select
 				b.{budget_against} as budget_against,
 				b.monthly_distribution,
@@ -194,10 +192,7 @@
 				{cond}
 			order by
 				b.fiscal_year
-		""".format(
-			budget_against=budget_against,
-			cond=cond,
-		),
+		""",
 		tuple(
 			[
 				filters.from_fiscal_year,
@@ -244,15 +239,13 @@
 
 	if filters.get("budget_against") == "Cost Center":
 		cc_lft, cc_rgt = frappe.db.get_value("Cost Center", name, ["lft", "rgt"])
-		cond = """
-				and lft >= "{lft}"
-				and rgt <= "{rgt}"
-			""".format(
-			lft=cc_lft, rgt=cc_rgt
-		)
+		cond = f"""
+				and lft >= "{cc_lft}"
+				and rgt <= "{cc_rgt}"
+			"""
 
 	ac_details = frappe.db.sql(
-		"""
+		f"""
 			select
 				gl.account,
 				gl.debit,
@@ -275,7 +268,7 @@
 					select
 						name
 					from
-						`tab{tab}`
+						`tab{filters.budget_against}`
 					where
 						name = gl.{budget_against}
 						{cond}
@@ -283,9 +276,7 @@
 				group by
 					gl.name
 				order by gl.fiscal_year
-		""".format(
-			tab=filters.budget_against, budget_against=budget_against, cond=cond
-		),
+		""",
 		(filters.from_fiscal_year, filters.to_fiscal_year, name),
 		as_dict=1,
 	)
@@ -314,7 +305,9 @@
 
 			tav_dict = cam_map[ccd.budget_against][ccd.account][ccd.fiscal_year][month]
 			month_percentage = (
-				tdd.get(ccd.monthly_distribution, {}).get(month, 0) if ccd.monthly_distribution else 100.0 / 12
+				tdd.get(ccd.monthly_distribution, {}).get(month, 0)
+				if ccd.monthly_distribution
+				else 100.0 / 12
 			)
 
 			tav_dict.target = flt(ccd.budget_amount) * month_percentage / 100
@@ -327,7 +320,6 @@
 
 
 def get_fiscal_years(filters):
-
 	fiscal_year = frappe.db.sql(
 		"""
 			select
@@ -344,7 +336,6 @@
 
 
 def get_chart_data(filters, columns, data):
-
 	if not data:
 		return None
 
@@ -360,7 +351,9 @@
 			else:
 				if group_months:
 					label = (
-						formatdate(from_date, format_string="MMM") + "-" + formatdate(to_date, format_string="MMM")
+						formatdate(from_date, format_string="MMM")
+						+ "-"
+						+ formatdate(to_date, format_string="MMM")
 					)
 					labels.append(label)
 				else:
diff --git a/erpnext/accounts/report/cash_flow/cash_flow.py b/erpnext/accounts/report/cash_flow/cash_flow.py
index d3b0692..c034f95 100644
--- a/erpnext/accounts/report/cash_flow/cash_flow.py
+++ b/erpnext/accounts/report/cash_flow/cash_flow.py
@@ -109,9 +109,7 @@
 	add_total_row_account(
 		data, data, _("Net Change in Cash"), period_list, company_currency, summary_data, filters
 	)
-	columns = get_columns(
-		filters.periodicity, period_list, filters.accumulated_values, filters.company
-	)
+	columns = get_columns(filters.periodicity, period_list, filters.accumulated_values, filters.company)
 
 	chart = get_chart_data(columns, data)
 
@@ -178,8 +176,8 @@
 
 	if filters.include_default_book_entries:
 		company_fb = frappe.get_cached_value("Company", company, "default_finance_book")
-		cond = """ AND (finance_book in (%s, %s, '') OR finance_book IS NULL)
-			""" % (
+		cond = """ AND (finance_book in ({}, {}, '') OR finance_book IS NULL)
+			""".format(
 			frappe.db.escape(filters.finance_book),
 			frappe.db.escape(company_fb),
 		)
@@ -193,15 +191,13 @@
 		cond += " and cost_center in %(cost_center)s"
 
 	gl_sum = frappe.db.sql_list(
-		"""
+		f"""
 		select sum(credit) - sum(debit)
 		from `tabGL Entry`
 		where company=%(company)s and posting_date >= %(start_date)s and posting_date <= %(end_date)s
 			and voucher_type != 'Period Closing Voucher'
 			and account in ( SELECT name FROM tabAccount WHERE account_type = %(account_type)s) {cond}
-	""".format(
-			cond=cond
-		),
+	""",
 		filters,
 	)
 
@@ -219,9 +215,7 @@
 	return start_date
 
 
-def add_total_row_account(
-	out, data, label, period_list, currency, summary_data, filters, consolidated=False
-):
+def add_total_row_account(out, data, label, period_list, currency, summary_data, filters, consolidated=False):
 	total_row = {
 		"account_name": "'" + _("{0}").format(label) + "'",
 		"account": "'" + _("{0}").format(label) + "'",
@@ -253,9 +247,7 @@
 	report_summary = []
 
 	for label, value in summary_data.items():
-		report_summary.append(
-			{"value": value, "label": label, "datatype": "Currency", "currency": currency}
-		)
+		report_summary.append({"value": value, "label": label, "datatype": "Currency", "currency": currency})
 
 	return report_summary
 
@@ -268,7 +260,7 @@
 			"values": [account.get(d.get("fieldname")) for d in columns[2:]],
 		}
 		for account in data
-		if account.get("parent_account") == None and account.get("currency")
+		if account.get("parent_account") is None and account.get("currency")
 	]
 	datasets = datasets[:-1]
 
diff --git a/erpnext/accounts/report/consolidated_financial_statement/consolidated_financial_statement.py b/erpnext/accounts/report/consolidated_financial_statement/consolidated_financial_statement.py
index 0051ba6..b20f3b3 100644
--- a/erpnext/accounts/report/consolidated_financial_statement/consolidated_financial_statement.py
+++ b/erpnext/accounts/report/consolidated_financial_statement/consolidated_financial_statement.py
@@ -55,9 +55,7 @@
 			fiscal_year, companies, columns, filters
 		)
 	elif filters.get("report") == "Profit and Loss Statement":
-		data, message, chart, report_summary = get_profit_loss_data(
-			fiscal_year, companies, columns, filters
-		)
+		data, message, chart, report_summary = get_profit_loss_data(fiscal_year, companies, columns, filters)
 	else:
 		data, report_summary = get_cash_flow_data(fiscal_year, companies, filters)
 
@@ -81,9 +79,7 @@
 		asset, liability, equity, companies, filters.get("company"), company_currency, True
 	)
 
-	message, opening_balance = prepare_companywise_opening_balance(
-		asset, liability, equity, companies
-	)
+	message, opening_balance = prepare_companywise_opening_balance(asset, liability, equity, companies)
 
 	if opening_balance:
 		unclosed = {
@@ -192,9 +188,7 @@
 
 	expense = get_data(companies, "Expense", "Debit", fiscal_year, filters, True)
 
-	net_profit_loss = get_net_profit_loss(
-		income, expense, companies, filters.company, company_currency, True
-	)
+	net_profit_loss = get_net_profit_loss(income, expense, companies, filters.company, company_currency, True)
 
 	return income, expense, net_profit_loss
 
@@ -323,9 +317,7 @@
 	return columns
 
 
-def get_data(
-	companies, root_type, balance_must_be, fiscal_year, filters=None, ignore_closing_entries=False
-):
+def get_data(companies, root_type, balance_must_be, fiscal_year, filters=None, ignore_closing_entries=False):
 	accounts, accounts_by_name, parent_children_map = get_account_heads(root_type, companies, filters)
 
 	if not accounts:
@@ -349,7 +341,6 @@
 		root_type,
 		as_dict=1,
 	):
-
 		set_gl_entries_by_account(
 			start_date,
 			end_date,
@@ -366,9 +357,7 @@
 	calculate_values(accounts_by_name, gl_entries_by_account, companies, filters, fiscal_year)
 	accumulate_values_into_parents(accounts, accounts_by_name, companies)
 
-	out = prepare_data(
-		accounts, start_date, end_date, balance_must_be, companies, company_currency, filters
-	)
+	out = prepare_data(accounts, start_date, end_date, balance_must_be, companies, company_currency, filters)
 
 	out = filter_out_zero_value_rows(
 		out, parent_children_map, show_zero_values=filters.get("show_zero_values")
@@ -388,9 +377,7 @@
 
 def calculate_values(accounts_by_name, gl_entries_by_account, companies, filters, fiscal_year):
 	start_date = (
-		fiscal_year.year_start_date
-		if filters.filter_based_on == "Fiscal Year"
-		else filters.period_start_date
+		fiscal_year.year_start_date if filters.filter_based_on == "Fiscal Year" else filters.period_start_date
 	)
 
 	for entries in gl_entries_by_account.values():
@@ -422,8 +409,12 @@
 							and parent_company_currency != child_company_currency
 							and filters.get("accumulated_in_group_company")
 						):
-							debit = convert(debit, parent_company_currency, child_company_currency, filters.end_date)
-							credit = convert(credit, parent_company_currency, child_company_currency, filters.end_date)
+							debit = convert(
+								debit, parent_company_currency, child_company_currency, filters.end_date
+							)
+							credit = convert(
+								credit, parent_company_currency, child_company_currency, filters.end_date
+							)
 
 						d[company] = d.get(company, 0.0) + flt(debit) - flt(credit)
 
@@ -507,10 +498,8 @@
 	lft, rgt = frappe.get_cached_value("Company", company, ["lft", "rgt"])
 
 	return frappe.db.sql_list(
-		"""select name from `tabCompany`
-		where lft >= {0} and rgt <= {1} order by lft, rgt""".format(
-			lft, rgt
-		)
+		f"""select name from `tabCompany`
+		where lft >= {lft} and rgt <= {rgt} order by lft, rgt"""
 	)
 
 
@@ -547,9 +536,7 @@
 	return accounts
 
 
-def prepare_data(
-	accounts, start_date, end_date, balance_must_be, companies, company_currency, filters
-):
+def prepare_data(accounts, start_date, end_date, balance_must_be, companies, company_currency, filters):
 	data = []
 
 	for d in accounts:
@@ -559,9 +546,7 @@
 		row = frappe._dict(
 			{
 				"account_name": (
-					"%s - %s" % (_(d.account_number), _(d.account_name))
-					if d.account_number
-					else _(d.account_name)
+					f"{_(d.account_number)} - {_(d.account_name)}" if d.account_number else _(d.account_name)
 				),
 				"account": _(d.name),
 				"parent_account": _(d.parent_account),
@@ -609,9 +594,7 @@
 ):
 	"""Returns a dict like { "account": [gl entries], ... }"""
 
-	company_lft, company_rgt = frappe.get_cached_value(
-		"Company", filters.get("company"), ["lft", "rgt"]
-	)
+	company_lft, company_rgt = frappe.get_cached_value("Company", filters.get("company"), ["lft", "rgt"])
 
 	companies = frappe.db.sql(
 		""" select name, default_currency from `tabCompany`
@@ -739,7 +722,7 @@
 	additional_conditions = []
 
 	if ignore_closing_entries:
-		additional_conditions.append((gle.voucher_type != "Period Closing Voucher"))
+		additional_conditions.append(gle.voucher_type != "Period Closing Voucher")
 
 	if from_date:
 		additional_conditions.append(gle.posting_date >= from_date)
@@ -802,7 +785,7 @@
 	def add_to_list(parent, level):
 		if level < depth:
 			children = parent_children_map.get(parent) or []
-			sort_accounts(children, is_root=True if parent == None else False)
+			sort_accounts(children, is_root=True if parent is None else False)
 
 			for child in children:
 				child.indent = level
diff --git a/erpnext/accounts/report/customer_ledger_summary/customer_ledger_summary.py b/erpnext/accounts/report/customer_ledger_summary/customer_ledger_summary.py
index f4a0175..7b99096 100644
--- a/erpnext/accounts/report/customer_ledger_summary/customer_ledger_summary.py
+++ b/erpnext/accounts/report/customer_ledger_summary/customer_ledger_summary.py
@@ -7,7 +7,7 @@
 from frappe.utils import getdate, nowdate
 
 
-class PartyLedgerSummaryReport(object):
+class PartyLedgerSummaryReport:
 	def __init__(self, filters=None):
 		self.filters = frappe._dict(filters or {})
 		self.filters.from_date = getdate(self.filters.from_date or nowdate())
@@ -21,9 +21,7 @@
 			frappe.throw(_("From Date must be before To Date"))
 
 		self.filters.party_type = args.get("party_type")
-		self.party_naming_by = frappe.db.get_single_value(
-			args.get("naming_by")[0], args.get("naming_by")[1]
-		)
+		self.party_naming_by = frappe.db.get_single_value(args.get("naming_by")[0], args.get("naming_by")[1])
 
 		self.get_gl_entries()
 		self.get_additional_columns()
@@ -49,7 +47,7 @@
 				.select(
 					customer.name, customer.territory, customer.customer_group, customer.default_sales_partner
 				)
-				.where((customer.disabled == 0))
+				.where(customer.disabled == 0)
 				.run(as_dict=True)
 			)
 
@@ -62,7 +60,7 @@
 			result = (
 				frappe.qb.from_(supplier)
 				.select(supplier.name, supplier.supplier_group)
-				.where((supplier.disabled == 0))
+				.where(supplier.disabled == 0)
 				.run(as_dict=True)
 			)
 
@@ -184,9 +182,7 @@
 		return columns
 
 	def get_data(self):
-		company_currency = frappe.get_cached_value(
-			"Company", self.filters.get("company"), "default_currency"
-		)
+		company_currency = frappe.get_cached_value("Company", self.filters.get("company"), "default_currency")
 		invoice_dr_or_cr = "debit" if self.filters.party_type == "Customer" else "credit"
 		reverse_dr_or_cr = "credit" if self.filters.party_type == "Customer" else "debit"
 
@@ -260,7 +256,7 @@
 			join = "left join `tabSupplier` p on gle.party = p.name"
 
 		self.gl_entries = frappe.db.sql(
-			"""
+			f"""
 			select
 				gle.posting_date, gle.party, gle.voucher_type, gle.voucher_no, gle.against_voucher_type,
 				gle.against_voucher, gle.debit, gle.credit, gle.is_opening {join_field}
@@ -270,9 +266,7 @@
 				gle.docstatus < 2 and gle.is_cancelled = 0 and gle.party_type=%(party_type)s and ifnull(gle.party, '') != ''
 				and gle.posting_date <= %(to_date)s {conditions}
 			order by gle.posting_date
-		""".format(
-				join=join, join_field=join_field, conditions=conditions
-			),
+		""",
 			self.filters,
 			as_dict=True,
 		)
@@ -296,22 +290,18 @@
 				)
 
 				conditions.append(
-					"""party in (select name from tabCustomer
-					where exists(select name from `tabCustomer Group` where lft >= {0} and rgt <= {1}
-						and name=tabCustomer.customer_group))""".format(
-						lft, rgt
-					)
+					f"""party in (select name from tabCustomer
+					where exists(select name from `tabCustomer Group` where lft >= {lft} and rgt <= {rgt}
+						and name=tabCustomer.customer_group))"""
 				)
 
 			if self.filters.get("territory"):
 				lft, rgt = frappe.db.get_value("Territory", self.filters.get("territory"), ["lft", "rgt"])
 
 				conditions.append(
-					"""party in (select name from tabCustomer
-					where exists(select name from `tabTerritory` where lft >= {0} and rgt <= {1}
-						and name=tabCustomer.territory))""".format(
-						lft, rgt
-					)
+					f"""party in (select name from tabCustomer
+					where exists(select name from `tabTerritory` where lft >= {lft} and rgt <= {rgt}
+						and name=tabCustomer.territory))"""
 				)
 
 			if self.filters.get("payment_terms_template"):
@@ -331,12 +321,10 @@
 
 				conditions.append(
 					"""exists(select name from `tabSales Team` steam where
-					steam.sales_person in (select name from `tabSales Person` where lft >= {0} and rgt <= {1})
+					steam.sales_person in (select name from `tabSales Person` where lft >= {} and rgt <= {})
 					and ((steam.parent = voucher_no and steam.parenttype = voucher_type)
 						or (steam.parent = against_voucher and steam.parenttype = against_voucher_type)
-						or (steam.parent = party and steam.parenttype = 'Customer')))""".format(
-						lft, rgt
-					)
+						or (steam.parent = party and steam.parenttype = 'Customer')))""".format(lft, rgt)
 				)
 
 		if self.filters.party_type == "Supplier":
@@ -392,7 +380,7 @@
 		)
 
 		gl_entries = frappe.db.sql(
-			"""
+			f"""
 			select
 				posting_date, account, party, voucher_type, voucher_no, debit, credit
 			from
@@ -406,10 +394,7 @@
 					where gle.party_type=%(party_type)s and ifnull(party, '') != ''
 					and gle.posting_date between %(from_date)s and %(to_date)s and gle.docstatus < 2 {conditions}
 				)
-			""".format(
-				accounts_query=accounts_query,
-				conditions=conditions,
-			),
+			""",
 			self.filters,
 			as_dict=True,
 		)
@@ -440,14 +425,14 @@
 
 			if parties and accounts:
 				if len(parties) == 1:
-					party = list(parties.keys())[0]
+					party = next(iter(parties.keys()))
 					for account, amount in accounts.items():
 						self.party_adjustment_accounts.add(account)
 						self.party_adjustment_details.setdefault(party, {})
 						self.party_adjustment_details[party].setdefault(account, 0)
 						self.party_adjustment_details[party][account] += amount
 				elif len(accounts) == 1 and not has_irrelevant_entry:
-					account = list(accounts.keys())[0]
+					account = next(iter(accounts.keys()))
 					self.party_adjustment_accounts.add(account)
 					for party, amount in parties.items():
 						self.party_adjustment_details.setdefault(party, {})
diff --git a/erpnext/accounts/report/deferred_revenue_and_expense/deferred_revenue_and_expense.py b/erpnext/accounts/report/deferred_revenue_and_expense/deferred_revenue_and_expense.py
index eebd61c..7036009 100644
--- a/erpnext/accounts/report/deferred_revenue_and_expense/deferred_revenue_and_expense.py
+++ b/erpnext/accounts/report/deferred_revenue_and_expense/deferred_revenue_and_expense.py
@@ -10,7 +10,7 @@
 from erpnext.accounts.utils import get_fiscal_year
 
 
-class Deferred_Item(object):
+class Deferred_Item:
 	"""
 	Helper class for processing items with deferred revenue/expense
 	"""
@@ -152,13 +152,11 @@
 					if posting.posted == "posted":
 						actual += self.get_amount(posting)
 
-			self.period_total.append(
-				frappe._dict({"key": period.key, "total": period_sum, "actual": actual})
-			)
+			self.period_total.append(frappe._dict({"key": period.key, "total": period_sum, "actual": actual}))
 		return self.period_total
 
 
-class Deferred_Invoice(object):
+class Deferred_Invoice:
 	def __init__(self, invoice, items, filters, period_list):
 		"""
 		Helper class for processing invoices with deferred revenue/expense items
@@ -219,7 +217,7 @@
 		return ret_data
 
 
-class Deferred_Revenue_and_Expense_Report(object):
+class Deferred_Revenue_and_Expense_Report:
 	def __init__(self, filters=None):
 		"""
 		Initialize deferred revenue/expense report with user provided filters or system defaults, if none is provided
diff --git a/erpnext/accounts/report/deferred_revenue_and_expense/test_deferred_revenue_and_expense.py b/erpnext/accounts/report/deferred_revenue_and_expense/test_deferred_revenue_and_expense.py
index 7b1a902..f8a965b 100644
--- a/erpnext/accounts/report/deferred_revenue_and_expense/test_deferred_revenue_and_expense.py
+++ b/erpnext/accounts/report/deferred_revenue_and_expense/test_deferred_revenue_and_expense.py
@@ -1,5 +1,3 @@
-import unittest
-
 import frappe
 from frappe import qb
 from frappe.tests.utils import FrappeTestCase, change_settings
@@ -13,8 +11,6 @@
 )
 from erpnext.accounts.test.accounts_mixin import AccountsTestMixin
 from erpnext.accounts.utils import get_fiscal_year
-from erpnext.buying.doctype.supplier.test_supplier import create_supplier
-from erpnext.stock.doctype.item.test_item import create_item
 
 
 class TestDeferredRevenueAndExpense(FrappeTestCase, AccountsTestMixin):
diff --git a/erpnext/accounts/report/dimension_wise_accounts_balance_report/dimension_wise_accounts_balance_report.py b/erpnext/accounts/report/dimension_wise_accounts_balance_report/dimension_wise_accounts_balance_report.py
index 5939a26..db984e8 100644
--- a/erpnext/accounts/report/dimension_wise_accounts_balance_report/dimension_wise_accounts_balance_report.py
+++ b/erpnext/accounts/report/dimension_wise_accounts_balance_report/dimension_wise_accounts_balance_report.py
@@ -15,7 +15,6 @@
 
 
 def execute(filters=None):
-
 	validate_filters(filters)
 	dimension_list = get_dimensions(filters)
 
@@ -90,9 +89,7 @@
 	gl_filters["dimensions"] = set(dimension_list)
 
 	if filters.get("include_default_book_entries"):
-		gl_filters["company_fb"] = frappe.get_cached_value(
-			"Company", filters.company, "default_finance_book"
-		)
+		gl_filters["company_fb"] = frappe.get_cached_value("Company", filters.company, "default_finance_book")
 
 	gl_entries = frappe.db.sql(
 		"""
@@ -119,7 +116,6 @@
 
 
 def format_gl_entries(gl_entries_by_account, accounts_by_name, dimension_list, dimension_type):
-
 	for entries in gl_entries_by_account.values():
 		for entry in entries:
 			d = accounts_by_name.get(entry.account)
@@ -151,7 +147,7 @@
 			"to_date": filters.to_date,
 			"currency": company_currency,
 			"account_name": (
-				"{} - {}".format(d.account_number, d.account_name) if d.account_number else d.account_name
+				f"{d.account_number} - {d.account_name}" if d.account_number else d.account_name
 			),
 		}
 
@@ -183,7 +179,7 @@
 def get_condition(dimension):
 	conditions = []
 
-	conditions.append("{0} in %(dimensions)s".format(frappe.scrub(dimension)))
+	conditions.append(f"{frappe.scrub(dimension)} in %(dimensions)s")
 
 	return " and {}".format(" and ".join(conditions)) if conditions else ""
 
diff --git a/erpnext/accounts/report/financial_ratios/financial_ratios.py b/erpnext/accounts/report/financial_ratios/financial_ratios.py
index 47b4fd0..c97cd89 100644
--- a/erpnext/accounts/report/financial_ratios/financial_ratios.py
+++ b/erpnext/accounts/report/financial_ratios/financial_ratios.py
@@ -67,7 +67,6 @@
 
 
 def get_ratios_data(filters, period_list, years):
-
 	data = []
 	assets, liabilities, income, expense = get_gl_data(filters, period_list, years)
 
@@ -113,9 +112,7 @@
 	add_solvency_ratios(
 		data, years, total_asset, total_liability, net_sales, cogs, total_income, total_expense
 	)
-	add_turnover_ratios(
-		data, years, period_list, filters, total_asset, net_sales, cogs, direct_expense
-	)
+	add_turnover_ratios(data, years, period_list, filters, total_asset, net_sales, cogs, direct_expense)
 
 	return data
 
@@ -180,9 +177,7 @@
 		profit_after_tax = flt(total_income.get(year)) + flt(total_expense.get(year))
 		share_holder_fund = flt(total_asset.get(year)) - flt(total_liability.get(year))
 
-		debt_equity_ratio[year] = calculate_ratio(
-			total_liability.get(year), share_holder_fund, precision
-		)
+		debt_equity_ratio[year] = calculate_ratio(total_liability.get(year), share_holder_fund, precision)
 		return_on_equity_ratio[year] = calculate_ratio(profit_after_tax, share_holder_fund, precision)
 
 		net_profit_ratio[year] = calculate_ratio(profit_after_tax, net_sales.get(year), precision)
@@ -198,9 +193,7 @@
 	data.append(return_on_equity_ratio)
 
 
-def add_turnover_ratios(
-	data, years, period_list, filters, total_asset, net_sales, cogs, direct_expense
-):
+def add_turnover_ratios(data, years, period_list, filters, total_asset, net_sales, cogs, direct_expense):
 	precision = frappe.db.get_single_value("System Settings", "float_precision")
 	data.append({"ratio": "Turnover Ratios"})
 
@@ -240,7 +233,6 @@
 	net_dict=None,
 	total_net=0,
 ):
-
 	for entry in root_type_data:
 		if not entry.get("parent_account") and entry.get("is_group"):
 			total_dict[year] = entry[year]
@@ -283,9 +275,7 @@
 			company=filters.company,
 			account_type=account_type,
 		)
-		avg_ratio[period["key"]] = flt(
-			(flt(closing_balance) + flt(opening_balance)) / 2, precision=precision
-		)
+		avg_ratio[period["key"]] = flt((flt(closing_balance) + flt(opening_balance)) / 2, precision=precision)
 
 	return avg_ratio
 
diff --git a/erpnext/accounts/report/financial_statements.py b/erpnext/accounts/report/financial_statements.py
index aadd873..6d763597 100644
--- a/erpnext/accounts/report/financial_statements.py
+++ b/erpnext/accounts/report/financial_statements.py
@@ -162,7 +162,6 @@
 	ignore_accumulated_values_for_fy=False,
 	total=True,
 ):
-
 	accounts = get_accounts(company, root_type)
 	if not accounts:
 		return None
@@ -178,7 +177,6 @@
 		root_type,
 		as_dict=1,
 	):
-
 		set_gl_entries_by_account(
 			company,
 			period_list[0]["year_start_date"] if only_current_fiscal_year else None,
@@ -242,7 +240,8 @@
 
 				if entry.posting_date <= period.to_date:
 					if (accumulated_values or entry.posting_date >= period.from_date) and (
-						not ignore_accumulated_values_for_fy or entry.fiscal_year == period.to_date_fiscal_year
+						not ignore_accumulated_values_for_fy
+						or entry.fiscal_year == period.to_date_fiscal_year
 					):
 						d[period.key] = d.get(period.key, 0.0) + flt(entry.debit) - flt(entry.credit)
 
@@ -286,9 +285,7 @@
 				"is_group": d.is_group,
 				"opening_balance": d.get("opening_balance", 0.0) * (1 if balance_must_be == "Debit" else -1),
 				"account_name": (
-					"%s - %s" % (_(d.account_number), _(d.account_name))
-					if d.account_number
-					else _(d.account_name)
+					f"{_(d.account_number)} - {_(d.account_name)}" if d.account_number else _(d.account_name)
 				),
 			}
 		)
@@ -382,7 +379,7 @@
 	def add_to_list(parent, level):
 		if level < depth:
 			children = parent_children_map.get(parent) or []
-			sort_accounts(children, is_root=True if parent == None else False)
+			sort_accounts(children, is_root=True if parent is None else False)
 
 			for child in children:
 				child.indent = level
@@ -573,7 +570,9 @@
 			company_fb = frappe.get_cached_value("Company", filters.company, "default_finance_book")
 
 			if filters.finance_book and company_fb and cstr(filters.finance_book) != cstr(company_fb):
-				frappe.throw(_("To use a different finance book, please uncheck 'Include Default FB Entries'"))
+				frappe.throw(
+					_("To use a different finance book, please uncheck 'Include Default FB Entries'")
+				)
 
 			query = query.where(
 				(gl_entry.finance_book.isin([cstr(filters.finance_book), cstr(company_fb), ""]))
diff --git a/erpnext/accounts/report/general_and_payment_ledger_comparison/general_and_payment_ledger_comparison.py b/erpnext/accounts/report/general_and_payment_ledger_comparison/general_and_payment_ledger_comparison.py
index 696a03b..89cf7e5 100644
--- a/erpnext/accounts/report/general_and_payment_ledger_comparison/general_and_payment_ledger_comparison.py
+++ b/erpnext/accounts/report/general_and_payment_ledger_comparison/general_and_payment_ledger_comparison.py
@@ -7,7 +7,7 @@
 from frappe.query_builder.functions import Sum
 
 
-class General_Payment_Ledger_Comparison(object):
+class General_Payment_Ledger_Comparison:
 	"""
 	A Utility report to compare Voucher-wise balance between General and Payment Ledger
 	"""
@@ -58,10 +58,9 @@
 
 		for acc_type, val in self.account_types.items():
 			if val.accounts:
-
 				filter_criterion = []
 				if self.filters.voucher_no:
-					filter_criterion.append((gle.voucher_no == self.filters.voucher_no))
+					filter_criterion.append(gle.voucher_no == self.filters.voucher_no)
 
 				if self.filters.period_start_date:
 					filter_criterion.append(gle.posting_date.gte(self.filters.period_start_date))
@@ -102,10 +101,9 @@
 
 		for acc_type, val in self.account_types.items():
 			if val.accounts:
-
 				filter_criterion = []
 				if self.filters.voucher_no:
-					filter_criterion.append((ple.voucher_no == self.filters.voucher_no))
+					filter_criterion.append(ple.voucher_no == self.filters.voucher_no)
 
 				if self.filters.period_start_date:
 					filter_criterion.append(ple.posting_date.gte(self.filters.period_start_date))
@@ -141,7 +139,7 @@
 		self.ple_balances = set()
 
 		# consolidate both receivable and payable balances in one set
-		for acc_type, val in self.account_types.items():
+		for _acc_type, val in self.account_types.items():
 			self.gle_balances = set(val.gle) | self.gle_balances
 			self.ple_balances = set(val.ple) | self.ple_balances
 
@@ -177,7 +175,6 @@
 
 	def get_columns(self):
 		self.columns = []
-		options = None
 		self.columns.append(
 			dict(
 				label=_("Company"),
diff --git a/erpnext/accounts/report/general_and_payment_ledger_comparison/test_general_and_payment_ledger_comparison.py b/erpnext/accounts/report/general_and_payment_ledger_comparison/test_general_and_payment_ledger_comparison.py
index 59e906b..afa81b8 100644
--- a/erpnext/accounts/report/general_and_payment_ledger_comparison/test_general_and_payment_ledger_comparison.py
+++ b/erpnext/accounts/report/general_and_payment_ledger_comparison/test_general_and_payment_ledger_comparison.py
@@ -1,5 +1,3 @@
-import unittest
-
 import frappe
 from frappe import qb
 from frappe.tests.utils import FrappeTestCase
@@ -40,9 +38,7 @@
 		)
 
 		# manually edit the payment ledger entry
-		ple = frappe.db.get_all(
-			"Payment Ledger Entry", filters={"voucher_no": sinv.name, "delinked": 0}
-		)[0]
+		ple = frappe.db.get_all("Payment Ledger Entry", filters={"voucher_no": sinv.name, "delinked": 0})[0]
 		frappe.db.set_value("Payment Ledger Entry", ple.name, "amount", sinv.grand_total - 1)
 
 		filters = frappe._dict({"company": self.company})
diff --git a/erpnext/accounts/report/general_ledger/general_ledger.py b/erpnext/accounts/report/general_ledger/general_ledger.py
index cea3a7b..800d7a5 100644
--- a/erpnext/accounts/report/general_ledger/general_ledger.py
+++ b/erpnext/accounts/report/general_ledger/general_ledger.py
@@ -102,9 +102,7 @@
 
 def set_account_currency(filters):
 	if filters.get("account") or (filters.get("party") and len(filters.party) == 1):
-		filters["company_currency"] = frappe.get_cached_value(
-			"Company", filters.company, "default_currency"
-		)
+		filters["company_currency"] = frappe.get_cached_value("Company", filters.company, "default_currency")
 		account_currency = None
 
 		if filters.get("account"):
@@ -164,9 +162,7 @@
 		credit_in_account_currency """
 
 	if filters.get("show_remarks"):
-		if remarks_length := frappe.db.get_single_value(
-			"Accounts Settings", "general_ledger_remarks_length"
-		):
+		if remarks_length := frappe.db.get_single_value("Accounts Settings", "general_ledger_remarks_length"):
 			select_fields += f",substr(remarks, 1, {remarks_length}) as 'remarks'"
 		else:
 			select_fields += """,remarks"""
@@ -197,7 +193,7 @@
 		)
 
 	gl_entries = frappe.db.sql(
-		"""
+		f"""
 		select
 			name as gl_entry, posting_date, account, party_type, party,
 			voucher_type, voucher_subtype, voucher_no, {dimension_fields}
@@ -205,15 +201,9 @@
 			against_voucher_type, against_voucher, account_currency,
 			against, is_opening, creation {select_fields}
 		from `tabGL Entry`
-		where company=%(company)s {conditions}
+		where company=%(company)s {get_conditions(filters)}
 		{order_by_statement}
-	""".format(
-			dimension_fields=dimension_fields,
-			transaction_currency_fields=transaction_currency_fields,
-			select_fields=select_fields,
-			conditions=get_conditions(filters),
-			order_by_statement=order_by_statement,
-		),
+	""",
 		filters,
 		as_dict=1,
 	)
@@ -283,7 +273,9 @@
 			if filters.get("company_fb") and cstr(filters.get("finance_book")) != cstr(
 				filters.get("company_fb")
 			):
-				frappe.throw(_("To use a different finance book, please uncheck 'Include Default FB Entries'"))
+				frappe.throw(
+					_("To use a different finance book, please uncheck 'Include Default FB Entries'")
+				)
 			else:
 				conditions.append("(finance_book in (%(finance_book)s, '') OR finance_book IS NULL)")
 		else:
@@ -315,9 +307,9 @@
 						filters[dimension.fieldname] = get_dimension_with_children(
 							dimension.document_type, filters.get(dimension.fieldname)
 						)
-						conditions.append("{0} in %({0})s".format(dimension.fieldname))
+						conditions.append(f"{dimension.fieldname} in %({dimension.fieldname})s")
 					else:
-						conditions.append("{0} in %({0})s".format(dimension.fieldname))
+						conditions.append(f"{dimension.fieldname} in %({dimension.fieldname})s")
 
 	return "and {}".format(" and ".join(conditions)) if conditions else ""
 
@@ -351,7 +343,7 @@
 	data.append(totals.opening)
 
 	if filters.get("group_by") != "Group by Voucher (Consolidated)":
-		for acc, acc_dict in gle_map.items():
+		for _acc, acc_dict in gle_map.items():
 			# acc
 			if acc_dict.entries:
 				# opening
@@ -383,7 +375,7 @@
 def get_totals_dict():
 	def _get_debit_credit_dict(label):
 		return _dict(
-			account="'{0}'".format(label),
+			account=f"'{label}'",
 			debit=0.0,
 			credit=0.0,
 			debit_in_account_currency=0.0,
@@ -432,9 +424,10 @@
 		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"):
+		if filters.get("show_net_values_in_party_account") and account_type_map.get(data[key].account) in (
+			"Receivable",
+			"Payable",
+		):
 			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
@@ -512,21 +505,19 @@
 
 def get_account_type_map(company):
 	account_type_map = frappe._dict(
-		frappe.get_all(
-			"Account", fields=["name", "account_type"], filters={"company": company}, as_list=1
-		)
+		frappe.get_all("Account", fields=["name", "account_type"], filters={"company": company}, as_list=1)
 	)
 
 	return account_type_map
 
 
 def get_result_as_list(data, filters):
-	balance, balance_in_account_currency = 0, 0
+	balance, _balance_in_account_currency = 0, 0
 	inv_details = get_supplier_invoice_details()
 
 	for d in data:
 		if not d.get("posting_date"):
-			balance, balance_in_account_currency = 0, 0
+			balance, _balance_in_account_currency = 0, 0
 
 		balance = get_balance(d, balance, "debit", "credit")
 		d["balance"] = balance
diff --git a/erpnext/accounts/report/general_ledger/test_general_ledger.py b/erpnext/accounts/report/general_ledger/test_general_ledger.py
index 75f9430..33b356f 100644
--- a/erpnext/accounts/report/general_ledger/test_general_ledger.py
+++ b/erpnext/accounts/report/general_ledger/test_general_ledger.py
@@ -203,9 +203,7 @@
 		revaluation.extend("accounts", accounts)
 		row = revaluation.accounts[0]
 		row.new_exchange_rate = 83
-		row.new_balance_in_base_currency = flt(
-			row.new_exchange_rate * flt(row.balance_in_account_currency)
-		)
+		row.new_balance_in_base_currency = flt(row.new_exchange_rate * flt(row.balance_in_account_currency))
 		row.gain_loss = row.new_balance_in_base_currency - flt(row.balance_in_base_currency)
 		revaluation.set_total_gain_loss()
 		revaluation = revaluation.save().submit()
diff --git a/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.py b/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.py
index a52aaff..00f9c3e 100644
--- a/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.py
+++ b/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.py
@@ -49,9 +49,7 @@
 		total=False,
 	)
 
-	columns = get_columns(
-		filters.periodicity, period_list, filters.accumulated_values, filters.company
-	)
+	columns = get_columns(filters.periodicity, period_list, filters.accumulated_values, filters.company)
 
 	gross_income = get_revenue(income, period_list)
 	gross_expense = get_revenue(expense, period_list)
@@ -119,9 +117,7 @@
 
 
 def get_revenue(data, period_list, include_in_gross=1):
-	revenue = [
-		item for item in data if item["include_in_gross"] == include_in_gross or item["is_group"] == 1
-	]
+	revenue = [item for item in data if item["include_in_gross"] == include_in_gross or item["is_group"] == 1]
 
 	data_to_be_removed = True
 	while data_to_be_removed:
diff --git a/erpnext/accounts/report/gross_profit/gross_profit.py b/erpnext/accounts/report/gross_profit/gross_profit.py
index 25958692..8e2d9c6 100644
--- a/erpnext/accounts/report/gross_profit/gross_profit.py
+++ b/erpnext/accounts/report/gross_profit/gross_profit.py
@@ -158,9 +158,7 @@
 	return columns, data
 
 
-def get_data_when_grouped_by_invoice(
-	columns, gross_profit_data, filters, group_wise_columns, data
-):
+def get_data_when_grouped_by_invoice(columns, gross_profit_data, filters, group_wise_columns, data):
 	column_names = get_column_names()
 
 	# to display item as Item Code: Item Name
@@ -395,7 +393,7 @@
 	)
 
 
-class GrossProfitGenerator(object):
+class GrossProfitGenerator:
 	def __init__(self, filters=None):
 		self.sle = {}
 		self.data = []
@@ -499,7 +497,8 @@
 				for i, row in enumerate(self.grouped[key]):
 					if row.indent == 1.0:
 						if (
-							row.parent in self.returned_invoices and row.item_code in self.returned_invoices[row.parent]
+							row.parent in self.returned_invoices
+							and row.item_code in self.returned_invoices[row.parent]
 						):
 							returned_item_rows = self.returned_invoices[row.parent][row.item_code]
 							for returned_item_row in returned_item_rows:
@@ -512,7 +511,9 @@
 										row.qty = 0
 										returned_item_row.qty += row.qty
 								row.base_amount += flt(returned_item_row.base_amount, self.currency_precision)
-							row.buying_amount = flt(flt(row.qty) * flt(row.buying_rate), self.currency_precision)
+							row.buying_amount = flt(
+								flt(row.qty) * flt(row.buying_rate), self.currency_precision
+							)
 						if flt(row.qty) or row.base_amount:
 							row = self.set_average_rate(row)
 							self.grouped_data.append(row)
@@ -567,9 +568,7 @@
 		new_row.buying_rate = (
 			flt(new_row.buying_amount / new_row.qty, self.float_precision) if new_row.qty else 0
 		)
-		new_row.base_rate = (
-			flt(new_row.base_amount / new_row.qty, self.float_precision) if new_row.qty else 0
-		)
+		new_row.base_rate = flt(new_row.base_amount / new_row.qty, self.float_precision) if new_row.qty else 0
 		return new_row
 
 	def set_average_gross_profit(self, new_row):
@@ -656,7 +655,7 @@
 			elif self.delivery_notes.get((row.parent, row.item_code), None):
 				#  check if Invoice has delivery notes
 				dn = self.delivery_notes.get((row.parent, row.item_code))
-				parenttype, parent, item_row, warehouse = (
+				parenttype, parent, item_row, _warehouse = (
 					"Delivery Note",
 					dn["delivery_note"],
 					dn["item_row"],
@@ -751,7 +750,7 @@
 		conditions += " and (is_return = 0 or (is_return=1 and return_against is null))"
 
 		if self.filters.item_group:
-			conditions += " and {0}".format(get_item_group_condition(self.filters.item_group))
+			conditions += f" and {get_item_group_condition(self.filters.item_group)}"
 
 		if self.filters.sales_person:
 			conditions += """
@@ -770,12 +769,10 @@
 
 		if self.filters.group_by == "Payment Term":
 			payment_term_cols = """,if(`tabSales Invoice`.is_return = 1,
-										'{0}',
-										coalesce(schedule.payment_term, '{1}')) as payment_term,
+										'{}',
+										coalesce(schedule.payment_term, '{}')) as payment_term,
 									schedule.invoice_portion,
-									schedule.payment_amount """.format(
-				_("Sales Return"), _("No Terms")
-			)
+									schedule.payment_amount """.format(_("Sales Return"), _("No Terms"))
 			payment_term_table = """ left join `tabPayment Schedule` schedule on schedule.parent = `tabSales Invoice`.name and
 																				`tabSales Invoice`.is_return = 0 """
 		else:
@@ -949,9 +946,7 @@
 		)
 
 	def get_bundle_item_details(self, item_code):
-		return frappe.db.get_value(
-			"Item", item_code, ["item_name", "description", "item_group", "brand"]
-		)
+		return frappe.db.get_value("Item", item_code, ["item_name", "description", "item_group", "brand"])
 
 	def get_stock_ledger_entries(self, item_code, warehouse):
 		if item_code and warehouse:
diff --git a/erpnext/accounts/report/gross_profit/test_gross_profit.py b/erpnext/accounts/report/gross_profit/test_gross_profit.py
index aa820aa..8d15900 100644
--- a/erpnext/accounts/report/gross_profit/test_gross_profit.py
+++ b/erpnext/accounts/report/gross_profit/test_gross_profit.py
@@ -1,7 +1,7 @@
 import frappe
 from frappe import qb
 from frappe.tests.utils import FrappeTestCase
-from frappe.utils import add_days, flt, nowdate
+from frappe.utils import flt, nowdate
 
 from erpnext.accounts.doctype.sales_invoice.sales_invoice import make_delivery_note
 from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice
diff --git a/erpnext/accounts/report/inactive_sales_items/inactive_sales_items.py b/erpnext/accounts/report/inactive_sales_items/inactive_sales_items.py
index 230b18c..df3fc48 100644
--- a/erpnext/accounts/report/inactive_sales_items/inactive_sales_items.py
+++ b/erpnext/accounts/report/inactive_sales_items/inactive_sales_items.py
@@ -92,7 +92,6 @@
 
 
 def get_sales_details(filters):
-	data = []
 	item_details_map = {}
 
 	date_field = "s.transaction_date" if filters["based_on"] == "Sales Order" else "s.posting_date"
@@ -116,7 +115,6 @@
 
 
 def get_territories(filters):
-
 	filter_dict = {}
 	if filters.get("territory"):
 		filter_dict.update({"name": filters["territory"]})
diff --git a/erpnext/accounts/report/item_wise_purchase_register/item_wise_purchase_register.py b/erpnext/accounts/report/item_wise_purchase_register/item_wise_purchase_register.py
index 9c6e2d0..4e7ab1b 100644
--- a/erpnext/accounts/report/item_wise_purchase_register/item_wise_purchase_register.py
+++ b/erpnext/accounts/report/item_wise_purchase_register/item_wise_purchase_register.py
@@ -140,7 +140,6 @@
 
 
 def get_columns(additional_table_columns, filters):
-
 	columns = []
 
 	if filters.get("group_by") != ("Item"):
@@ -194,7 +193,12 @@
 					"options": "Supplier",
 					"width": 120,
 				},
-				{"label": _("Supplier Name"), "fieldname": "supplier_name", "fieldtype": "Data", "width": 120},
+				{
+					"label": _("Supplier Name"),
+					"fieldname": "supplier_name",
+					"fieldtype": "Data",
+					"width": 120,
+				},
 			]
 		)
 
@@ -313,7 +317,7 @@
 	if additional_query_columns:
 		additional_query_columns = "," + ",".join(additional_query_columns)
 	return frappe.db.sql(
-		"""
+		f"""
 		select
 			`tabPurchase Invoice Item`.`name`, `tabPurchase Invoice Item`.`parent`,
 			`tabPurchase Invoice`.posting_date, `tabPurchase Invoice`.credit_to, `tabPurchase Invoice`.company,
@@ -326,14 +330,12 @@
 			`tabPurchase Invoice Item`.`purchase_receipt`, `tabPurchase Invoice Item`.`po_detail`,
 			`tabPurchase Invoice Item`.`expense_account`, `tabPurchase Invoice Item`.`stock_qty`,
 			`tabPurchase Invoice Item`.`stock_uom`, `tabPurchase Invoice Item`.`base_net_amount`,
-			`tabPurchase Invoice`.`supplier_name`, `tabPurchase Invoice`.`mode_of_payment` {0}
+			`tabPurchase Invoice`.`supplier_name`, `tabPurchase Invoice`.`mode_of_payment` {additional_query_columns}
 		from `tabPurchase Invoice`, `tabPurchase Invoice Item`, `tabItem`
 		where `tabPurchase Invoice`.name = `tabPurchase Invoice Item`.`parent` and
 			`tabItem`.name = `tabPurchase Invoice Item`.`item_code` and
-			`tabPurchase Invoice`.docstatus = 1 {1}
-	""".format(
-			additional_query_columns, conditions
-		),
+			`tabPurchase Invoice`.docstatus = 1 {conditions}
+	""",
 		filters,
 		as_dict=1,
 	)
diff --git a/erpnext/accounts/report/item_wise_sales_register/item_wise_sales_register.py b/erpnext/accounts/report/item_wise_sales_register/item_wise_sales_register.py
index a4f01fa..ce04af1 100644
--- a/erpnext/accounts/report/item_wise_sales_register/item_wise_sales_register.py
+++ b/erpnext/accounts/report/item_wise_sales_register/item_wise_sales_register.py
@@ -224,7 +224,12 @@
 					"options": "Customer",
 					"width": 120,
 				},
-				{"label": _("Customer Name"), "fieldname": "customer_name", "fieldtype": "Data", "width": 120},
+				{
+					"label": _("Customer Name"),
+					"fieldname": "customer_name",
+					"fieldtype": "Data",
+					"width": 120,
+				},
 			]
 		)
 
@@ -379,9 +384,7 @@
 		"""
 
 	if not filters.get("group_by"):
-		conditions += (
-			"ORDER BY `tabSales Invoice`.posting_date desc, `tabSales Invoice Item`.item_group desc"
-		)
+		conditions += "ORDER BY `tabSales Invoice`.posting_date desc, `tabSales Invoice Item`.item_group desc"
 	else:
 		conditions += get_group_by_conditions(filters, "Sales Invoice")
 
@@ -390,13 +393,13 @@
 
 def get_group_by_conditions(filters, doctype):
 	if filters.get("group_by") == "Invoice":
-		return "ORDER BY `tab{0} Item`.parent desc".format(doctype)
+		return f"ORDER BY `tab{doctype} Item`.parent desc"
 	elif filters.get("group_by") == "Item":
-		return "ORDER BY `tab{0} Item`.`item_code`".format(doctype)
+		return f"ORDER BY `tab{doctype} Item`.`item_code`"
 	elif filters.get("group_by") == "Item Group":
-		return "ORDER BY `tab{0} Item`.{1}".format(doctype, frappe.scrub(filters.get("group_by")))
+		return "ORDER BY `tab{} Item`.{}".format(doctype, frappe.scrub(filters.get("group_by")))
 	elif filters.get("group_by") in ("Customer", "Customer Group", "Territory", "Supplier"):
-		return "ORDER BY `tab{0}`.{1}".format(doctype, frappe.scrub(filters.get("group_by")))
+		return "ORDER BY `tab{}`.{}".format(doctype, frappe.scrub(filters.get("group_by")))
 
 
 def get_items(filters, additional_query_columns, additional_conditions=None):
@@ -423,14 +426,12 @@
 			`tabSales Invoice Item`.stock_qty, `tabSales Invoice Item`.stock_uom,
 			`tabSales Invoice Item`.base_net_rate, `tabSales Invoice Item`.base_net_amount,
 			`tabSales Invoice`.customer_name, `tabSales Invoice`.customer_group, `tabSales Invoice Item`.so_detail,
-			`tabSales Invoice`.update_stock, `tabSales Invoice Item`.uom, `tabSales Invoice Item`.qty {0}
+			`tabSales Invoice`.update_stock, `tabSales Invoice Item`.uom, `tabSales Invoice Item`.qty {}
 		from `tabSales Invoice`, `tabSales Invoice Item`, `tabItem`
 		where `tabSales Invoice`.name = `tabSales Invoice Item`.parent and
 			`tabItem`.name = `tabSales Invoice Item`.`item_code` and
-			`tabSales Invoice`.docstatus = 1 {1}
-		""".format(
-			additional_query_columns, conditions
-		),
+			`tabSales Invoice`.docstatus = 1 {}
+		""".format(additional_query_columns, conditions),
 		filters,
 		as_dict=1,
 	)  # nosec
@@ -460,20 +461,15 @@
 
 
 def get_grand_total(filters, doctype):
-
 	return frappe.db.sql(
-		""" SELECT
-		SUM(`tab{0}`.base_grand_total)
-		FROM `tab{0}`
-		WHERE `tab{0}`.docstatus = 1
+		f""" SELECT
+		SUM(`tab{doctype}`.base_grand_total)
+		FROM `tab{doctype}`
+		WHERE `tab{doctype}`.docstatus = 1
 		and posting_date between %s and %s
-	""".format(
-			doctype
-		),
+	""",
 		(filters.get("from_date"), filters.get("to_date")),
-	)[0][
-		0
-	]  # nosec
+	)[0][0]  # nosec
 
 
 def get_tax_accounts(
@@ -492,9 +488,7 @@
 	add_deduct_tax = "charge_type"
 
 	tax_amount_precision = (
-		get_field_precision(
-			frappe.get_meta(tax_doctype).get_field("tax_amount"), currency=company_currency
-		)
+		get_field_precision(frappe.get_meta(tax_doctype).get_field("tax_amount"), currency=company_currency)
 		or 2
 	)
 
@@ -504,11 +498,13 @@
 
 	conditions = ""
 	if doctype == "Purchase Invoice":
-		conditions = " and category in ('Total', 'Valuation and Total') and base_tax_amount_after_discount_amount != 0"
+		conditions = (
+			" and category in ('Total', 'Valuation and Total') and base_tax_amount_after_discount_amount != 0"
+		)
 		add_deduct_tax = "add_deduct_tax"
 
 	tax_details = frappe.db.sql(
-		"""
+		f"""
 		select
 			name, parent, description, item_wise_tax_detail, account_head,
 			charge_type, {add_deduct_tax}, base_tax_amount_after_discount_amount
@@ -519,11 +515,9 @@
 			and parent in (%s)
 			%s
 		order by description
-	""".format(
-			add_deduct_tax=add_deduct_tax
-		)
+	"""
 		% (tax_doctype, "%s", ", ".join(["%s"] * len(invoice_item_row)), conditions),
-		tuple([doctype] + list(invoice_item_row)),
+		tuple([doctype, *list(invoice_item_row)]),
 	)
 
 	account_doctype = frappe.qb.DocType("Account")
@@ -531,13 +525,13 @@
 	query = (
 		frappe.qb.from_(account_doctype)
 		.select(account_doctype.name)
-		.where((account_doctype.account_type == "Tax"))
+		.where(account_doctype.account_type == "Tax")
 	)
 
 	tax_accounts = query.run()
 
 	for (
-		name,
+		_name,
 		parent,
 		description,
 		item_wise_tax_detail,
@@ -598,7 +592,9 @@
 				itemised_tax.setdefault(d.name, {})[description] = frappe._dict(
 					{
 						"tax_rate": "NA",
-						"tax_amount": flt((tax_amount * d.base_net_amount) / d.base_net_total, tax_amount_precision),
+						"tax_amount": flt(
+							(tax_amount * d.base_net_amount) / d.base_net_total, tax_amount_precision
+						),
 					}
 				)
 
diff --git a/erpnext/accounts/report/payment_ledger/payment_ledger.py b/erpnext/accounts/report/payment_ledger/payment_ledger.py
index 8875d27..9852c6e 100644
--- a/erpnext/accounts/report/payment_ledger/payment_ledger.py
+++ b/erpnext/accounts/report/payment_ledger/payment_ledger.py
@@ -8,7 +8,7 @@
 from frappe.query_builder import Criterion
 
 
-class PaymentLedger(object):
+class PaymentLedger:
 	def __init__(self, filters=None):
 		self.filters = filters
 		self.columns, self.data = [], []
diff --git a/erpnext/accounts/report/payment_ledger/test_payment_ledger.py b/erpnext/accounts/report/payment_ledger/test_payment_ledger.py
index 5ae9b87..c982f31 100644
--- a/erpnext/accounts/report/payment_ledger/test_payment_ledger.py
+++ b/erpnext/accounts/report/payment_ledger/test_payment_ledger.py
@@ -1,5 +1,3 @@
-import unittest
-
 import frappe
 from frappe import qb
 from frappe.tests.utils import FrappeTestCase
@@ -57,7 +55,7 @@
 			income_account=self.income_account,
 			warehouse=self.warehouse,
 		)
-		pe = get_payment_entry(sinv.doctype, sinv.name).save().submit()
+		get_payment_entry(sinv.doctype, sinv.name).save().submit()
 
 		filters = frappe._dict({"company": self.company})
 		columns, data = execute(filters=filters)
diff --git a/erpnext/accounts/report/payment_period_based_on_invoice_date/payment_period_based_on_invoice_date.py b/erpnext/accounts/report/payment_period_based_on_invoice_date/payment_period_based_on_invoice_date.py
index eaeaa62..834eb5f 100644
--- a/erpnext/accounts/report/payment_period_based_on_invoice_date/payment_period_based_on_invoice_date.py
+++ b/erpnext/accounts/report/payment_period_based_on_invoice_date/payment_period_based_on_invoice_date.py
@@ -163,10 +163,8 @@
 		"""select
 		voucher_type, voucher_no, party_type, party, posting_date, debit, credit, remarks, against_voucher
 		from `tabGL Entry`
-		where company=%(company)s and voucher_type in ('Journal Entry', 'Payment Entry') and is_cancelled = 0 {0}
-	""".format(
-			get_conditions(filters)
-		),
+		where company=%(company)s and voucher_type in ('Journal Entry', 'Payment Entry') and is_cancelled = 0 {}
+	""".format(get_conditions(filters)),
 		filters,
 		as_dict=1,
 	)
@@ -175,7 +173,7 @@
 def get_invoice_posting_date_map(filters):
 	invoice_details = {}
 	dt = "Sales Invoice" if filters.get("payment_type") == _("Incoming") else "Purchase Invoice"
-	for t in frappe.db.sql("select name, posting_date, due_date from `tab{0}`".format(dt), as_dict=1):
+	for t in frappe.db.sql(f"select name, posting_date, due_date from `tab{dt}`", as_dict=1):
 		invoice_details[t.name] = t
 
 	return invoice_details
diff --git a/erpnext/accounts/report/pos_register/pos_register.py b/erpnext/accounts/report/pos_register/pos_register.py
index 488bb99..7640ae8 100644
--- a/erpnext/accounts/report/pos_register/pos_register.py
+++ b/erpnext/accounts/report/pos_register/pos_register.py
@@ -50,17 +50,19 @@
 	order_by = "p.posting_date"
 	select_mop_field, from_sales_invoice_payment, group_by_mop_condition = "", "", ""
 	if group_by_field == "mode_of_payment":
-		select_mop_field = ", sip.mode_of_payment, sip.base_amount - IF(sip.type='Cash', p.change_amount, 0) as paid_amount"
+		select_mop_field = (
+			", sip.mode_of_payment, sip.base_amount - IF(sip.type='Cash', p.change_amount, 0) as paid_amount"
+		)
 		from_sales_invoice_payment = ", `tabSales Invoice Payment` sip"
 		group_by_mop_condition = "sip.parent = p.name AND ifnull(sip.base_amount - IF(sip.type='Cash', p.change_amount, 0), 0) != 0 AND"
 		order_by += ", sip.mode_of_payment"
 
 	elif group_by_field:
-		order_by += ", p.{}".format(group_by_field)
+		order_by += f", p.{group_by_field}"
 		select_mop_field = ", p.base_paid_amount - p.change_amount  as paid_amount "
 
 	return frappe.db.sql(
-		"""
+		f"""
 		SELECT
 			p.posting_date, p.name as pos_invoice, p.pos_profile,
 			p.owner, p.customer, p.is_return, p.base_grand_total as grand_total {select_mop_field}
@@ -72,13 +74,7 @@
 			{conditions}
 		ORDER BY
 			{order_by}
-		""".format(
-			select_mop_field=select_mop_field,
-			from_sales_invoice_payment=from_sales_invoice_payment,
-			group_by_mop_condition=group_by_mop_condition,
-			conditions=conditions,
-			order_by=order_by,
-		),
+		""",
 		filters,
 		as_dict=1,
 	)
@@ -131,9 +127,7 @@
 
 
 def get_conditions(filters):
-	conditions = (
-		"company = %(company)s AND posting_date >= %(from_date)s AND posting_date <= %(to_date)s"
-	)
+	conditions = "company = %(company)s AND posting_date >= %(from_date)s AND posting_date <= %(to_date)s"
 
 	if filters.get("pos_profile"):
 		conditions += " AND pos_profile = %(pos_profile)s"
diff --git a/erpnext/accounts/report/profit_and_loss_statement/profit_and_loss_statement.py b/erpnext/accounts/report/profit_and_loss_statement/profit_and_loss_statement.py
index 12a8554..58610b2 100644
--- a/erpnext/accounts/report/profit_and_loss_statement/profit_and_loss_statement.py
+++ b/erpnext/accounts/report/profit_and_loss_statement/profit_and_loss_statement.py
@@ -57,9 +57,7 @@
 	if net_profit_loss:
 		data.append(net_profit_loss)
 
-	columns = get_columns(
-		filters.periodicity, period_list, filters.accumulated_values, filters.company
-	)
+	columns = get_columns(filters.periodicity, period_list, filters.accumulated_values, filters.company)
 
 	chart = get_chart_data(filters, columns, income, expense, net_profit_loss)
 
diff --git a/erpnext/accounts/report/profit_and_loss_statement/test_profit_and_loss_statement.py b/erpnext/accounts/report/profit_and_loss_statement/test_profit_and_loss_statement.py
index b4423ab..816c2b9 100644
--- a/erpnext/accounts/report/profit_and_loss_statement/test_profit_and_loss_statement.py
+++ b/erpnext/accounts/report/profit_and_loss_statement/test_profit_and_loss_statement.py
@@ -3,7 +3,7 @@
 
 import frappe
 from frappe.tests.utils import FrappeTestCase
-from frappe.utils import add_days, getdate, today
+from frappe.utils import getdate, today
 
 from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice
 from erpnext.accounts.report.financial_statements import get_period_list
@@ -61,7 +61,7 @@
 		)
 
 	def test_profit_and_loss_output_and_summary(self):
-		si = self.create_sales_invoice(qty=1, rate=150)
+		self.create_sales_invoice(qty=1, rate=150)
 
 		filters = self.get_report_filters()
 		period_list = get_period_list(
@@ -75,9 +75,7 @@
 		)
 
 		result = execute(filters)[1]
-		current_period = [x for x in period_list if x.from_date <= getdate() and x.to_date >= getdate()][
-			0
-		]
+		current_period = next(x for x in period_list if x.from_date <= getdate() and x.to_date >= getdate())
 		current_period_key = current_period.key
 		without_current_period = [x for x in period_list if x.key != current_period.key]
 		# all period except current period(whence invoice was posted), should be '0'
diff --git a/erpnext/accounts/report/purchase_register/purchase_register.py b/erpnext/accounts/report/purchase_register/purchase_register.py
index 39eb312..504c74b 100644
--- a/erpnext/accounts/report/purchase_register/purchase_register.py
+++ b/erpnext/accounts/report/purchase_register/purchase_register.py
@@ -316,16 +316,12 @@
 			tuple([inv.name for inv in invoice_list]),
 		)
 
-		purchase_taxes_query = get_taxes_query(
-			invoice_list, "Purchase Taxes and Charges", "Purchase Invoice"
-		)
+		purchase_taxes_query = get_taxes_query(invoice_list, "Purchase Taxes and Charges", "Purchase Invoice")
 		purchase_tax_accounts = purchase_taxes_query.run(as_dict=True, pluck="account_head")
 		tax_accounts = purchase_tax_accounts
 
 		if include_payments:
-			advance_taxes_query = get_taxes_query(
-				invoice_list, "Advance Taxes and Charges", "Payment Entry"
-			)
+			advance_taxes_query = get_taxes_query(invoice_list, "Advance Taxes and Charges", "Payment Entry")
 			advance_tax_accounts = advance_taxes_query.run(as_dict=True, pluck="account_head")
 			tax_accounts = set(tax_accounts + advance_tax_accounts)
 
@@ -399,7 +395,7 @@
 			pi.outstanding_amount,
 			pi.mode_of_payment,
 		)
-		.where((pi.docstatus == 1))
+		.where(pi.docstatus == 1)
 		.orderby(pi.posting_date, pi.name, order=Order.desc)
 	)
 
@@ -443,9 +439,7 @@
 		account_fieldname="paid_to",
 		party="supplier",
 		party_name="supplier_name",
-		party_account=get_party_account(
-			"Supplier", filters.supplier, filters.company, include_advance=True
-		),
+		party_account=get_party_account("Supplier", filters.supplier, filters.company, include_advance=True),
 	)
 	payment_entries = get_payment_entries(filters, args)
 	journal_entries = get_journal_entries(filters, args)
@@ -491,9 +485,7 @@
 	return internal_invoice_map
 
 
-def get_invoice_tax_map(
-	invoice_list, invoice_expense_map, expense_accounts, include_payments=False
-):
+def get_invoice_tax_map(invoice_list, invoice_expense_map, expense_accounts, include_payments=False):
 	tax_details = frappe.db.sql(
 		"""
 		select parent, account_head, case add_deduct_tax when "Add" then sum(base_tax_amount_after_discount_amount)
@@ -558,9 +550,7 @@
 			invoice_po_pr_map.setdefault(d.parent, frappe._dict()).setdefault("purchase_receipt", pr_list)
 
 		if d.project:
-			invoice_po_pr_map.setdefault(d.parent, frappe._dict()).setdefault("project", []).append(
-				d.project
-			)
+			invoice_po_pr_map.setdefault(d.parent, frappe._dict()).setdefault("project", []).append(d.project)
 
 	return invoice_po_pr_map
 
diff --git a/erpnext/accounts/report/purchase_register/test_purchase_register.py b/erpnext/accounts/report/purchase_register/test_purchase_register.py
index 6903662..a7a5c07 100644
--- a/erpnext/accounts/report/purchase_register/test_purchase_register.py
+++ b/erpnext/accounts/report/purchase_register/test_purchase_register.py
@@ -3,7 +3,7 @@
 
 import frappe
 from frappe.tests.utils import FrappeTestCase
-from frappe.utils import add_months, getdate, today
+from frappe.utils import add_months, today
 
 from erpnext.accounts.report.purchase_register.purchase_register import execute
 
@@ -13,9 +13,7 @@
 		frappe.db.sql("delete from `tabPurchase Invoice` where company='_Test Company 6'")
 		frappe.db.sql("delete from `tabGL Entry` where company='_Test Company 6'")
 
-		filters = frappe._dict(
-			company="_Test Company 6", from_date=add_months(today(), -1), to_date=today()
-		)
+		filters = frappe._dict(company="_Test Company 6", from_date=add_months(today(), -1), to_date=today())
 
 		pi = make_purchase_invoice()
 
@@ -40,7 +38,7 @@
 			supplier="_Test Supplier",
 		)
 
-		pi = make_purchase_invoice()
+		make_purchase_invoice()
 		pe = make_payment_entry()
 
 		report_results = execute(filters)
@@ -58,7 +56,7 @@
 	from erpnext.accounts.doctype.cost_center.test_cost_center import create_cost_center
 	from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse
 
-	gst_acc = create_account(
+	create_account(
 		account_name="GST",
 		account_type="Tax",
 		parent_account="Duties and Taxes - _TC6",
diff --git a/erpnext/accounts/report/sales_payment_summary/sales_payment_summary.py b/erpnext/accounts/report/sales_payment_summary/sales_payment_summary.py
index 0577214..7c2bf7e 100644
--- a/erpnext/accounts/report/sales_payment_summary/sales_payment_summary.py
+++ b/erpnext/accounts/report/sales_payment_summary/sales_payment_summary.py
@@ -144,9 +144,9 @@
 		"ON ("
 		"t1.parent = a.name and t1.base_total = a.base_total) "
 		"WHERE a.docstatus = 1"
-		" AND {conditions} "
+		f" AND {conditions} "
 		"GROUP BY "
-		"owner, posting_date, warehouse".format(conditions=conditions),
+		"owner, posting_date, warehouse",
 		filters,
 		as_dict=1,
 	)
@@ -156,7 +156,7 @@
 def get_sales_invoice_data(filters):
 	conditions = get_conditions(filters)
 	return frappe.db.sql(
-		"""
+		f"""
 		select
 			a.posting_date, a.owner,
 			sum(a.net_total) as "net_total",
@@ -168,9 +168,7 @@
 			and {conditions}
 			group by
 			a.owner, a.posting_date
-	""".format(
-			conditions=conditions
-		),
+	""",
 		filters,
 		as_dict=1,
 	)
@@ -182,7 +180,7 @@
 	invoice_list_names = ",".join("'" + invoice["name"] + "'" for invoice in invoice_list)
 	if invoice_list:
 		inv_mop = frappe.db.sql(
-			"""select a.owner,a.posting_date, ifnull(b.mode_of_payment, '') as mode_of_payment
+			f"""select a.owner,a.posting_date, ifnull(b.mode_of_payment, '') as mode_of_payment
 			from `tabSales Invoice` a, `tabSales Invoice Payment` b
 			where a.name = b.parent
 			and a.docstatus = 1
@@ -202,9 +200,7 @@
 			and a.docstatus = 1
 			and b.reference_type = 'Sales Invoice'
 			and b.reference_name in ({invoice_list_names})
-			""".format(
-				invoice_list_names=invoice_list_names
-			),
+			""",
 			as_dict=1,
 		)
 		for d in inv_mop:
@@ -215,11 +211,9 @@
 def get_invoices(filters):
 	conditions = get_conditions(filters)
 	return frappe.db.sql(
-		"""select a.name
+		f"""select a.name
 		from `tabSales Invoice` a
-		where a.docstatus = 1 and {conditions}""".format(
-			conditions=conditions
-		),
+		where a.docstatus = 1 and {conditions}""",
 		filters,
 		as_dict=1,
 	)
@@ -231,7 +225,7 @@
 	invoice_list_names = ",".join("'" + invoice["name"] + "'" for invoice in invoice_list)
 	if invoice_list:
 		inv_mop_detail = frappe.db.sql(
-			"""
+			f"""
 			select t.owner,
 			       t.posting_date,
 				   t.mode_of_payment,
@@ -264,23 +258,19 @@
 				group by a.owner, a.posting_date, mode_of_payment
 			) t
 			group by t.owner, t.posting_date, t.mode_of_payment
-			""".format(
-				invoice_list_names=invoice_list_names
-			),
+			""",
 			as_dict=1,
 		)
 
 		inv_change_amount = frappe.db.sql(
-			"""select a.owner, a.posting_date,
+			f"""select a.owner, a.posting_date,
 			ifnull(b.mode_of_payment, '') as mode_of_payment, sum(a.base_change_amount) as change_amount
 			from `tabSales Invoice` a, `tabSales Invoice Payment` b
 			where a.name = b.parent
 			and a.name in ({invoice_list_names})
 			and b.type = 'Cash'
 			and a.base_change_amount > 0
-			group by a.owner, a.posting_date, mode_of_payment""".format(
-				invoice_list_names=invoice_list_names
-			),
+			group by a.owner, a.posting_date, mode_of_payment""",
 			as_dict=1,
 		)
 
diff --git a/erpnext/accounts/report/sales_payment_summary/test_sales_payment_summary.py b/erpnext/accounts/report/sales_payment_summary/test_sales_payment_summary.py
index 3ad0ff2..3be96c6 100644
--- a/erpnext/accounts/report/sales_payment_summary/test_sales_payment_summary.py
+++ b/erpnext/accounts/report/sales_payment_summary/test_sales_payment_summary.py
@@ -33,7 +33,7 @@
 	def test_get_mode_of_payments(self):
 		filters = get_filters()
 
-		for dummy in range(2):
+		for _dummy in range(2):
 			si = create_sales_invoice_record()
 			si.insert()
 			si.submit()
@@ -53,8 +53,8 @@
 			pe.submit()
 
 		mop = get_mode_of_payments(filters)
-		self.assertTrue("Credit Card" in list(mop.values())[0])
-		self.assertTrue("Cash" in list(mop.values())[0])
+		self.assertTrue("Credit Card" in next(iter(mop.values())))
+		self.assertTrue("Cash" in next(iter(mop.values())))
 
 		# Cancel all Cash payment entry and check if this mode of payment is still fetched.
 		payment_entries = frappe.get_all(
@@ -67,13 +67,13 @@
 			pe.cancel()
 
 		mop = get_mode_of_payments(filters)
-		self.assertTrue("Credit Card" in list(mop.values())[0])
-		self.assertTrue("Cash" not in list(mop.values())[0])
+		self.assertTrue("Credit Card" in next(iter(mop.values())))
+		self.assertTrue("Cash" not in next(iter(mop.values())))
 
 	def test_get_mode_of_payments_details(self):
 		filters = get_filters()
 
-		for dummy in range(2):
+		for _dummy in range(2):
 			si = create_sales_invoice_record()
 			si.insert()
 			si.submit()
@@ -94,7 +94,7 @@
 
 		mopd = get_mode_of_payment_details(filters)
 
-		mopd_values = list(mopd.values())[0]
+		mopd_values = next(iter(mopd.values()))
 		for mopd_value in mopd_values:
 			if mopd_value[0] == "Credit Card":
 				cc_init_amount = mopd_value[1]
@@ -110,7 +110,7 @@
 			pe.cancel()
 
 		mopd = get_mode_of_payment_details(filters)
-		mopd_values = list(mopd.values())[0]
+		mopd_values = next(iter(mopd.values()))
 		for mopd_value in mopd_values:
 			if mopd_value[0] == "Credit Card":
 				cc_final_amount = mopd_value[1]
diff --git a/erpnext/accounts/report/sales_register/sales_register.py b/erpnext/accounts/report/sales_register/sales_register.py
index ec6dd72..f275695 100644
--- a/erpnext/accounts/report/sales_register/sales_register.py
+++ b/erpnext/accounts/report/sales_register/sales_register.py
@@ -129,7 +129,8 @@
 			if tax_acc not in income_accounts:
 				tax_amount_precision = (
 					get_field_precision(
-						frappe.get_meta("Sales Taxes and Charges").get_field("tax_amount"), currency=company_currency
+						frappe.get_meta("Sales Taxes and Charges").get_field("tax_amount"),
+						currency=company_currency,
 					)
 					or 2
 				)
@@ -357,9 +358,7 @@
 		tax_accounts = sales_tax_accounts
 
 		if include_payments:
-			advance_taxes_query = get_taxes_query(
-				invoice_list, "Advance Taxes and Charges", "Payment Entry"
-			)
+			advance_taxes_query = get_taxes_query(invoice_list, "Advance Taxes and Charges", "Payment Entry")
 			advance_tax_accounts = advance_taxes_query.run(as_dict=True, pluck="account_head")
 			tax_accounts = set(tax_accounts + advance_tax_accounts)
 
@@ -438,7 +437,7 @@
 			si.represents_company,
 			si.company,
 		)
-		.where((si.docstatus == 1))
+		.where(si.docstatus == 1)
 		.orderby(si.posting_date, si.name, order=Order.desc)
 	)
 
@@ -480,9 +479,7 @@
 		account_fieldname="paid_from",
 		party="customer",
 		party_name="customer_name",
-		party_account=get_party_account(
-			"Customer", filters.customer, filters.company, include_advance=True
-		),
+		party_account=get_party_account("Customer", filters.customer, filters.company, include_advance=True),
 	)
 	payment_entries = get_payment_entries(filters, args)
 	journal_entries = get_journal_entries(filters, args)
diff --git a/erpnext/accounts/report/share_balance/share_balance.py b/erpnext/accounts/report/share_balance/share_balance.py
index d02f53b..1d02a99 100644
--- a/erpnext/accounts/report/share_balance/share_balance.py
+++ b/erpnext/accounts/report/share_balance/share_balance.py
@@ -15,7 +15,7 @@
 
 	columns = get_columns(filters)
 
-	date = filters.get("date")
+	filters.get("date")
 
 	data = []
 
diff --git a/erpnext/accounts/report/share_ledger/share_ledger.py b/erpnext/accounts/report/share_ledger/share_ledger.py
index 629528e..ed65687 100644
--- a/erpnext/accounts/report/share_ledger/share_ledger.py
+++ b/erpnext/accounts/report/share_ledger/share_ledger.py
@@ -26,9 +26,9 @@
 		for transfer in transfers:
 			if transfer.transfer_type == "Transfer":
 				if transfer.from_shareholder == filters.get("shareholder"):
-					transfer.transfer_type += " to {}".format(transfer.to_shareholder)
+					transfer.transfer_type += f" to {transfer.to_shareholder}"
 				else:
-					transfer.transfer_type += " from {}".format(transfer.from_shareholder)
+					transfer.transfer_type += f" from {transfer.from_shareholder}"
 			row = [
 				filters.get("shareholder"),
 				transfer.date,
@@ -66,13 +66,11 @@
 	# if company:
 	# 	condition = 'AND company = %(company)s '
 	return frappe.db.sql(
-		"""SELECT * FROM `tabShare Transfer`
+		f"""SELECT * FROM `tabShare Transfer`
 		WHERE ((DATE(date) <= %(date)s AND from_shareholder = %(shareholder)s {condition})
 		OR (DATE(date) <= %(date)s AND to_shareholder = %(shareholder)s {condition}))
 		AND docstatus = 1
-		ORDER BY date""".format(
-			condition=condition
-		),
+		ORDER BY date""",
 		{"date": date, "shareholder": shareholder},
 		as_dict=1,
 	)
diff --git a/erpnext/accounts/report/tax_withholding_details/tax_withholding_details.py b/erpnext/accounts/report/tax_withholding_details/tax_withholding_details.py
index b18570b..ab50fcd 100644
--- a/erpnext/accounts/report/tax_withholding_details/tax_withholding_details.py
+++ b/erpnext/accounts/report/tax_withholding_details/tax_withholding_details.py
@@ -37,9 +37,7 @@
 		frappe.throw(_("From Date must be before To Date"))
 
 
-def get_result(
-	filters, tds_docs, tds_accounts, tax_category_map, journal_entry_party_map, net_total_map
-):
+def get_result(filters, tds_docs, tds_accounts, tax_category_map, journal_entry_party_map, net_total_map):
 	party_map = get_party_pan_map(filters.get("party_type"))
 	tax_rate_map = get_tax_rate_map(filters)
 	gle_map = get_gle_map(tds_docs)
@@ -92,9 +90,9 @@
 					party_type = "customer_type"
 
 				row = {
-					"pan"
-					if frappe.db.has_column(filters.party_type, "pan")
-					else "tax_id": party_map.get(party, {}).get("pan"),
+					"pan" if frappe.db.has_column(filters.party_type, "pan") else "tax_id": party_map.get(
+						party, {}
+					).get("pan"),
 					"party": party_map.get(party, {}).get("name"),
 				}
 
@@ -281,7 +279,7 @@
 	journal_entries = []
 	tax_category_map = frappe._dict()
 	net_total_map = frappe._dict()
-	or_filters = frappe._dict()
+	frappe._dict()
 	journal_entry_party_map = frappe._dict()
 	bank_accounts = frappe.get_all("Account", {"is_group": 0, "account_type": "Bank"}, pluck="name")
 
@@ -344,7 +342,7 @@
 	query = (
 		frappe.qb.from_(gle)
 		.select("voucher_no", "voucher_type", "against", "party")
-		.where((gle.is_cancelled == 0))
+		.where(gle.is_cancelled == 0)
 	)
 
 	if filters.get("from_date"):
diff --git a/erpnext/accounts/report/tds_computation_summary/tds_computation_summary.py b/erpnext/accounts/report/tds_computation_summary/tds_computation_summary.py
index 2b5566f..e14d932 100644
--- a/erpnext/accounts/report/tds_computation_summary/tds_computation_summary.py
+++ b/erpnext/accounts/report/tds_computation_summary/tds_computation_summary.py
@@ -67,13 +67,13 @@
 			},
 		)
 
-		party_category_wise_map.get((row.get("party"), row.get("section_code")))[
-			"total_amount"
-		] += row.get("total_amount", 0.0)
+		party_category_wise_map.get((row.get("party"), row.get("section_code")))["total_amount"] += row.get(
+			"total_amount", 0.0
+		)
 
-		party_category_wise_map.get((row.get("party"), row.get("section_code")))[
-			"tax_amount"
-		] += row.get("tax_amount", 0.0)
+		party_category_wise_map.get((row.get("party"), row.get("section_code")))["tax_amount"] += row.get(
+			"tax_amount", 0.0
+		)
 
 	final_result = get_final_result(party_category_wise_map)
 
@@ -82,7 +82,7 @@
 
 def get_final_result(party_category_wise_map):
 	out = []
-	for key, value in party_category_wise_map.items():
+	for _key, value in party_category_wise_map.items():
 		out.append(value)
 
 	return out
diff --git a/erpnext/accounts/report/trial_balance/trial_balance.py b/erpnext/accounts/report/trial_balance/trial_balance.py
index 2ff0eff..f216ece 100644
--- a/erpnext/accounts/report/trial_balance/trial_balance.py
+++ b/erpnext/accounts/report/trial_balance/trial_balance.py
@@ -120,9 +120,7 @@
 		ignore_opening_entries=True,
 	)
 
-	calculate_values(
-		accounts, gl_entries_by_account, opening_balances, filters.get("show_net_values")
-	)
+	calculate_values(accounts, gl_entries_by_account, opening_balances, filters.get("show_net_values"))
 	accumulate_values_into_parents(accounts, accounts_by_name)
 
 	data = prepare_data(accounts, filters, parent_children_map, company_currency)
@@ -170,9 +168,7 @@
 		)
 
 		# Report getting generate from the mid of a fiscal year
-		if getdate(last_period_closing_voucher[0].posting_date) < getdate(
-			add_days(filters.from_date, -1)
-		):
+		if getdate(last_period_closing_voucher[0].posting_date) < getdate(add_days(filters.from_date, -1)):
 			start_date = add_days(last_period_closing_voucher[0].posting_date, 1)
 			gle += get_opening_balance(
 				"GL Entry", filters, report_type, accounting_dimensions, start_date=start_date
@@ -253,9 +249,7 @@
 		if doctype == "Account Closing Balance":
 			opening_balance = opening_balance.where(closing_balance.is_period_closing_voucher_entry == 0)
 		else:
-			opening_balance = opening_balance.where(
-				closing_balance.voucher_type != "Period Closing Voucher"
-			)
+			opening_balance = opening_balance.where(closing_balance.voucher_type != "Period Closing Voucher")
 
 	if filters.cost_center:
 		lft, rgt = frappe.db.get_value("Cost Center", filters.cost_center, ["lft", "rgt"])
@@ -388,7 +382,7 @@
 			"to_date": filters.to_date,
 			"currency": company_currency,
 			"account_name": (
-				"{} - {}".format(d.account_number, d.account_name) if d.account_number else d.account_name
+				f"{d.account_number} - {d.account_name}" if d.account_number else d.account_name
 			),
 		}
 
diff --git a/erpnext/accounts/report/trial_balance_for_party/trial_balance_for_party.py b/erpnext/accounts/report/trial_balance_for_party/trial_balance_for_party.py
index ee22348..dd1a125 100644
--- a/erpnext/accounts/report/trial_balance_for_party/trial_balance_for_party.py
+++ b/erpnext/accounts/report/trial_balance_for_party/trial_balance_for_party.py
@@ -22,7 +22,7 @@
 
 def get_data(filters, show_party_name):
 	if filters.get("party_type") in ("Customer", "Supplier", "Employee", "Member"):
-		party_name_field = "{0}_name".format(frappe.scrub(filters.get("party_type")))
+		party_name_field = "{}_name".format(frappe.scrub(filters.get("party_type")))
 	elif filters.get("party_type") == "Shareholder":
 		party_name_field = "title"
 	else:
@@ -65,9 +65,7 @@
 		row.update({"debit": debit, "credit": credit})
 
 		# closing
-		closing_debit, closing_credit = toggle_debit_credit(
-			opening_debit + debit, opening_credit + credit
-		)
+		closing_debit, closing_credit = toggle_debit_credit(opening_debit + debit, opening_credit + credit)
 		row.update({"closing_debit": closing_debit, "closing_credit": closing_credit})
 
 		# totals
@@ -92,13 +90,12 @@
 
 
 def get_opening_balances(filters):
-
 	account_filter = ""
 	if filters.get("account"):
 		account_filter = "and account = %s" % (frappe.db.escape(filters.get("account")))
 
 	gle = frappe.db.sql(
-		"""
+		f"""
 		select party, sum(debit) as opening_debit, sum(credit) as opening_credit
 		from `tabGL Entry`
 		where company=%(company)s
@@ -106,9 +103,7 @@
 			and ifnull(party_type, '') = %(party_type)s and ifnull(party, '') != ''
 			and (posting_date < %(from_date)s or (ifnull(is_opening, 'No') = 'Yes' and posting_date <= %(to_date)s))
 			{account_filter}
-		group by party""".format(
-			account_filter=account_filter
-		),
+		group by party""",
 		{
 			"company": filters.company,
 			"from_date": filters.from_date,
@@ -127,13 +122,12 @@
 
 
 def get_balances_within_period(filters):
-
 	account_filter = ""
 	if filters.get("account"):
 		account_filter = "and account = %s" % (frappe.db.escape(filters.get("account")))
 
 	gle = frappe.db.sql(
-		"""
+		f"""
 		select party, sum(debit) as debit, sum(credit) as credit
 		from `tabGL Entry`
 		where company=%(company)s
@@ -142,9 +136,7 @@
 			and posting_date >= %(from_date)s and posting_date <= %(to_date)s
 			and ifnull(is_opening, 'No') = 'No'
 			{account_filter}
-		group by party""".format(
-			account_filter=account_filter
-		),
+		group by party""",
 		{
 			"company": filters.company,
 			"from_date": filters.from_date,
diff --git a/erpnext/accounts/report/utils.py b/erpnext/accounts/report/utils.py
index aed338a7..bd1b355 100644
--- a/erpnext/accounts/report/utils.py
+++ b/erpnext/accounts/report/utils.py
@@ -78,10 +78,10 @@
 	:return: Retrieved exchange rate
 	"""
 
-	rate = __exchange_rates.get("{0}-{1}@{2}".format(from_currency, to_currency, date))
+	rate = __exchange_rates.get(f"{from_currency}-{to_currency}@{date}")
 	if not rate:
 		rate = get_exchange_rate(from_currency, to_currency, date) or 1
-		__exchange_rates["{0}-{1}@{2}".format(from_currency, to_currency, date)] = rate
+		__exchange_rates[f"{from_currency}-{to_currency}@{date}"] = rate
 
 	return rate
 
@@ -136,9 +136,7 @@
 
 
 @frappe.whitelist()
-def get_invoiced_item_gross_margin(
-	sales_invoice=None, item_code=None, company=None, with_item_data=False
-):
+def get_invoiced_item_gross_margin(sales_invoice=None, item_code=None, company=None, with_item_data=False):
 	from erpnext.accounts.report.gross_profit.gross_profit import GrossProfitGenerator
 
 	sales_invoice = sales_invoice or frappe.form_dict.get("sales_invoice")
diff --git a/erpnext/accounts/report/voucher_wise_balance/voucher_wise_balance.py b/erpnext/accounts/report/voucher_wise_balance/voucher_wise_balance.py
index bd9e9fc..1918165 100644
--- a/erpnext/accounts/report/voucher_wise_balance/voucher_wise_balance.py
+++ b/erpnext/accounts/report/voucher_wise_balance/voucher_wise_balance.py
@@ -43,9 +43,7 @@
 	gle = frappe.qb.DocType("GL Entry")
 	query = (
 		frappe.qb.from_(gle)
-		.select(
-			gle.voucher_type, gle.voucher_no, Sum(gle.debit).as_("debit"), Sum(gle.credit).as_("credit")
-		)
+		.select(gle.voucher_type, gle.voucher_no, Sum(gle.debit).as_("debit"), Sum(gle.credit).as_("credit"))
 		.where(gle.is_cancelled == 0)
 		.groupby(gle.voucher_no)
 	)
diff --git a/erpnext/accounts/test/test_reports.py b/erpnext/accounts/test/test_reports.py
index 609f74e..c2e10f8 100644
--- a/erpnext/accounts/test/test_reports.py
+++ b/erpnext/accounts/test/test_reports.py
@@ -1,5 +1,4 @@
 import unittest
-from typing import List, Tuple
 
 from erpnext.tests.utils import ReportFilters, ReportName, execute_script_report
 
@@ -12,7 +11,7 @@
 }
 
 
-REPORT_FILTER_TEST_CASES: List[Tuple[ReportName, ReportFilters]] = [
+REPORT_FILTER_TEST_CASES: list[tuple[ReportName, ReportFilters]] = [
 	("General Ledger", {"group_by": "Group by Voucher (Consolidated)"}),
 	("General Ledger", {"group_by": "Group by Voucher (Consolidated)", "include_dimensions": 1}),
 	("Accounts Payable", {"range1": 30, "range2": 60, "range3": 90, "range4": 120}),
diff --git a/erpnext/accounts/test/test_utils.py b/erpnext/accounts/test/test_utils.py
index c439d4b..59cbc11 100644
--- a/erpnext/accounts/test/test_utils.py
+++ b/erpnext/accounts/test/test_utils.py
@@ -10,7 +10,6 @@
 	get_future_stock_vouchers,
 	get_voucherwise_gl_entries,
 	sort_stock_vouchers_by_posting_date,
-	update_reference_in_payment_entry,
 )
 from erpnext.stock.doctype.item.test_item import make_item
 from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import make_purchase_receipt
@@ -20,7 +19,7 @@
 class TestUtils(unittest.TestCase):
 	@classmethod
 	def setUpClass(cls):
-		super(TestUtils, cls).setUpClass()
+		super().setUpClass()
 		make_test_objects("Address", ADDRESS_RECORDS)
 
 	@classmethod
@@ -36,7 +35,6 @@
 		self.assertEqual(address, "_Test Shipping Address 2 Title-Shipping")
 
 	def test_get_voucher_wise_gl_entry(self):
-
 		pr = make_purchase_receipt(
 			item_code="_Test Item",
 			posting_date="2021-02-01",
@@ -144,12 +142,8 @@
 		frappe.db.set_default("supp_master_name", "Auto Name")
 
 		# Configure Autoname in Supplier DocType
-		make_property_setter(
-			"Supplier", None, "naming_rule", "Expression", "Data", for_doctype="Doctype"
-		)
-		make_property_setter(
-			"Supplier", None, "autoname", "SUP-.FY.-.#####", "Data", for_doctype="Doctype"
-		)
+		make_property_setter("Supplier", None, "naming_rule", "Expression", "Data", for_doctype="Doctype")
+		make_property_setter("Supplier", None, "autoname", "SUP-.FY.-.#####", "Data", for_doctype="Doctype")
 
 		fiscal_year = get_fiscal_year(nowdate())[0]
 
@@ -171,9 +165,7 @@
 		"address_title": "_Test Billing Address Title",
 		"city": "Lagos",
 		"country": "Nigeria",
-		"links": [
-			{"link_doctype": "Customer", "link_name": "_Test Customer 2", "doctype": "Dynamic Link"}
-		],
+		"links": [{"link_doctype": "Customer", "link_name": "_Test Customer 2", "doctype": "Dynamic Link"}],
 	},
 	{
 		"doctype": "Address",
@@ -182,9 +174,7 @@
 		"address_title": "_Test Shipping Address 1 Title",
 		"city": "Lagos",
 		"country": "Nigeria",
-		"links": [
-			{"link_doctype": "Customer", "link_name": "_Test Customer 2", "doctype": "Dynamic Link"}
-		],
+		"links": [{"link_doctype": "Customer", "link_name": "_Test Customer 2", "doctype": "Dynamic Link"}],
 	},
 	{
 		"doctype": "Address",
@@ -194,9 +184,7 @@
 		"city": "Lagos",
 		"country": "Nigeria",
 		"is_shipping_address": "1",
-		"links": [
-			{"link_doctype": "Customer", "link_name": "_Test Customer 2", "doctype": "Dynamic Link"}
-		],
+		"links": [{"link_doctype": "Customer", "link_name": "_Test Customer 2", "doctype": "Dynamic Link"}],
 	},
 	{
 		"doctype": "Address",
@@ -206,8 +194,6 @@
 		"city": "Lagos",
 		"country": "Nigeria",
 		"is_shipping_address": "1",
-		"links": [
-			{"link_doctype": "Customer", "link_name": "_Test Customer 1", "doctype": "Dynamic Link"}
-		],
+		"links": [{"link_doctype": "Customer", "link_name": "_Test Customer 1", "doctype": "Dynamic Link"}],
 	},
 ]
diff --git a/erpnext/accounts/utils.py b/erpnext/accounts/utils.py
index 02012ad..b61f195 100644
--- a/erpnext/accounts/utils.py
+++ b/erpnext/accounts/utils.py
@@ -3,7 +3,7 @@
 
 
 from json import loads
-from typing import TYPE_CHECKING, List, Optional, Tuple
+from typing import TYPE_CHECKING, Optional
 
 import frappe
 import frappe.defaults
@@ -29,7 +29,7 @@
 import erpnext
 
 # imported to enable erpnext.accounts.utils.get_account_currency
-from erpnext.accounts.doctype.account.account import get_account_currency  # noqa
+from erpnext.accounts.doctype.account.account import get_account_currency
 from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import get_dimensions
 from erpnext.stock import get_warehouse_account_map
 from erpnext.stock.utils import get_stock_value_on
@@ -81,9 +81,7 @@
 		FY = DocType("Fiscal Year")
 
 		query = (
-			frappe.qb.from_(FY)
-			.select(FY.name, FY.year_start_date, FY.year_end_date)
-			.where(FY.disabled == 0)
+			frappe.qb.from_(FY).select(FY.name, FY.year_start_date, FY.year_end_date).where(FY.disabled == 0)
 		)
 
 		if fiscal_year:
@@ -130,9 +128,7 @@
 			else:
 				return ((fy.name, fy.year_start_date, fy.year_end_date),)
 
-	error_msg = _("""{0} {1} is not in any active Fiscal Year""").format(
-		label, formatdate(transaction_date)
-	)
+	error_msg = _("""{0} {1} is not in any active Fiscal Year""").format(label, formatdate(transaction_date))
 	if company:
 		error_msg = _("""{0} for {1}""").format(error_msg, frappe.bold(company))
 
@@ -209,12 +205,12 @@
 		acc = frappe.get_doc("Account", account)
 
 	try:
-		year_start_date = get_fiscal_year(date, company=company, verbose=0)[1]
+		get_fiscal_year(date, company=company, verbose=0)[1]
 	except FiscalYearError:
 		if getdate(date) > getdate(nowdate()):
 			# if fiscal year not found and the date is greater than today
 			# get fiscal year for today's date and its corresponding year start date
-			year_start_date = get_fiscal_year(nowdate(), verbose=1)[1]
+			get_fiscal_year(nowdate(), verbose=1)[1]
 		else:
 			# this indicates that it is a date older than any existing fiscal year.
 			# hence, assuming balance as 0.0
@@ -229,15 +225,14 @@
 		cc = frappe.get_doc("Cost Center", cost_center)
 		if cc.is_group:
 			cond.append(
-				""" exists (
+				f""" exists (
 				select 1 from `tabCost Center` cc where cc.name = gle.cost_center
-				and cc.lft >= %s and cc.rgt <= %s
+				and cc.lft >= {cc.lft} and cc.rgt <= {cc.rgt}
 			)"""
-				% (cc.lft, cc.rgt)
 			)
 
 		else:
-			cond.append("""gle.cost_center = %s """ % (frappe.db.escape(cost_center),))
+			cond.append(f"""gle.cost_center = {frappe.db.escape(cost_center)} """)
 
 	if account:
 		if not (frappe.flags.ignore_account_permission or ignore_account_permission):
@@ -246,11 +241,10 @@
 		# different filter for group and ledger - improved performance
 		if acc.is_group:
 			cond.append(
-				"""exists (
+				f"""exists (
 				select name from `tabAccount` ac where ac.name = gle.account
-				and ac.lft >= %s and ac.rgt <= %s
+				and ac.lft >= {acc.lft} and ac.rgt <= {acc.rgt}
 			)"""
-				% (acc.lft, acc.rgt)
 			)
 
 			# If group and currency same as company,
@@ -258,7 +252,7 @@
 			if acc.account_currency == frappe.get_cached_value("Company", acc.company, "default_currency"):
 				in_account_currency = False
 		else:
-			cond.append("""gle.account = %s """ % (frappe.db.escape(account),))
+			cond.append(f"""gle.account = {frappe.db.escape(account)} """)
 
 	if account_type:
 		accounts = frappe.db.get_all(
@@ -277,8 +271,7 @@
 
 	if party_type and party:
 		cond.append(
-			"""gle.party_type = %s and gle.party = %s """
-			% (frappe.db.escape(party_type), frappe.db.escape(party))
+			f"""gle.party_type = {frappe.db.escape(party_type)} and gle.party = {frappe.db.escape(party)} """
 		)
 
 	if company:
@@ -295,11 +288,9 @@
 
 		bal = frappe.db.sql(
 			"""
-			SELECT {0}
+			SELECT {}
 			FROM `tabGL Entry` gle
-			WHERE {1}""".format(
-				select_field, " and ".join(cond)
-			),
+			WHERE {}""".format(select_field, " and ".join(cond)),
 			(precision, precision),
 		)[0][0]
 		# if bal is None, return 0
@@ -334,30 +325,25 @@
 
 		# for pl accounts, get balance within a fiscal year
 		if acc.report_type == "Profit and Loss":
-			cond.append(
-				"posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" % year_start_date
-			)
+			cond.append("posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" % year_start_date)
 
 		# different filter for group and ledger - improved performance
 		if acc.is_group:
 			cond.append(
-				"""exists (
+				f"""exists (
 				select name from `tabAccount` ac where ac.name = gle.account
-				and ac.lft >= %s and ac.rgt <= %s
+				and ac.lft >= {acc.lft} and ac.rgt <= {acc.rgt}
 			)"""
-				% (acc.lft, acc.rgt)
 			)
 		else:
-			cond.append("""gle.account = %s """ % (frappe.db.escape(account),))
+			cond.append(f"""gle.account = {frappe.db.escape(account)} """)
 
 		entries = frappe.db.sql(
 			"""
 			SELECT name, posting_date, account, party_type, party,debit,credit,
 				voucher_type, voucher_no, against_voucher_type, against_voucher
 			FROM `tabGL Entry` gle
-			WHERE {0}""".format(
-				" and ".join(cond)
-			),
+			WHERE {}""".format(" and ".join(cond)),
 			as_dict=True,
 		)
 
@@ -380,13 +366,11 @@
 					or (gle.against_voucher == gle.voucher_no and gle.get(dr_or_cr) > 0)
 				):
 					payment_amount = frappe.db.sql(
-						"""
-						SELECT {0}
+						f"""
+						SELECT {select_fields}
 						FROM `tabGL Entry` gle
 						WHERE docstatus < 2 and posting_date <= %(date)s and against_voucher = %(voucher_no)s
-						and party = %(party)s and name != %(name)s""".format(
-							select_fields
-						),
+						and party = %(party)s and name != %(name)s""",
 						{"date": date, "voucher_no": gle.voucher_no, "party": gle.party, "name": gle.name},
 					)[0][0]
 
@@ -441,7 +425,7 @@
 	args = make_tree_args(**args)
 
 	if args.parent_cost_center == args.company:
-		args.parent_cost_center = "{0} - {1}".format(
+		args.parent_cost_center = "{} - {}".format(
 			args.parent_cost_center, frappe.get_cached_value("Company", args.company, "abbr")
 		)
 
@@ -457,7 +441,7 @@
 
 
 def _build_dimensions_dict_for_exc_gain_loss(
-	entry: dict | object = None, active_dimensions: list = None
+	entry: dict | object = None, active_dimensions: list | None = None
 ):
 	dimensions_dict = frappe._dict()
 	if entry and active_dimensions:
@@ -535,7 +519,11 @@
 		# Only update outstanding for newly linked vouchers
 		for entry in entries:
 			update_voucher_outstanding(
-				entry.against_voucher_type, entry.against_voucher, entry.account, entry.party_type, entry.party
+				entry.against_voucher_type,
+				entry.against_voucher,
+				entry.account,
+				entry.party_type,
+				entry.party,
 			)
 		# update advance paid in Advance Receivable/Payable doctypes
 		if update_advance_paid:
@@ -566,15 +554,15 @@
 			.select(journal_acc[args.get("dr_or_cr")])
 			.where(
 				(journal_acc.account == args.get("account"))
-				& ((journal_acc.party_type == args.get("party_type")))
-				& ((journal_acc.party == args.get("party")))
+				& (journal_acc.party_type == args.get("party_type"))
+				& (journal_acc.party == args.get("party"))
 				& (
 					(journal_acc.reference_type.isnull())
 					| (journal_acc.reference_type.isin(["", "Sales Order", "Purchase Order"]))
 				)
-				& ((journal_entry.name == args.get("voucher_no")))
-				& ((journal_acc.name == args.get("voucher_detail_no")))
-				& ((journal_entry.docstatus == 1))
+				& (journal_entry.name == args.get("voucher_no"))
+				& (journal_acc.name == args.get("voucher_detail_no"))
+				& (journal_entry.docstatus == 1)
 			)
 		)
 
@@ -614,9 +602,7 @@
 
 
 def validate_allocated_amount(args):
-	precision = args.get("precision") or frappe.db.get_single_value(
-		"System Settings", "currency_precision"
-	)
+	precision = args.get("precision") or frappe.db.get_single_value("System Settings", "currency_precision")
 	if args.get("allocated_amount") < 0:
 		throw(_("Allocated amount cannot be negative"))
 	elif flt(args.get("allocated_amount"), precision) > flt(args.get("unadjusted_amount"), precision):
@@ -631,9 +617,9 @@
 
 	# Update Advance Paid in SO/PO since they might be getting unlinked
 	update_advance_paid = []
-	advance_payment_doctypes = frappe.get_hooks(
-		"advance_payment_receivable_doctypes"
-	) + frappe.get_hooks("advance_payment_payable_doctypes")
+	advance_payment_doctypes = frappe.get_hooks("advance_payment_receivable_doctypes") + frappe.get_hooks(
+		"advance_payment_payable_doctypes"
+	)
 	if jv_detail.get("reference_type") in advance_payment_doctypes:
 		update_advance_paid.append((jv_detail.reference_type, jv_detail.reference_name))
 
@@ -709,9 +695,9 @@
 		existing_row = payment_entry.get("references", {"name": d["voucher_detail_no"]})[0]
 
 		# Update Advance Paid in SO/PO since they are getting unlinked
-		advance_payment_doctypes = frappe.get_hooks(
-			"advance_payment_receivable_doctypes"
-		) + frappe.get_hooks("advance_payment_payable_doctypes")
+		advance_payment_doctypes = frappe.get_hooks("advance_payment_receivable_doctypes") + frappe.get_hooks(
+			"advance_payment_payable_doctypes"
+		)
 		if existing_row.get("reference_doctype") in advance_payment_doctypes:
 			update_advance_paid.append((existing_row.reference_doctype, existing_row.reference_name))
 
@@ -747,7 +733,7 @@
 
 
 def cancel_exchange_gain_loss_journal(
-	parent_doc: dict | object, referenced_dt: str = None, referenced_dn: str = None
+	parent_doc: dict | object, referenced_dt: str | None = None, referenced_dn: str | None = None
 ) -> None:
 	"""
 	Cancel Exchange Gain/Loss for Sales/Purchase Invoice, if they have any.
@@ -790,7 +776,7 @@
 
 
 def update_accounting_ledgers_after_reference_removal(
-	ref_type: str = None, ref_no: str = None, payment_name: str = None
+	ref_type: str | None = None, ref_no: str | None = None, payment_name: str | None = None
 ):
 	# General Ledger
 	gle = qb.DocType("GL Entry")
@@ -816,9 +802,7 @@
 		.set(ple.modified, now())
 		.set(ple.modified_by, frappe.session.user)
 		.where(
-			(ple.against_voucher_type == ref_type)
-			& (ple.against_voucher_no == ref_no)
-			& (ple.delinked == 0)
+			(ple.against_voucher_type == ref_type) & (ple.against_voucher_no == ref_no) & (ple.delinked == 0)
 		)
 	)
 
@@ -835,7 +819,7 @@
 		qb.from_(adv_type).delete().where(adv_type.parent == ref_doc.name).run()
 
 
-def unlink_ref_doc_from_payment_entries(ref_doc: object = None, payment_name: str = None):
+def unlink_ref_doc_from_payment_entries(ref_doc: object = None, payment_name: str | None = None):
 	remove_ref_doc_link_from_jv(ref_doc.doctype, ref_doc.name, payment_name)
 	remove_ref_doc_link_from_pe(ref_doc.doctype, ref_doc.name, payment_name)
 	update_accounting_ledgers_after_reference_removal(ref_doc.doctype, ref_doc.name, payment_name)
@@ -843,7 +827,7 @@
 
 
 def remove_ref_doc_link_from_jv(
-	ref_type: str = None, ref_no: str = None, payment_name: str = None
+	ref_type: str | None = None, ref_no: str | None = None, payment_name: str | None = None
 ):
 	jea = qb.DocType("Journal Entry Account")
 
@@ -883,7 +867,7 @@
 
 
 def remove_ref_doc_link_from_pe(
-	ref_type: str = None, ref_no: str = None, payment_name: str = None
+	ref_type: str | None = None, ref_no: str | None = None, payment_name: str | None = None
 ):
 	per = qb.DocType("Payment Entry Reference")
 	pay = qb.DocType("Payment Entry")
@@ -891,9 +875,7 @@
 	linked_pe = (
 		qb.from_(per)
 		.select(per.parent)
-		.where(
-			(per.reference_doctype == ref_type) & (per.reference_name == ref_no) & (per.docstatus.lt(2))
-		)
+		.where((per.reference_doctype == ref_type) & (per.reference_name == ref_no) & (per.docstatus.lt(2)))
 		.run(as_list=1)
 	)
 	linked_pe = convert_to_list(linked_pe)
@@ -906,9 +888,7 @@
 			.set(per.allocated_amount, 0)
 			.set(per.modified, now())
 			.set(per.modified_by, frappe.session.user)
-			.where(
-				(per.docstatus.lt(2) & (per.reference_doctype == ref_type) & (per.reference_name == ref_no))
-			)
+			.where(per.docstatus.lt(2) & (per.reference_doctype == ref_type) & (per.reference_name == ref_no))
 		)
 
 		if payment_name:
@@ -923,13 +903,15 @@
 
 				# Call cancel on only removed reference
 				references = [
-					x for x in pe_doc.references if x.reference_doctype == ref_type and x.reference_name == ref_no
+					x
+					for x in pe_doc.references
+					if x.reference_doctype == ref_type and x.reference_name == ref_no
 				]
 				[pe_doc.make_advance_gl_entries(x, cancel=1) for x in references]
 
 				pe_doc.clear_unallocated_reference_document_rows()
 				pe_doc.validate_payment_type_with_outstanding()
-			except Exception as e:
+			except Exception:
 				msg = _("There were issues unlinking payment entry {0}.").format(pe_doc.name)
 				msg += "<br>"
 				msg += _("Please cancel payment entry manually first")
@@ -939,9 +921,7 @@
 				pay.base_total_allocated_amount, pe_doc.base_total_allocated_amount
 			).set(pay.unallocated_amount, pe_doc.unallocated_amount).set(pay.modified, now()).set(
 				pay.modified_by, frappe.session.user
-			).where(
-				pay.name == pe
-			).run()
+			).where(pay.name == pe).run()
 
 		frappe.msgprint(_("Payment Entries {0} are un-linked").format("\n".join(linked_pe)))
 
@@ -975,9 +955,10 @@
 			dr_or_cr = d.voucher_type == "Sales Invoice" and "credit" or "debit"
 
 			frappe.db.sql(
-				"""update `tabGL Entry` set %s = %s + %s
-				where voucher_type = %s and voucher_no = %s and %s > 0 limit 1"""
-				% (dr_or_cr, dr_or_cr, "%s", "%s", "%s", dr_or_cr),
+				"""update `tabGL Entry` set {} = {} + {}
+				where voucher_type = {} and voucher_no = {} and {} > 0 limit 1""".format(
+					dr_or_cr, dr_or_cr, "%s", "%s", "%s", dr_or_cr
+				),
 				(d.diff, d.voucher_type, d.voucher_no),
 			)
 
@@ -1020,7 +1001,6 @@
 	limit=None,  # passed by reconciliation tool
 	voucher_no=None,  # filter passed by reconciliation tool
 ):
-
 	ple = qb.DocType("Payment Ledger Entry")
 	outstanding_invoices = []
 	precision = frappe.get_precision("Sales Invoice", "outstanding_amount") or 2
@@ -1083,15 +1063,11 @@
 					)
 				)
 
-	outstanding_invoices = sorted(
-		outstanding_invoices, key=lambda k: k["due_date"] or getdate(nowdate())
-	)
+	outstanding_invoices = sorted(outstanding_invoices, key=lambda k: k["due_date"] or getdate(nowdate()))
 	return outstanding_invoices
 
 
-def get_account_name(
-	account_type=None, root_type=None, is_group=None, account_currency=None, company=None
-):
+def get_account_name(account_type=None, root_type=None, is_group=None, account_currency=None, company=None):
 	"""return account based on matching conditions"""
 	return frappe.db.get_value(
 		"Account",
@@ -1124,7 +1100,7 @@
 	if frappe.db.has_column(doctype, "disabled") and not include_disabled:
 		filters.append(["disabled", "=", False])
 
-	filters.append(['ifnull(`{0}`,"")'.format(parent_fieldname), "=", "" if is_root else parent])
+	filters.append([f'ifnull(`{parent_fieldname}`,"")', "=", "" if is_root else parent])
 
 	if is_root:
 		fields += ["root_type", "report_type", "account_currency"] if doctype == "Account" else []
@@ -1144,7 +1120,6 @@
 
 @frappe.whitelist()
 def get_account_balances(accounts, company):
-
 	if isinstance(accounts, str):
 		accounts = loads(accounts)
 
@@ -1155,9 +1130,7 @@
 
 	for account in accounts:
 		account["company_currency"] = company_currency
-		account["balance"] = flt(
-			get_balance_on(account["value"], in_account_currency=False, company=company)
-		)
+		account["balance"] = flt(get_balance_on(account["value"], in_account_currency=False, company=company))
 		if account["account_currency"] and account["account_currency"] != company_currency:
 			account["balance_in_account_currency"] = flt(get_balance_on(account["value"], company=company))
 
@@ -1307,20 +1280,17 @@
 	warehouse_account=None,
 	company=None,
 ):
-	stock_vouchers = get_future_stock_vouchers(
-		posting_date, posting_time, for_warehouses, for_items, company
-	)
+	stock_vouchers = get_future_stock_vouchers(posting_date, posting_time, for_warehouses, for_items, company)
 	repost_gle_for_stock_vouchers(stock_vouchers, posting_date, company, warehouse_account)
 
 
 def repost_gle_for_stock_vouchers(
-	stock_vouchers: List[Tuple[str, str]],
+	stock_vouchers: list[tuple[str, str]],
 	posting_date: str,
-	company: Optional[str] = None,
+	company: str | None = None,
 	warehouse_account=None,
 	repost_doc: Optional["RepostItemValuation"] = None,
 ):
-
 	from erpnext.accounts.general_ledger import toggle_debit_credit_if_negative
 
 	if not stock_vouchers:
@@ -1366,16 +1336,12 @@
 
 def _delete_pl_entries(voucher_type, voucher_no):
 	ple = qb.DocType("Payment Ledger Entry")
-	qb.from_(ple).delete().where(
-		(ple.voucher_type == voucher_type) & (ple.voucher_no == voucher_no)
-	).run()
+	qb.from_(ple).delete().where((ple.voucher_type == voucher_type) & (ple.voucher_no == voucher_no)).run()
 
 
 def _delete_gl_entries(voucher_type, voucher_no):
 	gle = qb.DocType("GL Entry")
-	qb.from_(gle).delete().where(
-		(gle.voucher_type == voucher_type) & (gle.voucher_no == voucher_no)
-	).run()
+	qb.from_(gle).delete().where((gle.voucher_type == voucher_type) & (gle.voucher_no == voucher_no)).run()
 
 
 def _delete_accounting_ledger_entries(voucher_type, voucher_no):
@@ -1386,9 +1352,7 @@
 	_delete_pl_entries(voucher_type, voucher_no)
 
 
-def sort_stock_vouchers_by_posting_date(
-	stock_vouchers: List[Tuple[str, str]]
-) -> List[Tuple[str, str]]:
+def sort_stock_vouchers_by_posting_date(stock_vouchers: list[tuple[str, str]]) -> list[tuple[str, str]]:
 	sle = frappe.qb.DocType("Stock Ledger Entry")
 	voucher_nos = [v[1] for v in stock_vouchers]
 
@@ -1409,10 +1373,7 @@
 	return sorted_vouchers
 
 
-def get_future_stock_vouchers(
-	posting_date, posting_time, for_warehouses=None, for_items=None, company=None
-):
-
+def get_future_stock_vouchers(posting_date, posting_time, for_warehouses=None, for_items=None, company=None):
 	values = []
 	condition = ""
 	if for_items:
@@ -1428,16 +1389,14 @@
 		values.append(company)
 
 	future_stock_vouchers = frappe.db.sql(
-		"""select distinct sle.voucher_type, sle.voucher_no
+		f"""select distinct sle.voucher_type, sle.voucher_no
 		from `tabStock Ledger Entry` sle
 		where
 			timestamp(sle.posting_date, sle.posting_time) >= timestamp(%s, %s)
 			and is_cancelled = 0
 			{condition}
-		order by timestamp(sle.posting_date, sle.posting_time) asc, creation asc for update""".format(
-			condition=condition
-		),
-		tuple([posting_date, posting_time] + values),
+		order by timestamp(sle.posting_date, sle.posting_time) asc, creation asc for update""",
+		tuple([posting_date, posting_time, *values]),
 		as_dict=True,
 	)
 
@@ -1464,9 +1423,8 @@
 		select name, account, credit, debit, cost_center, project, voucher_type, voucher_no
 			from `tabGL Entry`
 		where
-			posting_date >= %s and voucher_no in (%s)"""
-		% ("%s", ", ".join(["%s"] * len(voucher_nos))),
-		tuple([posting_date] + voucher_nos),
+			posting_date >= {} and voucher_no in ({})""".format("%s", ", ".join(["%s"] * len(voucher_nos))),
+		tuple([posting_date, *voucher_nos]),
 		as_dict=1,
 	)
 
@@ -1505,16 +1463,16 @@
 def get_stock_accounts(company, voucher_type=None, voucher_no=None):
 	stock_accounts = [
 		d.name
-		for d in frappe.db.get_all(
-			"Account", {"account_type": "Stock", "company": company, "is_group": 0}
-		)
+		for d in frappe.db.get_all("Account", {"account_type": "Stock", "company": company, "is_group": 0})
 	]
 	if voucher_type and voucher_no:
 		if voucher_type == "Journal Entry":
 			stock_accounts = [
 				d.account
 				for d in frappe.db.get_all(
-					"Journal Entry Account", {"parent": voucher_no, "account": ["in", stock_accounts]}, "account"
+					"Journal Entry Account",
+					{"parent": voucher_no, "account": ["in", stock_accounts]},
+					"account",
 				)
 			]
 
@@ -1523,7 +1481,11 @@
 				d.account
 				for d in frappe.db.get_all(
 					"GL Entry",
-					{"voucher_type": voucher_type, "voucher_no": voucher_no, "account": ["in", stock_accounts]},
+					{
+						"voucher_type": voucher_type,
+						"voucher_no": voucher_no,
+						"account": ["in", stock_accounts],
+					},
 					"account",
 				)
 			]
@@ -1554,9 +1516,7 @@
 
 
 def get_journal_entry(account, stock_adjustment_account, amount):
-	db_or_cr_warehouse_account = (
-		"credit_in_account_currency" if amount < 0 else "debit_in_account_currency"
-	)
+	db_or_cr_warehouse_account = "credit_in_account_currency" if amount < 0 else "debit_in_account_currency"
 	db_or_cr_stock_adjustment_account = (
 		"debit_in_account_currency" if amount < 0 else "credit_in_account_currency"
 	)
@@ -1577,7 +1537,7 @@
 			frappe.delete_doc("Desktop Icon", icon)
 
 
-def create_err_and_its_journals(companies: list = None) -> None:
+def create_err_and_its_journals(companies: list | None = None) -> None:
 	if companies:
 		for company in companies:
 			err = frappe.new_doc("Exchange Rate Revaluation")
@@ -1634,9 +1594,7 @@
 		accounts_with_types = (
 			qb.from_(account)
 			.select(account.name, account.account_type)
-			.where(
-				(account.account_type.isin(["Receivable", "Payable"]) & (account.company.isin(companies)))
-			)
+			.where(account.account_type.isin(["Receivable", "Payable"]) & (account.company.isin(companies)))
 			.run(as_dict=True)
 		)
 		receivable_or_payable_accounts = [y.name for y in accounts_with_types]
@@ -1703,7 +1661,6 @@
 		ple_map = get_payment_ledger_entries(gl_entries, cancel=cancel)
 
 		for entry in ple_map:
-
 			ple = frappe.get_doc(entry)
 
 			if cancel:
@@ -1781,7 +1738,7 @@
 		query.run()
 
 
-class QueryPaymentLedger(object):
+class QueryPaymentLedger:
 	"""
 	Helper Class for Querying Payment Ledger Entry
 	"""
@@ -1949,7 +1906,8 @@
 				Table("outstanding").amount_in_account_currency.as_("outstanding_in_account_currency"),
 				(Table("vouchers").amount - Table("outstanding").amount).as_("paid_amount"),
 				(
-					Table("vouchers").amount_in_account_currency - Table("outstanding").amount_in_account_currency
+					Table("vouchers").amount_in_account_currency
+					- Table("outstanding").amount_in_account_currency
 				).as_("paid_amount_in_account_currency"),
 				Table("vouchers").due_date,
 				Table("vouchers").currency,
diff --git a/erpnext/assets/dashboard_fixtures.py b/erpnext/assets/dashboard_fixtures.py
index fc9ba38..3b1d144 100644
--- a/erpnext/assets/dashboard_fixtures.py
+++ b/erpnext/assets/dashboard_fixtures.py
@@ -12,7 +12,6 @@
 
 
 def get_data():
-
 	fiscal_year = _get_fiscal_year(nowdate())
 
 	if not fiscal_year:
@@ -168,9 +167,7 @@
 			"is_public": 1,
 			"show_percentage_stats": 1,
 			"stats_time_interval": "Monthly",
-			"filters_json": json.dumps(
-				[["Asset", "creation", "between", [year_start_date, year_end_date]]]
-			),
+			"filters_json": json.dumps([["Asset", "creation", "between", [year_start_date, year_end_date]]]),
 			"doctype": "Number Card",
 		},
 		{
diff --git a/erpnext/assets/doctype/asset/asset.py b/erpnext/assets/doctype/asset/asset.py
index 385797f..0311d3c 100644
--- a/erpnext/assets/doctype/asset/asset.py
+++ b/erpnext/assets/doctype/asset/asset.py
@@ -211,9 +211,7 @@
 				)
 
 		if self.is_existing_asset and self.purchase_invoice:
-			frappe.throw(
-				_("Purchase Invoice cannot be made against an existing asset {0}").format(self.name)
-			)
+			frappe.throw(_("Purchase Invoice cannot be made against an existing asset {0}").format(self.name))
 
 	def prepare_depreciation_data(self):
 		if self.calculate_depreciation:
@@ -274,9 +272,9 @@
 		for d in self.finance_books:
 			if d.depreciation_start_date == self.available_for_use_date:
 				frappe.throw(
-					_("Row #{}: Depreciation Posting Date should not be equal to Available for Use Date.").format(
-						d.idx
-					),
+					_(
+						"Row #{}: Depreciation Posting Date should not be equal to Available for Use Date."
+					).format(d.idx),
 					title=_("Incorrect Date"),
 				)
 
@@ -285,9 +283,7 @@
 			self.asset_category = frappe.get_cached_value("Item", self.item_code, "asset_category")
 
 		if self.item_code and not self.get("finance_books"):
-			finance_books = get_item_details(
-				self.item_code, self.asset_category, self.gross_purchase_amount
-			)
+			finance_books = get_item_details(self.item_code, self.asset_category, self.gross_purchase_amount)
 			self.set("finance_books", finance_books)
 
 	def validate_finance_books(self):
@@ -337,7 +333,9 @@
 				and not frappe.db.get_value("Purchase Invoice", self.purchase_invoice, "update_stock")
 			):
 				frappe.throw(
-					_("Update stock must be enabled for the purchase invoice {0}").format(self.purchase_invoice)
+					_("Update stock must be enabled for the purchase invoice {0}").format(
+						self.purchase_invoice
+					)
 				)
 
 		if not self.calculate_depreciation:
@@ -351,9 +349,7 @@
 		if self.is_existing_asset:
 			return
 
-		if self.available_for_use_date and getdate(self.available_for_use_date) < getdate(
-			self.purchase_date
-		):
+		if self.available_for_use_date and getdate(self.available_for_use_date) < getdate(self.purchase_date):
 			frappe.throw(_("Available-for-use Date should be after purchase date"))
 
 	def validate_gross_and_purchase_amount(self):
@@ -376,7 +372,7 @@
 			posting_date, posting_time = frappe.db.get_value(
 				reference_doctype, reference_docname, ["posting_date", "posting_time"]
 			)
-			transaction_date = get_datetime("{} {}".format(posting_date, posting_time))
+			transaction_date = get_datetime(f"{posting_date} {posting_time}")
 		assets = [
 			{
 				"asset": self.name,
@@ -416,7 +412,8 @@
 		if not row.depreciation_start_date:
 			if not self.available_for_use_date:
 				frappe.throw(
-					_("Row {0}: Depreciation Start Date is required").format(row.idx), title=_("Invalid Schedule")
+					_("Row {0}: Depreciation Start Date is required").format(row.idx),
+					title=_("Invalid Schedule"),
 				)
 			row.depreciation_start_date = get_last_day(self.available_for_use_date)
 
@@ -446,9 +443,7 @@
 					title=_("Invalid Schedule"),
 				)
 
-		if row.depreciation_start_date and getdate(row.depreciation_start_date) < getdate(
-			self.purchase_date
-		):
+		if row.depreciation_start_date and getdate(row.depreciation_start_date) < getdate(self.purchase_date):
 			frappe.throw(
 				_("Depreciation Row {0}: Next Depreciation Date cannot be before Purchase Date").format(
 					row.idx
@@ -567,11 +562,14 @@
 
 				if self.calculate_depreciation:
 					idx = self.get_default_finance_book_idx() or 0
-					expected_value_after_useful_life = self.finance_books[idx].expected_value_after_useful_life
+					expected_value_after_useful_life = self.finance_books[
+						idx
+					].expected_value_after_useful_life
 					value_after_depreciation = self.finance_books[idx].value_after_depreciation
 
 				if (
-					flt(value_after_depreciation) <= expected_value_after_useful_life or self.is_fully_depreciated
+					flt(value_after_depreciation) <= expected_value_after_useful_life
+					or self.is_fully_depreciated
 				):
 					status = "Fully Depreciated"
 				elif flt(value_after_depreciation) < flt(self.gross_purchase_amount):
@@ -604,9 +602,7 @@
 
 	@frappe.whitelist()
 	def get_manual_depreciation_entries(self):
-		(_, _, depreciation_expense_account) = get_depreciation_accounts(
-			self.asset_category, self.company
-		)
+		(_, _, depreciation_expense_account) = get_depreciation_accounts(self.asset_category, self.company)
 
 		gle = frappe.qb.DocType("GL Entry")
 
@@ -704,7 +700,6 @@
 			and self.purchase_receipt_amount
 			and getdate(self.available_for_use_date) <= getdate()
 		):
-
 			gl_entries.append(
 				self.get_gl_dict(
 					{
@@ -751,7 +746,8 @@
 		if args.get("depreciation_method") == "Double Declining Balance":
 			return 200.0 / (
 				(
-					flt(args.get("total_number_of_depreciations"), 2) * flt(args.get("frequency_of_depreciation"))
+					flt(args.get("total_number_of_depreciations"), 2)
+					* flt(args.get("frequency_of_depreciation"))
 				)
 				/ 12
 			)
@@ -795,9 +791,7 @@
 		asset = frappe.get_doc("Asset", asset.name)
 		if frappe.db.exists("Asset Repair", {"asset_name": asset.name, "repair_status": "Pending"}):
 			asset.set_status("Out of Order")
-		elif frappe.db.exists(
-			"Asset Maintenance Task", {"parent": asset.name, "next_due_date": today()}
-		):
+		elif frappe.db.exists("Asset Maintenance Task", {"parent": asset.name, "next_due_date": today()}):
 			asset.set_status("In Maintenance")
 		else:
 			asset.set_status()
@@ -881,9 +875,7 @@
 @frappe.whitelist()
 def create_asset_value_adjustment(asset, asset_category, company):
 	asset_value_adjustment = frappe.new_doc("Asset Value Adjustment")
-	asset_value_adjustment.update(
-		{"asset": asset, "company": company, "asset_category": asset_category}
-	)
+	asset_value_adjustment.update({"asset": asset, "company": company, "asset_category": asset_category})
 	return asset_value_adjustment
 
 
@@ -940,18 +932,14 @@
 		)
 
 	if not asset and not account:
-		account = get_asset_category_account(
-			account_name, asset_category=asset_category, company=company
-		)
+		account = get_asset_category_account(account_name, asset_category=asset_category, company=company)
 
 	if not account:
 		account = frappe.get_cached_value("Company", company, account_name)
 
 	if not account:
 		if not asset_category:
-			frappe.throw(
-				_("Set {0} in company {1}").format(account_name.replace("_", " ").title(), company)
-			)
+			frappe.throw(_("Set {0} in company {1}").format(account_name.replace("_", " ").title(), company))
 		else:
 			frappe.throw(
 				_("Set {0} in asset category {1} or company {2}").format(
@@ -980,7 +968,7 @@
 	je.voucher_type = "Depreciation Entry"
 	je.naming_series = depreciation_series
 	je.company = asset.company
-	je.remark = ("Depreciation Entry against asset {0}").format(asset_name)
+	je.remark = f"Depreciation Entry against asset {asset_name}"
 
 	je.append(
 		"accounts",
@@ -1081,15 +1069,11 @@
 
 	add_asset_activity(
 		asset.name,
-		_("Asset updated after being split into Asset {0}").format(
-			get_link_to_form("Asset", new_asset_name)
-		),
+		_("Asset updated after being split into Asset {0}").format(get_link_to_form("Asset", new_asset_name)),
 	)
 
 	for row in asset.get("finance_books"):
-		value_after_depreciation = flt(
-			(row.value_after_depreciation * remaining_qty) / asset.asset_quantity
-		)
+		value_after_depreciation = flt((row.value_after_depreciation * remaining_qty) / asset.asset_quantity)
 		expected_value_after_useful_life = flt(
 			(row.expected_value_after_useful_life * remaining_qty) / asset.asset_quantity
 		)
@@ -1103,9 +1087,7 @@
 			expected_value_after_useful_life,
 		)
 
-		current_asset_depr_schedule_doc = get_asset_depr_schedule_doc(
-			asset.name, "Active", row.finance_book
-		)
+		current_asset_depr_schedule_doc = get_asset_depr_schedule_doc(asset.name, "Active", row.finance_book)
 		new_asset_depr_schedule_doc = frappe.copy_doc(current_asset_depr_schedule_doc)
 
 		new_asset_depr_schedule_doc.set_draft_asset_depr_schedule_details(asset, row)
@@ -1120,9 +1102,7 @@
 
 		notes = _(
 			"This schedule was created when Asset {0} was updated after being split into new Asset {1}."
-		).format(
-			get_link_to_form(asset.doctype, asset.name), get_link_to_form(asset.doctype, new_asset_name)
-		)
+		).format(get_link_to_form(asset.doctype, asset.name), get_link_to_form(asset.doctype, new_asset_name))
 		new_asset_depr_schedule_doc.notes = notes
 
 		current_asset_depr_schedule_doc.flags.should_not_cancel_depreciation_entries = True
@@ -1146,9 +1126,7 @@
 	new_asset.split_from = asset.name
 
 	for row in new_asset.get("finance_books"):
-		row.value_after_depreciation = flt(
-			(row.value_after_depreciation * split_qty) / asset.asset_quantity
-		)
+		row.value_after_depreciation = flt((row.value_after_depreciation * split_qty) / asset.asset_quantity)
 		row.expected_value_after_useful_life = flt(
 			(row.expected_value_after_useful_life * split_qty) / asset.asset_quantity
 		)
@@ -1157,18 +1135,14 @@
 
 	add_asset_activity(
 		new_asset.name,
-		_("Asset created after being split from Asset {0}").format(
-			get_link_to_form("Asset", asset.name)
-		),
+		_("Asset created after being split from Asset {0}").format(get_link_to_form("Asset", asset.name)),
 	)
 
 	new_asset.submit()
 	new_asset.set_status()
 
 	for row in new_asset.get("finance_books"):
-		current_asset_depr_schedule_doc = get_asset_depr_schedule_doc(
-			asset.name, "Active", row.finance_book
-		)
+		current_asset_depr_schedule_doc = get_asset_depr_schedule_doc(asset.name, "Active", row.finance_book)
 		new_asset_depr_schedule_doc = frappe.copy_doc(current_asset_depr_schedule_doc)
 
 		new_asset_depr_schedule_doc.set_draft_asset_depr_schedule_details(new_asset, row)
diff --git a/erpnext/assets/doctype/asset/depreciation.py b/erpnext/assets/doctype/asset/depreciation.py
index 205f4b9..b6a4d91 100644
--- a/erpnext/assets/doctype/asset/depreciation.py
+++ b/erpnext/assets/doctype/asset/depreciation.py
@@ -71,7 +71,10 @@
 		) not in credit_and_debit_accounts_for_asset_category_and_company:
 			credit_and_debit_accounts_for_asset_category_and_company.update(
 				{
-					(asset_category, asset_company): get_credit_and_debit_accounts_for_asset_category_and_company(
+					(
+						asset_category,
+						asset_company,
+					): get_credit_and_debit_accounts_for_asset_category_and_company(
 						asset_category, asset_company
 					),
 				}
@@ -135,9 +138,7 @@
 
 def make_depreciation_entry_for_all_asset_depr_schedules(asset_doc, date=None):
 	for row in asset_doc.get("finance_books"):
-		asset_depr_schedule_name = get_asset_depr_schedule_name(
-			asset_doc.name, "Active", row.finance_book
-		)
+		asset_depr_schedule_name = get_asset_depr_schedule_name(asset_doc.name, "Active", row.finance_book)
 		make_depreciation_entry(asset_depr_schedule_name, date)
 
 
@@ -147,9 +148,7 @@
 	if not acc_frozen_upto:
 		return
 
-	frozen_accounts_modifier = frappe.db.get_single_value(
-		"Accounts Settings", "frozen_accounts_modifier"
-	)
+	frozen_accounts_modifier = frappe.db.get_single_value("Accounts Settings", "frozen_accounts_modifier")
 
 	if frozen_accounts_modifier not in frappe.get_roles() or frappe.session.user == "Administrator":
 		return getdate(acc_frozen_upto)
@@ -278,9 +277,7 @@
 	je.posting_date = depr_schedule.schedule_date
 	je.company = asset.company
 	je.finance_book = asset_depr_schedule_doc.finance_book
-	je.remark = "Depreciation Entry against {0} worth {1}".format(
-		asset.name, depr_schedule.depreciation_amount
-	)
+	je.remark = f"Depreciation Entry against {asset.name} worth {depr_schedule.depreciation_amount}"
 
 	credit_entry = {
 		"account": credit_account,
@@ -361,11 +358,7 @@
 		if not depreciation_expense_account:
 			depreciation_expense_account = accounts[1]
 
-	if (
-		not fixed_asset_account
-		or not accumulated_depreciation_account
-		or not depreciation_expense_account
-	):
+	if not fixed_asset_account or not accumulated_depreciation_account or not depreciation_expense_account:
 		frappe.throw(
 			_("Please set Depreciation related Accounts in Asset Category {0} or Company {1}").format(
 				asset_category, company
@@ -443,9 +436,7 @@
 	if asset.docstatus != 1:
 		frappe.throw(_("Asset {0} must be submitted").format(asset.name))
 	elif asset.status in ("Cancelled", "Sold", "Scrapped", "Capitalized", "Decapitalized"):
-		frappe.throw(
-			_("Asset {0} cannot be scrapped, as it is already {1}").format(asset.name, asset.status)
-		)
+		frappe.throw(_("Asset {0} cannot be scrapped, as it is already {1}").format(asset.name, asset.status))
 
 	date = today()
 
@@ -456,16 +447,14 @@
 	depreciate_asset(asset, date, notes)
 	asset.reload()
 
-	depreciation_series = frappe.get_cached_value(
-		"Company", asset.company, "series_for_depreciation_entry"
-	)
+	depreciation_series = frappe.get_cached_value("Company", asset.company, "series_for_depreciation_entry")
 
 	je = frappe.new_doc("Journal Entry")
 	je.voucher_type = "Journal Entry"
 	je.naming_series = depreciation_series
 	je.posting_date = date
 	je.company = asset.company
-	je.remark = "Scrap Entry for asset {0}".format(asset_name)
+	je.remark = f"Scrap Entry for asset {asset_name}"
 
 	for entry in get_gl_entries_on_asset_disposal(asset, date):
 		entry.update({"reference_type": "Asset", "reference_name": asset_name})
@@ -513,9 +502,7 @@
 
 	asset_doc.flags.ignore_validate_update_after_submit = True
 
-	make_new_active_asset_depr_schedules_and_cancel_current_ones(
-		asset_doc, notes, date_of_disposal=date
-	)
+	make_new_active_asset_depr_schedules_and_cancel_current_ones(asset_doc, notes, date_of_disposal=date)
 
 	asset_doc.save()
 
@@ -536,9 +523,7 @@
 
 	asset_doc.flags.ignore_validate_update_after_submit = True
 
-	make_new_active_asset_depr_schedules_and_cancel_current_ones(
-		asset_doc, notes, date_of_return=date
-	)
+	make_new_active_asset_depr_schedules_and_cancel_current_ones(asset_doc, notes, date_of_return=date)
 
 	modify_depreciation_schedule_for_asset_repairs(asset_doc, notes)
 
@@ -781,9 +766,7 @@
 	)
 
 	if not disposal_account:
-		frappe.throw(
-			_("Please set 'Gain/Loss Account on Asset Disposal' in Company {0}").format(company)
-		)
+		frappe.throw(_("Please set 'Gain/Loss Account on Asset Disposal' in Company {0}").format(company))
 	if not depreciation_cost_center:
 		frappe.throw(_("Please set 'Asset Depreciation Cost Center' in Company {0}").format(company))
 
@@ -796,7 +779,7 @@
 
 	if asset_doc.available_for_use_date > getdate(disposal_date):
 		frappe.throw(
-			"Disposal date {0} cannot be before available for use date {1} of the asset.".format(
+			"Disposal date {} cannot be before available for use date {} of the asset.".format(
 				disposal_date, asset_doc.available_for_use_date
 			)
 		)
diff --git a/erpnext/assets/doctype/asset/test_asset.py b/erpnext/assets/doctype/asset/test_asset.py
index 25d0105..088641a 100644
--- a/erpnext/assets/doctype/asset/test_asset.py
+++ b/erpnext/assets/doctype/asset/test_asset.py
@@ -109,9 +109,7 @@
 		self.assertRaises(frappe.ValidationError, asset.save)
 
 	def test_purchase_asset(self):
-		pr = make_purchase_receipt(
-			item_code="Macbook Pro", qty=1, rate=100000.0, location="Test Location"
-		)
+		pr = make_purchase_receipt(item_code="Macbook Pro", qty=1, rate=100000.0, location="Test Location")
 
 		asset_name = frappe.db.get_value("Asset", {"purchase_receipt": pr.name}, "name")
 		asset = frappe.get_doc("Asset", asset_name)
@@ -210,7 +208,7 @@
 		)
 
 		first_asset_depr_schedule = get_asset_depr_schedule_doc(asset.name, "Active")
-		self.assertEquals(first_asset_depr_schedule.status, "Active")
+		self.assertEqual(first_asset_depr_schedule.status, "Active")
 
 		post_depreciation_entries(date=add_months(purchase_date, 2))
 		asset.load_from_db()
@@ -219,15 +217,15 @@
 			asset.gross_purchase_amount - asset.finance_books[0].value_after_depreciation,
 			asset.precision("gross_purchase_amount"),
 		)
-		self.assertEquals(accumulated_depr_amount, 18000.0)
+		self.assertEqual(accumulated_depr_amount, 18000.0)
 
 		scrap_asset(asset.name)
 		asset.load_from_db()
 		first_asset_depr_schedule.load_from_db()
 
 		second_asset_depr_schedule = get_asset_depr_schedule_doc(asset.name, "Active")
-		self.assertEquals(second_asset_depr_schedule.status, "Active")
-		self.assertEquals(first_asset_depr_schedule.status, "Cancelled")
+		self.assertEqual(second_asset_depr_schedule.status, "Active")
+		self.assertEqual(first_asset_depr_schedule.status, "Cancelled")
 
 		accumulated_depr_amount = flt(
 			asset.gross_purchase_amount - asset.finance_books[0].value_after_depreciation,
@@ -237,7 +235,7 @@
 			asset.finance_books[0], 9000, get_last_day(add_months(purchase_date, 1)), date
 		)
 		pro_rata_amount = flt(pro_rata_amount, asset.precision("gross_purchase_amount"))
-		self.assertEquals(
+		self.assertEqual(
 			accumulated_depr_amount,
 			flt(18000.0 + pro_rata_amount, asset.precision("gross_purchase_amount")),
 		)
@@ -266,8 +264,8 @@
 		second_asset_depr_schedule.load_from_db()
 
 		third_asset_depr_schedule = get_asset_depr_schedule_doc(asset.name, "Active")
-		self.assertEquals(third_asset_depr_schedule.status, "Active")
-		self.assertEquals(second_asset_depr_schedule.status, "Cancelled")
+		self.assertEqual(third_asset_depr_schedule.status, "Active")
+		self.assertEqual(second_asset_depr_schedule.status, "Cancelled")
 
 		asset.load_from_db()
 		self.assertFalse(asset.journal_entry_for_scrap)
@@ -279,7 +277,7 @@
 		)
 		this_month_depr_amount = 9000.0 if is_last_day_of_the_month(date) else 0
 
-		self.assertEquals(accumulated_depr_amount, 18000.0 + this_month_depr_amount)
+		self.assertEqual(accumulated_depr_amount, 18000.0 + this_month_depr_amount)
 
 	def test_gle_made_by_asset_sale(self):
 		date = nowdate()
@@ -296,7 +294,7 @@
 		)
 
 		first_asset_depr_schedule = get_asset_depr_schedule_doc(asset.name, "Active")
-		self.assertEquals(first_asset_depr_schedule.status, "Active")
+		self.assertEqual(first_asset_depr_schedule.status, "Active")
 
 		post_depreciation_entries(date=add_months(purchase_date, 2))
 
@@ -312,8 +310,8 @@
 		first_asset_depr_schedule.load_from_db()
 
 		second_asset_depr_schedule = get_asset_depr_schedule_doc(asset.name, "Active")
-		self.assertEquals(second_asset_depr_schedule.status, "Active")
-		self.assertEquals(first_asset_depr_schedule.status, "Cancelled")
+		self.assertEqual(second_asset_depr_schedule.status, "Active")
+		self.assertEqual(first_asset_depr_schedule.status, "Cancelled")
 
 		pro_rata_amount, _, _ = _get_pro_rata_amt(
 			asset.finance_books[0], 9000, get_last_day(add_months(purchase_date, 1)), date
@@ -457,7 +455,7 @@
 		)
 
 		first_asset_depr_schedule = get_asset_depr_schedule_doc(asset.name, "Active")
-		self.assertEquals(first_asset_depr_schedule.status, "Active")
+		self.assertEqual(first_asset_depr_schedule.status, "Active")
 
 		post_depreciation_entries(date="2021-01-01")
 
@@ -471,9 +469,9 @@
 
 		second_asset_depr_schedule = get_asset_depr_schedule_doc(asset.name, "Active")
 		first_asset_depr_schedule_of_new_asset = get_asset_depr_schedule_doc(new_asset.name, "Active")
-		self.assertEquals(second_asset_depr_schedule.status, "Active")
-		self.assertEquals(first_asset_depr_schedule_of_new_asset.status, "Active")
-		self.assertEquals(first_asset_depr_schedule.status, "Cancelled")
+		self.assertEqual(second_asset_depr_schedule.status, "Active")
+		self.assertEqual(first_asset_depr_schedule_of_new_asset.status, "Active")
+		self.assertEqual(first_asset_depr_schedule.status, "Cancelled")
 
 		depr_schedule_of_asset = second_asset_depr_schedule.get("depreciation_schedule")
 		depr_schedule_of_new_asset = first_asset_depr_schedule_of_new_asset.get("depreciation_schedule")
@@ -505,9 +503,7 @@
 		self.assertEqual(jv.accounts[3].reference_name, new_asset.name)
 
 	def test_expense_head(self):
-		pr = make_purchase_receipt(
-			item_code="Macbook Pro", qty=2, rate=200000.0, location="Test Location"
-		)
+		pr = make_purchase_receipt(item_code="Macbook Pro", qty=2, rate=200000.0, location="Test Location")
 		doc = make_invoice(pr.name)
 
 		self.assertEqual("Asset Received But Not Billed - _TC", doc.items[0].expense_account)
@@ -617,9 +613,7 @@
 		self.assertFalse(gle)
 
 		# case 1 -- PR with cwip disabled, Asset with cwip enabled
-		pr = make_purchase_receipt(
-			item_code="Macbook Pro", qty=1, rate=200000.0, location="Test Location"
-		)
+		pr = make_purchase_receipt(item_code="Macbook Pro", qty=1, rate=200000.0, location="Test Location")
 		frappe.db.set_value("Asset Category", "Computers", "enable_cwip_accounting", 1)
 		frappe.db.set_value("Asset Category Account", name, "capital_work_in_progress_account", cwip_acc)
 		asset = frappe.db.get_value("Asset", {"purchase_receipt": pr.name, "docstatus": 0}, "name")
@@ -631,9 +625,7 @@
 		self.assertFalse(gle)
 
 		# case 2 -- PR with cwip enabled, Asset with cwip disabled
-		pr = make_purchase_receipt(
-			item_code="Macbook Pro", qty=1, rate=200000.0, location="Test Location"
-		)
+		pr = make_purchase_receipt(item_code="Macbook Pro", qty=1, rate=200000.0, location="Test Location")
 		frappe.db.set_value("Asset Category", "Computers", "enable_cwip_accounting", 0)
 		asset = frappe.db.get_value("Asset", {"purchase_receipt": pr.name, "docstatus": 0}, "name")
 		asset_doc = frappe.get_doc("Asset", asset)
@@ -1248,8 +1240,7 @@
 
 		je = frappe.get_doc("Journal Entry", get_depr_schedule(asset.name, "Active")[0].journal_entry)
 		accounting_entries = [
-			{"account": entry.account, "debit": entry.debit, "credit": entry.credit}
-			for entry in je.accounts
+			{"account": entry.account, "debit": entry.debit, "credit": entry.credit} for entry in je.accounts
 		]
 
 		for entry in accounting_entries:
@@ -1284,8 +1275,7 @@
 
 		je = frappe.get_doc("Journal Entry", get_depr_schedule(asset.name, "Active")[0].journal_entry)
 		accounting_entries = [
-			{"account": entry.account, "debit": entry.debit, "credit": entry.credit}
-			for entry in je.accounts
+			{"account": entry.account, "debit": entry.debit, "credit": entry.credit} for entry in je.accounts
 		]
 
 		for entry in accounting_entries:
@@ -1366,21 +1356,15 @@
 		post_depreciation_entries(date="2020-04-01")
 		asset.load_from_db()
 
-		asset_depr_schedule_doc_1 = get_asset_depr_schedule_doc(
-			asset.name, "Active", "Test Finance Book 1"
-		)
+		asset_depr_schedule_doc_1 = get_asset_depr_schedule_doc(asset.name, "Active", "Test Finance Book 1")
 		asset_depr_schedule_doc_1.clear_depr_schedule()
 		self.assertEqual(len(asset_depr_schedule_doc_1.get("depreciation_schedule")), 3)
 
-		asset_depr_schedule_doc_2 = get_asset_depr_schedule_doc(
-			asset.name, "Active", "Test Finance Book 2"
-		)
+		asset_depr_schedule_doc_2 = get_asset_depr_schedule_doc(asset.name, "Active", "Test Finance Book 2")
 		asset_depr_schedule_doc_2.clear_depr_schedule()
 		self.assertEqual(len(asset_depr_schedule_doc_2.get("depreciation_schedule")), 3)
 
-		asset_depr_schedule_doc_3 = get_asset_depr_schedule_doc(
-			asset.name, "Active", "Test Finance Book 3"
-		)
+		asset_depr_schedule_doc_3 = get_asset_depr_schedule_doc(asset.name, "Active", "Test Finance Book 3")
 		asset_depr_schedule_doc_3.clear_depr_schedule()
 		self.assertEqual(len(asset_depr_schedule_doc_3.get("depreciation_schedule")), 0)
 
@@ -1412,14 +1396,10 @@
 		)
 		asset.save()
 
-		asset_depr_schedule_doc_1 = get_asset_depr_schedule_doc(
-			asset.name, "Draft", "Test Finance Book 1"
-		)
+		asset_depr_schedule_doc_1 = get_asset_depr_schedule_doc(asset.name, "Draft", "Test Finance Book 1")
 		self.assertEqual(len(asset_depr_schedule_doc_1.get("depreciation_schedule")), 3)
 
-		asset_depr_schedule_doc_2 = get_asset_depr_schedule_doc(
-			asset.name, "Draft", "Test Finance Book 2"
-		)
+		asset_depr_schedule_doc_2 = get_asset_depr_schedule_doc(asset.name, "Draft", "Test Finance Book 2")
 		self.assertEqual(len(asset_depr_schedule_doc_2.get("depreciation_schedule")), 6)
 
 	def test_depreciation_entry_cancellation(self):
@@ -1521,13 +1501,13 @@
 		asset.finance_books[0].expected_value_after_useful_life = 100
 		asset.save()
 		asset.reload()
-		self.assertEquals(asset.finance_books[0].value_after_depreciation, 98000.0)
+		self.assertEqual(asset.finance_books[0].value_after_depreciation, 98000.0)
 
 		# changing expected_value_after_useful_life shouldn't affect value_after_depreciation
 		asset.finance_books[0].expected_value_after_useful_life = 200
 		asset.save()
 		asset.reload()
-		self.assertEquals(asset.finance_books[0].value_after_depreciation, 98000.0)
+		self.assertEqual(asset.finance_books[0].value_after_depreciation, 98000.0)
 
 	def test_asset_cost_center(self):
 		asset = create_asset(is_existing_asset=1, do_not_save=1)
diff --git a/erpnext/assets/doctype/asset_capitalization/asset_capitalization.py b/erpnext/assets/doctype/asset_capitalization/asset_capitalization.py
index 2f4d710..db9170c 100644
--- a/erpnext/assets/doctype/asset_capitalization/asset_capitalization.py
+++ b/erpnext/assets/doctype/asset_capitalization/asset_capitalization.py
@@ -70,9 +70,7 @@
 		amended_from: DF.Link | None
 		asset_items: DF.Table[AssetCapitalizationAssetItem]
 		asset_items_total: DF.Currency
-		capitalization_method: DF.Literal[
-			"", "Create a new composite asset", "Choose a WIP composite asset"
-		]
+		capitalization_method: DF.Literal["", "Create a new composite asset", "Choose a WIP composite asset"]
 		company: DF.Link
 		cost_center: DF.Link | None
 		entry_type: DF.Literal["Capitalization", "Decapitalization"]
@@ -147,7 +145,7 @@
 
 	def on_trash(self):
 		frappe.db.set_value("Asset", self.target_asset, "capitalized_in", None)
-		super(AssetCapitalization, self).on_trash()
+		super().on_trash()
 
 	def cancel_target_asset(self):
 		if self.entry_type == "Capitalization" and self.target_asset:
@@ -240,7 +238,9 @@
 
 			if target_asset.item_code != self.target_item_code:
 				frappe.throw(
-					_("Asset {0} does not belong to Item {1}").format(self.target_asset, self.target_item_code)
+					_("Asset {0} does not belong to Item {1}").format(
+						self.target_asset, self.target_item_code
+					)
 				)
 
 			if target_asset.status in ("Scrapped", "Sold", "Capitalized", "Decapitalized"):
@@ -255,7 +255,9 @@
 
 			if target_asset.company != self.company:
 				frappe.throw(
-					_("Target Asset {0} does not belong to company {1}").format(target_asset.name, self.company)
+					_("Target Asset {0} does not belong to company {1}").format(
+						target_asset.name, self.company
+					)
 				)
 
 	def validate_consumed_stock_item(self):
@@ -285,13 +287,17 @@
 
 				if asset.status in ("Draft", "Scrapped", "Sold", "Capitalized", "Decapitalized"):
 					frappe.throw(
-						_("Row #{0}: Consumed Asset {1} cannot be {2}").format(d.idx, asset.name, asset.status)
+						_("Row #{0}: Consumed Asset {1} cannot be {2}").format(
+							d.idx, asset.name, asset.status
+						)
 					)
 
 				if asset.docstatus == 0:
 					frappe.throw(_("Row #{0}: Consumed Asset {1} cannot be Draft").format(d.idx, asset.name))
 				elif asset.docstatus == 2:
-					frappe.throw(_("Row #{0}: Consumed Asset {1} cannot be cancelled").format(d.idx, asset.name))
+					frappe.throw(
+						_("Row #{0}: Consumed Asset {1} cannot be cancelled").format(d.idx, asset.name)
+					)
 
 				if asset.company != self.company:
 					frappe.throw(
@@ -444,9 +450,7 @@
 		elif self.docstatus == 2:
 			make_reverse_gl_entries(voucher_type=self.doctype, voucher_no=self.name)
 
-	def get_gl_entries(
-		self, warehouse_account=None, default_expense_account=None, default_cost_center=None
-	):
+	def get_gl_entries(self, warehouse_account=None, default_expense_account=None, default_cost_center=None):
 		# Stock GL Entries
 		gl_entries = []
 
@@ -460,15 +464,9 @@
 		target_account = self.get_target_account()
 		target_against = set()
 
-		self.get_gl_entries_for_consumed_stock_items(
-			gl_entries, target_account, target_against, precision
-		)
-		self.get_gl_entries_for_consumed_asset_items(
-			gl_entries, target_account, target_against, precision
-		)
-		self.get_gl_entries_for_consumed_service_items(
-			gl_entries, target_account, target_against, precision
-		)
+		self.get_gl_entries_for_consumed_stock_items(gl_entries, target_account, target_against, precision)
+		self.get_gl_entries_for_consumed_asset_items(gl_entries, target_account, target_against, precision)
+		self.get_gl_entries_for_consumed_service_items(gl_entries, target_account, target_against, precision)
 
 		self.get_gl_entries_for_target_item(gl_entries, target_against, precision)
 
@@ -480,9 +478,7 @@
 		else:
 			return self.warehouse_account[self.target_warehouse]["account"]
 
-	def get_gl_entries_for_consumed_stock_items(
-		self, gl_entries, target_account, target_against, precision
-	):
+	def get_gl_entries_for_consumed_stock_items(self, gl_entries, target_account, target_against, precision):
 		# Consumed Stock Items
 		for item_row in self.stock_items:
 			sle_list = self.sle_map.get(item_row.name)
@@ -511,9 +507,7 @@
 						)
 					)
 
-	def get_gl_entries_for_consumed_asset_items(
-		self, gl_entries, target_account, target_against, precision
-	):
+	def get_gl_entries_for_consumed_asset_items(self, gl_entries, target_account, target_against, precision):
 		# Consumed Assets
 		for item in self.asset_items:
 			asset = frappe.get_doc("Asset", item.asset)
@@ -522,7 +516,8 @@
 				notes = _(
 					"This schedule was created when Asset {0} was consumed through Asset Capitalization {1}."
 				).format(
-					get_link_to_form(asset.doctype, asset.name), get_link_to_form(self.doctype, self.get("name"))
+					get_link_to_form(asset.doctype, asset.name),
+					get_link_to_form(self.doctype, self.get("name")),
 				)
 				depreciate_asset(asset, self.posting_date, notes)
 				asset.reload()
@@ -642,9 +637,9 @@
 		)
 
 		frappe.msgprint(
-			_(
-				"Asset {0} has been created. Please set the depreciation details if any and submit it."
-			).format(get_link_to_form("Asset", asset_doc.name))
+			_("Asset {0} has been created. Please set the depreciation details if any and submit it.").format(
+				get_link_to_form("Asset", asset_doc.name)
+			)
 		)
 
 	def update_target_asset(self):
@@ -664,9 +659,9 @@
 		asset_doc.save()
 
 		frappe.msgprint(
-			_(
-				"Asset {0} has been updated. Please set the depreciation details if any and submit it."
-			).format(get_link_to_form("Asset", asset_doc.name))
+			_("Asset {0} has been updated. Please set the depreciation details if any and submit it.").format(
+				get_link_to_form("Asset", asset_doc.name)
+			)
 		)
 
 	def restore_consumed_asset_items(self):
@@ -805,9 +800,7 @@
 	item_defaults = get_item_defaults(item.name, args.company)
 	item_group_defaults = get_item_group_defaults(item.name, args.company)
 	brand_defaults = get_brand_defaults(item.name, args.company)
-	out.cost_center = get_default_cost_center(
-		args, item_defaults, item_group_defaults, brand_defaults
-	)
+	out.cost_center = get_default_cost_center(args, item_defaults, item_group_defaults, brand_defaults)
 
 	if args.item_code and out.warehouse:
 		incoming_rate_args = frappe._dict(
@@ -893,9 +886,7 @@
 		item_defaults = get_item_defaults(item.name, args.company)
 		item_group_defaults = get_item_group_defaults(item.name, args.company)
 		brand_defaults = get_brand_defaults(item.name, args.company)
-		out.cost_center = get_default_cost_center(
-			args, item_defaults, item_group_defaults, brand_defaults
-		)
+		out.cost_center = get_default_cost_center(args, item_defaults, item_group_defaults, brand_defaults)
 	return out
 
 
@@ -922,9 +913,7 @@
 	out.expense_account = get_default_expense_account(
 		args, item_defaults, item_group_defaults, brand_defaults
 	)
-	out.cost_center = get_default_cost_center(
-		args, item_defaults, item_group_defaults, brand_defaults
-	)
+	out.cost_center = get_default_cost_center(args, item_defaults, item_group_defaults, brand_defaults)
 
 	return out
 
diff --git a/erpnext/assets/doctype/asset_capitalization/test_asset_capitalization.py b/erpnext/assets/doctype/asset_capitalization/test_asset_capitalization.py
index ac7c90d..86a18c0 100644
--- a/erpnext/assets/doctype/asset_capitalization/test_asset_capitalization.py
+++ b/erpnext/assets/doctype/asset_capitalization/test_asset_capitalization.py
@@ -17,8 +17,6 @@
 )
 from erpnext.stock.doctype.item.test_item import create_item
 from erpnext.stock.doctype.serial_and_batch_bundle.test_serial_and_batch_bundle import (
-	get_batch_from_bundle,
-	get_serial_nos_from_bundle,
 	make_serial_batch_bundle,
 )
 
@@ -323,7 +321,7 @@
 		)
 
 		first_asset_depr_schedule = get_asset_depr_schedule_doc(consumed_asset.name, "Active")
-		self.assertEquals(first_asset_depr_schedule.status, "Active")
+		self.assertEqual(first_asset_depr_schedule.status, "Active")
 
 		# Create and submit Asset Captitalization
 		asset_capitalization = create_asset_capitalization(
@@ -357,8 +355,8 @@
 		first_asset_depr_schedule.load_from_db()
 
 		second_asset_depr_schedule = get_asset_depr_schedule_doc(consumed_asset.name, "Active")
-		self.assertEquals(second_asset_depr_schedule.status, "Active")
-		self.assertEquals(first_asset_depr_schedule.status, "Cancelled")
+		self.assertEqual(second_asset_depr_schedule.status, "Active")
+		self.assertEqual(first_asset_depr_schedule.status, "Cancelled")
 
 		depr_schedule_of_consumed_asset = second_asset_depr_schedule.get("depreciation_schedule")
 
@@ -367,9 +365,7 @@
 			for d in depr_schedule_of_consumed_asset
 			if getdate(d.schedule_date) == getdate(capitalization_date)
 		]
-		self.assertTrue(
-			consumed_depreciation_schedule and consumed_depreciation_schedule[0].journal_entry
-		)
+		self.assertTrue(consumed_depreciation_schedule and consumed_depreciation_schedule[0].journal_entry)
 		self.assertEqual(
 			consumed_depreciation_schedule[0].depreciation_amount, depreciation_before_disposal_amount
 		)
@@ -392,15 +388,9 @@
 
 
 def create_asset_capitalization_data():
-	create_item(
-		"Capitalization Target Stock Item", is_stock_item=1, is_fixed_asset=0, is_purchase_item=0
-	)
-	create_item(
-		"Capitalization Source Stock Item", is_stock_item=1, is_fixed_asset=0, is_purchase_item=0
-	)
-	create_item(
-		"Capitalization Source Service Item", is_stock_item=0, is_fixed_asset=0, is_purchase_item=0
-	)
+	create_item("Capitalization Target Stock Item", is_stock_item=1, is_fixed_asset=0, is_purchase_item=0)
+	create_item("Capitalization Source Stock Item", is_stock_item=1, is_fixed_asset=0, is_purchase_item=0)
+	create_item("Capitalization Source Service Item", is_stock_item=0, is_fixed_asset=0, is_purchase_item=0)
 
 
 def create_asset_capitalization(**args):
diff --git a/erpnext/assets/doctype/asset_category/asset_category.py b/erpnext/assets/doctype/asset_category/asset_category.py
index d401b81..8c2d301 100644
--- a/erpnext/assets/doctype/asset_category/asset_category.py
+++ b/erpnext/assets/doctype/asset_category/asset_category.py
@@ -57,7 +57,9 @@
 					account_currency = frappe.get_value("Account", d.get(type_of_account), "account_currency")
 					if account_currency != company_currency:
 						invalid_accounts.append(
-							frappe._dict({"type": type_of_account, "idx": d.idx, "account": d.get(type_of_account)})
+							frappe._dict(
+								{"type": type_of_account, "idx": d.idx, "account": d.get(type_of_account)}
+							)
 						)
 
 		for d in invalid_accounts:
diff --git a/erpnext/assets/doctype/asset_category/test_asset_category.py b/erpnext/assets/doctype/asset_category/test_asset_category.py
index 2c92656..516e27e00 100644
--- a/erpnext/assets/doctype/asset_category/test_asset_category.py
+++ b/erpnext/assets/doctype/asset_category/test_asset_category.py
@@ -31,9 +31,7 @@
 			pass
 
 	def test_cwip_accounting(self):
-		company_cwip_acc = frappe.db.get_value(
-			"Company", "_Test Company", "capital_work_in_progress_account"
-		)
+		frappe.db.get_value("Company", "_Test Company", "capital_work_in_progress_account")
 		frappe.db.set_value("Company", "_Test Company", "capital_work_in_progress_account", "")
 
 		asset_category = frappe.new_doc("Asset Category")
diff --git a/erpnext/assets/doctype/asset_depreciation_schedule/asset_depreciation_schedule.py b/erpnext/assets/doctype/asset_depreciation_schedule/asset_depreciation_schedule.py
index 6e16508..d22377d 100644
--- a/erpnext/assets/doctype/asset_depreciation_schedule/asset_depreciation_schedule.py
+++ b/erpnext/assets/doctype/asset_depreciation_schedule/asset_depreciation_schedule.py
@@ -275,9 +275,7 @@
 			row.depreciation_method in ("Written Down Value", "Double Declining Balance")
 			and cint(row.frequency_of_depreciation) != 12
 		):
-			has_wdv_or_dd_non_yearly_pro_rata = _check_is_pro_rata(
-				asset_doc, row, wdv_or_dd_non_yearly=True
-			)
+			has_wdv_or_dd_non_yearly_pro_rata = _check_is_pro_rata(asset_doc, row, wdv_or_dd_non_yearly=True)
 
 		skip_row = False
 		should_get_last_day = is_last_day_of_the_month(row.depreciation_start_date)
@@ -567,9 +565,7 @@
 		)
 
 
-def _get_pro_rata_amt(
-	row, depreciation_amount, from_date, to_date, has_wdv_or_dd_non_yearly_pro_rata=False
-):
+def _get_pro_rata_amt(row, depreciation_amount, from_date, to_date, has_wdv_or_dd_non_yearly_pro_rata=False):
 	days = date_diff(to_date, from_date)
 	months = month_diff(to_date, from_date)
 	if has_wdv_or_dd_non_yearly_pro_rata:
@@ -668,7 +664,9 @@
 			)
 			from_date = add_days(
 				get_last_day(
-					add_months(row.depreciation_start_date, (schedule_idx - 1) * row.frequency_of_depreciation)
+					add_months(
+						row.depreciation_start_date, (schedule_idx - 1) * row.frequency_of_depreciation
+					)
 				),
 				1,
 			)
@@ -694,7 +692,8 @@
 					)
 				),
 				add_days(
-					get_last_day(add_months(row.depreciation_start_date, -1 * row.frequency_of_depreciation)), 1
+					get_last_day(add_months(row.depreciation_start_date, -1 * row.frequency_of_depreciation)),
+					1,
 				),
 			)
 
@@ -703,7 +702,9 @@
 			)
 			from_date = add_days(
 				get_last_day(
-					add_months(row.depreciation_start_date, (schedule_idx - 1) * row.frequency_of_depreciation)
+					add_months(
+						row.depreciation_start_date, (schedule_idx - 1) * row.frequency_of_depreciation
+					)
 				),
 				1,
 			)
@@ -930,9 +931,7 @@
 	update_asset_finance_book_row=False,
 	new_depr_schedule=None,
 ):
-	current_asset_depr_schedule_doc = get_asset_depr_schedule_doc(
-		asset_doc.name, "Active", row.finance_book
-	)
+	current_asset_depr_schedule_doc = get_asset_depr_schedule_doc(asset_doc.name, "Active", row.finance_book)
 
 	if not current_asset_depr_schedule_doc:
 		frappe.throw(
diff --git a/erpnext/assets/doctype/asset_depreciation_schedule/test_asset_depreciation_schedule.py b/erpnext/assets/doctype/asset_depreciation_schedule/test_asset_depreciation_schedule.py
index 024121d..c55063f 100644
--- a/erpnext/assets/doctype/asset_depreciation_schedule/test_asset_depreciation_schedule.py
+++ b/erpnext/assets/doctype/asset_depreciation_schedule/test_asset_depreciation_schedule.py
@@ -18,7 +18,7 @@
 		asset = create_asset(item_code="Macbook Pro", calculate_depreciation=1, submit=1)
 
 		first_asset_depr_schedule = get_asset_depr_schedule_doc(asset.name, "Active")
-		self.assertEquals(first_asset_depr_schedule.status, "Active")
+		self.assertEqual(first_asset_depr_schedule.status, "Active")
 
 		second_asset_depr_schedule = frappe.get_doc(
 			{"doctype": "Asset Depreciation Schedule", "asset": asset.name, "finance_book": None}
diff --git a/erpnext/assets/doctype/asset_maintenance/asset_maintenance.py b/erpnext/assets/doctype/asset_maintenance/asset_maintenance.py
index 780f61f..99829df 100644
--- a/erpnext/assets/doctype/asset_maintenance/asset_maintenance.py
+++ b/erpnext/assets/doctype/asset_maintenance/asset_maintenance.py
@@ -92,9 +92,7 @@
 	if not start_date and not last_completion_date:
 		start_date = frappe.utils.now()
 
-	if last_completion_date and (
-		(start_date and last_completion_date > start_date) or not start_date
-	):
+	if last_completion_date and ((start_date and last_completion_date > start_date) or not start_date):
 		start_date = last_completion_date
 	if periodicity == "Daily":
 		next_due_date = add_days(start_date, 1)
diff --git a/erpnext/assets/doctype/asset_movement/asset_movement.py b/erpnext/assets/doctype/asset_movement/asset_movement.py
index ff52643..29c8b3c 100644
--- a/erpnext/assets/doctype/asset_movement/asset_movement.py
+++ b/erpnext/assets/doctype/asset_movement/asset_movement.py
@@ -54,7 +54,9 @@
 				if d.source_location:
 					if current_location != d.source_location:
 						frappe.throw(
-							_("Asset {0} does not belongs to the location {1}").format(d.asset, d.source_location)
+							_("Asset {0} does not belongs to the location {1}").format(
+								d.asset, d.source_location
+							)
 						)
 				else:
 					d.source_location = current_location
@@ -79,19 +81,25 @@
 						title=_("Incorrect Movement Purpose"),
 					)
 				if not d.target_location:
-					frappe.throw(_("Target Location is required while transferring Asset {0}").format(d.asset))
+					frappe.throw(
+						_("Target Location is required while transferring Asset {0}").format(d.asset)
+					)
 				if d.source_location == d.target_location:
 					frappe.throw(_("Source and Target Location cannot be same"))
 
 			if self.purpose == "Receipt":
 				if not (d.source_location) and not d.target_location and not d.to_employee:
 					frappe.throw(
-						_("Target Location or To Employee is required while receiving Asset {0}").format(d.asset)
+						_("Target Location or To Employee is required while receiving Asset {0}").format(
+							d.asset
+						)
 					)
 				elif d.source_location:
 					if d.from_employee and not d.target_location:
 						frappe.throw(
-							_("Target Location is required while receiving Asset {0} from an employee").format(d.asset)
+							_(
+								"Target Location is required while receiving Asset {0} from an employee"
+							).format(d.asset)
 						)
 					elif d.to_employee and d.target_location:
 						frappe.throw(
@@ -131,19 +139,17 @@
 			# latest entry corresponds to current document's location, employee when transaction date > previous dates
 			# In case of cancellation it corresponds to previous latest document's location, employee
 			latest_movement_entry = frappe.db.sql(
-				"""
+				f"""
 				SELECT asm_item.target_location, asm_item.to_employee
 				FROM `tabAsset Movement Item` asm_item, `tabAsset Movement` asm
 				WHERE
 					asm_item.parent=asm.name and
 					asm_item.asset=%(asset)s and
 					asm.company=%(company)s and
-					asm.docstatus=1 and {0}
+					asm.docstatus=1 and {cond}
 				ORDER BY
 					asm.transaction_date desc limit 1
-				""".format(
-					cond
-				),
+				""",
 				args,
 			)
 			if latest_movement_entry:
@@ -164,7 +170,9 @@
 			elif current_location:
 				add_asset_activity(
 					d.asset,
-					_("Asset transferred to Location {0}").format(get_link_to_form("Location", current_location)),
+					_("Asset transferred to Location {0}").format(
+						get_link_to_form("Location", current_location)
+					),
 				)
 			elif current_employee:
 				add_asset_activity(
diff --git a/erpnext/assets/doctype/asset_movement/test_asset_movement.py b/erpnext/assets/doctype/asset_movement/test_asset_movement.py
index 27e7e55..52590d2 100644
--- a/erpnext/assets/doctype/asset_movement/test_asset_movement.py
+++ b/erpnext/assets/doctype/asset_movement/test_asset_movement.py
@@ -20,9 +20,7 @@
 		make_location()
 
 	def test_movement(self):
-		pr = make_purchase_receipt(
-			item_code="Macbook Pro", qty=1, rate=100000.0, location="Test Location"
-		)
+		pr = make_purchase_receipt(item_code="Macbook Pro", qty=1, rate=100000.0, location="Test Location")
 
 		asset_name = frappe.db.get_value("Asset", {"purchase_receipt": pr.name}, "name")
 		asset = frappe.get_doc("Asset", asset_name)
@@ -51,7 +49,11 @@
 			purpose="Transfer",
 			company=asset.company,
 			assets=[
-				{"asset": asset.name, "source_location": "Test Location", "target_location": "Test Location 2"}
+				{
+					"asset": asset.name,
+					"source_location": "Test Location",
+					"target_location": "Test Location 2",
+				}
 			],
 			reference_doctype="Purchase Receipt",
 			reference_name=pr.name,
@@ -62,7 +64,11 @@
 			purpose="Transfer",
 			company=asset.company,
 			assets=[
-				{"asset": asset.name, "source_location": "Test Location 2", "target_location": "Test Location"}
+				{
+					"asset": asset.name,
+					"source_location": "Test Location 2",
+					"target_location": "Test Location",
+				}
 			],
 			reference_doctype="Purchase Receipt",
 			reference_name=pr.name,
@@ -97,9 +103,7 @@
 		self.assertEqual(frappe.db.get_value("Asset", asset.name, "location"), "Test Location")
 
 	def test_last_movement_cancellation(self):
-		pr = make_purchase_receipt(
-			item_code="Macbook Pro", qty=1, rate=100000.0, location="Test Location"
-		)
+		pr = make_purchase_receipt(item_code="Macbook Pro", qty=1, rate=100000.0, location="Test Location")
 
 		asset_name = frappe.db.get_value("Asset", {"purchase_receipt": pr.name}, "name")
 		asset = frappe.get_doc("Asset", asset_name)
@@ -129,7 +133,11 @@
 			purpose="Transfer",
 			company=asset.company,
 			assets=[
-				{"asset": asset.name, "source_location": "Test Location", "target_location": "Test Location 2"}
+				{
+					"asset": asset.name,
+					"source_location": "Test Location",
+					"target_location": "Test Location 2",
+				}
 			],
 			reference_doctype="Purchase Receipt",
 			reference_name=pr.name,
@@ -167,6 +175,4 @@
 def make_location():
 	for location in ["Pune", "Mumbai", "Nagpur"]:
 		if not frappe.db.exists("Location", location):
-			frappe.get_doc({"doctype": "Location", "location_name": location}).insert(
-				ignore_permissions=True
-			)
+			frappe.get_doc({"doctype": "Location", "location_name": location}).insert(ignore_permissions=True)
diff --git a/erpnext/assets/doctype/asset_repair/asset_repair.py b/erpnext/assets/doctype/asset_repair/asset_repair.py
index 10d36e6..27542bc 100644
--- a/erpnext/assets/doctype/asset_repair/asset_repair.py
+++ b/erpnext/assets/doctype/asset_repair/asset_repair.py
@@ -169,9 +169,7 @@
 
 	def check_for_stock_items_and_warehouse(self):
 		if not self.get("stock_items"):
-			frappe.throw(
-				_("Please enter Stock Items consumed during the Repair."), title=_("Missing Items")
-			)
+			frappe.throw(_("Please enter Stock Items consumed during the Repair."), title=_("Missing Items"))
 		if not self.warehouse:
 			frappe.throw(
 				_("Please enter Warehouse from which Stock Items consumed during the Repair were taken."),
@@ -263,9 +261,7 @@
 	def get_gl_entries(self):
 		gl_entries = []
 
-		fixed_asset_account = get_asset_account(
-			"fixed_asset_account", asset=self.asset, company=self.company
-		)
+		fixed_asset_account = get_asset_account("fixed_asset_account", asset=self.asset, company=self.company)
 		self.get_gl_entries_for_repair_cost(gl_entries, fixed_asset_account)
 		self.get_gl_entries_for_consumed_items(gl_entries, fixed_asset_account)
 
diff --git a/erpnext/assets/doctype/asset_repair/test_asset_repair.py b/erpnext/assets/doctype/asset_repair/test_asset_repair.py
index b3e0954..3a5acbe 100644
--- a/erpnext/assets/doctype/asset_repair/test_asset_repair.py
+++ b/erpnext/assets/doctype/asset_repair/test_asset_repair.py
@@ -199,9 +199,7 @@
 			self.assertEqual(expected_values[d.account][1], d.credit)
 
 	def test_gl_entries_with_periodical_inventory(self):
-		frappe.db.set_value(
-			"Company", "_Test Company", "default_expense_account", "Cost of Goods Sold - _TC"
-		)
+		frappe.db.set_value("Company", "_Test Company", "default_expense_account", "Cost of Goods Sold - _TC")
 		asset_repair = create_asset_repair(
 			capitalize_repair_cost=1,
 			stock_consumption=1,
@@ -244,7 +242,7 @@
 		asset = create_asset(calculate_depreciation=1, submit=1)
 
 		first_asset_depr_schedule = get_asset_depr_schedule_doc(asset.name, "Active")
-		self.assertEquals(first_asset_depr_schedule.status, "Active")
+		self.assertEqual(first_asset_depr_schedule.status, "Active")
 
 		initial_num_of_depreciations = num_of_depreciations(asset)
 		create_asset_repair(asset=asset, capitalize_repair_cost=1, submit=1)
@@ -253,8 +251,8 @@
 		first_asset_depr_schedule.load_from_db()
 
 		second_asset_depr_schedule = get_asset_depr_schedule_doc(asset.name, "Active")
-		self.assertEquals(second_asset_depr_schedule.status, "Active")
-		self.assertEquals(first_asset_depr_schedule.status, "Cancelled")
+		self.assertEqual(second_asset_depr_schedule.status, "Active")
+		self.assertEqual(first_asset_depr_schedule.status, "Cancelled")
 
 		self.assertEqual((initial_num_of_depreciations + 1), num_of_depreciations(asset))
 		self.assertEqual(
@@ -291,9 +289,7 @@
 
 	if args.stock_consumption:
 		asset_repair.stock_consumption = 1
-		asset_repair.warehouse = args.warehouse or create_warehouse(
-			"Test Warehouse", company=asset.company
-		)
+		asset_repair.warehouse = args.warehouse or create_warehouse("Test Warehouse", company=asset.company)
 
 		bundle = None
 		if args.serial_no:
diff --git a/erpnext/assets/doctype/asset_shift_allocation/asset_shift_allocation.py b/erpnext/assets/doctype/asset_shift_allocation/asset_shift_allocation.py
index 13915c7..323cb73 100644
--- a/erpnext/assets/doctype/asset_shift_allocation/asset_shift_allocation.py
+++ b/erpnext/assets/doctype/asset_shift_allocation/asset_shift_allocation.py
@@ -45,9 +45,7 @@
 		self.fetch_and_set_depr_schedule()
 
 	def validate(self):
-		self.asset_depr_schedule_doc = get_asset_depr_schedule_doc(
-			self.asset, "Active", self.finance_book
-		)
+		self.asset_depr_schedule_doc = get_asset_depr_schedule_doc(self.asset, "Active", self.finance_book)
 
 		self.validate_invalid_shift_change()
 		self.update_depr_schedule()
@@ -90,9 +88,7 @@
 			return
 
 		for i, sch in enumerate(self.depreciation_schedule):
-			if (
-				sch.journal_entry and self.asset_depr_schedule_doc.depreciation_schedule[i].shift != sch.shift
-			):
+			if sch.journal_entry and self.asset_depr_schedule_doc.depreciation_schedule[i].shift != sch.shift:
 				frappe.throw(
 					_(
 						"Row {0}: Shift cannot be changed since the depreciation has already been processed"
@@ -130,9 +126,7 @@
 
 	def allocate_shift_diff_in_depr_schedule(self):
 		asset_shift_factors_map = get_asset_shift_factors_map()
-		reverse_asset_shift_factors_map = {
-			asset_shift_factors_map[k]: k for k in asset_shift_factors_map
-		}
+		reverse_asset_shift_factors_map = {asset_shift_factors_map[k]: k for k in asset_shift_factors_map}
 
 		original_shift_factors_sum = sum(
 			flt(asset_shift_factors_map.get(schedule.shift))
@@ -162,9 +156,9 @@
 						)
 						diff = 0
 					except Exception:
-						frappe.throw(_("Could not auto update shifts. Shift with shift factor {0} needed.")).format(
-							shift_factor - diff
-						)
+						frappe.throw(
+							_("Could not auto update shifts. Shift with shift factor {0} needed.")
+						).format(shift_factor - diff)
 		elif diff < 0:
 			shift_factors = list(asset_shift_factors_map.values())
 			desc_shift_factors = sorted(shift_factors, reverse=True)
@@ -222,9 +216,9 @@
 							)
 							diff = 0
 						except Exception:
-							frappe.throw(_("Could not auto update shifts. Shift with shift factor {0} needed.")).format(
-								shift_factor + diff
-							)
+							frappe.throw(
+								_("Could not auto update shifts. Shift with shift factor {0} needed.")
+							).format(shift_factor + diff)
 
 	def create_new_asset_depr_schedule(self):
 		new_asset_depr_schedule_doc = frappe.copy_doc(self.asset_depr_schedule_doc)
@@ -273,9 +267,7 @@
 		return
 
 	# Include the current number in the subset
-	find_subsets_with_sum(
-		numbers, k - 1, target_sum - numbers[0], current_subset + [numbers[0]], result
-	)
+	find_subsets_with_sum(numbers, k - 1, target_sum - numbers[0], [*current_subset, numbers[0]], result)
 
 	# Exclude the current number from the subset
 	find_subsets_with_sum(numbers[1:], k, target_sum, current_subset, result)
diff --git a/erpnext/assets/doctype/asset_shift_factor/asset_shift_factor.py b/erpnext/assets/doctype/asset_shift_factor/asset_shift_factor.py
index 365a817..4af7067 100644
--- a/erpnext/assets/doctype/asset_shift_factor/asset_shift_factor.py
+++ b/erpnext/assets/doctype/asset_shift_factor/asset_shift_factor.py
@@ -25,9 +25,7 @@
 
 	def validate_default(self):
 		if self.default:
-			existing_default_shift_factor = frappe.db.get_value(
-				"Asset Shift Factor", {"default": 1}, "name"
-			)
+			existing_default_shift_factor = frappe.db.get_value("Asset Shift Factor", {"default": 1}, "name")
 
 			if existing_default_shift_factor:
 				frappe.throw(
diff --git a/erpnext/assets/doctype/asset_value_adjustment/asset_value_adjustment.py b/erpnext/assets/doctype/asset_value_adjustment/asset_value_adjustment.py
index 769571c..0d02347 100644
--- a/erpnext/assets/doctype/asset_value_adjustment/asset_value_adjustment.py
+++ b/erpnext/assets/doctype/asset_value_adjustment/asset_value_adjustment.py
@@ -98,7 +98,7 @@
 		je.naming_series = depreciation_series
 		je.posting_date = self.date
 		je.company = self.company
-		je.remark = "Depreciation Entry against {0} worth {1}".format(self.asset, self.difference_amount)
+		je.remark = f"Depreciation Entry against {self.asset} worth {self.difference_amount}"
 		je.finance_book = self.finance_book
 
 		credit_entry = {
diff --git a/erpnext/assets/doctype/asset_value_adjustment/test_asset_value_adjustment.py b/erpnext/assets/doctype/asset_value_adjustment/test_asset_value_adjustment.py
index 2c97bae..634ed41 100644
--- a/erpnext/assets/doctype/asset_value_adjustment/test_asset_value_adjustment.py
+++ b/erpnext/assets/doctype/asset_value_adjustment/test_asset_value_adjustment.py
@@ -23,9 +23,7 @@
 		)
 
 	def test_current_asset_value(self):
-		pr = make_purchase_receipt(
-			item_code="Macbook Pro", qty=1, rate=100000.0, location="Test Location"
-		)
+		pr = make_purchase_receipt(item_code="Macbook Pro", qty=1, rate=100000.0, location="Test Location")
 
 		asset_name = frappe.db.get_value("Asset", {"purchase_receipt": pr.name}, "name")
 		asset_doc = frappe.get_doc("Asset", asset_name)
@@ -52,9 +50,7 @@
 		self.assertEqual(current_value, 100000.0)
 
 	def test_asset_depreciation_value_adjustment(self):
-		pr = make_purchase_receipt(
-			item_code="Macbook Pro", qty=1, rate=120000.0, location="Test Location"
-		)
+		pr = make_purchase_receipt(item_code="Macbook Pro", qty=1, rate=120000.0, location="Test Location")
 
 		asset_name = frappe.db.get_value("Asset", {"purchase_receipt": pr.name}, "name")
 		asset_doc = frappe.get_doc("Asset", asset_name)
@@ -75,7 +71,7 @@
 		asset_doc.submit()
 
 		first_asset_depr_schedule = get_asset_depr_schedule_doc(asset_doc.name, "Active")
-		self.assertEquals(first_asset_depr_schedule.status, "Active")
+		self.assertEqual(first_asset_depr_schedule.status, "Active")
 
 		post_depreciation_entries(getdate("2023-08-21"))
 
@@ -92,8 +88,8 @@
 		first_asset_depr_schedule.load_from_db()
 
 		second_asset_depr_schedule = get_asset_depr_schedule_doc(asset_doc.name, "Active")
-		self.assertEquals(second_asset_depr_schedule.status, "Active")
-		self.assertEquals(first_asset_depr_schedule.status, "Cancelled")
+		self.assertEqual(second_asset_depr_schedule.status, "Active")
+		self.assertEqual(first_asset_depr_schedule.status, "Cancelled")
 
 		expected_gle = (
 			("_Test Accumulated Depreciations - _TC", 0.0, 4625.29),
diff --git a/erpnext/assets/doctype/location/location.py b/erpnext/assets/doctype/location/location.py
index 01228f4..03d0980 100644
--- a/erpnext/assets/doctype/location/location.py
+++ b/erpnext/assets/doctype/location/location.py
@@ -216,17 +216,15 @@
 		parent = ""
 
 	return frappe.db.sql(
-		"""
+		f"""
 		select
 			name as value,
 			is_group as expandable
 		from
 			`tabLocation` comp
 		where
-			ifnull(parent_location, "")={parent}
-		""".format(
-			parent=frappe.db.escape(parent)
-		),
+			ifnull(parent_location, "")={frappe.db.escape(parent)}
+		""",
 		as_dict=1,
 	)
 
diff --git a/erpnext/assets/doctype/location/test_location.py b/erpnext/assets/doctype/location/test_location.py
index b8563cb..3b5af61 100644
--- a/erpnext/assets/doctype/location/test_location.py
+++ b/erpnext/assets/doctype/location/test_location.py
@@ -31,9 +31,7 @@
 		ordered_test_location_features = sorted(
 			test_location_features, key=lambda x: x["properties"]["feature_of"]
 		)
-		ordered_formatted_locations = sorted(
-			formatted_locations, key=lambda x: x["properties"]["feature_of"]
-		)
+		ordered_formatted_locations = sorted(formatted_locations, key=lambda x: x["properties"]["feature_of"])
 
 		self.assertEqual(ordered_formatted_locations, ordered_test_location_features)
 		self.assertEqual(area, test_location.get("area"))
diff --git a/erpnext/assets/report/fixed_asset_register/fixed_asset_register.py b/erpnext/assets/report/fixed_asset_register/fixed_asset_register.py
index e689b05..f299d69 100644
--- a/erpnext/assets/report/fixed_asset_register/fixed_asset_register.py
+++ b/erpnext/assets/report/fixed_asset_register/fixed_asset_register.py
@@ -122,11 +122,7 @@
 	assets_record = frappe.db.get_all("Asset", filters=conditions, fields=fields)
 
 	for asset in assets_record:
-		if (
-			assets_linked_to_fb
-			and asset.calculate_depreciation
-			and asset.asset_id not in assets_linked_to_fb
-		):
+		if assets_linked_to_fb and asset.calculate_depreciation and asset.asset_id not in assets_linked_to_fb:
 			continue
 
 		asset_value = get_asset_value_after_depreciation(
@@ -240,9 +236,7 @@
 
 
 def get_asset_depreciation_amount_map(filters, finance_book):
-	start_date = (
-		filters.from_date if filters.filter_based_on == "Date Range" else filters.year_start_date
-	)
+	start_date = filters.from_date if filters.filter_based_on == "Date Range" else filters.year_start_date
 	end_date = filters.to_date if filters.filter_based_on == "Date Range" else filters.year_end_date
 
 	asset = frappe.qb.DocType("Asset")
@@ -259,9 +253,7 @@
 		.join(company)
 		.on(company.name == asset.company)
 		.select(asset.name.as_("asset"), Sum(gle.debit).as_("depreciation_amount"))
-		.where(
-			gle.account == IfNull(aca.depreciation_expense_account, company.depreciation_expense_account)
-		)
+		.where(gle.account == IfNull(aca.depreciation_expense_account, company.depreciation_expense_account))
 		.where(gle.debit != 0)
 		.where(gle.is_cancelled == 0)
 		.where(company.name == filters.company)
@@ -280,9 +272,7 @@
 		else:
 			query = query.where(asset.status.isin(["Sold", "Scrapped", "Capitalized", "Decapitalized"]))
 	if finance_book:
-		query = query.where(
-			(gle.finance_book.isin([cstr(finance_book), ""])) | (gle.finance_book.isnull())
-		)
+		query = query.where((gle.finance_book.isin([cstr(finance_book), ""])) | (gle.finance_book.isnull()))
 	else:
 		query = query.where((gle.finance_book.isin([""])) | (gle.finance_book.isnull()))
 	if filters.filter_based_on in ("Date Range", "Fiscal Year"):
diff --git a/erpnext/buying/doctype/purchase_order/purchase_order.py b/erpnext/buying/doctype/purchase_order/purchase_order.py
index e462820..13f1f3b 100644
--- a/erpnext/buying/doctype/purchase_order/purchase_order.py
+++ b/erpnext/buying/doctype/purchase_order/purchase_order.py
@@ -169,7 +169,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(PurchaseOrder, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 		self.status_updater = [
 			{
 				"source_dt": "Purchase Order Item",
@@ -190,7 +190,7 @@
 		self.set_onload("can_update_items", self.can_update_items())
 
 	def validate(self):
-		super(PurchaseOrder, self).validate()
+		super().validate()
 
 		self.set_status()
 
@@ -230,7 +230,7 @@
 		if self.is_subcontracted:
 			mri_compare_fields = [["project", "="]]
 
-		super(PurchaseOrder, self).validate_with_previous_doc(
+		super().validate_with_previous_doc(
 			{
 				"Supplier Quotation": {
 					"ref_dn_field": "supplier_quotation",
@@ -325,9 +325,7 @@
 		itemwise_min_order_qty = frappe._dict(
 			frappe.db.sql(
 				"""select name, min_order_qty
-			from tabItem where name in ({0})""".format(
-					", ".join(["%s"] * len(items))
-				),
+			from tabItem where name in ({})""".format(", ".join(["%s"] * len(items))),
 				items,
 			)
 		)
@@ -373,7 +371,9 @@
 							)
 						elif not frappe.get_value("Item", item.fg_item, "default_bom"):
 							frappe.throw(
-								_("Row #{0}: Default BOM not found for FG Item {1}").format(item.idx, item.fg_item)
+								_("Row #{0}: Default BOM not found for FG Item {1}").format(
+									item.idx, item.fg_item
+								)
 							)
 					if not item.fg_item_qty:
 						frappe.throw(_("Row #{0}: Finished Good Item Qty can not be zero").format(item.idx))
@@ -407,8 +407,9 @@
 					d.rate = d.base_rate / conversion_rate
 					d.last_purchase_rate = d.rate
 				else:
-
-					item_last_purchase_rate = frappe.get_cached_value("Item", d.item_code, "last_purchase_rate")
+					item_last_purchase_rate = frappe.get_cached_value(
+						"Item", d.item_code, "last_purchase_rate"
+					)
 					if item_last_purchase_rate:
 						d.base_price_list_rate = (
 							d.base_rate
@@ -443,7 +444,7 @@
 
 	def check_modified_date(self):
 		mod_db = frappe.db.sql("select modified from `tabPurchase Order` where name = %s", self.name)
-		date_diff = frappe.db.sql("select '%s' - '%s' " % (mod_db[0][0], cstr(self.modified)))
+		date_diff = frappe.db.sql(f"select '{mod_db[0][0]}' - '{cstr(self.modified)}' ")
 
 		if date_diff and date_diff[0][0]:
 			msgprint(
@@ -463,7 +464,7 @@
 		clear_doctype_notifications(self)
 
 	def on_submit(self):
-		super(PurchaseOrder, self).on_submit()
+		super().on_submit()
 
 		if self.is_against_so():
 			self.update_status_updater()
@@ -488,7 +489,7 @@
 
 	def on_cancel(self):
 		self.ignore_linked_doctypes = ("GL Entry", "Payment Ledger Entry")
-		super(PurchaseOrder, self).on_cancel()
+		super().on_cancel()
 
 		if self.is_against_so():
 			self.update_status_updater()
@@ -674,7 +675,9 @@
 		po = frappe.get_doc("Purchase Order", name)
 		if po.docstatus == 1:
 			if status == "Closed":
-				if po.status not in ("Cancelled", "Closed") and (po.per_received < 100 or po.per_billed < 100):
+				if po.status not in ("Cancelled", "Closed") and (
+					po.per_received < 100 or po.per_billed < 100
+				):
 					po.update_status(status)
 			else:
 				if po.status == "Closed":
@@ -845,9 +848,7 @@
 
 
 @frappe.whitelist()
-def make_subcontracting_order(
-	source_name, target_doc=None, save=False, submit=False, notify=False
-):
+def make_subcontracting_order(source_name, target_doc=None, save=False, submit=False, notify=False):
 	target_doc = get_mapped_subcontracting_order(source_name, target_doc)
 
 	if (save or submit) and frappe.has_permission(target_doc.doctype, "create"):
@@ -872,7 +873,6 @@
 
 
 def get_mapped_subcontracting_order(source_name, target_doc=None):
-
 	if target_doc and isinstance(target_doc, str):
 		target_doc = json.loads(target_doc)
 		for key in ["service_items", "items", "supplied_items"]:
diff --git a/erpnext/buying/doctype/purchase_order/test_purchase_order.py b/erpnext/buying/doctype/purchase_order/test_purchase_order.py
index c667ee8..64bf132 100644
--- a/erpnext/buying/doctype/purchase_order/test_purchase_order.py
+++ b/erpnext/buying/doctype/purchase_order/test_purchase_order.py
@@ -11,11 +11,13 @@
 
 from erpnext.accounts.doctype.payment_entry.payment_entry import get_payment_entry
 from erpnext.accounts.party import get_due_date_from_template
-from erpnext.buying.doctype.purchase_order.purchase_order import make_inter_company_sales_order
+from erpnext.buying.doctype.purchase_order.purchase_order import (
+	make_inter_company_sales_order,
+	make_purchase_receipt,
+)
 from erpnext.buying.doctype.purchase_order.purchase_order import (
 	make_purchase_invoice as make_pi_from_po,
 )
-from erpnext.buying.doctype.purchase_order.purchase_order import make_purchase_receipt
 from erpnext.controllers.accounts_controller import InvalidQtyError, update_child_qty_rate
 from erpnext.manufacturing.doctype.blanket_order.test_blanket_order import make_blanket_order
 from erpnext.stock.doctype.item.test_item import make_item
@@ -198,7 +200,7 @@
 		po.items[0].qty = 4
 		po.save()
 		po.submit()
-		pr = make_pr_against_po(po.name, 2)
+		make_pr_against_po(po.name, 2)
 
 		po.load_from_db()
 		existing_ordered_qty = get_ordered_qty()
@@ -228,7 +230,7 @@
 		po.items[0].qty = 4
 		po.save()
 		po.submit()
-		pr = make_pr_against_po(po.name, 2)
+		make_pr_against_po(po.name, 2)
 
 		po.reload()
 		first_item_of_po = po.get("items")[0]
@@ -469,9 +471,7 @@
 			make_purchase_receipt as make_purchase_receipt_return,
 		)
 
-		pr1 = make_purchase_receipt_return(
-			is_return=1, return_against=pr.name, qty=-3, do_not_submit=True
-		)
+		pr1 = make_purchase_receipt_return(is_return=1, return_against=pr.name, qty=-3, do_not_submit=True)
 		pr1.items[0].purchase_order = po.name
 		pr1.items[0].purchase_order_item = po.items[0].name
 		pr1.submit()
@@ -552,9 +552,7 @@
 		self.assertEqual(po.payment_schedule[0].payment_amount, 2500.0)
 		self.assertEqual(getdate(po.payment_schedule[0].due_date), getdate(po.transaction_date))
 		self.assertEqual(po.payment_schedule[1].payment_amount, 2500.0)
-		self.assertEqual(
-			getdate(po.payment_schedule[1].due_date), add_days(getdate(po.transaction_date), 30)
-		)
+		self.assertEqual(getdate(po.payment_schedule[1].due_date), add_days(getdate(po.transaction_date), 30))
 		pi = make_pi_from_po(po.name)
 		pi.save()
 
@@ -564,9 +562,7 @@
 		self.assertEqual(pi.payment_schedule[0].payment_amount, 2500.0)
 		self.assertEqual(getdate(pi.payment_schedule[0].due_date), getdate(po.transaction_date))
 		self.assertEqual(pi.payment_schedule[1].payment_amount, 2500.0)
-		self.assertEqual(
-			getdate(pi.payment_schedule[1].due_date), add_days(getdate(po.transaction_date), 30)
-		)
+		self.assertEqual(getdate(pi.payment_schedule[1].due_date), add_days(getdate(po.transaction_date), 30))
 		automatically_fetch_payment_terms(enable=0)
 
 	def test_warehouse_company_validation(self):
@@ -710,9 +706,9 @@
 				raise Exception
 
 	def test_default_payment_terms(self):
-		due_date = get_due_date_from_template(
-			"_Test Payment Term Template 1", "2023-02-03", None
-		).strftime("%Y-%m-%d")
+		due_date = get_due_date_from_template("_Test Payment Term Template 1", "2023-02-03", None).strftime(
+			"%Y-%m-%d"
+		)
 		self.assertEqual(due_date, "2023-03-31")
 
 	def test_terms_are_not_copied_if_automatically_fetch_payment_terms_is_unchecked(self):
@@ -763,9 +759,7 @@
 		pe_doc.cancel()
 
 	def create_account(self, account_name, company, currency, parent):
-		if not frappe.db.get_value(
-			"Account", filters={"account_name": account_name, "company": company}
-		):
+		if not frappe.db.get_value("Account", filters={"account_name": account_name, "company": company}):
 			account = frappe.get_doc(
 				{
 					"doctype": "Account",
@@ -796,9 +790,7 @@
 		company = "_Test Company"
 
 		# Setup default 'Advance Paid' account
-		account = self.create_account(
-			"Advance Paid", company, "INR", "Application of Funds (Assets) - _TC"
-		)
+		account = self.create_account("Advance Paid", company, "INR", "Application of Funds (Assets) - _TC")
 		company_doc = frappe.get_doc("Company", company)
 		company_doc.book_advance_payments_in_separate_party_account = True
 		company_doc.default_advance_paid_account = account.name
@@ -893,7 +885,7 @@
 		Second Purchase Order should not add on to Blanket Orders Ordered Quantity.
 		"""
 
-		bo = make_blanket_order(blanket_order_type="Purchasing", quantity=10, rate=10)
+		make_blanket_order(blanket_order_type="Purchasing", quantity=10, rate=10)
 
 		po = create_purchase_order(item_code="_Test Item", qty=5, against_blanket_order=1)
 		po_doc = frappe.get_doc("Purchase Order", po.get("name"))
@@ -1133,17 +1125,13 @@
 		from erpnext.accounts.doctype.payment_request.payment_request import make_payment_request
 
 		po = create_purchase_order()
-		self.assertEqual(
-			frappe.db.get_value(po.doctype, po.name, "advance_payment_status"), "Not Initiated"
-		)
+		self.assertEqual(frappe.db.get_value(po.doctype, po.name, "advance_payment_status"), "Not Initiated")
 
 		pr = make_payment_request(dt=po.doctype, dn=po.name, submit_doc=True, return_doc=True)
 		self.assertEqual(frappe.db.get_value(po.doctype, po.name, "advance_payment_status"), "Initiated")
 
 		pe = get_payment_entry(po.doctype, po.name).save().submit()
-		self.assertEqual(
-			frappe.db.get_value(po.doctype, po.name, "advance_payment_status"), "Fully Paid"
-		)
+		self.assertEqual(frappe.db.get_value(po.doctype, po.name, "advance_payment_status"), "Fully Paid")
 
 		pe.reload()
 		pe.cancel()
@@ -1151,9 +1139,7 @@
 
 		pr.reload()
 		pr.cancel()
-		self.assertEqual(
-			frappe.db.get_value(po.doctype, po.name, "advance_payment_status"), "Not Initiated"
-		)
+		self.assertEqual(frappe.db.get_value(po.doctype, po.name, "advance_payment_status"), "Not Initiated")
 
 	def test_po_billed_amount_against_return_entry(self):
 		from erpnext.accounts.doctype.purchase_invoice.purchase_invoice import make_debit_note
@@ -1316,15 +1302,11 @@
 
 
 def get_ordered_qty(item_code="_Test Item", warehouse="_Test Warehouse - _TC"):
-	return flt(
-		frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse}, "ordered_qty")
-	)
+	return flt(frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse}, "ordered_qty"))
 
 
 def get_requested_qty(item_code="_Test Item", warehouse="_Test Warehouse - _TC"):
-	return flt(
-		frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse}, "indented_qty")
-	)
+	return flt(frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse}, "indented_qty"))
 
 
 test_dependencies = ["BOM", "Item Price"]
diff --git a/erpnext/buying/doctype/request_for_quotation/request_for_quotation.py b/erpnext/buying/doctype/request_for_quotation/request_for_quotation.py
index fb4dc6a..059e36f 100644
--- a/erpnext/buying/doctype/request_for_quotation/request_for_quotation.py
+++ b/erpnext/buying/doctype/request_for_quotation/request_for_quotation.py
@@ -3,7 +3,6 @@
 
 
 import json
-from typing import Optional
 
 import frappe
 from frappe import _
@@ -65,9 +64,9 @@
 	def validate(self):
 		self.validate_duplicate_supplier()
 		self.validate_supplier_list()
-		super(RequestforQuotation, self).validate_qty_is_not_zero()
+		super().validate_qty_is_not_zero()
 		validate_for_items(self)
-		super(RequestforQuotation, self).set_qty_as_per_stock_uom()
+		super().set_qty_as_per_stock_uom()
 		self.update_email_id()
 
 		if self.docstatus < 1:
@@ -317,7 +316,7 @@
 
 	def update_rfq_supplier_status(self, sup_name=None):
 		for supplier in self.suppliers:
-			if sup_name == None or supplier.supplier == sup_name:
+			if sup_name is None or supplier.supplier == sup_name:
 				quote_status = _("Received")
 				for item in self.items:
 					sqi_count = frappe.db.sql(
@@ -348,9 +347,7 @@
 
 
 def check_portal_enabled(reference_doctype):
-	if not frappe.db.get_value(
-		"Portal Menu Item", {"reference_doctype": reference_doctype}, "enabled"
-	):
+	if not frappe.db.get_value("Portal Menu Item", {"reference_doctype": reference_doctype}, "enabled"):
 		frappe.throw(
 			_(
 				"The Access to Request for Quotation From Portal is Disabled. To Allow Access, Enable it in Portal Settings."
@@ -479,9 +476,9 @@
 def get_pdf(
 	name: str,
 	supplier: str,
-	print_format: Optional[str] = None,
-	language: Optional[str] = None,
-	letterhead: Optional[str] = None,
+	print_format: str | None = None,
+	language: str | None = None,
+	letterhead: str | None = None,
 ):
 	doc = frappe.get_doc("Request for Quotation", name)
 	if supplier:
@@ -556,9 +553,7 @@
 @frappe.whitelist()
 def get_supplier_tag():
 	filters = {"document_type": "Supplier"}
-	tags = list(
-		set(tag.tag for tag in frappe.get_all("Tag Link", filters=filters, fields=["tag"]) if tag)
-	)
+	tags = list(set(tag.tag for tag in frappe.get_all("Tag Link", filters=filters, fields=["tag"]) if tag))
 
 	return tags
 
@@ -571,7 +566,7 @@
 		conditions += "and rfq.name like '%%" + txt + "%%' "
 
 	if filters.get("transaction_date"):
-		conditions += "and rfq.transaction_date = '{0}'".format(filters.get("transaction_date"))
+		conditions += "and rfq.transaction_date = '{}'".format(filters.get("transaction_date"))
 
 	rfq_data = frappe.db.sql(
 		f"""
diff --git a/erpnext/buying/doctype/request_for_quotation/test_request_for_quotation.py b/erpnext/buying/doctype/request_for_quotation/test_request_for_quotation.py
index fe1466c..4effe13 100644
--- a/erpnext/buying/doctype/request_for_quotation/test_request_for_quotation.py
+++ b/erpnext/buying/doctype/request_for_quotation/test_request_for_quotation.py
@@ -75,9 +75,7 @@
 
 		rfq = make_request_for_quotation(supplier_data=supplier_wt_appos)
 
-		sq = make_supplier_quotation_from_rfq(
-			rfq.name, for_supplier=supplier_wt_appos[0].get("supplier")
-		)
+		sq = make_supplier_quotation_from_rfq(rfq.name, for_supplier=supplier_wt_appos[0].get("supplier"))
 		sq.submit()
 
 		frappe.form_dict.name = rfq.name
@@ -108,9 +106,7 @@
 			row = item.append("uoms", {"uom": "Kg", "conversion_factor": 2})
 			row.db_update()
 
-		rfq = make_request_for_quotation(
-			item_code="_Test Multi UOM RFQ Item", uom="Kg", conversion_factor=2
-		)
+		rfq = make_request_for_quotation(item_code="_Test Multi UOM RFQ Item", uom="Kg", conversion_factor=2)
 		rfq.get("items")[0].rate = 100
 		rfq.supplier = rfq.suppliers[0].supplier
 
diff --git a/erpnext/buying/doctype/supplier/supplier.py b/erpnext/buying/doctype/supplier/supplier.py
index c8ed5aa..0df17fd 100644
--- a/erpnext/buying/doctype/supplier/supplier.py
+++ b/erpnext/buying/doctype/supplier/supplier.py
@@ -11,9 +11,8 @@
 )
 from frappe.model.naming import set_name_by_naming_series, set_name_from_naming_options
 
-from erpnext.accounts.party import (  # noqa
+from erpnext.accounts.party import (
 	get_dashboard_info,
-	get_timeline_data,
 	validate_party_accounts,
 )
 from erpnext.controllers.website_list_for_contact import add_role_for_portal_user
@@ -126,9 +125,7 @@
 			return
 
 		user_doc.add_roles("Supplier")
-		frappe.msgprint(
-			_("Added Supplier Role to User {0}.").format(frappe.bold(user_doc.name)), alert=True
-		)
+		frappe.msgprint(_("Added Supplier Role to User {0}.").format(frappe.bold(user_doc.name)), alert=True)
 
 	def validate(self):
 		self.flags.is_new_doc = self.is_new()
@@ -230,6 +227,6 @@
 		.where(
 			(dynamic_link.link_name == supplier)
 			& (dynamic_link.link_doctype == "Supplier")
-			& (contact.name.like("%{0}%".format(txt)))
+			& (contact.name.like(f"%{txt}%"))
 		)
 	).run(as_dict=False)
diff --git a/erpnext/buying/doctype/supplier/test_supplier.py b/erpnext/buying/doctype/supplier/test_supplier.py
index 55974ea..e4475c7 100644
--- a/erpnext/buying/doctype/supplier/test_supplier.py
+++ b/erpnext/buying/doctype/supplier/test_supplier.py
@@ -3,7 +3,6 @@
 
 
 import frappe
-from frappe.custom.doctype.property_setter.property_setter import make_property_setter
 from frappe.test_runner import make_test_records
 
 from erpnext.accounts.party import get_due_date
@@ -183,7 +182,6 @@
 
 class TestSupplierPortal(FrappeTestCase):
 	def test_portal_user_can_access_supplier_data(self):
-
 		supplier = create_supplier()
 
 		user = frappe.generate_hash() + "@example.com"
diff --git a/erpnext/buying/doctype/supplier_quotation/supplier_quotation.py b/erpnext/buying/doctype/supplier_quotation/supplier_quotation.py
index 52bd83b..456ed8e 100644
--- a/erpnext/buying/doctype/supplier_quotation/supplier_quotation.py
+++ b/erpnext/buying/doctype/supplier_quotation/supplier_quotation.py
@@ -104,7 +104,7 @@
 	# end: auto-generated types
 
 	def validate(self):
-		super(SupplierQuotation, self).validate()
+		super().validate()
 
 		if not self.status:
 			self.status = "Draft"
@@ -130,7 +130,7 @@
 		pass
 
 	def validate_with_previous_doc(self):
-		super(SupplierQuotation, self).validate_with_previous_doc(
+		super().validate_with_previous_doc(
 			{
 				"Material Request": {
 					"ref_dn_field": "prevdoc_docname",
diff --git a/erpnext/buying/doctype/supplier_scorecard/supplier_scorecard.py b/erpnext/buying/doctype/supplier_scorecard/supplier_scorecard.py
index 0a6024f..a114271 100644
--- a/erpnext/buying/doctype/supplier_scorecard/supplier_scorecard.py
+++ b/erpnext/buying/doctype/supplier_scorecard/supplier_scorecard.py
@@ -66,7 +66,11 @@
 			for c2 in self.standings:
 				if c1 != c2:
 					if c1.max_grade > c2.min_grade and c1.min_grade < c2.max_grade:
-						throw(_("Overlap in scoring between {0} and {1}").format(c1.standing_name, c2.standing_name))
+						throw(
+							_("Overlap in scoring between {0} and {1}").format(
+								c1.standing_name, c2.standing_name
+							)
+						)
 				if c2.min_grade == score:
 					score = c2.max_grade
 		if score < 100:
@@ -77,7 +81,6 @@
 			)
 
 	def validate_criteria_weights(self):
-
 		weight = 0
 		for c in self.criteria:
 			weight += c.weight
@@ -196,7 +199,6 @@
 
 @frappe.whitelist()
 def make_all_scorecards(docname):
-
 	sc = frappe.get_doc("Supplier Scorecard", docname)
 	supplier = frappe.get_doc("Supplier", sc.supplier)
 
diff --git a/erpnext/buying/doctype/supplier_scorecard_criteria/supplier_scorecard_criteria.py b/erpnext/buying/doctype/supplier_scorecard_criteria/supplier_scorecard_criteria.py
index f19ab94..e04d1f9 100644
--- a/erpnext/buying/doctype/supplier_scorecard_criteria/supplier_scorecard_criteria.py
+++ b/erpnext/buying/doctype/supplier_scorecard_criteria/supplier_scorecard_criteria.py
@@ -43,8 +43,8 @@
 		regex = r"\{(.*?)\}"
 
 		mylist = re.finditer(regex, test_formula, re.MULTILINE | re.DOTALL)
-		for dummy1, match in enumerate(mylist):
-			for dummy2 in range(0, len(match.groups())):
+		for _dummy1, match in enumerate(mylist):
+			for _dummy2 in range(0, len(match.groups())):
 				test_formula = test_formula.replace("{" + match.group(1) + "}", "0")
 
 		try:
@@ -78,8 +78,8 @@
 	regex = r"\{(.*?)\}"
 
 	mylist = re.finditer(regex, criteria.formula, re.MULTILINE | re.DOTALL)
-	for dummy1, match in enumerate(mylist):
-		for dummy2 in range(0, len(match.groups())):
+	for _dummy1, match in enumerate(mylist):
+		for _dummy2 in range(0, len(match.groups())):
 			try:
 				var = frappe.db.sql(
 					"""
@@ -94,6 +94,8 @@
 				)[0]
 				my_variables.append(var)
 			except Exception:
-				frappe.throw(_("Unable to find variable:") + " " + str(match.group(1)), InvalidFormulaVariable)
+				frappe.throw(
+					_("Unable to find variable:") + " " + str(match.group(1)), InvalidFormulaVariable
+				)
 
 	return my_variables
diff --git a/erpnext/buying/doctype/supplier_scorecard_period/supplier_scorecard_period.py b/erpnext/buying/doctype/supplier_scorecard_period/supplier_scorecard_period.py
index e6ef166..5311ef0 100644
--- a/erpnext/buying/doctype/supplier_scorecard_period/supplier_scorecard_period.py
+++ b/erpnext/buying/doctype/supplier_scorecard_period/supplier_scorecard_period.py
@@ -47,7 +47,6 @@
 		self.calculate_score()
 
 	def validate_criteria_weights(self):
-
 		weight = 0
 		for c in self.criteria:
 			weight += c.weight
@@ -70,14 +69,17 @@
 				crit.score = min(
 					crit.max_score,
 					max(
-						0, frappe.safe_eval(self.get_eval_statement(crit.formula), None, {"max": max, "min": min})
+						0,
+						frappe.safe_eval(
+							self.get_eval_statement(crit.formula), None, {"max": max, "min": min}
+						),
 					),
 				)
 			except Exception:
 				frappe.throw(
-					_("Could not solve criteria score function for {0}. Make sure the formula is valid.").format(
-						crit.criteria_name
-					),
+					_(
+						"Could not solve criteria score function for {0}. Make sure the formula is valid."
+					).format(crit.criteria_name),
 					frappe.ValidationError,
 				)
 				crit.score = 0
@@ -108,7 +110,7 @@
 			if var.value:
 				if var.param_name in my_eval_statement:
 					my_eval_statement = my_eval_statement.replace(
-						"{" + var.param_name + "}", "{:.2f}".format(var.value)
+						"{" + var.param_name + "}", f"{var.value:.2f}"
 					)
 			else:
 				if var.param_name in my_eval_statement:
diff --git a/erpnext/buying/report/procurement_tracker/test_procurement_tracker.py b/erpnext/buying/report/procurement_tracker/test_procurement_tracker.py
index 9b53421..ebceb7f 100644
--- a/erpnext/buying/report/procurement_tracker/test_procurement_tracker.py
+++ b/erpnext/buying/report/procurement_tracker/test_procurement_tracker.py
@@ -2,17 +2,8 @@
 # For license information, please see license.txt
 
 
-from datetime import datetime
-
-import frappe
 from frappe.tests.utils import FrappeTestCase
 
-from erpnext.buying.doctype.purchase_order.purchase_order import make_purchase_receipt
-from erpnext.buying.report.procurement_tracker.procurement_tracker import execute
-from erpnext.stock.doctype.material_request.material_request import make_purchase_order
-from erpnext.stock.doctype.material_request.test_material_request import make_material_request
-from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse
-
 
 class TestProcurementTracker(FrappeTestCase):
 	pass
diff --git a/erpnext/buying/report/purchase_order_analysis/purchase_order_analysis.py b/erpnext/buying/report/purchase_order_analysis/purchase_order_analysis.py
index b88efe1..b23c3f5 100644
--- a/erpnext/buying/report/purchase_order_analysis/purchase_order_analysis.py
+++ b/erpnext/buying/report/purchase_order_analysis/purchase_order_analysis.py
@@ -68,9 +68,7 @@
 			po.company,
 			po_item.name,
 		)
-		.where(
-			(po_item.parent == po.name) & (po.status.notin(("Stopped", "Closed"))) & (po.docstatus == 1)
-		)
+		.where((po_item.parent == po.name) & (po.status.notin(("Stopped", "Closed"))) & (po.docstatus == 1))
 		.groupby(po_item.name)
 		.orderby(po.transaction_date)
 	)
@@ -80,9 +78,7 @@
 			query = query.where(po[field] == filters.get(field))
 
 	if filters.get("from_date") and filters.get("to_date"):
-		query = query.where(
-			po.transaction_date.between(filters.get("from_date"), filters.get("to_date"))
-		)
+		query = query.where(po.transaction_date.between(filters.get("from_date"), filters.get("to_date")))
 
 	if filters.get("status"):
 		query = query.where(po.status.isin(filters.get("status")))
diff --git a/erpnext/buying/report/requested_items_to_order_and_receive/requested_items_to_order_and_receive.py b/erpnext/buying/report/requested_items_to_order_and_receive/requested_items_to_order_and_receive.py
index d431010..55189a7 100644
--- a/erpnext/buying/report/requested_items_to_order_and_receive/requested_items_to_order_and_receive.py
+++ b/erpnext/buying/report/requested_items_to_order_and_receive/requested_items_to_order_and_receive.py
@@ -57,9 +57,7 @@
 				"qty_to_receive"
 			),
 			Sum(Coalesce(mr_item.received_qty, 0)).as_("received_qty"),
-			(Sum(Coalesce(mr_item.stock_qty, 0)) - Sum(Coalesce(mr_item.ordered_qty, 0))).as_(
-				"qty_to_order"
-			),
+			(Sum(Coalesce(mr_item.stock_qty, 0)) - Sum(Coalesce(mr_item.ordered_qty, 0))).as_("qty_to_order"),
 			mr_item.item_name,
 			mr_item.description,
 			mr.company,
diff --git a/erpnext/buying/report/subcontract_order_summary/subcontract_order_summary.py b/erpnext/buying/report/subcontract_order_summary/subcontract_order_summary.py
index 0213051..130cada 100644
--- a/erpnext/buying/report/subcontract_order_summary/subcontract_order_summary.py
+++ b/erpnext/buying/report/subcontract_order_summary/subcontract_order_summary.py
@@ -112,7 +112,7 @@
 
 
 def get_subcontracted_data(order_details, data):
-	for key, details in order_details.items():
+	for _key, details in order_details.items():
 		res = details.order_item
 		for index, row in enumerate(details.supplied_items):
 			if index != 0:
diff --git a/erpnext/buying/report/subcontracted_item_to_be_received/test_subcontracted_item_to_be_received.py b/erpnext/buying/report/subcontracted_item_to_be_received/test_subcontracted_item_to_be_received.py
index d13d970..d90be66 100644
--- a/erpnext/buying/report/subcontracted_item_to_be_received/test_subcontracted_item_to_be_received.py
+++ b/erpnext/buying/report/subcontracted_item_to_be_received/test_subcontracted_item_to_be_received.py
@@ -62,7 +62,9 @@
 					"from_date": frappe.utils.get_datetime(
 						frappe.utils.add_to_date(sco.transaction_date, days=-10)
 					),
-					"to_date": frappe.utils.get_datetime(frappe.utils.add_to_date(sco.transaction_date, days=10)),
+					"to_date": frappe.utils.get_datetime(
+						frappe.utils.add_to_date(sco.transaction_date, days=10)
+					),
 				}
 			)
 		)
diff --git a/erpnext/buying/report/subcontracted_raw_materials_to_be_transferred/test_subcontracted_raw_materials_to_be_transferred.py b/erpnext/buying/report/subcontracted_raw_materials_to_be_transferred/test_subcontracted_raw_materials_to_be_transferred.py
index 1602957..7b4ec5c 100644
--- a/erpnext/buying/report/subcontracted_raw_materials_to_be_transferred/test_subcontracted_raw_materials_to_be_transferred.py
+++ b/erpnext/buying/report/subcontracted_raw_materials_to_be_transferred/test_subcontracted_raw_materials_to_be_transferred.py
@@ -48,7 +48,9 @@
 					"from_date": frappe.utils.get_datetime(
 						frappe.utils.add_to_date(sco.transaction_date, days=-10)
 					),
-					"to_date": frappe.utils.get_datetime(frappe.utils.add_to_date(sco.transaction_date, days=10)),
+					"to_date": frappe.utils.get_datetime(
+						frappe.utils.add_to_date(sco.transaction_date, days=10)
+					),
 				}
 			)
 		)
diff --git a/erpnext/buying/report/supplier_quotation_comparison/supplier_quotation_comparison.py b/erpnext/buying/report/supplier_quotation_comparison/supplier_quotation_comparison.py
index 73b7d45..684cd3a 100644
--- a/erpnext/buying/report/supplier_quotation_comparison/supplier_quotation_comparison.py
+++ b/erpnext/buying/report/supplier_quotation_comparison/supplier_quotation_comparison.py
@@ -82,18 +82,14 @@
 	group_wise_map = defaultdict(list)
 	supplier_qty_price_map = {}
 
-	group_by_field = (
-		"supplier_name" if filters.get("group_by") == "Group by Supplier" else "item_code"
-	)
+	group_by_field = "supplier_name" if filters.get("group_by") == "Group by Supplier" else "item_code"
 	company_currency = frappe.db.get_default("currency")
 	float_precision = cint(frappe.db.get_default("float_precision")) or 2
 
 	for data in supplier_quotation_data:
 		group = data.get(group_by_field)  # get item or supplier value for this row
 
-		supplier_currency = frappe.db.get_value(
-			"Supplier", data.get("supplier_name"), "default_currency"
-		)
+		supplier_currency = frappe.db.get_value("Supplier", data.get("supplier_name"), "default_currency")
 
 		if supplier_currency:
 			exchange_rate = get_exchange_rate(supplier_currency, company_currency)
diff --git a/erpnext/buying/utils.py b/erpnext/buying/utils.py
index 61e5e6a..a120a49 100644
--- a/erpnext/buying/utils.py
+++ b/erpnext/buying/utils.py
@@ -3,7 +3,6 @@
 
 
 import json
-from typing import Dict
 
 import frappe
 from frappe import _
@@ -82,7 +81,7 @@
 			row.set(field, qty_data[field])
 
 
-def validate_item_and_get_basic_data(row) -> Dict:
+def validate_item_and_get_basic_data(row) -> dict:
 	item = frappe.db.get_values(
 		"Item",
 		filters={"name": row.item_code},
@@ -96,12 +95,7 @@
 
 
 def validate_stock_item_warehouse(row, item) -> None:
-	if (
-		item.is_stock_item == 1
-		and row.qty
-		and not row.warehouse
-		and not row.get("delivered_by_supplier")
-	):
+	if item.is_stock_item == 1 and row.qty and not row.warehouse and not row.get("delivered_by_supplier"):
 		frappe.throw(
 			_("Row #{1}: Warehouse is mandatory for stock Item {0}").format(
 				frappe.bold(row.item_code), row.idx
@@ -113,9 +107,7 @@
 	status = frappe.db.get_value(doctype, docname, "status")
 
 	if status in ("Closed", "On Hold"):
-		frappe.throw(
-			_("{0} {1} status is {2}").format(doctype, docname, status), frappe.InvalidStatusError
-		)
+		frappe.throw(_("{0} {1} status is {2}").format(doctype, docname, status), frappe.InvalidStatusError)
 
 
 @frappe.whitelist()
diff --git a/erpnext/communication/doctype/communication_medium_timeslot/communication_medium_timeslot.py b/erpnext/communication/doctype/communication_medium_timeslot/communication_medium_timeslot.py
index 4cd65fa..aed5c73 100644
--- a/erpnext/communication/doctype/communication_medium_timeslot/communication_medium_timeslot.py
+++ b/erpnext/communication/doctype/communication_medium_timeslot/communication_medium_timeslot.py
@@ -15,9 +15,7 @@
 	if TYPE_CHECKING:
 		from frappe.types import DF
 
-		day_of_week: DF.Literal[
-			"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
-		]
+		day_of_week: DF.Literal["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
 		employee_group: DF.Link
 		from_time: DF.Time
 		parent: DF.Data
diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index 3b83c7c..d90e09e 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -95,7 +95,7 @@
 
 class AccountsController(TransactionBase):
 	def __init__(self, *args, **kwargs):
-		super(AccountsController, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 
 	def get_print_settings(self):
 		print_setting_fields = []
@@ -214,14 +214,13 @@
 		self.validate_return_against_account()
 
 		if self.doctype in ["Purchase Invoice", "Sales Invoice"]:
-			if invalid_advances := [
-				x for x in self.advances if not x.reference_type or not x.reference_name
-			]:
+			if invalid_advances := [x for x in self.advances if not x.reference_type or not x.reference_name]:
 				frappe.throw(
 					_(
 						"Rows: {0} in {1} section are Invalid. Reference Name should point to a valid Payment Entry or Journal Entry."
 					).format(
-						frappe.bold(comma_and([x.idx for x in invalid_advances])), frappe.bold(_("Advance Payments"))
+						frappe.bold(comma_and([x.idx for x in invalid_advances])),
+						frappe.bold(_("Advance Payments")),
 					)
 				)
 
@@ -387,9 +386,7 @@
 			frappe.delete_doc("Batch", row.name)
 
 	def validate_return_against_account(self):
-		if (
-			self.doctype in ["Sales Invoice", "Purchase Invoice"] and self.is_return and self.return_against
-		):
+		if self.doctype in ["Sales Invoice", "Purchase Invoice"] and self.is_return and self.return_against:
 			cr_dr_account_field = "debit_to" if self.doctype == "Sales Invoice" else "credit_to"
 			cr_dr_account_label = "Debit To" if self.doctype == "Sales Invoice" else "Credit To"
 			cr_dr_account = self.get(cr_dr_account_field)
@@ -422,11 +419,7 @@
 						item.set(field_map.get(self.doctype), default_deferred_account)
 
 	def validate_auto_repeat_subscription_dates(self):
-		if (
-			self.get("from_date")
-			and self.get("to_date")
-			and getdate(self.from_date) > getdate(self.to_date)
-		):
+		if self.get("from_date") and self.get("to_date") and getdate(self.from_date) > getdate(self.to_date):
 			frappe.throw(_("To Date cannot be before From Date"), title=_("Invalid Auto Repeat Date"))
 
 	def validate_deferred_start_and_end_date(self):
@@ -434,11 +427,15 @@
 			if d.get("enable_deferred_revenue") or d.get("enable_deferred_expense"):
 				if not (d.service_start_date and d.service_end_date):
 					frappe.throw(
-						_("Row #{0}: Service Start and End Date is required for deferred accounting").format(d.idx)
+						_("Row #{0}: Service Start and End Date is required for deferred accounting").format(
+							d.idx
+						)
 					)
 				elif getdate(d.service_start_date) > getdate(d.service_end_date):
 					frappe.throw(
-						_("Row #{0}: Service Start Date cannot be greater than Service End Date").format(d.idx)
+						_("Row #{0}: Service Start Date cannot be greater than Service End Date").format(
+							d.idx
+						)
 					)
 				elif getdate(self.posting_date) > getdate(d.service_end_date):
 					frappe.throw(
@@ -497,7 +494,9 @@
 				if not self.cash_bank_account:
 					# show message that the amount is not paid
 					frappe.throw(
-						_("Note: Payment Entry will not be created since 'Cash or Bank Account' was not specified")
+						_(
+							"Note: Payment Entry will not be created since 'Cash or Bank Account' was not specified"
+						)
 					)
 
 				if cint(self.is_return) and self.grand_total > self.paid_amount:
@@ -541,7 +540,11 @@
 
 			if date_field and self.get(date_field):
 				validate_fiscal_year(
-					self.get(date_field), self.fiscal_year, self.company, self.meta.get_label(date_field), self
+					self.get(date_field),
+					self.fiscal_year,
+					self.company,
+					self.meta.get_label(date_field),
+					self,
 				)
 
 	def validate_party_accounts(self):
@@ -611,7 +614,9 @@
 
 			if tax_updated:
 				frappe.msgprint(
-					_("Disabled tax included prices since this {} is an internal transfer").format(self.doctype),
+					_("Disabled tax included prices since this {} is an internal transfer").format(
+						self.doctype
+					),
 					alert=1,
 				)
 
@@ -704,7 +709,7 @@
 				parent_dict[fieldname] = self.get(fieldname)
 
 			if self.doctype in ["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"]:
-				document_type = "{} Item".format(self.doctype)
+				document_type = f"{self.doctype} Item"
 				parent_dict.update({"document_type": document_type})
 
 			# party_name field used for customer in quotation
@@ -743,7 +748,9 @@
 							if item.get(fieldname) is None or fieldname in force_item_fields:
 								item.set(fieldname, value)
 
-							elif fieldname in ["cost_center", "conversion_factor"] and not item.get(fieldname):
+							elif fieldname in ["cost_center", "conversion_factor"] and not item.get(
+								fieldname
+							):
 								item.set(fieldname, value)
 
 							elif fieldname == "serial_no":
@@ -779,7 +786,8 @@
 					# Items add via promotional scheme may not have cost center set
 					if hasattr(item, "cost_center") and not item.get("cost_center"):
 						item.set(
-							"cost_center", self.get("cost_center") or erpnext.get_default_cost_center(self.company)
+							"cost_center",
+							self.get("cost_center") or erpnext.get_default_cost_center(self.company),
 						)
 
 					if ret.get("pricing_rules"):
@@ -904,7 +912,7 @@
 			if isinstance(item_tax_rate, str):
 				item_tax_rate = parse_json(item_tax_rate)
 
-			for account_head, rate in item_tax_rate.items():
+			for account_head, _rate in item_tax_rate.items():
 				row = self.get_tax_row(account_head)
 
 				if not row:
@@ -932,9 +940,7 @@
 		if self.taxes_and_charges and frappe.get_cached_value(
 			taxes_and_charges_doctype, self.taxes_and_charges, "disabled"
 		):
-			frappe.throw(
-				_("{0} '{1}' is disabled").format(taxes_and_charges_doctype, self.taxes_and_charges)
-			)
+			frappe.throw(_("{0} '{1}' is disabled").format(taxes_and_charges_doctype, self.taxes_and_charges))
 
 	def validate_tax_account_company(self):
 		for d in self.get("taxes"):
@@ -1108,9 +1114,8 @@
 		self.set(parentfield, self.get(parentfield, {"allocated_amount": ["not in", [0, None, ""]]}))
 
 		frappe.db.sql(
-			"""delete from `tab%s` where parentfield=%s and parent = %s
-			and allocated_amount = 0"""
-			% (childtype, "%s", "%s"),
+			"""delete from `tab{}` where parentfield={} and parent = {}
+			and allocated_amount = 0""".format(childtype, "%s", "%s"),
 			(parentfield, self.name),
 		)
 
@@ -1206,9 +1211,7 @@
 		return res
 
 	def is_inclusive_tax(self):
-		is_inclusive = cint(
-			frappe.db.get_single_value("Accounts Settings", "show_inclusive_tax_in_print")
-		)
+		is_inclusive = cint(frappe.db.get_single_value("Accounts Settings", "show_inclusive_tax_in_print"))
 
 		if is_inclusive:
 			is_inclusive = 0
@@ -1251,7 +1254,6 @@
 		for d in self.get("advances"):
 			advance_exchange_rate = d.ref_exchange_rate
 			if d.allocated_amount and self.conversion_rate != advance_exchange_rate:
-
 				base_allocated_amount_in_ref_rate = advance_exchange_rate * d.allocated_amount
 				base_allocated_amount_in_inv_rate = self.conversion_rate * d.allocated_amount
 				difference = base_allocated_amount_in_ref_rate - base_allocated_amount_in_inv_rate
@@ -1324,7 +1326,7 @@
 		return False
 
 	def make_exchange_gain_loss_journal(
-		self, args: dict = None, dimensions_dict: dict = None
+		self, args: dict | None = None, dimensions_dict: dict | None = None
 	) -> None:
 		"""
 		Make Exchange Gain/Loss journal for Invoices and Payments
@@ -1344,7 +1346,6 @@
 							flt(arg.get("difference_amount", 0), precision) != 0
 							or flt(arg.get("exchange_gain_loss", 0), precision) != 0
 						) and arg.get("difference_account"):
-
 							party_account = arg.get("account")
 							gain_loss_account = arg.get("difference_account")
 							difference_amount = arg.get("difference_amount") or arg.get("exchange_gain_loss")
@@ -1395,8 +1396,8 @@
 				gain_loss_to_book = [x for x in self.references if x.exchange_gain_loss != 0]
 				booked = []
 				if gain_loss_to_book:
-					vtypes = [x.reference_doctype for x in gain_loss_to_book]
-					vnames = [x.reference_name for x in gain_loss_to_book]
+					[x.reference_doctype for x in gain_loss_to_book]
+					[x.reference_name for x in gain_loss_to_book]
 					je = qb.DocType("Journal Entry")
 					jea = qb.DocType("Journal Entry Account")
 					parents = (
@@ -1509,7 +1510,9 @@
 						"allocated_amount": flt(d.allocated_amount),
 						"precision": d.precision("advance_amount"),
 						"exchange_rate": (
-							self.conversion_rate if self.party_account_currency != self.company_currency else 1
+							self.conversion_rate
+							if self.party_account_currency != self.company_currency
+							else 1
 						),
 						"grand_total": (
 							self.base_grand_total
@@ -1670,9 +1673,12 @@
 								"account": item.discount_account,
 								"against": self.customer,
 								"debit": flt(
-									discount_amount * self.get("conversion_rate"), item.precision("discount_amount")
+									discount_amount * self.get("conversion_rate"),
+									item.precision("discount_amount"),
 								),
-								"debit_in_account_currency": flt(discount_amount, item.precision("discount_amount")),
+								"debit_in_account_currency": flt(
+									discount_amount, item.precision("discount_amount")
+								),
 								"cost_center": item.cost_center,
 								"project": item.project,
 							},
@@ -1688,9 +1694,12 @@
 								"account": income_account,
 								"against": self.customer,
 								"credit": flt(
-									discount_amount * self.get("conversion_rate"), item.precision("discount_amount")
+									discount_amount * self.get("conversion_rate"),
+									item.precision("discount_amount"),
 								),
-								"credit_in_account_currency": flt(discount_amount, item.precision("discount_amount")),
+								"credit_in_account_currency": flt(
+									discount_amount, item.precision("discount_amount")
+								),
 								"cost_center": item.cost_center,
 								"project": item.project or self.project,
 							},
@@ -1730,9 +1739,7 @@
 		total_overbilled_amt = 0.0
 
 		reference_names = [d.get(item_ref_dn) for d in self.get("items") if d.get(item_ref_dn)]
-		reference_details = self.get_billing_reference_details(
-			reference_names, ref_dt + " Item", based_on
-		)
+		reference_details = self.get_billing_reference_details(reference_names, ref_dt + " Item", based_on)
 
 		for item in self.get("items"):
 			if not item.get(item_ref_dn):
@@ -1919,9 +1926,7 @@
 
 		self.set_advance_payment_status(advance_paid, order_total)
 
-	def set_advance_payment_status(
-		self, advance_paid: float | None = None, order_total: float | None = None
-	):
+	def set_advance_payment_status(self, advance_paid: float | None = None, order_total: float | None = None):
 		new_status = None
 		# if money is paid set the paid states
 		if advance_paid:
@@ -1957,17 +1962,13 @@
 
 	def raise_missing_debit_credit_account_error(self, party_type, party):
 		"""Raise an error if debit to/credit to account does not exist."""
-		db_or_cr = (
-			frappe.bold("Debit To") if self.doctype == "Sales Invoice" else frappe.bold("Credit To")
-		)
+		db_or_cr = frappe.bold("Debit To") if self.doctype == "Sales Invoice" else frappe.bold("Credit To")
 		rec_or_pay = "Receivable" if self.doctype == "Sales Invoice" else "Payable"
 
 		link_to_party = frappe.utils.get_link_to_form(party_type, party)
 		link_to_company = frappe.utils.get_link_to_form("Company", self.company)
 
-		message = _("{0} Account not found against Customer {1}.").format(
-			db_or_cr, frappe.bold(party) or ""
-		)
+		message = _("{0} Account not found against Customer {1}.").format(db_or_cr, frappe.bold(party) or "")
 		message += "<br>" + _("Please set one of the following:") + "<br>"
 		message += (
 			"<br><ul><li>"
@@ -2020,7 +2021,6 @@
 					and party_account_currency != self.company_currency
 					and self.currency != party_account_currency
 				):
-
 					frappe.throw(
 						_("Accounting Entry for {0}: {1} can only be made in currency: {2}").format(
 							party_type, party, party_account_currency
@@ -2041,9 +2041,7 @@
 
 		party_type, party = self.get_party()
 		party_gle_currency = get_party_gle_currency(party_type, party, self.company)
-		party_account = (
-			self.get("debit_to") if self.doctype == "Sales Invoice" else self.get("credit_to")
-		)
+		party_account = self.get("debit_to") if self.doctype == "Sales Invoice" else self.get("credit_to")
 		party_account_currency = get_account_currency(party_account)
 		allow_multi_currency_invoices_against_single_party_account = frappe.db.get_singles_value(
 			"Accounts Settings", "allow_multi_currency_invoices_against_single_party_account"
@@ -2066,10 +2064,8 @@
 			consider_for_total_advance = True
 			if adv.reference_name == linked_doc_name:
 				frappe.db.sql(
-					"""delete from `tab{0} Advance`
-					where name = %s""".format(
-						self.doctype
-					),
+					f"""delete from `tab{self.doctype} Advance`
+					where name = %s""",
 					adv.name,
 				)
 				consider_for_total_advance = False
@@ -2281,7 +2277,9 @@
 		for d in self.get("payment_schedule"):
 			if self.doctype == "Sales Order" and getdate(d.due_date) < getdate(self.transaction_date):
 				frappe.throw(
-					_("Row {0}: Due Date in the Payment Terms table cannot be before Posting Date").format(d.idx)
+					_("Row {0}: Due Date in the Payment Terms table cannot be before Posting Date").format(
+						d.idx
+					)
 				)
 			elif d.due_date in dates:
 				li.append(_("{0} in row {1}").format(d.due_date, d.idx))
@@ -2289,9 +2287,7 @@
 
 		if li:
 			duplicates = "<br>" + "<br>".join(li)
-			frappe.throw(
-				_("Rows with duplicate due dates in other rows were found: {0}").format(duplicates)
-			)
+			frappe.throw(_("Rows with duplicate due dates in other rows were found: {0}").format(duplicates))
 
 	def validate_payment_schedule_amount(self):
 		if (self.doctype == "Sales Invoice" and self.is_pos) or self.get("is_opening") == "Yes":
@@ -2414,7 +2410,7 @@
 		jv.voucher_type = "Journal Entry"
 		jv.posting_date = self.posting_date
 		jv.company = self.company
-		jv.remark = "Adjustment for {} {}".format(self.doctype, self.name)
+		jv.remark = f"Adjustment for {self.doctype} {self.name}"
 
 		reconcilation_entry = frappe._dict()
 		advance_entry = frappe._dict()
@@ -2424,9 +2420,7 @@
 		reconcilation_entry.party = secondary_party
 		reconcilation_entry.reference_type = self.doctype
 		reconcilation_entry.reference_name = self.name
-		reconcilation_entry.cost_center = self.cost_center or erpnext.get_default_cost_center(
-			self.company
-		)
+		reconcilation_entry.cost_center = self.cost_center or erpnext.get_default_cost_center(self.company)
 
 		advance_entry.account = primary_account
 		advance_entry.party_type = primary_party_type
@@ -2472,7 +2466,7 @@
 	def check_if_fields_updated(self, fields_to_check, child_tables):
 		# Check if any field affecting accounting entry is altered
 		doc_before_update = self.get_doc_before_save()
-		accounting_dimensions = get_accounting_dimensions() + ["cost_center", "project"]
+		accounting_dimensions = [*get_accounting_dimensions(), "cost_center", "project"]
 
 		# Parent Level Accounts excluding party account
 		fields_to_check += accounting_dimensions
@@ -2505,9 +2499,7 @@
 
 @frappe.whitelist()
 def get_tax_rate(account_head):
-	return frappe.get_cached_value(
-		"Account", account_head, ["tax_rate", "account_name"], as_dict=True
-	)
+	return frappe.get_cached_value("Account", account_head, ["tax_rate", "account_name"], as_dict=True)
 
 
 @frappe.whitelist()
@@ -2537,7 +2529,7 @@
 	tax_master = frappe.get_doc(master_doctype, master_name)
 
 	taxes_and_charges = []
-	for i, tax in enumerate(tax_master.get("taxes")):
+	for _i, tax in enumerate(tax_master.get("taxes")):
 		tax = tax.as_dict()
 
 		for fieldname in default_fields + child_table_fields:
@@ -2656,9 +2648,7 @@
 ):
 	if (not conversion_rate) and (account_currency != company_currency):
 		frappe.throw(
-			_("Account: {0} with currency: {1} can not be selected").format(
-				gl_dict.account, account_currency
-			)
+			_("Account: {0} with currency: {1} can not be selected").format(gl_dict.account, account_currency)
 		)
 
 	gl_dict["account_currency"] = (
@@ -2668,9 +2658,7 @@
 	# set debit/credit in account currency if not provided
 	if flt(gl_dict.debit) and not flt(gl_dict.debit_in_account_currency):
 		gl_dict.debit_in_account_currency = (
-			gl_dict.debit
-			if account_currency == company_currency
-			else flt(gl_dict.debit / conversion_rate, 2)
+			gl_dict.debit if account_currency == company_currency else flt(gl_dict.debit / conversion_rate, 2)
 		)
 
 	if flt(gl_dict.credit) and not flt(gl_dict.credit_in_account_currency):
@@ -2755,7 +2743,6 @@
 	limit=None,
 	condition=None,
 ):
-
 	payment_entries = []
 	payment_entry = frappe.qb.DocType("Payment Entry")
 
@@ -2851,7 +2838,7 @@
 		if condition.get("to_payment_date"):
 			common_filter_conditions.append(payment_entry.posting_date.lte(condition["to_payment_date"]))
 
-		if condition.get("get_payments") == True:
+		if condition.get("get_payments") is True:
 			if condition.get("cost_center"):
 				common_filter_conditions.append(payment_entry.cost_center == condition["cost_center"])
 
@@ -2943,9 +2930,7 @@
 
 	schedule = []
 	for d in terms_doc.get("terms"):
-		term_details = get_payment_term_details(
-			d, posting_date, grand_total, base_grand_total, bill_date
-		)
+		term_details = get_payment_term_details(d, posting_date, grand_total, base_grand_total, bill_date)
 		schedule.append(term_details)
 
 	return schedule
@@ -3063,9 +3048,7 @@
 					tax_row.db_insert()
 
 
-def set_order_defaults(
-	parent_doctype, parent_doctype_name, child_doctype, child_docname, trans_item
-):
+def set_order_defaults(parent_doctype, parent_doctype_name, child_doctype, child_docname, trans_item):
 	"""
 	Returns a Sales/Purchase Order Item child item containing the default values
 	"""
@@ -3081,9 +3064,7 @@
 	child_item.stock_uom = item.stock_uom
 	child_item.uom = trans_item.get("uom") or item.stock_uom
 	child_item.warehouse = get_item_warehouse(item, p_doc, overwrite_warehouse=True)
-	conversion_factor = flt(
-		get_conversion_factor(item.item_code, child_item.uom).get("conversion_factor")
-	)
+	conversion_factor = flt(get_conversion_factor(item.item_code, child_item.uom).get("conversion_factor"))
 	child_item.conversion_factor = flt(trans_item.get("conversion_factor")) or conversion_factor
 
 	if child_doctype == "Purchase Order Item":
@@ -3230,9 +3211,7 @@
 
 	def get_new_child_item(item_row):
 		child_doctype = "Sales Order Item" if parent_doctype == "Sales Order" else "Purchase Order Item"
-		return set_order_defaults(
-			parent_doctype, parent_doctype_name, child_doctype, child_docname, item_row
-		)
+		return set_order_defaults(parent_doctype, parent_doctype_name, child_doctype, child_docname, item_row)
 
 	def validate_quantity(child_item, new_data):
 		if not flt(new_data.get("qty")):
@@ -3246,9 +3225,7 @@
 		if parent_doctype == "Sales Order" and flt(new_data.get("qty")) < flt(child_item.delivered_qty):
 			frappe.throw(_("Cannot set quantity less than delivered quantity"))
 
-		if parent_doctype == "Purchase Order" and flt(new_data.get("qty")) < flt(
-			child_item.received_qty
-		):
+		if parent_doctype == "Purchase Order" and flt(new_data.get("qty")) < flt(child_item.received_qty):
 			frappe.throw(_("Cannot set quantity less than received quantity"))
 
 	def should_update_supplied_items(doc) -> bool:
@@ -3263,9 +3240,7 @@
 			item.supplied_qty or item.consumed_qty or item.returned_qty for item in doc.supplied_items
 		)
 
-		update_supplied_items = (
-			any_qty_changed or items_added_or_removed or any_conversion_factor_changed
-		)
+		update_supplied_items = any_qty_changed or items_added_or_removed or any_conversion_factor_changed
 		if update_supplied_items and supplied_items_processed:
 			frappe.throw(_("Item qty can not be updated as raw materials are already processed."))
 
@@ -3275,7 +3250,9 @@
 		if is_new:
 			if not new_data.get("fg_item"):
 				frappe.throw(
-					_("Finished Good Item is not specified for service item {0}").format(new_data["item_code"])
+					_("Finished Good Item is not specified for service item {0}").format(
+						new_data["item_code"]
+					)
 				)
 			else:
 				is_sub_contracted_item, default_bom = frappe.db.get_value(
@@ -3324,8 +3301,9 @@
 			prev_rate, new_rate = flt(child_item.get("rate")), flt(d.get("rate"))
 			prev_qty, new_qty = flt(child_item.get("qty")), flt(d.get("qty"))
 			prev_fg_qty, new_fg_qty = flt(child_item.get("fg_item_qty")), flt(d.get("fg_item_qty"))
-			prev_con_fac, new_con_fac = flt(child_item.get("conversion_factor")), flt(
-				d.get("conversion_factor")
+			prev_con_fac, new_con_fac = (
+				flt(child_item.get("conversion_factor")),
+				flt(d.get("conversion_factor")),
 			)
 			prev_uom, new_uom = child_item.get("uom"), d.get("uom")
 
@@ -3417,7 +3395,8 @@
 				if parent_doctype in sales_doctypes:
 					child_item.margin_type = "Amount"
 					child_item.margin_rate_or_amount = flt(
-						child_item.rate - child_item.price_list_rate, child_item.precision("margin_rate_or_amount")
+						child_item.rate - child_item.price_list_rate,
+						child_item.precision("margin_rate_or_amount"),
 					)
 					child_item.rate_with_margin = child_item.rate
 			else:
@@ -3519,9 +3498,7 @@
 				parent.create_stock_reservation_entries()
 
 
-def check_if_child_table_updated(
-	child_table_before_update, child_table_after_update, fields_to_check
-):
+def check_if_child_table_updated(child_table_before_update, child_table_after_update, fields_to_check):
 	fields_to_check = list(fields_to_check) + get_accounting_dimensions() + ["cost_center", "project"]
 
 	# Check if any field affecting accounting entry is altered
diff --git a/erpnext/controllers/buying_controller.py b/erpnext/controllers/buying_controller.py
index c530727..58bcc8c 100644
--- a/erpnext/controllers/buying_controller.py
+++ b/erpnext/controllers/buying_controller.py
@@ -28,7 +28,7 @@
 	def validate(self):
 		self.set_rate_for_standalone_debit_note()
 
-		super(BuyingController, self).validate()
+		super().validate()
 		if getattr(self, "supplier", None) and not self.supplier_name:
 			self.supplier_name = frappe.db.get_value("Supplier", self.supplier, "supplier_name")
 
@@ -45,9 +45,7 @@
 		if self.doctype == "Purchase Invoice":
 			self.validate_purchase_receipt_if_update_stock()
 
-		if self.doctype == "Purchase Receipt" or (
-			self.doctype == "Purchase Invoice" and self.update_stock
-		):
+		if self.doctype == "Purchase Receipt" or (self.doctype == "Purchase Invoice" and self.update_stock):
 			# self.validate_purchase_return()
 			self.validate_rejected_warehouse()
 			self.validate_accepted_rejected_qty()
@@ -64,12 +62,10 @@
 			self.set_serial_and_batch_bundle()
 
 	def onload(self):
-		super(BuyingController, self).onload()
+		super().onload()
 		self.set_onload(
 			"backflush_based_on",
-			frappe.db.get_single_value(
-				"Buying Settings", "backflush_raw_materials_of_subcontract_based_on"
-			),
+			frappe.db.get_single_value("Buying Settings", "backflush_raw_materials_of_subcontract_based_on"),
 		)
 
 	def create_package_for_transfer(self) -> None:
@@ -128,7 +124,7 @@
 					row.margin_rate_or_amount = 0.0
 
 	def set_missing_values(self, for_validate=False):
-		super(BuyingController, self).set_missing_values(for_validate)
+		super().set_missing_values(for_validate)
 
 		self.set_supplier_from_item_default()
 		self.set_price_list_currency("Buying")
@@ -188,9 +184,7 @@
 		if self.doctype not in ["Purchase Receipt", "Purchase Invoice"] or not self.is_return:
 			return
 
-		purchase_doc_field = (
-			"purchase_receipt" if self.doctype == "Purchase Receipt" else "purchase_invoice"
-		)
+		purchase_doc_field = "purchase_receipt" if self.doctype == "Purchase Receipt" else "purchase_invoice"
 		not_cancelled_asset = []
 		if self.return_against:
 			not_cancelled_asset = [
@@ -508,7 +502,6 @@
 				pr_qty = flt(flt(d.qty) * flt(d.conversion_factor), d.precision("stock_qty"))
 
 				if pr_qty:
-
 					if d.from_warehouse and (
 						(not cint(self.is_return) and self.docstatus == 1)
 						or (cint(self.is_return) and self.docstatus == 2)
@@ -546,7 +539,9 @@
 							"serial_and_batch_bundle": (
 								d.serial_and_batch_bundle
 								if not self.is_internal_transfer() or self.is_return
-								else self.get_package_for_target_warehouse(d, type_of_transaction=type_of_transaction)
+								else self.get_package_for_target_warehouse(
+									d, type_of_transaction=type_of_transaction
+								)
 							),
 						},
 					)
@@ -604,7 +599,9 @@
 						d,
 						{
 							"warehouse": d.rejected_warehouse,
-							"actual_qty": flt(flt(d.rejected_qty) * flt(d.conversion_factor), d.precision("stock_qty")),
+							"actual_qty": flt(
+								flt(d.rejected_qty) * flt(d.conversion_factor), d.precision("stock_qty")
+							),
 							"incoming_rate": 0.0,
 							"serial_and_batch_bundle": d.rejected_serial_and_batch_bundle,
 						},
@@ -670,7 +667,7 @@
 			update_last_purchase_rate(self, is_submit=1)
 
 	def on_cancel(self):
-		super(BuyingController, self).on_cancel()
+		super().on_cancel()
 
 		if self.get("is_return"):
 			return
@@ -695,7 +692,9 @@
 						"doctype": self.doctype,
 						"company": self.company,
 						"posting_date": (
-							self.schedule_date if self.doctype == "Material Request" else self.transaction_date
+							self.schedule_date
+							if self.doctype == "Material Request"
+							else self.transaction_date
 						),
 					}
 				)
@@ -727,17 +726,21 @@
 							asset = self.make_asset(d, is_grouped_asset=True)
 							created_assets.append(asset)
 						else:
-							for qty in range(cint(d.qty)):
+							for _qty in range(cint(d.qty)):
 								asset = self.make_asset(d)
 								created_assets.append(asset)
 
 						if len(created_assets) > 5:
 							# dont show asset form links if more than 5 assets are created
 							messages.append(
-								_("{} Assets created for {}").format(len(created_assets), frappe.bold(d.item_code))
+								_("{} Assets created for {}").format(
+									len(created_assets), frappe.bold(d.item_code)
+								)
 							)
 						else:
-							assets_link = list(map(lambda d: frappe.utils.get_link_to_form("Asset", d), created_assets))
+							assets_link = list(
+								map(lambda d: frappe.utils.get_link_to_form("Asset", d), created_assets)
+							)
 							assets_link = frappe.bold(",".join(assets_link))
 
 							is_plural = "s" if len(created_assets) != 1 else ""
@@ -748,9 +751,9 @@
 							)
 					else:
 						frappe.throw(
-							_("Row {}: Asset Naming Series is mandatory for the auto creation for item {}").format(
-								d.idx, frappe.bold(d.item_code)
-							)
+							_(
+								"Row {}: Asset Naming Series is mandatory for the auto creation for item {}"
+							).format(d.idx, frappe.bold(d.item_code))
 						)
 				else:
 					messages.append(
@@ -912,11 +915,9 @@
 	invalid_items = [
 		d[0]
 		for d in frappe.db.sql(
-			"""
-		select item_code from tabItem where name in ({0}) and {1}=0
-		""".format(
-				item_list, fieldname
-			),
+			f"""
+		select item_code from tabItem where name in ({item_list}) and {fieldname}=0
+		""",
 			as_list=True,
 		)
 	]
diff --git a/erpnext/controllers/item_variant.py b/erpnext/controllers/item_variant.py
index 1eee9ea..7a1db6d 100644
--- a/erpnext/controllers/item_variant.py
+++ b/erpnext/controllers/item_variant.py
@@ -64,9 +64,7 @@
 	variant.flags.ignore_mandatory = True
 	variant.save()
 
-	if not frappe.db.exists(
-		"Item Manufacturer", {"item_code": variant.name, "manufacturer": manufacturer}
-	):
+	if not frappe.db.exists("Item Manufacturer", {"item_code": variant.name, "manufacturer": manufacturer}):
 		manufacturer_doc = frappe.new_doc("Item Manufacturer")
 		manufacturer_doc.update(
 			{
@@ -130,9 +128,7 @@
 		)
 
 
-def validate_item_attribute_value(
-	attributes_list, attribute, attribute_value, item, from_variant=True
-):
+def validate_item_attribute_value(attributes_list, attribute, attribute_value, item, from_variant=True):
 	allow_rename_attribute_value = frappe.db.get_single_value(
 		"Item Variant Settings", "allow_rename_attribute_value"
 	)
@@ -179,9 +175,7 @@
 
 
 def find_variant(template, args, variant_item_code=None):
-	possible_variants = [
-		i for i in get_item_codes_by_attributes(args, template) if i != variant_item_code
-	]
+	possible_variants = [i for i in get_item_codes_by_attributes(args, template) if i != variant_item_code]
 
 	for variant in possible_variants:
 		variant = frappe.get_doc("Item", variant)
@@ -357,7 +351,9 @@
 			if variant.attributes:
 				attributes_description = item.description + " "
 				for d in variant.attributes:
-					attributes_description += "<div>" + d.attribute + ": " + cstr(d.attribute_value) + "</div>"
+					attributes_description += (
+						"<div>" + d.attribute + ": " + cstr(d.attribute_value) + "</div>"
+					)
 
 				if attributes_description not in variant.description:
 					variant.description = attributes_description
@@ -391,8 +387,8 @@
 		abbreviations.append(abbr_or_value)
 
 	if abbreviations:
-		variant.item_code = "{0}-{1}".format(template_item_code, "-".join(abbreviations))
-		variant.item_name = "{0}-{1}".format(template_item_name, "-".join(abbreviations))
+		variant.item_code = "{}-{}".format(template_item_code, "-".join(abbreviations))
+		variant.item_name = "{}-{}".format(template_item_name, "-".join(abbreviations))
 
 
 @frappe.whitelist()
diff --git a/erpnext/controllers/print_settings.py b/erpnext/controllers/print_settings.py
index 59f13c6..f997116 100644
--- a/erpnext/controllers/print_settings.py
+++ b/erpnext/controllers/print_settings.py
@@ -40,7 +40,7 @@
 
 
 def format_columns(display_columns, compact_fields):
-	compact_fields = compact_fields + ["image", "item_code", "item_name"]
+	compact_fields = [*compact_fields, "image", "item_code", "item_name"]
 	final_columns = []
 	for column in display_columns:
 		if column not in compact_fields:
diff --git a/erpnext/controllers/queries.py b/erpnext/controllers/queries.py
index 960ebb7..4764629 100644
--- a/erpnext/controllers/queries.py
+++ b/erpnext/controllers/queries.py
@@ -98,7 +98,7 @@
 			account_type_condition = "AND account_type in %(account_types)s"
 
 		accounts = frappe.db.sql(
-			"""
+			f"""
 			SELECT name, parent_account
 			FROM `tabAccount`
 			WHERE `tabAccount`.docstatus!=2
@@ -108,20 +108,16 @@
 				AND disabled = %(disabled)s
 				AND (account_currency = %(currency)s or ifnull(account_currency, '') = '')
 				AND `{searchfield}` LIKE %(txt)s
-				{mcond}
+				{get_match_cond(doctype)}
 			ORDER BY idx DESC, name
 			LIMIT %(limit)s offset %(offset)s
-		""".format(
-				account_type_condition=account_type_condition,
-				searchfield=searchfield,
-				mcond=get_match_cond(doctype),
-			),
+		""",
 			dict(
 				account_types=filters.get("account_type"),
 				company=filters.get("company"),
 				disabled=filters.get("disabled", 0),
 				currency=company_currency,
-				txt="%{}%".format(txt),
+				txt=f"%{txt}%",
 				offset=start,
 				limit=page_len,
 			),
@@ -176,7 +172,9 @@
 		if filters.get("customer") or filters.get("supplier"):
 			party = filters.get("customer") or filters.get("supplier")
 			item_rules_list = frappe.get_all(
-				"Party Specific Item", filters={"party": party}, fields=["restrict_based_on", "based_on_value"]
+				"Party Specific Item",
+				filters={"party": party},
+				fields=["restrict_based_on", "based_on_value"],
 			)
 
 			filters_dict = {}
@@ -325,11 +323,11 @@
 
 	return frappe.db.sql(
 		"""
-		select %(fields)s
+		select {fields}
 		from `tabDelivery Note`
-		where `tabDelivery Note`.`%(key)s` like %(txt)s and
+		where `tabDelivery Note`.`{key}` like {txt} and
 			`tabDelivery Note`.docstatus = 1
-			and status not in ('Stopped', 'Closed') %(fcond)s
+			and status not in ('Stopped', 'Closed') {fcond}
 			and (
 				(`tabDelivery Note`.is_return = 0 and `tabDelivery Note`.per_billed < 100)
 				or (`tabDelivery Note`.grand_total = 0 and `tabDelivery Note`.per_billed < 100)
@@ -338,17 +336,16 @@
 					and return_against in (select name from `tabDelivery Note` where per_billed < 100)
 				)
 			)
-			%(mcond)s order by `tabDelivery Note`.`%(key)s` asc limit %(page_len)s offset %(start)s
-	"""
-		% {
-			"fields": ", ".join(["`tabDelivery Note`.{0}".format(f) for f in fields]),
-			"key": searchfield,
-			"fcond": get_filters_cond(doctype, filters, []),
-			"mcond": get_match_cond(doctype),
-			"start": start,
-			"page_len": page_len,
-			"txt": "%(txt)s",
-		},
+			{mcond} order by `tabDelivery Note`.`{key}` asc limit {page_len} offset {start}
+	""".format(
+			fields=", ".join([f"`tabDelivery Note`.{f}" for f in fields]),
+			key=searchfield,
+			fcond=get_filters_cond(doctype, filters, []),
+			mcond=get_match_cond(doctype),
+			start=start,
+			page_len=page_len,
+			txt="%(txt)s",
+		),
 		{"txt": ("%%%s%%" % txt)},
 		as_dict=as_dict,
 	)
@@ -362,9 +359,7 @@
 	searchfields = meta.get_search_fields()
 
 	batches = get_batches_from_stock_ledger_entries(searchfields, txt, filters, start, page_len)
-	batches.extend(
-		get_batches_from_serial_and_batch_bundle(searchfields, txt, filters, start, page_len)
-	)
+	batches.extend(get_batches_from_serial_and_batch_bundle(searchfields, txt, filters, start, page_len))
 
 	filtered_batches = get_filterd_batches(batches)
 
@@ -377,7 +372,7 @@
 def get_empty_batches(filters, start, page_len, filtered_batches=None, txt=None):
 	query_filter = {"item": filters.get("item_code")}
 	if txt:
-		query_filter["name"] = ("like", "%{0}%".format(txt))
+		query_filter["name"] = ("like", f"%{txt}%")
 
 	exclude_batches = [batch[0] for batch in filtered_batches] if filtered_batches else []
 	if exclude_batches:
@@ -403,7 +398,7 @@
 			batches[batch_data[0]][1] += batch_data[1]
 
 	filterd_batch = []
-	for batch, batch_data in batches.items():
+	for _batch, batch_data in batches.items():
 		if batch_data[1] > 0:
 			filterd_batch.append(tuple(batch_data))
 
@@ -424,7 +419,7 @@
 			stock_ledger_entry.batch_no,
 			Sum(stock_ledger_entry.actual_qty).as_("qty"),
 		)
-		.where(((batch_table.expiry_date >= expiry_date) | (batch_table.expiry_date.isnull())))
+		.where((batch_table.expiry_date >= expiry_date) | (batch_table.expiry_date.isnull()))
 		.where(stock_ledger_entry.is_cancelled == 0)
 		.where(
 			(stock_ledger_entry.item_code == filters.get("item_code"))
@@ -448,9 +443,9 @@
 		query = query.select(batch_table[field])
 
 	if txt:
-		txt_condition = batch_table.name.like("%{0}%".format(txt))
-		for field in searchfields + ["name"]:
-			txt_condition |= batch_table[field].like("%{0}%".format(txt))
+		txt_condition = batch_table.name.like(f"%{txt}%")
+		for field in [*searchfields, "name"]:
+			txt_condition |= batch_table[field].like(f"%{txt}%")
 
 		query = query.where(txt_condition)
 
@@ -474,7 +469,7 @@
 			bundle.batch_no,
 			Sum(bundle.qty).as_("qty"),
 		)
-		.where(((batch_table.expiry_date >= expiry_date) | (batch_table.expiry_date.isnull())))
+		.where((batch_table.expiry_date >= expiry_date) | (batch_table.expiry_date.isnull()))
 		.where(stock_ledger_entry.is_cancelled == 0)
 		.where(
 			(stock_ledger_entry.item_code == filters.get("item_code"))
@@ -498,9 +493,9 @@
 		bundle_query = bundle_query.select(batch_table[field])
 
 	if txt:
-		txt_condition = batch_table.name.like("%{0}%".format(txt))
-		for field in searchfields + ["name"]:
-			txt_condition |= batch_table[field].like("%{0}%".format(txt))
+		txt_condition = batch_table.name.like(f"%{txt}%")
+		for field in [*searchfields, "name"]:
+			txt_condition |= batch_table[field].like(f"%{txt}%")
 
 		bundle_query = bundle_query.where(txt_condition)
 
@@ -515,7 +510,7 @@
 
 	if isinstance(filters, dict):
 		for key, val in filters.items():
-			if isinstance(val, (list, tuple)):
+			if isinstance(val, list | tuple):
 				filter_list.append([doctype, key, val[0], val[1]])
 			else:
 				filter_list.append([doctype, key, "=", val])
@@ -576,24 +571,20 @@
 	condition += f"and tabAccount.disabled = {filters.get('disabled', 0)}"
 
 	return frappe.db.sql(
-		"""select tabAccount.name from `tabAccount`
+		f"""select tabAccount.name from `tabAccount`
 			where (tabAccount.report_type = "Profit and Loss"
 					or tabAccount.account_type in ("Income Account", "Temporary"))
 				and tabAccount.is_group=0
-				and tabAccount.`{key}` LIKE %(txt)s
-				{condition} {match_condition}
-			order by idx desc, name""".format(
-			condition=condition, match_condition=get_match_cond(doctype), key=searchfield
-		),
+				and tabAccount.`{searchfield}` LIKE %(txt)s
+				{condition} {get_match_cond(doctype)}
+			order by idx desc, name""",
 		{"txt": "%" + txt + "%", "company": filters.get("company", "")},
 	)
 
 
 @frappe.whitelist()
 @frappe.validate_and_sanitize_search_inputs
-def get_filtered_dimensions(
-	doctype, txt, searchfield, start, page_len, filters, reference_doctype=None
-):
+def get_filtered_dimensions(doctype, txt, searchfield, start, page_len, filters, reference_doctype=None):
 	from erpnext.accounts.doctype.accounting_dimension_filter.accounting_dimension_filter import (
 		get_dimension_filter_map,
 	)
@@ -659,15 +650,13 @@
 		condition += "and tabAccount.company = %(company)s"
 
 	return frappe.db.sql(
-		"""select tabAccount.name from `tabAccount`
+		f"""select tabAccount.name from `tabAccount`
 		where (tabAccount.report_type = "Profit and Loss"
 				or tabAccount.account_type in ("Expense Account", "Fixed Asset", "Temporary", "Asset Received But Not Billed", "Capital Work in Progress"))
 			and tabAccount.is_group=0
 			and tabAccount.docstatus!=2
-			and tabAccount.{key} LIKE %(txt)s
-			{condition} {match_condition}""".format(
-			condition=condition, key=searchfield, match_condition=get_match_cond(doctype)
-		),
+			and tabAccount.{searchfield} LIKE %(txt)s
+			{condition} {get_match_cond(doctype)}""",
 		{"company": filters.get("company", ""), "txt": "%" + txt + "%"},
 	)
 
@@ -706,7 +695,7 @@
 		mcond=get_match_cond(doctype),
 		start=start,
 		page_len=page_len,
-		txt=frappe.db.escape("%{0}%".format(txt)),
+		txt=frappe.db.escape(f"%{txt}%"),
 	)
 
 	return frappe.db.sql(query)
@@ -726,9 +715,7 @@
 	query = """select batch_id from `tabBatch`
 			where disabled = 0
 			and (expiry_date >= CURRENT_DATE or expiry_date IS NULL)
-			and name like {txt}""".format(
-		txt=frappe.db.escape("%{0}%".format(txt))
-	)
+			and name like {txt}""".format(txt=frappe.db.escape(f"%{txt}%"))
 
 	if filters and filters.get("item"):
 		query += " and item = {item}".format(item=frappe.db.escape(filters.get("item")))
@@ -762,9 +749,7 @@
 		select pr.name
 		from `tabPurchase Receipt` pr, `tabPurchase Receipt Item` pritem
 		where pr.docstatus = 1 and pritem.parent = pr.name
-		and pr.name like {txt}""".format(
-		txt=frappe.db.escape("%{0}%".format(txt))
-	)
+		and pr.name like {txt}""".format(txt=frappe.db.escape(f"%{txt}%"))
 
 	if filters and filters.get("item_code"):
 		query += " and pritem.item_code = {item_code}".format(
@@ -781,9 +766,7 @@
 		select pi.name
 		from `tabPurchase Invoice` pi, `tabPurchase Invoice Item` piitem
 		where pi.docstatus = 1 and piitem.parent = pi.name
-		and pi.name like {txt}""".format(
-		txt=frappe.db.escape("%{0}%".format(txt))
-	)
+		and pi.name like {txt}""".format(txt=frappe.db.escape(f"%{txt}%"))
 
 	if filters and filters.get("item_code"):
 		query += " and piitem.item_code = {item_code}".format(
@@ -805,7 +788,6 @@
 @frappe.whitelist()
 @frappe.validate_and_sanitize_search_inputs
 def get_tax_template(doctype, txt, searchfield, start, page_len, filters):
-
 	item_doc = frappe.get_cached_doc("Item", filters.get("item_code"))
 	item_group = filters.get("item_group")
 	company = filters.get("company")
@@ -817,9 +799,7 @@
 		item_group = item_group_doc.parent_item_group
 
 	if not taxes:
-		return frappe.get_all(
-			"Item Tax Template", filters={"disabled": 0, "company": company}, as_list=True
-		)
+		return frappe.get_all("Item Tax Template", filters={"disabled": 0, "company": company}, as_list=True)
 	else:
 		valid_from = filters.get("valid_from")
 		valid_from = valid_from[1] if isinstance(valid_from, list) else valid_from
diff --git a/erpnext/controllers/sales_and_purchase_return.py b/erpnext/controllers/sales_and_purchase_return.py
index 5594816..83f3410 100644
--- a/erpnext/controllers/sales_and_purchase_return.py
+++ b/erpnext/controllers/sales_and_purchase_return.py
@@ -28,9 +28,7 @@
 
 def validate_return_against(doc):
 	if not frappe.db.exists(doc.doctype, doc.return_against):
-		frappe.throw(
-			_("Invalid {0}: {1}").format(doc.meta.get_label("return_against"), doc.return_against)
-		)
+		frappe.throw(_("Invalid {0}: {1}").format(doc.meta.get_label("return_against"), doc.return_against))
 	else:
 		ref_doc = frappe.get_doc(doc.doctype, doc.return_against)
 
@@ -42,8 +40,8 @@
 			and ref_doc.docstatus.is_submitted()
 		):
 			# validate posting date time
-			return_posting_datetime = "%s %s" % (doc.posting_date, doc.get("posting_time") or "00:00:00")
-			ref_posting_datetime = "%s %s" % (
+			return_posting_datetime = "{} {}".format(doc.posting_date, doc.get("posting_time") or "00:00:00")
+			ref_posting_datetime = "{} {}".format(
 				ref_doc.posting_date,
 				ref_doc.get("posting_time") or "00:00:00",
 			)
@@ -81,7 +79,7 @@
 		select_fields += ",rejected_qty, received_qty"
 
 	for d in frappe.db.sql(
-		"""select {0} from `tab{1} Item` where parent = %s""".format(select_fields, doc.doctype),
+		f"""select {select_fields} from `tab{doc.doctype} Item` where parent = %s""",
 		doc.return_against,
 		as_dict=1,
 	):
@@ -229,17 +227,15 @@
 			sum(abs(child.received_qty) * child.conversion_factor) as received_qty"""
 
 	data = frappe.db.sql(
-		"""
-		select {0}
+		f"""
+		select {column}
 		from
-			`tab{1} Item` child, `tab{2}` par
+			`tab{doc.doctype} Item` child, `tab{doc.doctype}` par
 		where
 			child.parent = par.name and par.docstatus = 1
 			and par.is_return = 1 and par.return_against = %s
 		group by item_code
-	""".format(
-			column, doc.doctype, doc.doctype
-		),
+	""",
 		doc.return_against,
 		as_dict=1,
 	)
@@ -272,22 +268,22 @@
 		party_type = "customer"
 
 	fields = [
-		"sum(abs(`tab{0}`.qty)) as qty".format(child_doctype),
+		f"sum(abs(`tab{child_doctype}`.qty)) as qty",
 	]
 
 	if doctype != "Subcontracting Receipt":
 		fields += [
-			"sum(abs(`tab{0}`.stock_qty)) as stock_qty".format(child_doctype),
+			f"sum(abs(`tab{child_doctype}`.stock_qty)) as stock_qty",
 		]
 
 	if doctype in ("Purchase Receipt", "Purchase Invoice", "Subcontracting Receipt"):
 		fields += [
-			"sum(abs(`tab{0}`.rejected_qty)) as rejected_qty".format(child_doctype),
-			"sum(abs(`tab{0}`.received_qty)) as received_qty".format(child_doctype),
+			f"sum(abs(`tab{child_doctype}`.rejected_qty)) as rejected_qty",
+			f"sum(abs(`tab{child_doctype}`.received_qty)) as received_qty",
 		]
 
 		if doctype == "Purchase Receipt":
-			fields += ["sum(abs(`tab{0}`.received_stock_qty)) as received_stock_qty".format(child_doctype)]
+			fields += [f"sum(abs(`tab{child_doctype}`.received_stock_qty)) as received_stock_qty"]
 
 	# Used retrun against and supplier and is_retrun because there is an index added for it
 	data = frappe.get_all(
@@ -305,9 +301,7 @@
 	return data[0]
 
 
-def make_return_doc(
-	doctype: str, source_name: str, target_doc=None, return_against_rejected_qty=False
-):
+def make_return_doc(doctype: str, source_name: str, target_doc=None, return_against_rejected_qty=False):
 	from frappe.model.mapper import get_mapped_doc
 
 	company = frappe.db.get_value("Delivery Note", source_name, "company")
@@ -648,8 +642,7 @@
 					"docstatus": ["=", 1],
 				},
 			},
-			doctype
-			+ " Item": {
+			doctype + " Item": {
 				"doctype": doctype + " Item",
 				"field_map": {"serial_no": "serial_no", "batch_no": "batch_no", "bom": "bom"},
 				"postprocess": update_item,
@@ -747,19 +740,13 @@
 	if reference_voucher_detail_no:
 		filters["voucher_detail_no"] = reference_voucher_detail_no
 
-	if (
-		voucher_type in ["Purchase Receipt", "Purchase Invoice"]
-		and item_row
-		and item_row.get("warehouse")
-	):
+	if voucher_type in ["Purchase Receipt", "Purchase Invoice"] and item_row and item_row.get("warehouse"):
 		filters["warehouse"] = item_row.get("warehouse")
 
 	return filters
 
 
-def get_returned_serial_nos(
-	child_doc, parent_doc, serial_no_field=None, ignore_voucher_detail_no=None
-):
+def get_returned_serial_nos(child_doc, parent_doc, serial_no_field=None, ignore_voucher_detail_no=None):
 	from erpnext.stock.doctype.serial_no.serial_no import (
 		get_serial_nos as get_serial_nos_from_serial_no,
 	)
@@ -809,9 +796,7 @@
 	return serial_nos
 
 
-def get_returned_batches(
-	child_doc, parent_doc, batch_no_field=None, ignore_voucher_detail_no=None
-):
+def get_returned_batches(child_doc, parent_doc, batch_no_field=None, ignore_voucher_detail_no=None):
 	from erpnext.stock.serial_batch_bundle import get_batches_from_bundle
 
 	batches = frappe._dict()
diff --git a/erpnext/controllers/selling_controller.py b/erpnext/controllers/selling_controller.py
index 9d86cb2..89e47b4 100644
--- a/erpnext/controllers/selling_controller.py
+++ b/erpnext/controllers/selling_controller.py
@@ -20,13 +20,13 @@
 		self.flags.ignore_permlevel_for_fields = ["selling_price_list", "price_list_currency"]
 
 	def onload(self):
-		super(SellingController, self).onload()
+		super().onload()
 		if self.doctype in ("Sales Order", "Delivery Note", "Sales Invoice"):
 			for item in self.get("items") + (self.get("packed_items") or []):
 				item.update(get_bin_details(item.item_code, item.warehouse, include_child_warehouses=True))
 
 	def validate(self):
-		super(SellingController, self).validate()
+		super().validate()
 		self.validate_items()
 		if not self.get("is_debit_note"):
 			self.validate_max_discount()
@@ -44,7 +44,7 @@
 				self.set_serial_and_batch_bundle(table_field)
 
 	def set_missing_values(self, for_validate=False):
-		super(SellingController, self).set_missing_values(for_validate)
+		super().set_missing_values(for_validate)
 
 		# set contact and address details for customer, if they are not mentioned
 		self.set_missing_lead_customer_details(for_validate=for_validate)
@@ -290,7 +290,10 @@
 
 			if flt(item.base_net_rate) < flt(last_valuation_rate_in_sales_uom):
 				throw_message(
-					item.idx, item.item_name, last_valuation_rate_in_sales_uom, "valuation rate (Moving Average)"
+					item.idx,
+					item.item_name,
+					last_valuation_rate_in_sales_uom,
+					"valuation rate (Moving Average)",
 				)
 
 	def get_item_list(self):
@@ -419,7 +422,8 @@
 					"Cancelled"
 				]:
 					frappe.throw(
-						_("{0} {1} is cancelled or closed").format(_("Sales Order"), so), frappe.InvalidStatusError
+						_("{0} {1} is cancelled or closed").format(_("Sales Order"), so),
+						frappe.InvalidStatusError,
 					)
 
 				sales_order.update_reserved_qty(so_item_rows)
@@ -623,7 +627,8 @@
 		if self.doctype in ["Sales Order", "Quotation"]:
 			for item in self.items:
 				item.gross_profit = flt(
-					((item.base_rate - flt(item.valuation_rate)) * item.stock_qty), self.precision("amount", item)
+					((item.base_rate - flt(item.valuation_rate)) * item.stock_qty),
+					self.precision("amount", item),
 				)
 
 	def set_customer_address(self):
@@ -700,9 +705,9 @@
 			if d.get("target_warehouse") and d.get("warehouse") == d.get("target_warehouse"):
 				warehouse = frappe.bold(d.get("target_warehouse"))
 				frappe.throw(
-					_("Row {0}: Delivery Warehouse ({1}) and Customer Warehouse ({2}) can not be same").format(
-						d.idx, warehouse, warehouse
-					)
+					_(
+						"Row {0}: Delivery Warehouse ({1}) and Customer Warehouse ({2}) can not be same"
+					).format(d.idx, warehouse, warehouse)
 				)
 
 		if not self.get("is_internal_customer") and any(d.get("target_warehouse") for d in items):
@@ -730,14 +735,10 @@
 	if child.get("use_serial_batch_fields"):
 		return
 
-	if not frappe.db.get_single_value(
-		"Stock Settings", "auto_create_serial_and_batch_bundle_for_outward"
-	):
+	if not frappe.db.get_single_value("Stock Settings", "auto_create_serial_and_batch_bundle_for_outward"):
 		return
 
-	item_details = frappe.db.get_value(
-		"Item", child.item_code, ["has_serial_no", "has_batch_no"], as_dict=1
-	)
+	item_details = frappe.db.get_value("Item", child.item_code, ["has_serial_no", "has_batch_no"], as_dict=1)
 
 	if not item_details.has_serial_no and not item_details.has_batch_no:
 		return
diff --git a/erpnext/controllers/status_updater.py b/erpnext/controllers/status_updater.py
index fcbec22..17f072e 100644
--- a/erpnext/controllers/status_updater.py
+++ b/erpnext/controllers/status_updater.py
@@ -257,9 +257,7 @@
 						"""select item_code, `{target_ref_field}`,
 						`{target_field}`, parenttype, parent from `tab{target_dt}`
 						where `{target_ref_field}` < `{target_field}`
-						and name=%s and docstatus=1""".format(
-							**args
-						),
+						and name=%s and docstatus=1""".format(**args),
 						args["name"],
 						as_dict=1,
 					)
@@ -304,9 +302,7 @@
 		role_allowed_to_over_bill = frappe.db.get_single_value(
 			"Accounts Settings", "role_allowed_to_over_bill"
 		)
-		role = (
-			role_allowed_to_over_deliver_receive if qty_or_amount == "qty" else role_allowed_to_over_bill
-		)
+		role = role_allowed_to_over_deliver_receive if qty_or_amount == "qty" else role_allowed_to_over_bill
 
 		overflow_percent = (
 			(item[args["target_field"]] - item[args["target_ref_field"]]) / item[args["target_ref_field"]]
@@ -417,12 +413,11 @@
 					args["second_source_extra_cond"] = ""
 
 				args["second_source_condition"] = frappe.db.sql(
-					""" select ifnull((select sum(%(second_source_field)s)
-					from `tab%(second_source_dt)s`
-					where `%(second_join_field)s`='%(detail_id)s'
-					and (`tab%(second_source_dt)s`.docstatus=1)
-					%(second_source_extra_cond)s), 0) """
-					% args
+					""" select ifnull((select sum({second_source_field})
+					from `tab{second_source_dt}`
+					where `{second_join_field}`='{detail_id}'
+					and (`tab{second_source_dt}`.docstatus=1)
+					{second_source_extra_cond}), 0) """.format(**args)
 				)[0][0]
 
 			if args["detail_id"]:
@@ -432,11 +427,10 @@
 				args["source_dt_value"] = (
 					frappe.db.sql(
 						"""
-						(select ifnull(sum(%(source_field)s), 0)
-							from `tab%(source_dt)s` where `%(join_field)s`='%(detail_id)s'
-							and (docstatus=1 %(cond)s) %(extra_cond)s)
-				"""
-						% args
+						(select ifnull(sum({source_field}), 0)
+							from `tab{source_dt}` where `{join_field}`='{detail_id}'
+							and (docstatus=1 {cond}) {extra_cond})
+				""".format(**args)
 					)[0][0]
 					or 0.0
 				)
@@ -445,10 +439,9 @@
 					args["source_dt_value"] += flt(args["second_source_condition"])
 
 				frappe.db.sql(
-					"""update `tab%(target_dt)s`
-					set %(target_field)s = %(source_dt_value)s %(update_modified)s
-					where name='%(detail_id)s'"""
-					% args
+					"""update `tab{target_dt}`
+					set {target_field} = {source_dt_value} {update_modified}
+					where name='{detail_id}'""".format(**args)
 				)
 
 	def _update_percent_field_in_targets(self, args, update_modified=True):
@@ -475,26 +468,24 @@
 
 		if args.get("target_parent_field"):
 			frappe.db.sql(
-				"""update `tab%(target_parent_dt)s`
-				set %(target_parent_field)s = round(
+				"""update `tab{target_parent_dt}`
+				set {target_parent_field} = round(
 					ifnull((select
-						ifnull(sum(case when abs(%(target_ref_field)s) > abs(%(target_field)s) then abs(%(target_field)s) else abs(%(target_ref_field)s) end), 0)
-						/ sum(abs(%(target_ref_field)s)) * 100
-					from `tab%(target_dt)s` where parent='%(name)s' and parenttype='%(target_parent_dt)s' having sum(abs(%(target_ref_field)s)) > 0), 0), 6)
-					%(update_modified)s
-				where name='%(name)s'"""
-				% args
+						ifnull(sum(case when abs({target_ref_field}) > abs({target_field}) then abs({target_field}) else abs({target_ref_field}) end), 0)
+						/ sum(abs({target_ref_field})) * 100
+					from `tab{target_dt}` where parent='{name}' and parenttype='{target_parent_dt}' having sum(abs({target_ref_field})) > 0), 0), 6)
+					{update_modified}
+				where name='{name}'""".format(**args)
 			)
 
 			# update field
 			if args.get("status_field"):
 				frappe.db.sql(
-					"""update `tab%(target_parent_dt)s`
-					set %(status_field)s = (case when %(target_parent_field)s<0.001 then 'Not %(keyword)s'
-					else case when %(target_parent_field)s>=99.999999 then 'Fully %(keyword)s'
-					else 'Partly %(keyword)s' end end)
-					where name='%(name)s'"""
-					% args
+					"""update `tab{target_parent_dt}`
+					set {status_field} = (case when {target_parent_field}<0.001 then 'Not {keyword}'
+					else case when {target_parent_field}>=99.999999 then 'Fully {keyword}'
+					else 'Partly {keyword}' end end)
+					where name='{name}'""".format(**args)
 				)
 
 			if update_modified:
@@ -507,21 +498,19 @@
 			args["update_modified"] = ""
 			return
 
-		args["update_modified"] = ", modified = {0}, modified_by = {1}".format(
+		args["update_modified"] = ", modified = {}, modified_by = {}".format(
 			frappe.db.escape(now()), frappe.db.escape(frappe.session.user)
 		)
 
 	def update_billing_status_for_zero_amount_refdoc(self, ref_dt):
 		ref_fieldname = frappe.scrub(ref_dt)
 
-		ref_docs = [
-			item.get(ref_fieldname) for item in (self.get("items") or []) if item.get(ref_fieldname)
-		]
+		ref_docs = [item.get(ref_fieldname) for item in (self.get("items") or []) if item.get(ref_fieldname)]
 		if not ref_docs:
 			return
 
 		zero_amount_refdocs = frappe.db.sql_list(
-			"""
+			f"""
 			SELECT
 				name
 			from
@@ -530,9 +519,7 @@
 				docstatus = 1
 				and base_net_total = 0
 				and name in %(ref_docs)s
-		""".format(
-				ref_dt=ref_dt
-			),
+		""",
 			{"ref_docs": ref_docs},
 		)
 
@@ -543,9 +530,8 @@
 		for ref_dn in zero_amount_refdoc:
 			ref_doc_qty = flt(
 				frappe.db.sql(
-					"""select ifnull(sum(qty), 0) from `tab%s Item`
-				where parent=%s"""
-					% (ref_dt, "%s"),
+					"""select ifnull(sum(qty), 0) from `tab{} Item`
+				where parent={}""".format(ref_dt, "%s"),
 					(ref_dn),
 				)[0][0]
 			)
@@ -553,8 +539,7 @@
 			billed_qty = flt(
 				frappe.db.sql(
 					"""select ifnull(sum(qty), 0)
-				from `tab%s Item` where %s=%s and docstatus=1"""
-					% (self.doctype, ref_fieldname, "%s"),
+				from `tab{} Item` where {}={} and docstatus=1""".format(self.doctype, ref_fieldname, "%s"),
 					(ref_dn),
 				)[0][0]
 			)
@@ -612,13 +597,13 @@
 	)
 
 	if qty_or_amount == "qty" and not qty_allowance:
-		if global_qty_allowance == None:
+		if global_qty_allowance is None:
 			global_qty_allowance = flt(
 				frappe.get_cached_value("Stock Settings", None, "over_delivery_receipt_allowance")
 			)
 		qty_allowance = global_qty_allowance
 	elif qty_or_amount == "amount" and not over_billing_allowance:
-		if global_amount_allowance == None:
+		if global_amount_allowance is None:
 			global_amount_allowance = flt(
 				frappe.get_cached_value("Accounts Settings", None, "over_billing_allowance")
 			)
diff --git a/erpnext/controllers/stock_controller.py b/erpnext/controllers/stock_controller.py
index a1946e8..5f11c59 100644
--- a/erpnext/controllers/stock_controller.py
+++ b/erpnext/controllers/stock_controller.py
@@ -3,7 +3,6 @@
 
 import json
 from collections import defaultdict
-from typing import List, Tuple
 
 import frappe
 from frappe import _, bold
@@ -45,7 +44,7 @@
 
 class StockController(AccountsController):
 	def validate(self):
-		super(StockController, self).validate()
+		super().validate()
 
 		if self.docstatus == 0:
 			for table_name in ["items", "packed_items", "supplied_items"]:
@@ -289,7 +288,9 @@
 		throw_error = False
 		if row.serial_no:
 			serial_nos = frappe.get_all(
-				"Serial and Batch Entry", fields=["serial_no"], filters={"parent": row.serial_and_batch_bundle}
+				"Serial and Batch Entry",
+				fields=["serial_no"],
+				filters={"parent": row.serial_and_batch_bundle},
 			)
 			serial_nos = sorted([cstr(d.serial_no) for d in serial_nos])
 			parsed_serial_nos = get_serial_nos(row.serial_no)
@@ -323,10 +324,7 @@
 			for row in self.items:
 				row.use_serial_batch_fields = 1
 
-	def get_gl_entries(
-		self, warehouse_account=None, default_expense_account=None, default_cost_center=None
-	):
-
+	def get_gl_entries(self, warehouse_account=None, default_expense_account=None, default_cost_center=None):
 		if not warehouse_account:
 			warehouse_account = get_warehouse_account_map(self.company)
 
@@ -364,7 +362,9 @@
 									"project": item_row.project or self.get("project"),
 									"remarks": self.get("remarks") or _("Accounting Entry for Stock"),
 									"debit": flt(sle.stock_value_difference, precision),
-									"is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
+									"is_opening": item_row.get("is_opening")
+									or self.get("is_opening")
+									or "No",
 								},
 								warehouse_account[sle.warehouse]["account_currency"],
 								item=item_row,
@@ -380,7 +380,9 @@
 									"remarks": self.get("remarks") or _("Accounting Entry for Stock"),
 									"debit": -1 * flt(sle.stock_value_difference, precision),
 									"project": item_row.get("project") or self.get("project"),
-									"is_opening": item_row.get("is_opening") or self.get("is_opening") or "No",
+									"is_opening": item_row.get("is_opening")
+									or self.get("is_opening")
+									or "No",
 								},
 								item=item_row,
 							)
@@ -447,9 +449,7 @@
 
 	def get_debit_field_precision(self):
 		if not frappe.flags.debit_field_precision:
-			frappe.flags.debit_field_precision = frappe.get_precision(
-				"GL Entry", "debit_in_account_currency"
-			)
+			frappe.flags.debit_field_precision = frappe.get_precision("GL Entry", "debit_in_account_currency")
 
 		return frappe.flags.debit_field_precision
 
@@ -482,7 +482,7 @@
 
 			return details
 
-	def get_items_and_warehouses(self) -> Tuple[List[str], List[str]]:
+	def get_items_and_warehouses(self) -> tuple[list[str], list[str]]:
 		"""Get list of items and warehouses affected by a transaction"""
 
 		if not (hasattr(self, "items") or hasattr(self, "packed_items")):
@@ -763,9 +763,7 @@
 		if item_codes:
 			serialized_items = frappe.db.sql_list(
 				"""select name from `tabItem`
-				where has_serial_no=1 and name in ({})""".format(
-					", ".join(["%s"] * len(item_codes))
-				),
+				where has_serial_no=1 and name in ({})""".format(", ".join(["%s"] * len(item_codes))),
 				tuple(item_codes),
 			)
 
@@ -854,16 +852,12 @@
 
 	def validate_qi_submission(self, row):
 		"""Check if QI is submitted on row level, during submission"""
-		action = frappe.db.get_single_value(
-			"Stock Settings", "action_if_quality_inspection_is_not_submitted"
-		)
+		action = frappe.db.get_single_value("Stock Settings", "action_if_quality_inspection_is_not_submitted")
 		qa_docstatus = frappe.db.get_value("Quality Inspection", row.quality_inspection, "docstatus")
 
 		if qa_docstatus != 1:
 			link = frappe.utils.get_link_to_form("Quality Inspection", row.quality_inspection)
-			msg = (
-				f"Row #{row.idx}: Quality Inspection {link} is not submitted for the item: {row.item_code}"
-			)
+			msg = f"Row #{row.idx}: Quality Inspection {link} is not submitted for the item: {row.item_code}"
 			if action == "Stop":
 				frappe.throw(_(msg), title=_("Inspection Submission"), exc=QualityInspectionNotSubmittedError)
 			else:
@@ -927,9 +921,7 @@
 				row.from_warehouse = None
 
 	def validate_in_transit_warehouses(self):
-		if (
-			self.doctype == "Sales Invoice" and self.get("update_stock")
-		) or self.doctype == "Delivery Note":
+		if (self.doctype == "Sales Invoice" and self.get("update_stock")) or self.doctype == "Delivery Note":
 			for item in self.get("items"):
 				if not item.target_warehouse:
 					frappe.throw(
@@ -1098,7 +1090,9 @@
 					if self.doctype == "Stock Reconciliation":
 						stock_qty = flt(item.qty)
 					else:
-						stock_qty = flt(item.transfer_qty) if self.doctype == "Stock Entry" else flt(item.stock_qty)
+						stock_qty = (
+							flt(item.transfer_qty) if self.doctype == "Stock Entry" else flt(item.stock_qty)
+						)
 
 					rule_name = rule.get("name")
 					if not rule_map[rule_name]:
@@ -1114,9 +1108,7 @@
 					frappe.throw(msg=message, title=_("Over Receipt"))
 
 	def prepare_over_receipt_message(self, rule, values):
-		message = _(
-			"{0} qty of Item {1} is being received into Warehouse {2} with capacity {3}."
-		).format(
+		message = _("{0} qty of Item {1} is being received into Warehouse {2} with capacity {3}.").format(
 			frappe.bold(values["qty_put"]),
 			frappe.bold(values["item"]),
 			frappe.bold(values["warehouse"]),
@@ -1167,7 +1159,6 @@
 		item=None,
 		posting_date=None,
 	):
-
 		gl_entry = {
 			"account": account,
 			"cost_center": cost_center,
@@ -1312,9 +1303,7 @@
 
 
 def get_gl_entries_for_preview(doctype, docname, fields):
-	return frappe.get_all(
-		"GL Entry", filters={"voucher_type": doctype, "voucher_no": docname}, fields=fields
-	)
+	return frappe.get_all("GL Entry", filters={"voucher_type": doctype, "voucher_no": docname}, fields=fields)
 
 
 def get_columns(raw_columns, fields):
@@ -1439,9 +1428,7 @@
 			and is_cancelled = 0
 		GROUP BY
 			item_code, warehouse
-		""".format(
-			" or ".join(or_conditions)
-		),
+		""".format(" or ".join(or_conditions)),
 		args,
 		as_dict=1,
 	)
diff --git a/erpnext/controllers/subcontracting_controller.py b/erpnext/controllers/subcontracting_controller.py
index ffc7f91..fc66345 100644
--- a/erpnext/controllers/subcontracting_controller.py
+++ b/erpnext/controllers/subcontracting_controller.py
@@ -21,7 +21,7 @@
 
 class SubcontractingController(StockController):
 	def __init__(self, *args, **kwargs):
-		super(SubcontractingController, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 		if self.get("is_old_subcontracting_flow"):
 			self.subcontract_data = frappe._dict(
 				{
@@ -53,7 +53,7 @@
 			self.validate_items()
 			self.create_raw_materials_supplied()
 		else:
-			super(SubcontractingController, self).validate()
+			super().validate()
 
 	def validate_rejected_warehouse(self):
 		for item in self.get("items"):
@@ -108,14 +108,20 @@
 
 					if not is_active:
 						frappe.throw(
-							_("Row {0}: Please select an active BOM for Item {1}.").format(item.idx, item.item_name)
+							_("Row {0}: Please select an active BOM for Item {1}.").format(
+								item.idx, item.item_name
+							)
 						)
 					if bom_item != item.item_code:
 						frappe.throw(
-							_("Row {0}: Please select an valid BOM for Item {1}.").format(item.idx, item.item_name)
+							_("Row {0}: Please select an valid BOM for Item {1}.").format(
+								item.idx, item.item_name
+							)
 						)
 				else:
-					frappe.throw(_("Row {0}: Please select a BOM for Item {1}.").format(item.idx, item.item_name))
+					frappe.throw(
+						_("Row {0}: Please select a BOM for Item {1}.").format(item.idx, item.item_name)
+					)
 			else:
 				item.bom = None
 
@@ -190,7 +196,6 @@
 				fields=["item_code", "(qty - received_qty) as qty", "parent", "name"],
 				filters={"docstatus": 1, "parent": ("in", self.subcontract_orders)},
 			):
-
 				self.qty_to_be_received[(row.item_code, row.parent)] += row.qty
 
 	def __get_transferred_items(self):
@@ -286,9 +291,7 @@
 		if not receipt_items:
 			return ([], {}) if return_consumed_items else None
 
-		receipt_items = {
-			item.name: item.get(self.subcontract_data.order_field) for item in receipt_items
-		}
+		receipt_items = {item.name: item.get(self.subcontract_data.order_field) for item in receipt_items}
 		consumed_materials = self.__get_consumed_items(doctype, receipt_items.keys())
 
 		voucher_nos = [d.voucher_no for d in consumed_materials if d.voucher_no]
@@ -459,9 +462,7 @@
 			[doctype, "sourced_by_supplier", "=", 0],
 		]
 
-		return (
-			frappe.get_all("BOM", fields=fields, filters=filters, order_by=f"`tab{doctype}`.`idx`") or []
-		)
+		return frappe.get_all("BOM", fields=fields, filters=filters, order_by=f"`tab{doctype}`.`idx`") or []
 
 	def __update_reserve_warehouse(self, row, item):
 		if self.doctype == self.subcontract_data.order_doctype:
@@ -476,9 +477,7 @@
 		if not self.available_materials.get(key):
 			return
 
-		if (
-			not self.available_materials[key]["serial_no"] and not self.available_materials[key]["batch_no"]
-		):
+		if not self.available_materials[key]["serial_no"] and not self.available_materials[key]["batch_no"]:
 			return
 
 		serial_nos = []
@@ -761,7 +760,9 @@
 		for row in self.get("supplied_items"):
 			if row.reference_name == name and row.serial_and_batch_bundle:
 				if row.consumed_qty != abs(
-					frappe.get_cached_value("Serial and Batch Bundle", row.serial_and_batch_bundle, "total_qty")
+					frappe.get_cached_value(
+						"Serial and Batch Bundle", row.serial_and_batch_bundle, "total_qty"
+					)
 				):
 					return row
 
@@ -1048,7 +1049,8 @@
 
 				if mr_obj.status in ["Stopped", "Cancelled"]:
 					frappe.throw(
-						_("Material Request {0} is cancelled or stopped").format(mr), frappe.InvalidStatusError
+						_("Material Request {0} is cancelled or stopped").format(mr),
+						frappe.InvalidStatusError,
 					)
 
 				mr_obj.update_requested_qty(mr_item_rows)
@@ -1131,8 +1133,10 @@
 
 			for fg_item_code in fg_item_code_list:
 				for rm_item in rm_items:
-
-					if rm_item.get("main_item_code") == fg_item_code or rm_item.get("item_code") == fg_item_code:
+					if (
+						rm_item.get("main_item_code") == fg_item_code
+						or rm_item.get("item_code") == fg_item_code
+					):
 						rm_item_code = rm_item.get("rm_item_code")
 						items_dict = {
 							rm_item_code: {
@@ -1142,15 +1146,22 @@
 								"description": item_wh.get(rm_item_code, {}).get("description", ""),
 								"qty": rm_item.get("qty")
 								or max(rm_item.get("required_qty") - rm_item.get("total_supplied_qty"), 0),
-								"from_warehouse": rm_item.get("warehouse") or rm_item.get("reserve_warehouse"),
+								"from_warehouse": rm_item.get("warehouse")
+								or rm_item.get("reserve_warehouse"),
 								"to_warehouse": subcontract_order.supplier_warehouse,
 								"stock_uom": rm_item.get("stock_uom"),
 								"serial_and_batch_bundle": rm_item.get("serial_and_batch_bundle"),
 								"main_item_code": fg_item_code,
-								"allow_alternative_item": item_wh.get(rm_item_code, {}).get("allow_alternative_item"),
+								"allow_alternative_item": item_wh.get(rm_item_code, {}).get(
+									"allow_alternative_item"
+								),
 								"use_serial_batch_fields": rm_item.get("use_serial_batch_fields"),
-								"serial_no": rm_item.get("serial_no") if rm_item.get("use_serial_batch_fields") else None,
-								"batch_no": rm_item.get("batch_no") if rm_item.get("use_serial_batch_fields") else None,
+								"serial_no": rm_item.get("serial_no")
+								if rm_item.get("use_serial_batch_fields")
+								else None,
+								"batch_no": rm_item.get("batch_no")
+								if rm_item.get("use_serial_batch_fields")
+								else None,
 							}
 						}
 
@@ -1164,9 +1175,7 @@
 			frappe.throw(_("No Items selected for transfer."))
 
 
-def add_items_in_ste(
-	ste_doc, row, qty, rm_details, rm_detail_field="sco_rm_detail", batch_no=None
-):
+def add_items_in_ste(ste_doc, row, qty, rm_details, rm_detail_field="sco_rm_detail", batch_no=None):
 	item = ste_doc.append("items", row.item_details)
 
 	rm_detail = list(set(row.get(f"{rm_detail_field}s")).intersection(rm_details))
@@ -1211,7 +1220,7 @@
 	ste_doc.company = order_doc.company
 	ste_doc.is_return = 1
 
-	for key, value in available_materials.items():
+	for _key, value in available_materials.items():
 		if not value.qty:
 			continue
 
@@ -1228,9 +1237,7 @@
 
 
 @frappe.whitelist()
-def get_materials_from_supplier(
-	subcontract_order, rm_details, order_doctype="Subcontracting Order"
-):
+def get_materials_from_supplier(subcontract_order, rm_details, order_doctype="Subcontracting Order"):
 	if isinstance(rm_details, str):
 		rm_details = json.loads(rm_details)
 
@@ -1244,6 +1251,4 @@
 			_("Materials are already received against the {0} {1}").format(order_doctype, subcontract_order)
 		)
 
-	return make_return_stock_entry_for_subcontract(
-		doc.available_materials, doc, rm_details, order_doctype
-	)
+	return make_return_stock_entry_for_subcontract(doc.available_materials, doc, rm_details, order_doctype)
diff --git a/erpnext/controllers/taxes_and_totals.py b/erpnext/controllers/taxes_and_totals.py
index 69d8caa..d90c14a 100644
--- a/erpnext/controllers/taxes_and_totals.py
+++ b/erpnext/controllers/taxes_and_totals.py
@@ -22,7 +22,7 @@
 from erpnext.utilities.regional import temporary_flag
 
 
-class calculate_taxes_and_totals(object):
+class calculate_taxes_and_totals:
 	def __init__(self, doc: Document):
 		self.doc = doc
 		frappe.flags.round_off_applicable_accounts = []
@@ -160,7 +160,8 @@
 				elif item.price_list_rate:
 					if not item.rate or (item.pricing_rules and item.discount_percentage > 0):
 						item.rate = flt(
-							item.price_list_rate * (1.0 - (item.discount_percentage / 100.0)), item.precision("rate")
+							item.price_list_rate * (1.0 - (item.discount_percentage / 100.0)),
+							item.precision("rate"),
 						)
 
 						item.discount_amount = item.price_list_rate * (item.discount_percentage / 100.0)
@@ -181,7 +182,8 @@
 					item.rate_with_margin, item.base_rate_with_margin = self.calculate_margin(item)
 					if flt(item.rate_with_margin) > 0:
 						item.rate = flt(
-							item.rate_with_margin * (1.0 - (item.discount_percentage / 100.0)), item.precision("rate")
+							item.rate_with_margin * (1.0 - (item.discount_percentage / 100.0)),
+							item.precision("rate"),
 						)
 
 						if item.discount_amount and not item.discount_percentage:
@@ -197,7 +199,9 @@
 				item.net_rate = item.rate
 
 				if (
-					not item.qty and self.doc.get("is_return") and self.doc.get("doctype") != "Purchase Receipt"
+					not item.qty
+					and self.doc.get("is_return")
+					and self.doc.get("doctype") != "Purchase Receipt"
 				):
 					item.amount = flt(-1 * item.rate, item.precision("amount"))
 				elif not item.qty and self.doc.get("is_debit_note"):
@@ -283,7 +287,9 @@
 
 				item.net_amount = flt(amount / (1 + cumulated_tax_fraction), item.precision("net_amount"))
 				item.net_rate = flt(item.net_amount / item.qty, item.precision("net_rate"))
-				item.discount_percentage = flt(item.discount_percentage, item.precision("discount_percentage"))
+				item.discount_percentage = flt(
+					item.discount_percentage, item.precision("discount_percentage")
+				)
 
 				self._set_in_company_currency(item, ["net_rate", "net_amount"])
 
@@ -344,7 +350,6 @@
 		self.doc.round_floats_in(self.doc, ["total", "base_total", "net_total", "base_net_total"])
 
 	def calculate_shipping_charges(self):
-
 		# Do not apply shipping rule for POS
 		if self.doc.get("is_pos"):
 			return
@@ -356,9 +361,7 @@
 			self._calculate()
 
 	def calculate_taxes(self):
-		rounding_adjustment_computed = self.doc.get("is_consolidated") and self.doc.get(
-			"rounding_adjustment"
-		)
+		rounding_adjustment_computed = self.doc.get("is_consolidated") and self.doc.get("rounding_adjustment")
 		if not rounding_adjustment_computed:
 			self.doc.rounding_adjustment = 0
 
@@ -398,7 +401,9 @@
 				# set tax after discount
 				tax.tax_amount_after_discount_amount += current_tax_amount
 
-				current_tax_amount = self.get_tax_amount_if_for_valuation_or_deduction(current_tax_amount, tax)
+				current_tax_amount = self.get_tax_amount_if_for_valuation_or_deduction(
+					current_tax_amount, tax
+				)
 
 				# note: grand_total_for_current_item contains the contribution of
 				# item's amount, previously applied tax and the current tax on that item
@@ -462,9 +467,7 @@
 		if tax.charge_type == "Actual":
 			# distribute the tax amount proportionally to each item row
 			actual = flt(tax.tax_amount, tax.precision("tax_amount"))
-			current_tax_amount = (
-				item.net_amount * actual / self.doc.net_total if self.doc.net_total else 0.0
-			)
+			current_tax_amount = item.net_amount * actual / self.doc.net_total if self.doc.net_total else 0.0
 
 		elif tax.charge_type == "On Net Total":
 			current_tax_amount = (tax_rate / 100.0) * item.net_amount
@@ -596,9 +599,7 @@
 				else self.doc.base_net_total
 			)
 
-			self._set_in_company_currency(
-				self.doc, ["taxes_and_charges_added", "taxes_and_charges_deducted"]
-			)
+			self._set_in_company_currency(self.doc, ["taxes_and_charges_added", "taxes_and_charges_deducted"])
 
 		self.doc.round_floats_in(self.doc, ["grand_total", "base_grand_total"])
 
@@ -652,12 +653,11 @@
 				frappe.throw(_("Please select Apply Discount On"))
 
 			self.doc.base_discount_amount = flt(
-				self.doc.discount_amount * self.doc.conversion_rate, self.doc.precision("base_discount_amount")
+				self.doc.discount_amount * self.doc.conversion_rate,
+				self.doc.precision("base_discount_amount"),
 			)
 
-			if self.doc.apply_discount_on == "Grand Total" and self.doc.get(
-				"is_cash_or_non_trade_discount"
-			):
+			if self.doc.apply_discount_on == "Grand Total" and self.doc.get("is_cash_or_non_trade_discount"):
 				self.discount_amount_applied = True
 				return
 
@@ -682,12 +682,17 @@
 						or total_for_discount_amount == self.doc.net_total
 					) and i == len(self._items) - 1:
 						discount_amount_loss = flt(
-							self.doc.net_total - net_total - self.doc.discount_amount, self.doc.precision("net_total")
+							self.doc.net_total - net_total - self.doc.discount_amount,
+							self.doc.precision("net_total"),
 						)
 
-						item.net_amount = flt(item.net_amount + discount_amount_loss, item.precision("net_amount"))
+						item.net_amount = flt(
+							item.net_amount + discount_amount_loss, item.precision("net_amount")
+						)
 
-					item.net_rate = flt(item.net_amount / item.qty, item.precision("net_rate")) if item.qty else 0
+					item.net_rate = (
+						flt(item.net_amount / item.qty, item.precision("net_rate")) if item.qty else 0
+					)
 
 					self._set_in_company_currency(item, ["net_rate", "net_amount"])
 
@@ -942,7 +947,9 @@
 		total_paid_amount = 0
 		for payment in self.doc.get("payments"):
 			total_paid_amount += (
-				payment.amount if self.doc.party_account_currency == self.doc.currency else payment.base_amount
+				payment.amount
+				if self.doc.party_account_currency == self.doc.currency
+				else payment.base_amount
 			)
 
 		pending_amount = total_amount_to_pay - total_paid_amount
@@ -1016,7 +1023,7 @@
 
 @erpnext.allow_regional
 def get_itemised_tax_breakup_header(item_doctype, tax_accounts):
-	return [_("Item"), _("Taxable Amount")] + tax_accounts
+	return [_("Item"), _("Taxable Amount"), *tax_accounts]
 
 
 @erpnext.allow_regional
@@ -1084,7 +1091,7 @@
 				row["tax_amount"] = flt(row["tax_amount"], precision)
 
 
-class init_landed_taxes_and_totals(object):
+class init_landed_taxes_and_totals:
 	def __init__(self, doc):
 		self.doc = doc
 		self.tax_field = "taxes" if self.doc.doctype == "Landed Cost Voucher" else "additional_costs"
diff --git a/erpnext/controllers/tests/test_accounts_controller.py b/erpnext/controllers/tests/test_accounts_controller.py
index 2170628..2105a3e 100644
--- a/erpnext/controllers/tests/test_accounts_controller.py
+++ b/erpnext/controllers/tests/test_accounts_controller.py
@@ -1,18 +1,15 @@
 # Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
 # For license information, please see license.txt
 
-import unittest
 
 import frappe
 from frappe import qb
 from frappe.query_builder.functions import Sum
-from frappe.tests.utils import FrappeTestCase, change_settings
-from frappe.utils import add_days, flt, getdate, nowdate
+from frappe.tests.utils import FrappeTestCase
+from frappe.utils import add_days, getdate, nowdate
 
-from erpnext import get_default_cost_center
 from erpnext.accounts.doctype.payment_entry.payment_entry import get_payment_entry
 from erpnext.accounts.doctype.payment_entry.test_payment_entry import create_payment_entry
-from erpnext.accounts.doctype.purchase_invoice.test_purchase_invoice import make_purchase_invoice
 from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice
 from erpnext.accounts.party import get_party_account
 from erpnext.stock.doctype.item.test_item import create_item
@@ -173,9 +170,7 @@
 		)
 		return sinv
 
-	def create_payment_entry(
-		self, amount=1, source_exc_rate=75, posting_date=nowdate(), customer=None
-	):
+	def create_payment_entry(self, amount=1, source_exc_rate=75, posting_date=nowdate(), customer=None):
 		"""
 		Helper function to populate default values in payment entry
 		"""
@@ -293,9 +288,7 @@
 			.run(as_dict=True)[0]
 		)
 		self.assertEqual(outstanding, current_outstanding.outstanding)
-		self.assertEqual(
-			outstanding_in_account_currency, current_outstanding.outstanding_in_account_currency
-		)
+		self.assertEqual(outstanding_in_account_currency, current_outstanding.outstanding_in_account_currency)
 
 	def test_10_payment_against_sales_invoice(self):
 		# Sales Invoice in Foreign Currency
@@ -401,7 +394,6 @@
 		adv.reload()
 
 		# sales invoice with advance(partial amount)
-		rate = 80
 		rate_in_account_currency = 1
 		si = self.create_sales_invoice(
 			qty=2, conversion_rate=80, rate=rate_in_account_currency, do_not_submit=True
@@ -788,7 +780,9 @@
 				self.assert_ledger_outstanding(si.doctype, si.name, 0.0, 0.0)
 
 				# Exchange Gain/Loss Journal should've been created.
-				exc_je_for_si = [x for x in self.get_journals_for(si.doctype, si.name) if x.parent != adv.name]
+				exc_je_for_si = [
+					x for x in self.get_journals_for(si.doctype, si.name) if x.parent != adv.name
+				]
 				exc_je_for_adv = self.get_journals_for(adv.doctype, adv.name)
 				self.assertNotEqual(exc_je_for_si, [])
 				self.assertEqual(len(exc_je_for_si), 1)
@@ -1253,7 +1247,9 @@
 			with self.subTest(x=x):
 				self.assertEqual(
 					[self.cost_center, self.cost_center],
-					frappe.db.get_all("Journal Entry Account", filters={"parent": x.parent}, pluck="cost_center"),
+					frappe.db.get_all(
+						"Journal Entry Account", filters={"parent": x.parent}, pluck="cost_center"
+					),
 				)
 
 		frappe.db.set_value("Company", self.company, "cost_center", cc)
@@ -1382,13 +1378,14 @@
 			with self.subTest(x=x):
 				self.assertEqual(
 					[cr_note.department, cr_note.department],
-					frappe.db.get_all("Journal Entry Account", filters={"parent": x.parent}, pluck="department"),
+					frappe.db.get_all(
+						"Journal Entry Account", filters={"parent": x.parent}, pluck="department"
+					),
 				)
 
 	def test_92_dimension_inhertiance_exc_gain_loss(self):
 		# Sales Invoice in Foreign Currency
 		self.setup_dimensions()
-		rate = 80
 		rate_in_account_currency = 1
 		dpt = "Research & Development"
 
diff --git a/erpnext/controllers/tests/test_mapper.py b/erpnext/controllers/tests/test_mapper.py
index 919bcda..9dbcf6c 100644
--- a/erpnext/controllers/tests/test_mapper.py
+++ b/erpnext/controllers/tests/test_mapper.py
@@ -29,7 +29,6 @@
 		self.assertEqual(set(d for d in src_items), set(d.item_code for d in updated_so.items))
 
 	def make_quotation(self, item_list, customer):
-
 		qtn = frappe.get_doc(
 			{
 				"doctype": "Quotation",
diff --git a/erpnext/controllers/tests/test_qty_based_taxes.py b/erpnext/controllers/tests/test_qty_based_taxes.py
index 2e9dfd2..e7896b5 100644
--- a/erpnext/controllers/tests/test_qty_based_taxes.py
+++ b/erpnext/controllers/tests/test_qty_based_taxes.py
@@ -25,7 +25,7 @@
 				"account_name": uuid4(),
 				"account_type": "Tax",
 				"company": self.company.name,
-				"parent_account": "Duties and Taxes - {self.company.abbr}".format(self=self),
+				"parent_account": f"Duties and Taxes - {self.company.abbr}",
 			}
 		).insert()
 		self.item_group = frappe.get_doc(
diff --git a/erpnext/controllers/tests/test_queries.py b/erpnext/controllers/tests/test_queries.py
index c536d1c..0ef108e 100644
--- a/erpnext/controllers/tests/test_queries.py
+++ b/erpnext/controllers/tests/test_queries.py
@@ -7,13 +7,10 @@
 
 
 def add_default_params(func, doctype):
-	return partial(
-		func, doctype=doctype, txt="", searchfield="name", start=0, page_len=20, filters=None
-	)
+	return partial(func, doctype=doctype, txt="", searchfield="name", start=0, page_len=20, filters=None)
 
 
 class TestQueries(unittest.TestCase):
-
 	# All tests are based on doctype/test_records.json
 
 	def assert_nested_in(self, item, container):
diff --git a/erpnext/controllers/tests/test_subcontracting_controller.py b/erpnext/controllers/tests/test_subcontracting_controller.py
index 7374e1e..b0c57e9 100644
--- a/erpnext/controllers/tests/test_subcontracting_controller.py
+++ b/erpnext/controllers/tests/test_subcontracting_controller.py
@@ -16,8 +16,6 @@
 from erpnext.manufacturing.doctype.production_plan.test_production_plan import make_bom
 from erpnext.stock.doctype.item.test_item import make_item
 from erpnext.stock.doctype.serial_and_batch_bundle.test_serial_and_batch_bundle import (
-	get_batch_from_bundle,
-	get_serial_nos_from_bundle,
 	make_serial_batch_bundle,
 )
 from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
@@ -351,7 +349,6 @@
 		- Create the 3 SCR against the SCO and split Subcontracted Items into two batches.
 		- Keep the qty as 2 for Subcontracted Item in the SCR.
 		"""
-		from erpnext.stock.serial_batch_bundle import get_batch_nos
 
 		set_backflush_based_on("BOM")
 		service_items = [
@@ -434,7 +431,7 @@
 		scr1.set_missing_values()
 		scr1.submit()
 
-		for key, value in get_supplied_items(scr1).items():
+		for _key, value in get_supplied_items(scr1).items():
 			self.assertEqual(value.qty, 4)
 
 		frappe.flags.add_debugger = True
@@ -446,7 +443,7 @@
 		scr2.set_missing_values()
 		scr2.submit()
 
-		for key, value in get_supplied_items(scr2).items():
+		for _key, value in get_supplied_items(scr2).items():
 			self.assertEqual(value.qty, 4)
 
 		scr3 = make_subcontracting_receipt(sco.name)
@@ -456,7 +453,7 @@
 		scr3.set_missing_values()
 		scr3.submit()
 
-		for key, value in get_supplied_items(scr3).items():
+		for _key, value in get_supplied_items(scr3).items():
 			self.assertEqual(value.qty, 2)
 
 	def test_item_with_batch_based_on_material_transfer(self):
@@ -700,9 +697,7 @@
 
 		scr1 = make_subcontracting_receipt(sco.name)
 		scr1.save()
-		bundle = frappe.get_doc(
-			"Serial and Batch Bundle", scr1.supplied_items[0].serial_and_batch_bundle
-		)
+		bundle = frappe.get_doc("Serial and Batch Bundle", scr1.supplied_items[0].serial_and_batch_bundle)
 		original_serial_no = ""
 		for row in bundle.entries:
 			if row.idx == 1:
@@ -773,7 +768,6 @@
 		scr1.items[0].qty = 5
 		scr1.save()
 
-		transferred_batch_no = ""
 		for key, value in get_supplied_items(scr1).items():
 			details = itemwise_details.get(key)
 			self.assertEqual(value.qty, 3)
@@ -1139,9 +1133,7 @@
 
 def update_item_details(child_row, details):
 	details.qty += (
-		child_row.get("qty")
-		if child_row.doctype == "Stock Entry Detail"
-		else child_row.get("consumed_qty")
+		child_row.get("qty") if child_row.doctype == "Stock Entry Detail" else child_row.get("consumed_qty")
 	)
 
 	details.use_serial_batch_fields = child_row.get("use_serial_batch_fields")
@@ -1152,7 +1144,9 @@
 				details.serial_no.append(row.serial_no)
 
 			if row.batch_no:
-				details.batch_no[row.batch_no] += row.qty * (-1 if doc.type_of_transaction == "Outward" else 1)
+				details.batch_no[row.batch_no] += row.qty * (
+					-1 if doc.type_of_transaction == "Outward" else 1
+				)
 	else:
 		if child_row.serial_no:
 			details.serial_no.extend(get_serial_nos(child_row.serial_no))
@@ -1268,7 +1262,9 @@
 			make_item(item, properties)
 
 
-def make_service_item(item, properties={}):
+def make_service_item(item, properties=None):
+	if properties is None:
+		properties = {}
 	if not frappe.db.exists("Item", item):
 		properties.update({"is_stock_item": 0})
 		make_item(item, properties)
@@ -1316,9 +1312,7 @@
 
 
 def set_backflush_based_on(based_on):
-	frappe.db.set_single_value(
-		"Buying Settings", "backflush_raw_materials_of_subcontract_based_on", based_on
-	)
+	frappe.db.set_single_value("Buying Settings", "backflush_raw_materials_of_subcontract_based_on", based_on)
 
 
 def get_subcontracting_order(**args):
diff --git a/erpnext/controllers/tests/test_transaction_base.py b/erpnext/controllers/tests/test_transaction_base.py
index 1471543..ab5525a 100644
--- a/erpnext/controllers/tests/test_transaction_base.py
+++ b/erpnext/controllers/tests/test_transaction_base.py
@@ -44,7 +44,10 @@
 					item_code="_Test Item", qty=1, basic_rate=200, s_warehouse="_Test Warehouse - _TC"
 				),
 				frappe._dict(
-					item_code="_Test FG Item", qty=4, t_warehouse="_Test Warehouse 1 - _TC", is_finished_item=1
+					item_code="_Test FG Item",
+					qty=4,
+					t_warehouse="_Test Warehouse 1 - _TC",
+					is_finished_item=1,
 				),
 			],
 		)
diff --git a/erpnext/controllers/trends.py b/erpnext/controllers/trends.py
index 1fb722e..18fe776 100644
--- a/erpnext/controllers/trends.py
+++ b/erpnext/controllers/trends.py
@@ -100,12 +100,11 @@
 		else:
 			inc = 1
 		data1 = frappe.db.sql(
-			""" select %s from `tab%s` t1, `tab%s Item` t2 %s
-					where t2.parent = t1.name and t1.company = %s and %s between %s and %s and
-					t1.docstatus = 1 %s %s
-					group by %s
-				"""
-			% (
+			""" select {} from `tab{}` t1, `tab{} Item` t2 {}
+					where t2.parent = t1.name and t1.company = {} and {} between {} and {} and
+					t1.docstatus = 1 {} {}
+					group by {}
+				""".format(
 				query_details,
 				conditions["trans"],
 				conditions["trans"],
@@ -130,11 +129,10 @@
 
 			# to get distinct value of col specified by group_by in filter
 			row = frappe.db.sql(
-				"""select DISTINCT(%s) from `tab%s` t1, `tab%s Item` t2 %s
-						where t2.parent = t1.name and t1.company = %s and %s between %s and %s
-						and t1.docstatus = 1 and %s = %s %s %s
-					"""
-				% (
+				"""select DISTINCT({}) from `tab{}` t1, `tab{} Item` t2 {}
+						where t2.parent = t1.name and t1.company = {} and {} between {} and {}
+						and t1.docstatus = 1 and {} = {} {} {}
+					""".format(
 					sel_col,
 					conditions["trans"],
 					conditions["trans"],
@@ -157,11 +155,10 @@
 
 				# get data for group_by filter
 				row1 = frappe.db.sql(
-					""" select %s , %s from `tab%s` t1, `tab%s Item` t2 %s
-							where t2.parent = t1.name and t1.company = %s and %s between %s and %s
-							and t1.docstatus = 1 and %s = %s and %s = %s %s %s
-						"""
-					% (
+					""" select {} , {} from `tab{}` t1, `tab{} Item` t2 {}
+							where t2.parent = t1.name and t1.company = {} and {} between {} and {}
+							and t1.docstatus = 1 and {} = {} and {} = {} {} {}
+						""".format(
 						sel_col,
 						conditions["period_wise_select"],
 						conditions["trans"],
@@ -190,12 +187,11 @@
 				data.append(des)
 	else:
 		data = frappe.db.sql(
-			""" select %s from `tab%s` t1, `tab%s Item` t2 %s
-					where t2.parent = t1.name and t1.company = %s and %s between %s and %s and
-					t1.docstatus = 1 %s %s
-					group by %s
-				"""
-			% (
+			""" select {} from `tab{}` t1, `tab{} Item` t2 {}
+					where t2.parent = t1.name and t1.company = {} and {} between {} and {} and
+					t1.docstatus = 1 {} {}
+					group by {}
+				""".format(
 				query_details,
 				conditions["trans"],
 				conditions["trans"],
@@ -260,13 +256,13 @@
 
 
 def get_period_wise_query(bet_dates, trans_date, query_details):
-	query_details += """SUM(IF(t1.%(trans_date)s BETWEEN '%(sd)s' AND '%(ed)s', t2.stock_qty, NULL)),
-					SUM(IF(t1.%(trans_date)s BETWEEN '%(sd)s' AND '%(ed)s', t2.base_net_amount, NULL)),
-				""" % {
-		"trans_date": trans_date,
-		"sd": bet_dates[0],
-		"ed": bet_dates[1],
-	}
+	query_details += """SUM(IF(t1.{trans_date} BETWEEN '{sd}' AND '{ed}', t2.stock_qty, NULL)),
+					SUM(IF(t1.{trans_date} BETWEEN '{sd}' AND '{ed}', t2.base_net_amount, NULL)),
+				""".format(
+		trans_date=trans_date,
+		sd=bet_dates[0],
+		ed=bet_dates[1],
+	)
 	return query_details
 
 
@@ -282,7 +278,7 @@
 	increment = {"Monthly": 1, "Quarterly": 3, "Half-Yearly": 6, "Yearly": 12}.get(period)
 
 	period_date_ranges = []
-	for i in range(1, 13, increment):
+	for _i in range(1, 13, increment):
 		period_end_date = getdate(year_start_date) + relativedelta(months=increment, days=-1)
 		if period_end_date > getdate(year_end_date):
 			period_end_date = year_end_date
@@ -331,9 +327,7 @@
 			"Territory:Link/Territory:120",
 		]
 		based_on_details["based_on_select"] = "t1.customer_name, t1.territory, "
-		based_on_details["based_on_group_by"] = (
-			"t1.party_name" if trans == "Quotation" else "t1.customer"
-		)
+		based_on_details["based_on_group_by"] = "t1.party_name" if trans == "Quotation" else "t1.customer"
 		based_on_details["addl_tables"] = ""
 
 	elif based_on == "Customer Group":
diff --git a/erpnext/controllers/website_list_for_contact.py b/erpnext/controllers/website_list_for_contact.py
index 0a0abda..f5cbf67 100644
--- a/erpnext/controllers/website_list_for_contact.py
+++ b/erpnext/controllers/website_list_for_contact.py
@@ -81,9 +81,7 @@
 	filters["docstatus"] = ["<", "2"] if doctype in ["Supplier Quotation", "Purchase Invoice"] else 1
 
 	if (user != "Guest" and is_website_user()) or doctype == "Request for Quotation":
-		parties_doctype = (
-			"Request for Quotation Supplier" if doctype == "Request for Quotation" else doctype
-		)
+		parties_doctype = "Request for Quotation Supplier" if doctype == "Request for Quotation" else doctype
 		# find party for this contact
 		customers, suppliers = get_customers_suppliers(parties_doctype, user)
 
@@ -303,6 +301,4 @@
 		return
 
 	user_doc.add_roles(role)
-	frappe.msgprint(
-		_("Added {1} Role to User {0}.").format(frappe.bold(user_doc.name), role), alert=True
-	)
+	frappe.msgprint(_("Added {1} Role to User {0}.").format(frappe.bold(user_doc.name), role), alert=True)
diff --git a/erpnext/crm/doctype/appointment/appointment.py b/erpnext/crm/doctype/appointment/appointment.py
index 541f77b..b41064c 100644
--- a/erpnext/crm/doctype/appointment/appointment.py
+++ b/erpnext/crm/doctype/appointment/appointment.py
@@ -198,7 +198,9 @@
 				"starts_on": self.scheduled_time,
 				"status": "Open",
 				"type": "Public",
-				"send_reminder": frappe.db.get_single_value("Appointment Booking Settings", "email_reminders"),
+				"send_reminder": frappe.db.get_single_value(
+					"Appointment Booking Settings", "email_reminders"
+				),
 				"event_participants": [
 					dict(reference_doctype=self.appointment_with, reference_docname=self.party)
 				],
@@ -251,9 +253,7 @@
 
 
 def _check_agent_availability(agent_email, scheduled_time):
-	appointemnts_at_scheduled_time = frappe.get_all(
-		"Appointment", filters={"scheduled_time": scheduled_time}
-	)
+	appointemnts_at_scheduled_time = frappe.get_all("Appointment", filters={"scheduled_time": scheduled_time})
 	for appointment in appointemnts_at_scheduled_time:
 		if appointment._assign == agent_email:
 			return False
diff --git a/erpnext/crm/doctype/appointment_booking_settings/appointment_booking_settings.py b/erpnext/crm/doctype/appointment_booking_settings/appointment_booking_settings.py
index 77e8727..5286901 100644
--- a/erpnext/crm/doctype/appointment_booking_settings/appointment_booking_settings.py
+++ b/erpnext/crm/doctype/appointment_booking_settings/appointment_booking_settings.py
@@ -45,13 +45,13 @@
 
 	def save(self):
 		self.number_of_agents = len(self.agent_list)
-		super(AppointmentBookingSettings, self).save()
+		super().save()
 
 	def validate_availability_of_slots(self):
 		for record in self.availability_of_slots:
 			from_time = datetime.datetime.strptime(self.min_date + record.from_time, self.format_string)
 			to_time = datetime.datetime.strptime(self.min_date + record.to_time, self.format_string)
-			timedelta = to_time - from_time
+			to_time - from_time
 			self.validate_from_and_to_time(from_time, to_time, record)
 			self.duration_is_divisible(from_time, to_time)
 
@@ -65,6 +65,4 @@
 	def duration_is_divisible(self, from_time, to_time):
 		timedelta = to_time - from_time
 		if timedelta.total_seconds() % (self.appointment_duration * 60):
-			frappe.throw(
-				_("The difference between from time and To Time must be a multiple of Appointment")
-			)
+			frappe.throw(_("The difference between from time and To Time must be a multiple of Appointment"))
diff --git a/erpnext/crm/doctype/appointment_booking_slots/appointment_booking_slots.py b/erpnext/crm/doctype/appointment_booking_slots/appointment_booking_slots.py
index ee936dd..ae640e6 100644
--- a/erpnext/crm/doctype/appointment_booking_slots/appointment_booking_slots.py
+++ b/erpnext/crm/doctype/appointment_booking_slots/appointment_booking_slots.py
@@ -15,9 +15,7 @@
 	if TYPE_CHECKING:
 		from frappe.types import DF
 
-		day_of_week: DF.Literal[
-			"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
-		]
+		day_of_week: DF.Literal["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
 		from_time: DF.Time
 		parent: DF.Data
 		parentfield: DF.Data
diff --git a/erpnext/crm/doctype/availability_of_slots/availability_of_slots.py b/erpnext/crm/doctype/availability_of_slots/availability_of_slots.py
index 67b6fde..95198e2 100644
--- a/erpnext/crm/doctype/availability_of_slots/availability_of_slots.py
+++ b/erpnext/crm/doctype/availability_of_slots/availability_of_slots.py
@@ -15,9 +15,7 @@
 	if TYPE_CHECKING:
 		from frappe.types import DF
 
-		day_of_week: DF.Literal[
-			"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
-		]
+		day_of_week: DF.Literal["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
 		from_time: DF.Time
 		parent: DF.Data
 		parentfield: DF.Data
diff --git a/erpnext/crm/doctype/contract/contract.py b/erpnext/crm/doctype/contract/contract.py
index 6f9dcde..6c3aace 100644
--- a/erpnext/crm/doctype/contract/contract.py
+++ b/erpnext/crm/doctype/contract/contract.py
@@ -49,12 +49,12 @@
 		name = self.party_name
 
 		if self.contract_template:
-			name += " - {} Agreement".format(self.contract_template)
+			name += f" - {self.contract_template} Agreement"
 
 		# If identical, append contract name with the next number in the iteration
 		if frappe.db.exists("Contract", name):
-			count = len(frappe.get_all("Contract", filters={"name": ["like", "%{}%".format(name)]}))
-			name = "{} - {}".format(name, count)
+			count = len(frappe.get_all("Contract", filters={"name": ["like", f"%{name}%"]}))
+			name = f"{name} - {count}"
 
 		self.name = _(name)
 
diff --git a/erpnext/crm/doctype/lead/lead.py b/erpnext/crm/doctype/lead/lead.py
index f3c7e57..c65fbf9 100644
--- a/erpnext/crm/doctype/lead/lead.py
+++ b/erpnext/crm/doctype/lead/lead.py
@@ -61,9 +61,7 @@
 		qualification_status: DF.Literal["Unqualified", "In Process", "Qualified"]
 		qualified_by: DF.Link | None
 		qualified_on: DF.Date | None
-		request_type: DF.Literal[
-			"", "Product Enquiry", "Request for Information", "Suggestions", "Other"
-		]
+		request_type: DF.Literal["", "Product Enquiry", "Request for Information", "Suggestions", "Other"]
 		salutation: DF.Link | None
 		source: DF.Link | None
 		state: DF.Data | None
@@ -187,9 +185,7 @@
 			self.contact_doc.save()
 
 	def update_prospect(self):
-		lead_row_name = frappe.db.get_value(
-			"Prospect Lead", filters={"lead": self.name}, fieldname="name"
-		)
+		lead_row_name = frappe.db.get_value("Prospect Lead", filters={"lead": self.name}, fieldname="name")
 		if lead_row_name:
 			lead_row = frappe.get_doc("Prospect Lead", lead_row_name)
 			lead_row.update(
@@ -239,9 +235,7 @@
 		)
 
 	def has_lost_quotation(self):
-		return frappe.db.get_value(
-			"Quotation", {"party_name": self.name, "docstatus": 1, "status": "Lost"}
-		)
+		return frappe.db.get_value("Quotation", {"party_name": self.name, "docstatus": 1, "status": "Lost"})
 
 	@frappe.whitelist()
 	def create_prospect_and_contact(self, data):
@@ -520,9 +514,9 @@
 	leads = frappe.get_all(
 		"Lead",
 		or_filters={
-			"phone": ["like", "%{}".format(number)],
-			"whatsapp_no": ["like", "%{}".format(number)],
-			"mobile_no": ["like", "%{}".format(number)],
+			"phone": ["like", f"%{number}"],
+			"whatsapp_no": ["like", f"%{number}"],
+			"mobile_no": ["like", f"%{number}"],
 		},
 		limit=1,
 		order_by="creation DESC",
@@ -549,9 +543,7 @@
 	link_open_events("Lead", lead, prospect)
 
 	frappe.msgprint(
-		_("Lead {0} has been added to prospect {1}.").format(
-			frappe.bold(lead), frappe.bold(prospect.name)
-		),
+		_("Lead {0} has been added to prospect {1}.").format(frappe.bold(lead), frappe.bold(prospect.name)),
 		title=_("Lead -> Prospect"),
 		indicator="green",
 	)
diff --git a/erpnext/crm/doctype/lead/test_lead.py b/erpnext/crm/doctype/lead/test_lead.py
index 8fe688d..bab9947 100644
--- a/erpnext/crm/doctype/lead/test_lead.py
+++ b/erpnext/crm/doctype/lead/test_lead.py
@@ -134,9 +134,7 @@
 		self.assertEqual(event.event_participants[1].reference_docname, opportunity.name)
 
 		self.assertTrue(
-			frappe.db.get_value(
-				"ToDo", {"reference_type": "Opportunity", "reference_name": opportunity.name}
-			)
+			frappe.db.get_value("ToDo", {"reference_type": "Opportunity", "reference_name": opportunity.name})
 		)
 
 	def test_copy_events_from_lead_to_prospect(self):
@@ -194,7 +192,7 @@
 			"doctype": "Lead",
 			"first_name": args.first_name or "_Test",
 			"last_name": args.last_name or "Lead",
-			"email_id": args.email_id or "new_lead_{}@example.com".format(random_string(5)),
+			"email_id": args.email_id or f"new_lead_{random_string(5)}@example.com",
 			"company_name": args.company_name or "_Test Company",
 		}
 	).insert()
diff --git a/erpnext/crm/doctype/opportunity/opportunity.py b/erpnext/crm/doctype/opportunity/opportunity.py
index 7abbb63..bddb331 100644
--- a/erpnext/crm/doctype/opportunity/opportunity.py
+++ b/erpnext/crm/doctype/opportunity/opportunity.py
@@ -370,9 +370,7 @@
 		quotation.conversion_rate = exchange_rate
 
 		# get default taxes
-		taxes = get_default_taxes_and_charges(
-			"Sales Taxes and Charges Template", company=quotation.company
-		)
+		taxes = get_default_taxes_and_charges("Sales Taxes and Charges Template", company=quotation.company)
 		if taxes.get("taxes"):
 			quotation.update(taxes)
 
@@ -478,9 +476,7 @@
 
 def auto_close_opportunity():
 	"""auto close the `Replied` Opportunities after 7 days"""
-	auto_close_after_days = (
-		frappe.db.get_single_value("CRM Settings", "close_opportunity_after_days") or 15
-	)
+	auto_close_after_days = frappe.db.get_single_value("CRM Settings", "close_opportunity_after_days") or 15
 
 	table = frappe.qb.DocType("Opportunity")
 	opportunities = (
diff --git a/erpnext/crm/doctype/opportunity/test_opportunity.py b/erpnext/crm/doctype/opportunity/test_opportunity.py
index 247e20d..6ec3ca4 100644
--- a/erpnext/crm/doctype/opportunity/test_opportunity.py
+++ b/erpnext/crm/doctype/opportunity/test_opportunity.py
@@ -4,7 +4,7 @@
 import unittest
 
 import frappe
-from frappe.utils import add_days, now_datetime, random_string, today
+from frappe.utils import now_datetime, random_string, today
 
 from erpnext.crm.doctype.lead.lead import make_customer
 from erpnext.crm.doctype.lead.test_lead import make_lead
@@ -32,9 +32,7 @@
 
 		self.assertTrue(opp_doc.party_name)
 		self.assertEqual(opp_doc.opportunity_from, "Lead")
-		self.assertEqual(
-			frappe.db.get_value("Lead", opp_doc.party_name, "email_id"), opp_doc.contact_email
-		)
+		self.assertEqual(frappe.db.get_value("Lead", opp_doc.party_name, "email_id"), opp_doc.contact_email)
 
 		# create new customer and create new contact against 'new.opportunity@example.com'
 		customer = make_customer(opp_doc.party_name).insert(ignore_permissions=True)
@@ -64,9 +62,7 @@
 		opportunity_comment_count = frappe.db.count(
 			"Comment", {"reference_doctype": opp_doc.doctype, "reference_name": opp_doc.name}
 		)
-		opportunity_communication_count = len(
-			get_linked_communication_list(opp_doc.doctype, opp_doc.name)
-		)
+		opportunity_communication_count = len(get_linked_communication_list(opp_doc.doctype, opp_doc.name))
 		self.assertEqual(opportunity_comment_count, 2)
 		self.assertEqual(opportunity_communication_count, 2)
 
@@ -77,7 +73,7 @@
 
 
 def make_opportunity_from_lead():
-	new_lead_email_id = "new{}@example.com".format(random_string(5))
+	new_lead_email_id = f"new{random_string(5)}@example.com"
 	args = {
 		"doctype": "Opportunity",
 		"contact_email": new_lead_email_id,
@@ -126,9 +122,7 @@
 	return opp_doc
 
 
-def create_communication(
-	reference_doctype, reference_name, sender, sent_or_received=None, creation=None
-):
+def create_communication(reference_doctype, reference_name, sender, sent_or_received=None, creation=None):
 	communication = frappe.get_doc(
 		{
 			"doctype": "Communication",
diff --git a/erpnext/crm/doctype/prospect/test_prospect.py b/erpnext/crm/doctype/prospect/test_prospect.py
index 874f84c..c3930ee 100644
--- a/erpnext/crm/doctype/prospect/test_prospect.py
+++ b/erpnext/crm/doctype/prospect/test_prospect.py
@@ -34,7 +34,7 @@
 	prospect_doc = frappe.get_doc(
 		{
 			"doctype": "Prospect",
-			"company_name": args.company_name or "_Test Company {}".format(random_string(3)),
+			"company_name": args.company_name or f"_Test Company {random_string(3)}",
 		}
 	).insert()
 
diff --git a/erpnext/crm/doctype/utils.py b/erpnext/crm/doctype/utils.py
index 3eca994..c42db17 100644
--- a/erpnext/crm/doctype/utils.py
+++ b/erpnext/crm/doctype/utils.py
@@ -3,7 +3,6 @@
 
 @frappe.whitelist()
 def get_last_interaction(contact=None, lead=None):
-
 	if not contact and not lead:
 		return
 
@@ -23,16 +22,14 @@
 			# remove extra appended 'OR'
 			query_condition = query_condition[:-2]
 			last_communication = frappe.db.sql(
-				"""
+				f"""
 				SELECT `name`, `content`
 				FROM `tabCommunication`
 				WHERE `sent_or_received`='Received'
-				AND ({})
+				AND ({query_condition})
 				ORDER BY `creation`
 				LIMIT 1
-			""".format(
-					query_condition
-				),
+			""",
 				values,
 				as_dict=1,
 			)  # nosec
diff --git a/erpnext/crm/report/campaign_efficiency/campaign_efficiency.py b/erpnext/crm/report/campaign_efficiency/campaign_efficiency.py
index be7f5ca..6d01bd2 100644
--- a/erpnext/crm/report/campaign_efficiency/campaign_efficiency.py
+++ b/erpnext/crm/report/campaign_efficiency/campaign_efficiency.py
@@ -33,13 +33,11 @@
 	conditions = get_filter_conditions(filters)
 
 	lead_details = frappe.db.sql(
-		"""
+		f"""
 		select {based_on_field}, name
 		from `tabLead`
 		where {based_on_field} is not null and {based_on_field} != '' {conditions}
-	""".format(
-			based_on_field=based_on_field, conditions=conditions
-		),
+	""",
 		filters,
 		as_dict=1,
 	)
@@ -82,9 +80,7 @@
 		where quotation_to = 'Lead' and party_name in (%s)"""
 		% ", ".join(["%s"] * len(leads)),
 		tuple(leads),
-	)[0][
-		0
-	]  # nosec
+	)[0][0]  # nosec
 
 
 def get_lead_opp_count(leads):
diff --git a/erpnext/crm/report/lost_opportunity/lost_opportunity.py b/erpnext/crm/report/lost_opportunity/lost_opportunity.py
index b37cfa4..eb09711 100644
--- a/erpnext/crm/report/lost_opportunity/lost_opportunity.py
+++ b/erpnext/crm/report/lost_opportunity/lost_opportunity.py
@@ -67,7 +67,7 @@
 
 def get_data(filters):
 	return frappe.db.sql(
-		"""
+		f"""
 		SELECT
 			`tabOpportunity`.name,
 			`tabOpportunity`.opportunity_from,
@@ -79,17 +79,15 @@
 			`tabOpportunity`.territory
 		FROM
 			`tabOpportunity`
-			{join}
+			{get_join(filters)}
 		WHERE
 			`tabOpportunity`.status = 'Lost' and `tabOpportunity`.company = %(company)s
 			AND DATE(`tabOpportunity`.modified) BETWEEN %(from_date)s AND %(to_date)s
-			{conditions}
+			{get_conditions(filters)}
 		GROUP BY
 			`tabOpportunity`.name
 		ORDER BY
-			`tabOpportunity`.creation asc  """.format(
-			conditions=get_conditions(filters), join=get_join(filters)
-		),
+			`tabOpportunity`.creation asc  """,
 		filters,
 		as_dict=1,
 	)
@@ -119,9 +117,7 @@
 		join = """JOIN `tabOpportunity Lost Reason Detail`
 			ON `tabOpportunity Lost Reason Detail`.parenttype = 'Opportunity' and
 			`tabOpportunity Lost Reason Detail`.parent = `tabOpportunity`.name and
-			`tabOpportunity Lost Reason Detail`.lost_reason = '{0}'
-			""".format(
-			filters.get("lost_reason")
-		)
+			`tabOpportunity Lost Reason Detail`.lost_reason = '{}'
+			""".format(filters.get("lost_reason"))
 
 	return join
diff --git a/erpnext/crm/report/opportunity_summary_by_sales_stage/opportunity_summary_by_sales_stage.py b/erpnext/crm/report/opportunity_summary_by_sales_stage/opportunity_summary_by_sales_stage.py
index 8093117..5a36c99 100644
--- a/erpnext/crm/report/opportunity_summary_by_sales_stage/opportunity_summary_by_sales_stage.py
+++ b/erpnext/crm/report/opportunity_summary_by_sales_stage/opportunity_summary_by_sales_stage.py
@@ -14,7 +14,7 @@
 	return OpportunitySummaryBySalesStage(filters).run()
 
 
-class OpportunitySummaryBySalesStage(object):
+class OpportunitySummaryBySalesStage:
 	def __init__(self, filters=None):
 		self.filters = frappe._dict(filters or {})
 
@@ -199,7 +199,6 @@
 		return filters
 
 	def get_chart_data(self):
-		labels = []
 		datasets = []
 		values = [0] * len(self.sales_stage_list)
 
diff --git a/erpnext/crm/report/prospects_engaged_but_not_converted/prospects_engaged_but_not_converted.py b/erpnext/crm/report/prospects_engaged_but_not_converted/prospects_engaged_but_not_converted.py
index 50c42ef..39b49b2 100644
--- a/erpnext/crm/report/prospects_engaged_but_not_converted/prospects_engaged_but_not_converted.py
+++ b/erpnext/crm/report/prospects_engaged_but_not_converted/prospects_engaged_but_not_converted.py
@@ -62,9 +62,7 @@
 	lead_details = []
 	lead_filters = get_lead_filters(filters)
 
-	for lead in frappe.get_all(
-		"Lead", fields=["name", "lead_name", "company_name"], filters=lead_filters
-	):
+	for lead in frappe.get_all("Lead", fields=["name", "lead_name", "company_name"], filters=lead_filters):
 		data = frappe.db.sql(
 			"""
 			select
@@ -90,7 +88,7 @@
 		)
 
 		for lead_info in data:
-			lead_data = [lead.name, lead.lead_name, lead.company_name] + list(lead_info)
+			lead_data = [lead.name, lead.lead_name, lead.company_name, *list(lead_info)]
 			lead_details.append(lead_data)
 
 	return lead_details
diff --git a/erpnext/crm/report/sales_pipeline_analytics/sales_pipeline_analytics.py b/erpnext/crm/report/sales_pipeline_analytics/sales_pipeline_analytics.py
index 4f7436f..9cc69d2 100644
--- a/erpnext/crm/report/sales_pipeline_analytics/sales_pipeline_analytics.py
+++ b/erpnext/crm/report/sales_pipeline_analytics/sales_pipeline_analytics.py
@@ -17,7 +17,7 @@
 	return SalesPipelineAnalytics(filters).run()
 
 
-class SalesPipelineAnalytics(object):
+class SalesPipelineAnalytics:
 	def __init__(self, filters=None):
 		self.filters = frappe._dict(filters or {})
 
@@ -98,7 +98,7 @@
 				"Opportunity",
 				filters=self.get_conditions(),
 				fields=[self.based_on, self.data_based_on, self.duration],
-				group_by="{},{}".format(self.group_by_based_on, self.group_by_period),
+				group_by=f"{self.group_by_based_on},{self.group_by_period}",
 				order_by=self.group_by_period,
 			)
 
@@ -230,7 +230,7 @@
 		current_date = date.today()
 		month_number = date.today().month
 
-		for month in range(month_number, 13):
+		for _month in range(month_number, 13):
 			month_list.append(current_date.strftime("%B"))
 			current_date = current_date + relativedelta(months=1)
 
diff --git a/erpnext/crm/utils.py b/erpnext/crm/utils.py
index 7374520..c543c38 100644
--- a/erpnext/crm/utils.py
+++ b/erpnext/crm/utils.py
@@ -94,9 +94,7 @@
 			"Opportunity", reference_name, ["opportunity_from", "party_name"]
 		)
 		if opportunity_from == "Lead":
-			prospect = frappe.db.get_value(
-				"Prospect Opportunity", {"opportunity": reference_name}, "parent"
-			)
+			prospect = frappe.db.get_value("Prospect Opportunity", {"opportunity": reference_name}, "parent")
 		if opportunity_from == "Prospect":
 			prospect = party_name
 
diff --git a/erpnext/erpnext_integrations/doctype/plaid_settings/plaid_settings.py b/erpnext/erpnext_integrations/doctype/plaid_settings/plaid_settings.py
index dc5a329..edfab47 100644
--- a/erpnext/erpnext_integrations/doctype/plaid_settings/plaid_settings.py
+++ b/erpnext/erpnext_integrations/doctype/plaid_settings/plaid_settings.py
@@ -143,7 +143,9 @@
 				result.append(new_account.name)
 			except frappe.UniqueValidationError:
 				frappe.msgprint(
-					_("Bank account {0} already exists and could not be created again").format(account["name"])
+					_("Bank account {0} already exists and could not be created again").format(
+						account["name"]
+					)
 				)
 			except Exception:
 				frappe.log_error("Plaid Link Error")
@@ -220,9 +222,7 @@
 				f"Plaid added {len(result)} new Bank Transactions from '{bank_account}' between {start_date} and {end_date}"
 			)
 
-			frappe.db.set_value(
-				"Bank Account", bank_account, "last_integration_date", last_transaction_date
-			)
+			frappe.db.set_value("Bank Account", bank_account, "last_integration_date", last_transaction_date)
 	except Exception:
 		frappe.log_error(frappe.get_traceback(), _("Plaid transactions sync error"))
 
@@ -244,9 +244,7 @@
 
 	transactions = []
 	try:
-		transactions = plaid.get_transactions(
-			start_date=start_date, end_date=end_date, account_id=account_id
-		)
+		transactions = plaid.get_transactions(start_date=start_date, end_date=end_date, account_id=account_id)
 	except ItemError as e:
 		if e.code == "ITEM_LOGIN_REQUIRED":
 			msg = _("There was an error syncing transactions.") + " "
diff --git a/erpnext/erpnext_integrations/doctype/quickbooks_migrator/quickbooks_migrator.py b/erpnext/erpnext_integrations/doctype/quickbooks_migrator/quickbooks_migrator.py
index ec7a6e9..5175cbd 100644
--- a/erpnext/erpnext_integrations/doctype/quickbooks_migrator/quickbooks_migrator.py
+++ b/erpnext/erpnext_integrations/doctype/quickbooks_migrator/quickbooks_migrator.py
@@ -65,10 +65,8 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(QuickBooksMigrator, self).__init__(*args, **kwargs)
-		self.oauth = OAuth2Session(
-			client_id=self.client_id, redirect_uri=self.redirect_url, scope=self.scope
-		)
+		super().__init__(*args, **kwargs)
+		self.oauth = OAuth2Session(client_id=self.client_id, redirect_uri=self.redirect_url, scope=self.scope)
 		if not self.authorization_url and self.authorization_endpoint:
 			self.authorization_url = self.oauth.authorization_url(self.authorization_endpoint)[0]
 
@@ -76,9 +74,7 @@
 		if self.company:
 			# We need a Cost Center corresponding to the selected erpnext Company
 			self.default_cost_center = frappe.db.get_value("Company", self.company, "cost_center")
-			company_warehouses = frappe.get_all(
-				"Warehouse", filters={"company": self.company, "is_group": 0}
-			)
+			company_warehouses = frappe.get_all("Warehouse", filters={"company": self.company, "is_group": 0})
 			if company_warehouses:
 				self.default_warehouse = company_warehouses[0].name
 		if self.authorization_endpoint:
@@ -226,14 +222,14 @@
 				if not frappe.db.exists(
 					{
 						"doctype": "Account",
-						"name": encode_company_abbr("{} - QB".format(root), self.company),
+						"name": encode_company_abbr(f"{root} - QB", self.company),
 						"company": self.company,
 					}
 				):
 					frappe.get_doc(
 						{
 							"doctype": "Account",
-							"account_name": "{} - QB".format(root),
+							"account_name": f"{root} - QB",
 							"root_type": root,
 							"is_group": "1",
 							"company": self.company,
@@ -245,13 +241,10 @@
 
 	def _migrate_entries(self, entity):
 		try:
-			query_uri = "{}/company/{}/query".format(
-				self.api_endpoint,
-				self.quickbooks_company_id,
-			)
+			query_uri = f"{self.api_endpoint}/company/{self.quickbooks_company_id}/query"
 			max_result_count = 1000
 			# Count number of entries
-			response = self._get(query_uri, params={"query": """SELECT COUNT(*) FROM {}""".format(entity)})
+			response = self._get(query_uri, params={"query": f"""SELECT COUNT(*) FROM {entity}"""})
 			entry_count = response.json()["QueryResponse"]["totalCount"]
 
 			# fetch pages and accumulate
@@ -273,9 +266,7 @@
 
 	def _fetch_general_ledger(self):
 		try:
-			query_uri = "{}/company/{}/reports/GeneralLedger".format(
-				self.api_endpoint, self.quickbooks_company_id
-			)
+			query_uri = f"{self.api_endpoint}/company/{self.quickbooks_company_id}/reports/GeneralLedger"
 			response = self._get(
 				query_uri,
 				params={
@@ -604,7 +595,9 @@
 						"is_stock_item": 0,
 						"item_group": "All Item Groups",
 						"company": self.company,
-						"item_defaults": [{"company": self.company, "default_warehouse": self.default_warehouse}],
+						"item_defaults": [
+							{"company": self.company, "default_warehouse": self.default_warehouse}
+						],
 					}
 					if "ExpenseAccountRef" in item:
 						expense_account = self._get_account_name_by_id(item["ExpenseAccountRef"]["value"])
@@ -644,7 +637,9 @@
 		try:
 			if preference["SalesFormsPrefs"]["AllowShipping"]:
 				default_shipping_account_id = preference["SalesFormsPrefs"]["DefaultShippingAccount"]
-				self.default_shipping_account = self._get_account_name_by_id(self, default_shipping_account_id)
+				self.default_shipping_account = self._get_account_name_by_id(
+					self, default_shipping_account_id
+				)
 				self.save()
 		except Exception as e:
 			self._log_error(e, preference)
@@ -752,7 +747,9 @@
 							"item_code": item["name"],
 							"conversion_factor": 1,
 							"uom": item["stock_uom"],
-							"description": line.get("Description", line["SalesItemLineDetail"]["ItemRef"]["name"]),
+							"description": line.get(
+								"Description", line["SalesItemLineDetail"]["ItemRef"]["name"]
+							),
 							"qty": line["SalesItemLineDetail"]["Qty"],
 							"price_list_rate": line["SalesItemLineDetail"]["UnitPrice"],
 							"cost_center": self.default_cost_center,
@@ -1024,7 +1021,11 @@
 					si_quickbooks_id = "Invoice - {}".format(linked_transaction["TxnId"])
 					# Invoice could have been saved as a Sales Invoice or a Journal Entry
 					if frappe.db.exists(
-						{"doctype": "Sales Invoice", "quickbooks_id": si_quickbooks_id, "company": self.company}
+						{
+							"doctype": "Sales Invoice",
+							"quickbooks_id": si_quickbooks_id,
+							"company": self.company,
+						}
 					):
 						sales_invoice = frappe.get_all(
 							"Sales Invoice",
@@ -1040,7 +1041,11 @@
 						party_account = sales_invoice["debit_to"]
 
 					if frappe.db.exists(
-						{"doctype": "Journal Entry", "quickbooks_id": si_quickbooks_id, "company": self.company}
+						{
+							"doctype": "Journal Entry",
+							"quickbooks_id": si_quickbooks_id,
+							"company": self.company,
+						}
 					):
 						journal_entry = frappe.get_doc(
 							"Journal Entry",
@@ -1050,9 +1055,9 @@
 							},
 						)
 						# Invoice saved as a Journal Entry must have party and party_type set on line containing Receivable Account
-						customer_account_line = list(
+						customer_account_line = next(
 							filter(lambda acc: acc.party_type == "Customer", journal_entry.accounts)
-						)[0]
+						)
 
 						reference_type = "Journal Entry"
 						reference_name = journal_entry.name
@@ -1094,7 +1099,11 @@
 				if linked_transaction["TxnType"] == "Bill":
 					pi_quickbooks_id = "Bill - {}".format(linked_transaction["TxnId"])
 					if frappe.db.exists(
-						{"doctype": "Purchase Invoice", "quickbooks_id": pi_quickbooks_id, "company": self.company}
+						{
+							"doctype": "Purchase Invoice",
+							"quickbooks_id": pi_quickbooks_id,
+							"company": self.company,
+						}
 					):
 						purchase_invoice = frappe.get_all(
 							"Purchase Invoice",
@@ -1229,7 +1238,9 @@
 				else:
 					accounts.append(
 						{
-							"account": self._get_account_name_by_id(line["DepositLineDetail"]["AccountRef"]["value"]),
+							"account": self._get_account_name_by_id(
+								line["DepositLineDetail"]["AccountRef"]["value"]
+							),
 							"credit_in_account_currency": line["Amount"],
 							"cost_center": self.default_cost_center,
 						}
@@ -1284,7 +1295,7 @@
 			return taxes
 		for line in entry["TxnTaxDetail"]["TaxLine"]:
 			tax_rate = line["TaxLineDetail"]["TaxRateRef"]["value"]
-			account_head = self._get_account_name_by_id("TaxRate - {}".format(tax_rate))
+			account_head = self._get_account_name_by_id(f"TaxRate - {tax_rate}")
 			tax_type_applicable = self._get_tax_type(tax_rate)
 			if tax_type_applicable == "TaxOnAmount":
 				taxes.append(
@@ -1333,7 +1344,7 @@
 								return tax_rate_detail["TaxRateRef"]["value"]
 
 	def _get_parent_row_id(self, tax_rate, taxes):
-		tax_account = self._get_account_name_by_id("TaxRate - {}".format(tax_rate))
+		tax_account = self._get_account_name_by_id(f"TaxRate - {tax_rate}")
 		for index, tax in enumerate(taxes):
 			if tax["account_head"] == tax_account:
 				return index + 1
@@ -1358,7 +1369,7 @@
 	def _get(self, *args, **kwargs):
 		kwargs["headers"] = {
 			"Accept": "application/json",
-			"Authorization": "Bearer {}".format(self.access_token),
+			"Authorization": f"Bearer {self.access_token}",
 		}
 		response = requests.get(*args, **kwargs)
 		# HTTP Status code 401 here means that the access_token is expired
@@ -1370,18 +1381,18 @@
 		return response
 
 	def _get_account_name_by_id(self, quickbooks_id):
-		return frappe.get_all(
-			"Account", filters={"quickbooks_id": quickbooks_id, "company": self.company}
-		)[0]["name"]
+		return frappe.get_all("Account", filters={"quickbooks_id": quickbooks_id, "company": self.company})[
+			0
+		]["name"]
 
 	def _publish(self, *args, **kwargs):
 		frappe.publish_realtime("quickbooks_progress_update", *args, **kwargs, user=self.modified_by)
 
 	def _get_unique_account_name(self, quickbooks_name, number=0):
 		if number:
-			quickbooks_account_name = "{} - {} - QB".format(quickbooks_name, number)
+			quickbooks_account_name = f"{quickbooks_name} - {number} - QB"
 		else:
-			quickbooks_account_name = "{} - QB".format(quickbooks_name)
+			quickbooks_account_name = f"{quickbooks_name} - QB"
 		company_encoded_account_name = encode_company_abbr(quickbooks_account_name, self.company)
 		if frappe.db.exists(
 			{"doctype": "Account", "name": company_encoded_account_name, "company": self.company}
diff --git a/erpnext/erpnext_integrations/doctype/tally_migration/tally_migration.py b/erpnext/erpnext_integrations/doctype/tally_migration/tally_migration.py
index 8cba24a..c811b38 100644
--- a/erpnext/erpnext_integrations/doctype/tally_migration/tally_migration.py
+++ b/erpnext/erpnext_integrations/doctype/tally_migration/tally_migration.py
@@ -190,7 +190,7 @@
 
 		def get_children_and_parent_dict(accounts):
 			children, parents = {}, {}
-			for parent, account, is_group in accounts:
+			for parent, account, _is_group in accounts:
 				children.setdefault(parent, set()).add(account)
 				parents.setdefault(account, set()).add(parent)
 				parents[account].update(parents.get(parent, []))
@@ -235,7 +235,9 @@
 						{
 							"doctype": party_type,
 							"customer_name": account.NAME.string.strip(),
-							"tax_id": account.INCOMETAXNUMBER.string.strip() if account.INCOMETAXNUMBER else None,
+							"tax_id": account.INCOMETAXNUMBER.string.strip()
+							if account.INCOMETAXNUMBER
+							else None,
 							"customer_group": "All Customer Groups",
 							"territory": "All Territories",
 							"customer_type": "Individual",
@@ -249,7 +251,9 @@
 						{
 							"doctype": party_type,
 							"supplier_name": account.NAME.string.strip(),
-							"pan": account.INCOMETAXNUMBER.string.strip() if account.INCOMETAXNUMBER else None,
+							"pan": account.INCOMETAXNUMBER.string.strip()
+							if account.INCOMETAXNUMBER
+							else None,
 							"supplier_group": "All Supplier Groups",
 							"supplier_type": "Individual",
 						}
@@ -265,7 +269,9 @@
 							"address_line2": address[140:].strip(),
 							"country": account.COUNTRYNAME.string.strip() if account.COUNTRYNAME else None,
 							"state": account.LEDSTATENAME.string.strip() if account.LEDSTATENAME else None,
-							"gst_state": account.LEDSTATENAME.string.strip() if account.LEDSTATENAME else None,
+							"gst_state": account.LEDSTATENAME.string.strip()
+							if account.LEDSTATENAME
+							else None,
 							"pin_code": account.PINCODE.string.strip() if account.PINCODE else None,
 							"mobile": account.LEDGERPHONE.string.strip() if account.LEDGERPHONE else None,
 							"phone": account.LEDGERPHONE.string.strip() if account.LEDGERPHONE else None,
@@ -607,7 +613,7 @@
 				if new_year.year_start_date.year == new_year.year_end_date.year:
 					new_year.year = new_year.year_start_date.year
 				else:
-					new_year.year = "{}-{}".format(new_year.year_start_date.year, new_year.year_end_date.year)
+					new_year.year = f"{new_year.year_start_date.year}-{new_year.year_end_date.year}"
 				new_year.save()
 				oldest_year = new_year
 
diff --git a/erpnext/erpnext_integrations/utils.py b/erpnext/erpnext_integrations/utils.py
index 1924ffb..ea38b0b 100644
--- a/erpnext/erpnext_integrations/utils.py
+++ b/erpnext/erpnext_integrations/utils.py
@@ -13,7 +13,9 @@
 
 		if frappe.request and settings and settings.get(secret_key) and not frappe.flags.in_test:
 			sig = base64.b64encode(
-				hmac.new(settings.get(secret_key).encode("utf8"), frappe.request.data, hashlib.sha256).digest()
+				hmac.new(
+					settings.get(secret_key).encode("utf8"), frappe.request.data, hashlib.sha256
+				).digest()
 			)
 
 			if frappe.request.data and sig != bytes(frappe.get_request_header(hmac_key).encode()):
@@ -26,7 +28,7 @@
 
 
 def get_webhook_address(connector_name, method, exclude_uri=False, force_https=False):
-	endpoint = "erpnext.erpnext_integrations.connectors.{0}.{1}".format(connector_name, method)
+	endpoint = f"erpnext.erpnext_integrations.connectors.{connector_name}.{method}"
 
 	if exclude_uri:
 		return endpoint
diff --git a/erpnext/hooks.py b/erpnext/hooks.py
index 0d70476..013cfb1 100644
--- a/erpnext/hooks.py
+++ b/erpnext/hooks.py
@@ -28,9 +28,7 @@
 
 override_doctype_class = {"Address": "erpnext.accounts.custom.address.ERPNextAddress"}
 
-override_whitelisted_methods = {
-	"frappe.www.contact.send_message": "erpnext.templates.utils.send_message"
-}
+override_whitelisted_methods = {"frappe.www.contact.send_message": "erpnext.templates.utils.send_message"}
 
 welcome_email = "erpnext.setup.utils.welcome_email"
 
@@ -262,9 +260,7 @@
 	{"name": "call-disconnect", "src": "/assets/erpnext/sounds/call-disconnect.mp3", "volume": 0.2},
 ]
 
-has_upload_permission = {
-	"Employee": "erpnext.setup.doctype.employee.employee.has_upload_permission"
-}
+has_upload_permission = {"Employee": "erpnext.setup.doctype.employee.employee.has_upload_permission"}
 
 has_website_permission = {
 	"Sales Order": "erpnext.controllers.website_list_for_contact.has_website_permission",
@@ -466,9 +462,7 @@
 	</span>
 """
 
-get_translated_dict = {
-	("doctype", "Global Defaults"): "frappe.geo.country_info.get_translated_dict"
-}
+get_translated_dict = {("doctype", "Global Defaults"): "frappe.geo.country_info.get_translated_dict"}
 
 bot_parsers = [
 	"erpnext.utilities.bot.FindItemBot",
@@ -557,9 +551,7 @@
 get_entries_for_bank_reconciliation_statement = "erpnext.accounts.report.bank_reconciliation_statement.bank_reconciliation_statement.get_entries_for_bank_reconciliation_statement"
 
 regional_overrides = {
-	"France": {
-		"erpnext.tests.test_regional.test_method": "erpnext.regional.france.utils.test_method"
-	},
+	"France": {"erpnext.tests.test_regional.test_method": "erpnext.regional.france.utils.test_method"},
 	"United Arab Emirates": {
 		"erpnext.controllers.taxes_and_totals.update_itemised_tax_data": "erpnext.regional.united_arab_emirates.utils.update_itemised_tax_data",
 		"erpnext.accounts.doctype.purchase_invoice.purchase_invoice.make_regional_gl_entries": "erpnext.regional.united_arab_emirates.utils.make_regional_gl_entries",
@@ -629,9 +621,7 @@
 	],
 }
 
-additional_timeline_content = {
-	"*": ["erpnext.telephony.doctype.call_log.call_log.get_linked_call_logs"]
-}
+additional_timeline_content = {"*": ["erpnext.telephony.doctype.call_log.call_log.get_linked_call_logs"]}
 
 
 extend_bootinfo = [
diff --git a/erpnext/maintenance/doctype/maintenance_schedule/maintenance_schedule.py b/erpnext/maintenance/doctype/maintenance_schedule/maintenance_schedule.py
index 50ec1f2..1bc0f19 100644
--- a/erpnext/maintenance/doctype/maintenance_schedule/maintenance_schedule.py
+++ b/erpnext/maintenance/doctype/maintenance_schedule/maintenance_schedule.py
@@ -163,7 +163,7 @@
 		date_diff = (getdate(end_date) - getdate(start_date)).days
 		add_by = date_diff / no_of_visit
 
-		for visit in range(cint(no_of_visit)):
+		for _visit in range(cint(no_of_visit)):
 			if getdate(start_date_copy) < getdate(end_date):
 				start_date_copy = add_days(start_date_copy, add_by)
 				if len(schedule_list) < no_of_visit:
@@ -190,9 +190,8 @@
 		)
 
 		if not validated and holidays:
-
 			# max iterations = len(holidays)
-			for i in range(len(holidays)):
+			for _i in range(len(holidays)):
 				if schedule_date in holidays:
 					schedule_date = add_days(schedule_date, -1)
 				else:
@@ -251,7 +250,7 @@
 		doc_before_save = self.get_doc_before_save()
 		if not doc_before_save:
 			return
-		for prev_item, item in zip(doc_before_save.items, self.items):
+		for prev_item, item in zip(doc_before_save.items, self.items, strict=False):
 			fields = [
 				"item_code",
 				"start_date",
@@ -334,9 +333,7 @@
 					)
 				)
 
-			if sr_details.amc_expiry_date and getdate(sr_details.amc_expiry_date) >= getdate(
-				amc_start_date
-			):
+			if sr_details.amc_expiry_date and getdate(sr_details.amc_expiry_date) >= getdate(amc_start_date):
 				throw(
 					_("Serial No {0} is under maintenance contract upto {1}").format(
 						serial_no, sr_details.amc_expiry_date
diff --git a/erpnext/maintenance/doctype/maintenance_visit/maintenance_visit.py b/erpnext/maintenance/doctype/maintenance_visit/maintenance_visit.py
index b43b419..990cda6 100644
--- a/erpnext/maintenance/doctype/maintenance_visit/maintenance_visit.py
+++ b/erpnext/maintenance/doctype/maintenance_visit/maintenance_visit.py
@@ -69,13 +69,17 @@
 						self.mntc_date
 					) > get_datetime(end_date):
 						frappe.throw(
-							_("Date must be between {0} and {1}").format(format_date(start_date), format_date(end_date))
+							_("Date must be between {0} and {1}").format(
+								format_date(start_date), format_date(end_date)
+							)
 						)
 			else:
 				for purpose in self.purposes:
 					if purpose.maintenance_schedule_detail:
 						item_ref = frappe.db.get_value(
-							"Maintenance Schedule Detail", purpose.maintenance_schedule_detail, "item_reference"
+							"Maintenance Schedule Detail",
+							purpose.maintenance_schedule_detail,
+							"item_reference",
 						)
 						if item_ref:
 							start_date, end_date = frappe.db.get_value(
diff --git a/erpnext/manufacturing/doctype/blanket_order/blanket_order.py b/erpnext/manufacturing/doctype/blanket_order/blanket_order.py
index e44d484..feb1147 100644
--- a/erpnext/manufacturing/doctype/blanket_order/blanket_order.py
+++ b/erpnext/manufacturing/doctype/blanket_order/blanket_order.py
@@ -186,7 +186,7 @@
 						allowed_qty = remaining_qty + (remaining_qty * (allowance / 100))
 						if allowed_qty < item_data[item.item_code]:
 							frappe.throw(
-								_("Item {0} cannot be ordered more than {1} against Blanket Order {2}.").format(
-									item.item_code, allowed_qty, bo_name
-								)
+								_(
+									"Item {0} cannot be ordered more than {1} against Blanket Order {2}."
+								).format(item.item_code, allowed_qty, bo_name)
 							)
diff --git a/erpnext/manufacturing/doctype/blanket_order/test_blanket_order.py b/erpnext/manufacturing/doctype/blanket_order/test_blanket_order.py
index 3f3b6f0..a6eb18f 100644
--- a/erpnext/manufacturing/doctype/blanket_order/test_blanket_order.py
+++ b/erpnext/manufacturing/doctype/blanket_order/test_blanket_order.py
@@ -98,9 +98,7 @@
 		customer = "_Test Customer"
 		supplier = "_Test Supplier"
 
-		if not frappe.db.exists(
-			"Item Customer Detail", {"customer_name": customer, "parent": item_code}
-		):
+		if not frappe.db.exists("Item Customer Detail", {"customer_name": customer, "parent": item_code}):
 			item_doc.append("customer_items", {"customer_name": customer, "ref_code": "CUST-REF-1"})
 			item_doc.save()
 
diff --git a/erpnext/manufacturing/doctype/bom/bom.py b/erpnext/manufacturing/doctype/bom/bom.py
index 27c8493..cb56172 100644
--- a/erpnext/manufacturing/doctype/bom/bom.py
+++ b/erpnext/manufacturing/doctype/bom/bom.py
@@ -5,7 +5,6 @@
 import re
 from collections import deque
 from operator import itemgetter
-from typing import Dict, List
 
 import frappe
 from frappe import _
@@ -33,11 +32,9 @@
 	# ref: https://docs.python.org/3/reference/datamodel.html#slots
 	__slots__ = ["name", "child_items", "is_bom", "item_code", "qty", "exploded_qty", "bom_qty"]
 
-	def __init__(
-		self, name: str, is_bom: bool = True, exploded_qty: float = 1.0, qty: float = 1
-	) -> None:
+	def __init__(self, name: str, is_bom: bool = True, exploded_qty: float = 1.0, qty: float = 1) -> None:
 		self.name = name  # name of node, BOM number if is_bom else item_code
-		self.child_items: List["BOMTree"] = []  # list of child items
+		self.child_items: list["BOMTree"] = []  # list of child items
 		self.is_bom = is_bom  # true if the node is a BOM and not a leaf item
 		self.item_code: str = None  # item_code associated with node
 		self.qty = qty  # required unit quantity to make one unit of parent item.
@@ -63,7 +60,7 @@
 					BOMTree(item.item_code, is_bom=False, exploded_qty=exploded_qty, qty=qty)
 				)
 
-	def level_order_traversal(self) -> List["BOMTree"]:
+	def level_order_traversal(self) -> list["BOMTree"]:
 		"""Get level order traversal of tree.
 		E.g. for following tree the traversal will return list of nodes in order from top to bottom.
 		BOM:
@@ -219,7 +216,7 @@
 		self.name = name
 
 	@staticmethod
-	def get_next_version_index(existing_boms: List[str]) -> int:
+	def get_next_version_index(existing_boms: list[str]) -> int:
 		# split by "/" and "-"
 		delimiters = ["/", "-"]
 		pattern = "|".join(map(re.escape, delimiters))
@@ -426,10 +423,7 @@
 		return ret_item
 
 	def validate_bom_currency(self, item):
-		if (
-			item.get("bom_no")
-			and frappe.db.get_value("BOM", item.get("bom_no"), "currency") != self.currency
-		):
+		if item.get("bom_no") and frappe.db.get_value("BOM", item.get("bom_no"), "currency") != self.currency:
 			frappe.throw(
 				_("Row {0}: Currency of the BOM #{1} should be equal to the selected currency {2}").format(
 					item.idx, item.bom_no, self.currency
@@ -446,9 +440,9 @@
 			rate = get_valuation_rate(arg)
 		elif arg:
 			# Customer Provided parts and Supplier sourced parts will have zero rate
-			if not frappe.db.get_value(
-				"Item", arg["item_code"], "is_customer_provided_item"
-			) and not arg.get("sourced_by_supplier"):
+			if not frappe.db.get_value("Item", arg["item_code"], "is_customer_provided_item") and not arg.get(
+				"sourced_by_supplier"
+			):
 				if arg.get("bom_no") and self.set_rate_of_sub_assembly_item_based_on_bom:
 					rate = flt(self.get_bom_unitcost(arg["bom_no"])) * (arg.get("conversion_factor") or 1)
 				else:
@@ -464,7 +458,8 @@
 							)
 						else:
 							frappe.msgprint(
-								_("{0} not found for item {1}").format(self.rm_cost_as_per, arg["item_code"]), alert=True
+								_("{0} not found for item {1}").format(self.rm_cost_as_per, arg["item_code"]),
+								alert=True,
 							)
 		return flt(rate) * flt(self.plc_conversion_rate or 1) / (self.conversion_rate or 1)
 
@@ -813,7 +808,7 @@
 				# Only db_update if changed
 				row.db_update()
 
-	def get_rm_rate_map(self) -> Dict[str, float]:
+	def get_rm_rate_map(self) -> dict[str, float]:
 		"Create Raw Material-Rate map for Exploded Items. Fetch rate from Items table or Subassembly BOM."
 		rm_rate_map = {}
 
@@ -1189,9 +1184,7 @@
 
 @frappe.whitelist()
 def get_bom_items(bom, company, qty=1, fetch_exploded=1):
-	items = get_bom_items_as_dict(
-		bom, company, qty, fetch_exploded, include_non_stock_items=True
-	).values()
+	items = get_bom_items_as_dict(bom, company, qty, fetch_exploded, include_non_stock_items=True).values()
 	items = list(items)
 	items.sort(key=functools.cmp_to_key(lambda a, b: a.item_code > b.item_code and 1 or -1))
 	return items
@@ -1323,9 +1316,7 @@
 		)
 
 	if work_order and work_order.additional_operating_cost and work_order.qty:
-		additional_operating_cost_per_unit = flt(work_order.additional_operating_cost) / flt(
-			work_order.qty
-		)
+		additional_operating_cost_per_unit = flt(work_order.additional_operating_cost) / flt(work_order.qty)
 
 		if additional_operating_cost_per_unit:
 			stock_entry.append(
@@ -1402,9 +1393,7 @@
 	order_by = "idx desc, name, item_name"
 
 	fields = ["name", "item_name", "item_group", "description"]
-	fields.extend(
-		[field for field in searchfields if field not in ["name", "item_group", "description"]]
-	)
+	fields.extend([field for field in searchfields if field not in ["name", "item_group", "description"]])
 
 	searchfields = searchfields + [
 		field
@@ -1422,12 +1411,12 @@
 	or_cond_filters = {}
 	if txt:
 		for s_field in searchfields:
-			or_cond_filters[s_field] = ("like", "%{0}%".format(txt))
+			or_cond_filters[s_field] = ("like", f"%{txt}%")
 
 		barcodes = frappe.get_all(
 			"Item Barcode",
 			fields=["distinct parent as item_code"],
-			filters={"barcode": ("like", "%{0}%".format(txt))},
+			filters={"barcode": ("like", f"%{txt}%")},
 		)
 
 		barcodes = [d.item_code for d in barcodes]
@@ -1528,9 +1517,7 @@
 			continue
 
 		qty = flt(row.qty) * flt(qty)
-		items = get_bom_items_as_dict(
-			row.bom_no, company, qty=qty, fetch_exploded=0, fetch_scrap_items=1
-		)
+		items = get_bom_items_as_dict(row.bom_no, company, qty=qty, fetch_exploded=0, fetch_scrap_items=1)
 		scrap_items.update(items)
 
 		get_scrap_items_from_sub_assemblies(row.bom_no, company, qty, scrap_items)
diff --git a/erpnext/manufacturing/doctype/bom/test_bom.py b/erpnext/manufacturing/doctype/bom/test_bom.py
index 2debf91..d02b51c 100644
--- a/erpnext/manufacturing/doctype/bom/test_bom.py
+++ b/erpnext/manufacturing/doctype/bom/test_bom.py
@@ -10,7 +10,6 @@
 from frappe.utils import cstr, flt
 
 from erpnext.controllers.tests.test_subcontracting_controller import (
-	make_stock_in_entry,
 	set_backflush_based_on,
 )
 from erpnext.manufacturing.doctype.bom.bom import BOMRecursionError, item_query, make_variant_bom
@@ -200,9 +199,7 @@
 
 		reset_item_valuation_rate(
 			item_code="_Test Item",
-			warehouse_list=frappe.get_all(
-				"Warehouse", {"is_group": 0, "company": bom.company}, pluck="name"
-			),
+			warehouse_list=frappe.get_all("Warehouse", {"is_group": 0, "company": bom.company}, pluck="name"),
 			qty=200,
 			rate=200,
 		)
@@ -344,7 +341,7 @@
 
 		self.assertEqual(len(reqd_order), len(created_order))
 
-		for reqd_item, created_item in zip(reqd_order, created_order):
+		for reqd_item, created_item in zip(reqd_order, created_order, strict=False):
 			self.assertEqual(reqd_item, created_item.item_code)
 
 	@timeout
@@ -383,7 +380,7 @@
 
 		self.assertEqual(len(reqd_order), len(created_order))
 
-		for reqd_item, created_item in zip(reqd_order, created_order):
+		for reqd_item, created_item in zip(reqd_order, created_order, strict=False):
 			self.assertEqual(reqd_item.item_code, created_item.item_code)
 			self.assertEqual(reqd_item.qty, created_item.qty)
 			self.assertEqual(reqd_item.exploded_qty, created_item.exploded_qty)
@@ -452,9 +449,7 @@
 		test_items = query(txt="_Test")
 		filtered = query(txt="_Test Item 2")
 
-		self.assertNotEqual(
-			len(test_items), len(filtered), msg="Item filtering showing excessive results"
-		)
+		self.assertNotEqual(len(test_items), len(filtered), msg="Item filtering showing excessive results")
 		self.assertTrue(0 < len(filtered) <= 3, msg="Item filtering showing excessive results")
 
 	@timeout
@@ -516,7 +511,6 @@
 
 	@timeout
 	def test_version_index(self):
-
 		bom = frappe.new_doc("BOM")
 
 		version_index_test_cases = [
@@ -571,7 +565,6 @@
 
 	@timeout
 	def test_clear_inpection_quality(self):
-
 		bom = frappe.copy_doc(test_records[2], ignore_no_copy=True)
 		bom.docstatus = 0
 		bom.is_default = 0
@@ -686,9 +679,7 @@
 
 		bom = make_bom(item=fg_item, raw_materials=[rm_item])
 
-		create_stock_reconciliation(
-			item_code=rm_item, warehouse="_Test Warehouse - _TC", qty=100, rate=600
-		)
+		create_stock_reconciliation(item_code=rm_item, warehouse="_Test Warehouse - _TC", qty=100, rate=600)
 
 		bom.load_from_db()
 		bom.update_cost()
@@ -699,8 +690,6 @@
 		self.assertFalse(bom.flags.cost_updated)
 
 	def test_bom_with_service_item_cost(self):
-		from erpnext.stock.doctype.stock_entry.test_stock_entry import make_stock_entry
-
 		rm_item = make_item(properties={"is_stock_item": 1, "valuation_rate": 1000.0}).name
 
 		service_item = make_item(properties={"is_stock_item": 0}).name
@@ -793,7 +782,9 @@
 		for item_code, subtree in bom_tree.items():
 			bom_item_code = prefix + item_code
 			if not frappe.db.exists("Item", bom_item_code):
-				frappe.get_doc(doctype="Item", item_code=bom_item_code, item_group="_Test Item Group").insert()
+				frappe.get_doc(
+					doctype="Item", item_code=bom_item_code, item_group="_Test Item Group"
+				).insert()
 			create_items(subtree)
 
 	create_items(tree)
diff --git a/erpnext/manufacturing/doctype/bom_creator/bom_creator.py b/erpnext/manufacturing/doctype/bom_creator/bom_creator.py
index 1709a1f..dcfc798 100644
--- a/erpnext/manufacturing/doctype/bom_creator/bom_creator.py
+++ b/erpnext/manufacturing/doctype/bom_creator/bom_creator.py
@@ -101,9 +101,7 @@
 				has_completed = False
 				break
 
-		if not frappe.get_cached_value(
-			"BOM", {"bom_creator": self.name, "item": self.item_code}, "name"
-		):
+		if not frappe.get_cached_value("BOM", {"bom_creator": self.name, "item": self.item_code}, "name"):
 			has_completed = False
 
 		if has_completed:
@@ -237,7 +235,8 @@
 			if row.is_expandable:
 				if (row.item_code, row.name) not in production_item_wise_rm:
 					production_item_wise_rm.setdefault(
-						(row.item_code, row.name), frappe._dict({"items": [], "bom_no": "", "fg_item_data": row})
+						(row.item_code, row.name),
+						frappe._dict({"items": [], "bom_no": "", "fg_item_data": row}),
 					)
 
 			production_item_wise_rm[(row.fg_item, row.fg_reference_id)]["items"].append(row)
@@ -404,7 +403,6 @@
 				"conversion_factor": 1,
 				"fg_reference_id": name,
 				"stock_qty": bom_item.qty,
-				"fg_reference_id": name,
 				"do_not_explode": 1,
 				"is_expandable": 1,
 				"stock_uom": item_info.stock_uom,
diff --git a/erpnext/manufacturing/doctype/bom_creator/test_bom_creator.py b/erpnext/manufacturing/doctype/bom_creator/test_bom_creator.py
index ee5886c..a835de7 100644
--- a/erpnext/manufacturing/doctype/bom_creator/test_bom_creator.py
+++ b/erpnext/manufacturing/doctype/bom_creator/test_bom_creator.py
@@ -9,8 +9,6 @@
 from erpnext.manufacturing.doctype.bom_creator.bom_creator import (
 	add_item,
 	add_sub_assembly,
-	delete_node,
-	edit_qty,
 )
 from erpnext.stock.doctype.item.test_item import make_item
 
diff --git a/erpnext/manufacturing/doctype/bom_update_log/bom_update_log.py b/erpnext/manufacturing/doctype/bom_update_log/bom_update_log.py
index 9891e39..758dc07 100644
--- a/erpnext/manufacturing/doctype/bom_update_log/bom_update_log.py
+++ b/erpnext/manufacturing/doctype/bom_update_log/bom_update_log.py
@@ -1,7 +1,7 @@
 # Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
 # For license information, please see license.txt
 import json
-from typing import Any, Dict, List, Optional, Tuple, Union
+from typing import Any
 
 import frappe
 from frappe import _
@@ -51,9 +51,7 @@
 		table = DocType("BOM Update Log")
 		frappe.db.delete(
 			table,
-			filters=(
-				(table.creation < (Now() - Interval(days=days))) & (table.update_type == "Update Cost")
-			),
+			filters=((table.creation < (Now() - Interval(days=days))) & (table.update_type == "Update Cost")),
 		)
 
 	def validate(self):
@@ -123,7 +121,7 @@
 
 def run_replace_bom_job(
 	doc: "BOMUpdateLog",
-	boms: Optional[Dict[str, str]] = None,
+	boms: dict[str, str] | None = None,
 ) -> None:
 	try:
 		doc.db_set("status", "In Progress")
@@ -146,8 +144,8 @@
 
 
 def process_boms_cost_level_wise(
-	update_doc: "BOMUpdateLog", parent_boms: List[str] = None
-) -> Union[None, Tuple]:
+	update_doc: "BOMUpdateLog", parent_boms: list[str] | None = None
+) -> None | tuple:
 	"Queue jobs at the start of new BOM Level in 'Update Cost' Jobs."
 
 	current_boms = {}
@@ -180,9 +178,7 @@
 		handle_exception(update_doc)
 
 
-def queue_bom_cost_jobs(
-	current_boms_list: List[str], update_doc: "BOMUpdateLog", current_level: int
-) -> None:
+def queue_bom_cost_jobs(current_boms_list: list[str], update_doc: "BOMUpdateLog", current_level: int) -> None:
 	"Queue batches of 20k BOMs of the same level to process parallelly"
 	batch_no = 0
 
@@ -266,8 +262,8 @@
 
 
 def get_processed_current_boms(
-	log: Dict[str, Any], bom_batches: Dict[str, Any]
-) -> Tuple[List[str], Dict[str, Any]]:
+	log: dict[str, Any], bom_batches: dict[str, Any]
+) -> tuple[list[str], dict[str, Any]]:
 	"""
 	Aggregate all BOMs from BOM Update Batch rows into 'processed_boms' field
 	and into current boms list.
diff --git a/erpnext/manufacturing/doctype/bom_update_log/bom_updation_utils.py b/erpnext/manufacturing/doctype/bom_update_log/bom_updation_utils.py
index f013b88..fed7a00 100644
--- a/erpnext/manufacturing/doctype/bom_update_log/bom_updation_utils.py
+++ b/erpnext/manufacturing/doctype/bom_update_log/bom_updation_utils.py
@@ -4,7 +4,7 @@
 import copy
 import json
 from collections import defaultdict
-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
+from typing import TYPE_CHECKING, Any
 
 if TYPE_CHECKING:
 	from erpnext.manufacturing.doctype.bom_update_log.bom_update_log import BOMUpdateLog
@@ -13,7 +13,7 @@
 from frappe import _
 
 
-def replace_bom(boms: Dict, log_name: str) -> None:
+def replace_bom(boms: dict, log_name: str) -> None:
 	"Replace current BOM with new BOM in parent BOMs."
 
 	current_bom = boms.get("current_bom")
@@ -43,9 +43,7 @@
 		bom_obj.save_version()
 
 
-def update_cost_in_level(
-	doc: "BOMUpdateLog", bom_list: List[str], batch_name: Union[int, str]
-) -> None:
+def update_cost_in_level(doc: "BOMUpdateLog", bom_list: list[str], batch_name: int | str) -> None:
 	"Updates Cost for BOMs within a given level. Runs via background jobs."
 
 	try:
@@ -69,7 +67,7 @@
 			frappe.db.commit()  # nosemgrep
 
 
-def get_ancestor_boms(new_bom: str, bom_list: Optional[List] = None) -> List:
+def get_ancestor_boms(new_bom: str, bom_list: list | None = None) -> list:
 	"Recursively get all ancestors of BOM."
 
 	bom_list = bom_list or []
@@ -101,9 +99,7 @@
 		.set(bom_item.bom_no, new_bom)
 		.set(bom_item.rate, unit_cost)
 		.set(bom_item.amount, (bom_item.stock_qty * unit_cost))
-		.where(
-			(bom_item.bom_no == current_bom) & (bom_item.docstatus < 2) & (bom_item.parenttype == "BOM")
-		)
+		.where((bom_item.bom_no == current_bom) & (bom_item.docstatus < 2) & (bom_item.parenttype == "BOM"))
 	).run()
 
 
@@ -116,7 +112,7 @@
 	return frappe.utils.flt(new_bom_unitcost[0][0])
 
 
-def update_cost_in_boms(bom_list: List[str]) -> None:
+def update_cost_in_boms(bom_list: list[str]) -> None:
 	"Updates cost in given BOMs. Returns current and total updated BOMs."
 
 	for index, bom in enumerate(bom_list):
@@ -128,9 +124,7 @@
 			frappe.db.commit()  # nosemgrep
 
 
-def get_next_higher_level_boms(
-	child_boms: List[str], processed_boms: Dict[str, bool]
-) -> List[str]:
+def get_next_higher_level_boms(child_boms: list[str], processed_boms: dict[str, bool]) -> list[str]:
 	"Generate immediate higher level dependants with no unresolved dependencies (children)."
 
 	def _all_children_are_processed(parent_bom):
@@ -156,7 +150,7 @@
 	return list(resolved_dependants)
 
 
-def get_leaf_boms() -> List[str]:
+def get_leaf_boms() -> list[str]:
 	"Get BOMs that have no dependencies."
 
 	bom = frappe.qb.DocType("BOM")
@@ -209,7 +203,7 @@
 	return child_parent_map, parent_child_map
 
 
-def set_values_in_log(log_name: str, values: Dict[str, Any], commit: bool = False) -> None:
+def set_values_in_log(log_name: str, values: dict[str, Any], commit: bool = False) -> None:
 	"Update BOM Update Log record."
 
 	if not values:
diff --git a/erpnext/manufacturing/doctype/bom_update_log/test_bom_update_log.py b/erpnext/manufacturing/doctype/bom_update_log/test_bom_update_log.py
index 30e6f5e..13bf69f 100644
--- a/erpnext/manufacturing/doctype/bom_update_log/test_bom_update_log.py
+++ b/erpnext/manufacturing/doctype/bom_update_log/test_bom_update_log.py
@@ -81,9 +81,7 @@
 		for item_code in items:
 			remove_bom(item_code)
 
-		bom_tree = {
-			"B-Item A": {"B-Item B": {"B-Item C": {}}, "B-Item D": {"B-Item E": {"B-Item F": {}}}}
-		}
+		bom_tree = {"B-Item A": {"B-Item B": {"B-Item C": {}}, "B-Item D": {"B-Item E": {"B-Item F": {}}}}}
 
 		root_bom = create_nested_bom(bom_tree, prefix="")
 
diff --git a/erpnext/manufacturing/doctype/bom_update_tool/bom_update_tool.py b/erpnext/manufacturing/doctype/bom_update_tool/bom_update_tool.py
index 9552116..2e8dba1 100644
--- a/erpnext/manufacturing/doctype/bom_update_tool/bom_update_tool.py
+++ b/erpnext/manufacturing/doctype/bom_update_tool/bom_update_tool.py
@@ -2,7 +2,7 @@
 # For license information, please see license.txt
 
 import json
-from typing import TYPE_CHECKING, Dict, Literal, Optional, Union
+from typing import TYPE_CHECKING, Literal
 
 if TYPE_CHECKING:
 	from erpnext.manufacturing.doctype.bom_update_log.bom_update_log import BOMUpdateLog
@@ -28,9 +28,7 @@
 
 
 @frappe.whitelist()
-def enqueue_replace_bom(
-	boms: Optional[Union[Dict, str]] = None, args: Optional[Union[Dict, str]] = None
-) -> "BOMUpdateLog":
+def enqueue_replace_bom(boms: dict | str | None = None, args: dict | str | None = None) -> "BOMUpdateLog":
 	"""Returns a BOM Update Log (that queues a job) for BOM Replacement."""
 	boms = boms or args
 	if isinstance(boms, str):
@@ -60,7 +58,7 @@
 
 
 def create_bom_update_log(
-	boms: Optional[Dict[str, str]] = None,
+	boms: dict[str, str] | None = None,
 	update_type: Literal["Replace BOM", "Update Cost"] = "Replace BOM",
 ) -> "BOMUpdateLog":
 	"""Creates a BOM Update Log that handles the background job."""
diff --git a/erpnext/manufacturing/doctype/job_card/job_card.py b/erpnext/manufacturing/doctype/job_card/job_card.py
index 5a072b5..11894a0 100644
--- a/erpnext/manufacturing/doctype/job_card/job_card.py
+++ b/erpnext/manufacturing/doctype/job_card/job_card.py
@@ -128,9 +128,7 @@
 	# end: auto-generated types
 
 	def onload(self):
-		excess_transfer = frappe.db.get_single_value(
-			"Manufacturing Settings", "job_card_excess_transfer"
-		)
+		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_closed", self.is_work_order_closed())
 		self.set_onload("has_stock_entry", self.has_stock_entry())
@@ -159,9 +157,7 @@
 
 		wo_qty = flt(frappe.get_cached_value("Work Order", self.work_order, "qty"))
 
-		completed_qty = flt(
-			frappe.db.get_value("Work Order Operation", self.operation_id, "completed_qty")
-		)
+		completed_qty = flt(frappe.db.get_value("Work Order Operation", self.operation_id, "completed_qty"))
 
 		over_production_percentage = flt(
 			frappe.db.get_single_value("Manufacturing Settings", "overproduction_percentage_for_work_order")
@@ -454,7 +450,9 @@
 
 				# If remaining time fit in workstation time logs else split hours as per workstation time
 				if time_in_mins > row.remaining_time_in_mins:
-					row.planned_end_time = add_to_date(row.planned_start_time, minutes=row.remaining_time_in_mins)
+					row.planned_end_time = add_to_date(
+						row.planned_start_time, minutes=row.remaining_time_in_mins
+					)
 					row.remaining_time_in_mins = 0
 				else:
 					row.planned_end_time = add_to_date(row.planned_start_time, minutes=time_in_mins)
@@ -574,7 +572,9 @@
 					row.completed_time = row.completed_time / len(set(operation_deatils.employee))
 
 					if operation_deatils.completed_qty:
-						row.completed_qty = operation_deatils.completed_qty / len(set(operation_deatils.employee))
+						row.completed_qty = operation_deatils.completed_qty / len(
+							set(operation_deatils.employee)
+						)
 			else:
 				row.status = "Pending"
 				row.completed_time = 0.0
@@ -646,10 +646,7 @@
 			)
 
 	def validate_job_card(self):
-		if (
-			self.work_order
-			and frappe.get_cached_value("Work Order", self.work_order, "status") == "Stopped"
-		):
+		if self.work_order and frappe.get_cached_value("Work Order", self.work_order, "status") == "Stopped":
 			frappe.throw(
 				_("Transaction not allowed against stopped Work Order {0}").format(
 					get_link_to_form("Work Order", self.work_order)
@@ -668,9 +665,7 @@
 			flt(self.total_completed_qty, precision) + flt(self.process_loss_qty, precision)
 		)
 
-		if self.for_quantity and flt(total_completed_qty, precision) != flt(
-			self.for_quantity, precision
-		):
+		if self.for_quantity and flt(total_completed_qty, precision) != flt(self.for_quantity, precision):
 			total_completed_qty_label = bold(_("Total Completed Qty"))
 			qty_to_manufacture = bold(_("Qty to Manufacture"))
 
@@ -730,9 +725,8 @@
 			return
 
 		for_quantity, time_in_mins, process_loss_qty = 0, 0, 0
-		from_time_list, to_time_list = [], []
+		_from_time_list, _to_time_list = [], []
 
-		field = "operation_id"
 		data = self.get_current_operation_data()
 		if data and len(data) > 0:
 			for_quantity = flt(data[0].completed_qty)
@@ -768,9 +762,7 @@
 		if wo.produced_qty > for_quantity + process_loss_qty:
 			first_part_msg = _(
 				"The {0} {1} is used to calculate the valuation cost for the finished good {2}."
-			).format(
-				frappe.bold(_("Job Card")), frappe.bold(self.name), frappe.bold(self.production_item)
-			)
+			).format(frappe.bold(_("Job Card")), frappe.bold(self.name), frappe.bold(self.production_item))
 
 			second_part_msg = _(
 				"Kindly cancel the Manufacturing Entries first against the work order {0}."
@@ -837,9 +829,7 @@
 			from frappe.query_builder.functions import Sum
 
 			job_card_items_transferred_qty = {}
-			job_card_items = [
-				x.get("job_card_item") for x in ste_doc.get("items") if x.get("job_card_item")
-			]
+			job_card_items = [x.get("job_card_item") for x in ste_doc.get("items") if x.get("job_card_item")]
 
 			if job_card_items:
 				se = frappe.qb.DocType("Stock Entry")
@@ -972,9 +962,7 @@
 
 	def set_wip_warehouse(self):
 		if not self.wip_warehouse:
-			self.wip_warehouse = frappe.db.get_single_value(
-				"Manufacturing Settings", "default_wip_warehouse"
-			)
+			self.wip_warehouse = frappe.db.get_single_value("Manufacturing Settings", "default_wip_warehouse")
 
 	def validate_operation_id(self):
 		if (
@@ -1014,7 +1002,7 @@
 			order_by="sequence_id, idx",
 		)
 
-		message = "Job Card {0}: As per the sequence of the operations in the work order {1}".format(
+		message = "Job Card {}: As per the sequence of the operations in the work order {}".format(
 			bold(self.name), bold(get_link_to_form("Work Order", self.work_order))
 		)
 
@@ -1085,7 +1073,7 @@
 		return []
 	args = {"parent": filters.get("work_order")}
 	if txt:
-		args["operation"] = ("like", "%{0}%".format(txt))
+		args["operation"] = ("like", f"%{txt}%")
 
 	return frappe.get_all(
 		"Work Order Operation",
@@ -1206,16 +1194,14 @@
 	conditions = get_filters_cond("Job Card", filters, [])
 
 	job_cards = frappe.db.sql(
-		""" SELECT `tabJob Card`.name, `tabJob Card`.work_order,
+		f""" SELECT `tabJob Card`.name, `tabJob Card`.work_order,
 			`tabJob Card`.status, ifnull(`tabJob Card`.remarks, ''),
 			min(`tabJob Card Time Log`.from_time) as from_time,
 			max(`tabJob Card Time Log`.to_time) as to_time
 		FROM `tabJob Card` , `tabJob Card Time Log`
 		WHERE
-			`tabJob Card`.name = `tabJob Card Time Log`.parent {0}
-			group by `tabJob Card`.name""".format(
-			conditions
-		),
+			`tabJob Card`.name = `tabJob Card Time Log`.parent {conditions}
+			group by `tabJob Card`.name""",
 		as_dict=1,
 	)
 
diff --git a/erpnext/manufacturing/doctype/job_card/test_job_card.py b/erpnext/manufacturing/doctype/job_card/test_job_card.py
index bde0548..b0644b4 100644
--- a/erpnext/manufacturing/doctype/job_card/test_job_card.py
+++ b/erpnext/manufacturing/doctype/job_card/test_job_card.py
@@ -59,7 +59,6 @@
 		frappe.db.rollback()
 
 	def test_job_card_operations(self):
-
 		job_cards = frappe.get_all(
 			"Job Card", filters={"work_order": self.work_order.name}, fields=["operation_id", "name"]
 		)
@@ -252,7 +251,6 @@
 
 	@change_settings("Manufacturing Settings", {"job_card_excess_transfer": 0})
 	def test_job_card_excess_material_transfer_block(self):
-
 		self.transfer_material_against = "Job Card"
 		self.source_warehouse = "Stores - _TC"
 
@@ -276,7 +274,6 @@
 
 	@change_settings("Manufacturing Settings", {"job_card_excess_transfer": 0})
 	def test_job_card_excess_material_transfer_with_no_reference(self):
-
 		self.transfer_material_against = "Job Card"
 		self.source_warehouse = "Stores - _TC"
 
diff --git a/erpnext/manufacturing/doctype/manufacturing_settings/manufacturing_settings.py b/erpnext/manufacturing/doctype/manufacturing_settings/manufacturing_settings.py
index 9a50111..84dbce2 100644
--- a/erpnext/manufacturing/doctype/manufacturing_settings/manufacturing_settings.py
+++ b/erpnext/manufacturing/doctype/manufacturing_settings/manufacturing_settings.py
@@ -42,8 +42,7 @@
 
 def get_mins_between_operations():
 	return relativedelta(
-		minutes=cint(frappe.db.get_single_value("Manufacturing Settings", "mins_between_operations"))
-		or 10
+		minutes=cint(frappe.db.get_single_value("Manufacturing Settings", "mins_between_operations")) or 10
 	)
 
 
diff --git a/erpnext/manufacturing/doctype/plant_floor/plant_floor.py b/erpnext/manufacturing/doctype/plant_floor/plant_floor.py
index d30b7d1..e6fcf1a 100644
--- a/erpnext/manufacturing/doctype/plant_floor/plant_floor.py
+++ b/erpnext/manufacturing/doctype/plant_floor/plant_floor.py
@@ -67,22 +67,15 @@
 
 @frappe.whitelist()
 def get_stock_summary(warehouse, start=0, item_code=None, item_group=None):
-	stock_details = get_stock_details(
-		warehouse, start=start, item_code=item_code, item_group=item_group
-	)
+	stock_details = get_stock_details(warehouse, start=start, item_code=item_code, item_group=item_group)
 
 	max_count = 0.0
 	for d in stock_details:
 		d.actual_or_pending = (
-			d.projected_qty
-			+ d.reserved_qty
-			+ d.reserved_qty_for_production
-			+ d.reserved_qty_for_sub_contract
+			d.projected_qty + d.reserved_qty + d.reserved_qty_for_production + d.reserved_qty_for_sub_contract
 		)
 		d.pending_qty = 0
-		d.total_reserved = (
-			d.reserved_qty + d.reserved_qty_for_production + d.reserved_qty_for_sub_contract
-		)
+		d.total_reserved = d.reserved_qty + d.reserved_qty_for_production + d.reserved_qty_for_sub_contract
 		if d.actual_or_pending > d.actual_qty:
 			d.pending_qty = d.actual_or_pending - d.actual_qty
 
diff --git a/erpnext/manufacturing/doctype/production_plan/production_plan.py b/erpnext/manufacturing/doctype/production_plan/production_plan.py
index c852f84..82075ad 100644
--- a/erpnext/manufacturing/doctype/production_plan/production_plan.py
+++ b/erpnext/manufacturing/doctype/production_plan/production_plan.py
@@ -387,9 +387,7 @@
 		if not self.get("material_requests") or not self.get_so_mr_list(
 			"material_request", "material_requests"
 		):
-			frappe.throw(
-				_("Please fill the Material Requests table"), title=_("Material Requests Required")
-			)
+			frappe.throw(_("Please fill the Material Requests table"), title=_("Material Requests Required"))
 
 		mr_list = self.get_so_mr_list("material_request", "material_requests")
 
@@ -667,7 +665,10 @@
 				item_dict[(d.item_code, d.material_request_item, d.warehouse)] = item_details
 			else:
 				item_details.update(
-					{"qty": flt(item_dict.get(key, {}).get("qty")) + (flt(d.planned_qty) - flt(d.ordered_qty))}
+					{
+						"qty": flt(item_dict.get(key, {}).get("qty"))
+						+ (flt(d.planned_qty) - flt(d.ordered_qty))
+					}
 				)
 				item_dict[key] = item_details
 
@@ -693,7 +694,7 @@
 	def make_work_order_for_finished_goods(self, wo_list, default_warehouses):
 		items_data = self.get_production_items()
 
-		for key, item in items_data.items():
+		for _key, item in items_data.items():
 			if self.sub_assembly_items:
 				item["use_multi_level_bom"] = 0
 
@@ -880,7 +881,7 @@
 
 		if material_request_list:
 			material_request_list = [
-				"""<a href="/app/Form/Material Request/{0}">{1}</a>""".format(m.name, m.name)
+				f"""<a href="/app/Form/Material Request/{m.name}">{m.name}</a>"""
 				for m in material_request_list
 			]
 			msgprint(_("{0} created").format(comma_and(material_request_list)))
@@ -1006,9 +1007,7 @@
 		return sub_assembly_items_store
 
 	def all_items_completed(self):
-		all_items_produced = all(
-			flt(d.planned_qty) - flt(d.produced_qty) < 0.000001 for d in self.po_items
-		)
+		all_items_produced = all(flt(d.planned_qty) - flt(d.produced_qty) < 0.000001 for d in self.po_items)
 		if not all_items_produced:
 			return False
 
@@ -1051,9 +1050,7 @@
 
 	doc.warehouse = None
 	frappe.flags.show_qty_in_stock_uom = 1
-	items = get_items_for_material_requests(
-		doc, warehouses=warehouses, get_parent_warehouse_data=True
-	)
+	items = get_items_for_material_requests(doc, warehouses=warehouses, get_parent_warehouse_data=True)
 
 	for d in items:
 		item_list.append(
@@ -1097,9 +1094,7 @@
 	build_csv_response(item_list, doc.name)
 
 
-def get_exploded_items(
-	item_details, company, bom_no, include_non_stock_items, planned_qty=1, doc=None
-):
+def get_exploded_items(item_details, company, bom_no, include_non_stock_items, planned_qty=1, doc=None):
 	bei = frappe.qb.DocType("BOM Explosion Item")
 	bom = frappe.qb.DocType("BOM")
 	item = frappe.qb.DocType("Item")
@@ -1252,11 +1247,7 @@
 	elif total_qty > bin_dict.get("projected_qty", 0):
 		required_qty = total_qty - bin_dict.get("projected_qty", 0)
 
-	if (
-		doc.get("consider_minimum_order_qty")
-		and required_qty > 0
-		and required_qty < row["min_order_qty"]
-	):
+	if doc.get("consider_minimum_order_qty") and required_qty > 0 and required_qty < row["min_order_qty"]:
 		required_qty = row["min_order_qty"]
 
 	item_group_defaults = get_item_group_defaults(row.item_code, company)
@@ -1280,9 +1271,7 @@
 	if include_safety_stock:
 		required_qty += flt(row["safety_stock"])
 
-	item_details = frappe.get_cached_value(
-		"Item", row.item_code, ["purchase_uom", "stock_uom"], as_dict=1
-	)
+	item_details = frappe.get_cached_value("Item", row.item_code, ["purchase_uom", "stock_uom"], as_dict=1)
 
 	conversion_factor = 1.0
 	if (
@@ -1335,7 +1324,9 @@
 			& (pi.parent_item == so_item.item_code)
 			& (
 				ExistsCriterion(
-					frappe.qb.from_(bom).select(bom.name).where((bom.item == pi.item_code) & (bom.is_active == 1))
+					frappe.qb.from_(bom)
+					.select(bom.name)
+					.where((bom.item == pi.item_code) & (bom.is_active == 1))
 				)
 			)
 		)
@@ -1378,7 +1369,7 @@
 		)
 
 	open_so_query = open_so_query.where(
-		(ExistsCriterion(open_so_subquery1) | ExistsCriterion(open_so_subquery2))
+		ExistsCriterion(open_so_subquery1) | ExistsCriterion(open_so_subquery2)
 	)
 
 	open_so = open_so_query.run(as_dict=True)
@@ -1500,9 +1491,7 @@
 			data["include_exploded_items"] = 1
 
 		planned_qty = data.get("required_qty") or data.get("planned_qty")
-		ignore_existing_ordered_qty = (
-			data.get("ignore_existing_ordered_qty") or ignore_existing_ordered_qty
-		)
+		ignore_existing_ordered_qty = data.get("ignore_existing_ordered_qty") or ignore_existing_ordered_qty
 		warehouse = doc.get("for_warehouse")
 
 		item_details = {}
@@ -1535,7 +1524,12 @@
 				elif data.get("include_exploded_items") and include_subcontracted_items:
 					# fetch exploded items from BOM
 					item_details = get_exploded_items(
-						item_details, company, bom_no, include_non_stock_items, planned_qty=planned_qty, doc=doc
+						item_details,
+						company,
+						bom_no,
+						include_non_stock_items,
+						planned_qty=planned_qty,
+						doc=doc,
 					)
 				else:
 					item_details = get_subitems(
@@ -1690,7 +1684,7 @@
 
 	return {
 		"bom_no": item_details.get("bom_no"),
-		"stock_uom": item_details.get("stock_uom")
+		"stock_uom": item_details.get("stock_uom"),
 		# 		"description": item_details.get("description")
 	}
 
@@ -1733,7 +1727,9 @@
 				)
 
 				if d.value:
-					get_sub_assembly_items(d.value, bom_data, stock_qty, company, warehouse, indent=indent + 1)
+					get_sub_assembly_items(
+						d.value, bom_data, stock_qty, company, warehouse, indent=indent + 1
+					)
 
 
 def set_default_warehouses(row, default_warehouses):
@@ -1875,9 +1871,7 @@
 
 
 @frappe.whitelist()
-def sales_order_query(
-	doctype=None, txt=None, searchfield=None, start=None, page_len=None, filters=None
-):
+def sales_order_query(doctype=None, txt=None, searchfield=None, start=None, page_len=None, filters=None):
 	frappe.has_permission("Production Plan", throw=True)
 
 	if not filters:
diff --git a/erpnext/manufacturing/doctype/production_plan/test_production_plan.py b/erpnext/manufacturing/doctype/production_plan/test_production_plan.py
index 0bf3705..8957c11 100644
--- a/erpnext/manufacturing/doctype/production_plan/test_production_plan.py
+++ b/erpnext/manufacturing/doctype/production_plan/test_production_plan.py
@@ -110,9 +110,7 @@
 	def test_production_plan_start_date(self):
 		"Test if Work Order has same Planned Start Date as Prod Plan."
 		planned_date = add_to_date(date=None, days=3)
-		plan = create_production_plan(
-			item_code="Test Production Item 1", planned_start_date=planned_date
-		)
+		plan = create_production_plan(item_code="Test Production Item 1", planned_start_date=planned_date)
 		plan.make_work_order()
 
 		work_orders = frappe.get_all(
@@ -213,9 +211,7 @@
 		)
 
 		wo_doc = frappe.get_doc("Work Order", work_order)
-		wo_doc.update(
-			{"wip_warehouse": "Work In Progress - _TC", "fg_warehouse": "Finished Goods - _TC"}
-		)
+		wo_doc.update({"wip_warehouse": "Work In Progress - _TC", "fg_warehouse": "Finished Goods - _TC"})
 		wo_doc.submit()
 
 		so_wo_qty = frappe.db.get_value("Sales Order Item", sales_order_item, "work_order_qty")
@@ -400,7 +396,7 @@
 		from erpnext.manufacturing.doctype.bom.test_bom import create_nested_bom
 
 		bom_tree_1 = {"Test Laptop": {"Test Motherboard": {"Test Motherboard Wires": {}}}}
-		bom = create_nested_bom(bom_tree_1, prefix="")
+		create_nested_bom(bom_tree_1, prefix="")
 
 		item_doc = frappe.get_doc("Item", "Test Motherboard")
 		company = "_Test Company"
@@ -515,14 +511,10 @@
 
 	def test_pp_to_mr_customer_provided(self):
 		"Test Material Request from Production Plan for Customer Provided Item."
-		create_item(
-			"CUST-0987", is_customer_provided_item=1, customer="_Test Customer", is_purchase_item=0
-		)
+		create_item("CUST-0987", is_customer_provided_item=1, customer="_Test Customer", is_purchase_item=0)
 		create_item("Production Item CUST")
 
-		for item, raw_materials in {
-			"Production Item CUST": ["Raw Material Item 1", "CUST-0987"]
-		}.items():
+		for item, raw_materials in {"Production Item CUST": ["Raw Material Item 1", "CUST-0987"]}.items():
 			if not frappe.db.get_value("BOM", {"item": item}):
 				make_bom(item=item, raw_materials=raw_materials)
 		production_plan = create_production_plan(item_code="Production Item CUST")
@@ -675,7 +667,7 @@
 			items_data[(pln.po_items[0].name, item, None)]["qty"] = qty
 
 			# Create and Submit Work Order for each item in items_data
-			for key, item in items_data.items():
+			for _key, item in items_data.items():
 				if pln.sub_assembly_items:
 					item["use_multi_level_bom"] = 0
 
@@ -844,7 +836,6 @@
 		self.assertEqual(pln.po_items[0].planned_qty, 0.55)
 
 	def test_temporary_name_relinking(self):
-
 		pp = frappe.new_doc("Production Plan")
 
 		# this can not be unittested so mocking data that would be expected
@@ -860,7 +851,7 @@
 			pp.append("sub_assembly_items", {"production_plan_item": po_item.temporary_name})
 		pp._rename_temporary_references()
 
-		for po_item, subassy_item in zip(pp.po_items, pp.sub_assembly_items):
+		for po_item, subassy_item in zip(pp.po_items, pp.sub_assembly_items, strict=False):
 			self.assertEqual(po_item.name, subassy_item.production_plan_item)
 
 		# bad links should be erased
@@ -871,7 +862,7 @@
 
 		# reattempting on same doc shouldn't change anything
 		pp._rename_temporary_references()
-		for po_item, subassy_item in zip(pp.po_items, pp.sub_assembly_items):
+		for po_item, subassy_item in zip(pp.po_items, pp.sub_assembly_items, strict=False):
 			self.assertEqual(po_item.name, subassy_item.production_plan_item)
 
 	def test_produced_qty_for_multi_level_bom_item(self):
@@ -1148,9 +1139,7 @@
 			wo_doc.fg_warehouse = "_Test Warehouse - _TC"
 			wo_doc.submit()
 
-		reserved_qty_after_mr = flt(
-			frappe.db.get_value("Bin", bin_name, "reserved_qty_for_production_plan")
-		)
+		reserved_qty_after_mr = flt(frappe.db.get_value("Bin", bin_name, "reserved_qty_for_production_plan"))
 		self.assertEqual(reserved_qty_after_mr, before_qty)
 
 	def test_from_warehouse_for_purchase_material_request(self):
@@ -1158,7 +1147,7 @@
 		from erpnext.stock.utils import get_or_make_bin
 
 		create_item("RM-TEST-123 For Purchase", valuation_rate=100)
-		bin_name = get_or_make_bin("RM-TEST-123 For Purchase", "_Test Warehouse - _TC")
+		get_or_make_bin("RM-TEST-123 For Purchase", "_Test Warehouse - _TC")
 		t_warehouse = create_warehouse("_Test Store - _TC")
 		make_stock_entry(
 			item_code="Raw Material Item 1",
@@ -1168,9 +1157,7 @@
 		)
 
 		plan = create_production_plan(item_code="Test Production Item 1", do_not_save=1)
-		mr_items = get_items_for_material_requests(
-			plan.as_dict(), warehouses=[{"warehouse": t_warehouse}]
-		)
+		mr_items = get_items_for_material_requests(plan.as_dict(), warehouses=[{"warehouse": t_warehouse}])
 
 		for d in mr_items:
 			plan.append("mr_items", d)
@@ -1468,9 +1455,7 @@
 		)
 
 		pln.for_warehouse = rm_warehouse
-		items = get_items_for_material_requests(
-			pln.as_dict(), warehouses=[{"warehouse": store_warehouse}]
-		)
+		items = get_items_for_material_requests(pln.as_dict(), warehouses=[{"warehouse": store_warehouse}])
 
 		for row in items:
 			self.assertEqual(row.get("quantity"), 10.0)
@@ -1479,9 +1464,7 @@
 			self.assertEqual(row.get("from_warehouse"), store_warehouse)
 			self.assertEqual(row.get("conversion_factor"), 1.0)
 
-		items = get_items_for_material_requests(
-			pln.as_dict(), warehouses=[{"warehouse": pln.for_warehouse}]
-		)
+		items = get_items_for_material_requests(pln.as_dict(), warehouses=[{"warehouse": pln.for_warehouse}])
 
 		for row in items:
 			self.assertEqual(row.get("quantity"), 1.0)
@@ -1496,7 +1479,7 @@
 		fg_item = make_item(properties={"is_stock_item": 1, "stock_uom": "_Test UOM 1"}).name
 		rm_item = make_item(properties={"is_stock_item": 1, "stock_uom": "_Test UOM 1"}).name
 
-		store_warehouse = create_warehouse("Store Warehouse", company="_Test Company")
+		create_warehouse("Store Warehouse", company="_Test Company")
 		rm_warehouse = create_warehouse("RM Warehouse", company="_Test Company")
 
 		make_bom(item=fg_item, raw_materials=[rm_item], source_warehouse="_Test Warehouse - _TC")
@@ -1532,7 +1515,6 @@
 
 	def test_min_order_qty_in_pp(self):
 		from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse
-		from erpnext.stock.utils import get_or_make_bin
 
 		fg_item = make_item(properties={"is_stock_item": 1}).name
 		rm_item = make_item(properties={"is_stock_item": 1, "min_order_qty": 1000}).name
@@ -1554,9 +1536,6 @@
 			self.assertEqual(d.get("quantity"), 1000.0)
 
 	def test_fg_item_quantity(self):
-		from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse
-		from erpnext.stock.utils import get_or_make_bin
-
 		fg_item = make_item(properties={"is_stock_item": 1}).name
 		rm_item = make_item(properties={"is_stock_item": 1}).name
 
diff --git a/erpnext/manufacturing/doctype/routing/routing.py b/erpnext/manufacturing/doctype/routing/routing.py
index 4bef380..70a2a19 100644
--- a/erpnext/manufacturing/doctype/routing/routing.py
+++ b/erpnext/manufacturing/doctype/routing/routing.py
@@ -47,9 +47,9 @@
 				row.sequence_id = sequence_id + 1
 			elif sequence_id and row.sequence_id and cint(sequence_id) > cint(row.sequence_id):
 				frappe.throw(
-					_("At row #{0}: the sequence id {1} cannot be less than previous row sequence id {2}").format(
-						row.idx, row.sequence_id, sequence_id
-					)
+					_(
+						"At row #{0}: the sequence id {1} cannot be less than previous row sequence id {2}"
+					).format(row.idx, row.sequence_id, sequence_id)
 				)
 
 			sequence_id = row.sequence_id
diff --git a/erpnext/manufacturing/doctype/work_order/test_work_order.py b/erpnext/manufacturing/doctype/work_order/test_work_order.py
index b56e9e1..e451898 100644
--- a/erpnext/manufacturing/doctype/work_order/test_work_order.py
+++ b/erpnext/manufacturing/doctype/work_order/test_work_order.py
@@ -1,7 +1,6 @@
 # Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors
 # License: GNU General Public License v3. See license.txt
 
-import copy
 
 import frappe
 from frappe.tests.utils import FrappeTestCase, change_settings, timeout
@@ -45,7 +44,6 @@
 		frappe.db.rollback()
 
 	def check_planned_qty(self):
-
 		planned0 = (
 			frappe.db.get_value(
 				"Bin", {"item_code": "_Test FG Item", "warehouse": "_Test Warehouse 1 - _TC"}, "planned_qty"
@@ -134,9 +132,7 @@
 		# reserved qty for production is updated
 		self.assertEqual(cint(bin1_at_start.reserved_qty_for_production) + 2, reserved_qty_on_submission)
 
-		test_stock_entry.make_stock_entry(
-			item_code="_Test Item", target=warehouse, qty=100, basic_rate=100
-		)
+		test_stock_entry.make_stock_entry(item_code="_Test Item", target=warehouse, qty=100, basic_rate=100)
 		test_stock_entry.make_stock_entry(
 			item_code="_Test Item Home Desktop 100", target=warehouse, qty=100, basic_rate=100
 		)
@@ -146,9 +142,7 @@
 
 		bin1_at_completion = get_bin(item, warehouse)
 
-		self.assertEqual(
-			cint(bin1_at_completion.reserved_qty_for_production), reserved_qty_on_submission - 1
-		)
+		self.assertEqual(cint(bin1_at_completion.reserved_qty_for_production), reserved_qty_on_submission - 1)
 
 	def test_production_item(self):
 		wo_order = make_wo_order_test_record(item="_Test FG Item", qty=1, do_not_save=True)
@@ -183,9 +177,7 @@
 			cint(self.bin1_at_start.reserved_qty_for_production) + 2,
 			cint(self.bin1_on_submit.reserved_qty_for_production),
 		)
-		self.assertEqual(
-			cint(self.bin1_at_start.projected_qty), cint(self.bin1_on_submit.projected_qty) + 2
-		)
+		self.assertEqual(cint(self.bin1_at_start.projected_qty), cint(self.bin1_on_submit.projected_qty) + 2)
 
 	def test_reserved_qty_for_production_cancel(self):
 		self.test_reserved_qty_for_production_submit()
@@ -239,7 +231,6 @@
 		)
 
 	def test_reserved_qty_for_production_closed(self):
-
 		wo1 = make_wo_order_test_record(item="_Test FG Item", qty=2, source_warehouse=self.warehouse)
 		item = wo1.required_items[0].item_code
 		bin_before = get_bin(item, self.warehouse)
@@ -371,7 +362,9 @@
 		for item in s.items:
 			if item.bom_no and item.item_code in scrap_item_details:
 				self.assertEqual(wo_order_details.scrap_warehouse, item.t_warehouse)
-				self.assertEqual(flt(wo_order_details.qty) * flt(scrap_item_details[item.item_code]), item.qty)
+				self.assertEqual(
+					flt(wo_order_details.qty) * flt(scrap_item_details[item.item_code]), item.qty
+				)
 
 	def test_allow_overproduction(self):
 		allow_overproduction("overproduction_percentage_for_work_order", 0)
@@ -485,7 +478,7 @@
 		)
 		self.assertEqual(len(job_cards), len(bom.operations))
 
-		for i, job_card in enumerate(job_cards):
+		for _i, job_card in enumerate(job_cards):
 			doc = frappe.get_doc("Job Card", job_card)
 			for row in doc.scheduled_time_logs:
 				doc.append(
@@ -585,9 +578,7 @@
 		for item in ["Test Batch Size Item For BOM", "Test Batch Size Item RM 1 For BOM"]:
 			make_item(item, {"include_item_in_manufacturing": 1, "is_stock_item": 1})
 
-		bom_name = frappe.db.get_value(
-			"BOM", {"item": fg_item, "is_active": 1, "with_operations": 1}, "name"
-		)
+		bom_name = frappe.db.get_value("BOM", {"item": fg_item, "is_active": 1, "with_operations": 1}, "name")
 
 		if not bom_name:
 			bom = make_bom(item=fg_item, rate=1000, raw_materials=[rm1], do_not_save=True)
@@ -639,9 +630,7 @@
 
 			make_item(item, item_args)
 
-		bom_name = frappe.db.get_value(
-			"BOM", {"item": fg_item, "is_active": 1, "with_operations": 1}, "name"
-		)
+		bom_name = frappe.db.get_value("BOM", {"item": fg_item, "is_active": 1, "with_operations": 1}, "name")
 
 		if not bom_name:
 			bom = make_bom(item=fg_item, rate=1000, raw_materials=[rm1], do_not_save=True)
@@ -867,7 +856,6 @@
 		)
 
 		qty = 10
-		scrap_qty = 0.25  # bom item qty = 1, consider as 25% of FG
 		source_warehouse = "Stores - _TC"
 		wip_warehouse = "_Test Warehouse - _TC"
 		fg_item_non_whole, _, bom_item = create_process_loss_bom_items()
@@ -1755,9 +1743,7 @@
 
 		self.assertRaises(frappe.ValidationError, job_card2.save)
 
-		frappe.db.set_single_value(
-			"Manufacturing Settings", "overproduction_percentage_for_work_order", 100
-		)
+		frappe.db.set_single_value("Manufacturing Settings", "overproduction_percentage_for_work_order", 100)
 
 		job_card2 = frappe.copy_doc(job_card_doc)
 		job_card2.time_logs = []
@@ -1766,9 +1752,7 @@
 	def test_op_cost_and_scrap_based_on_sub_assemblies(self):
 		# Make Sub Assembly BOM 1
 
-		frappe.db.set_single_value(
-			"Manufacturing Settings", "set_op_cost_and_scrape_from_sub_assemblies", 1
-		)
+		frappe.db.set_single_value("Manufacturing Settings", "set_op_cost_and_scrape_from_sub_assemblies", 1)
 
 		items = {
 			"Test Final FG Item": 0,
@@ -1784,7 +1768,7 @@
 			if not frappe.db.exists("Item", item):
 				item_properties = {"is_stock_item": 1, "valuation_rate": items[item]}
 
-				make_item(item_code=item, properties=item_properties),
+				(make_item(item_code=item, properties=item_properties),)
 
 		prepare_boms_for_sub_assembly_test()
 
@@ -1805,15 +1789,11 @@
 			if item.is_scrap_item:
 				scrap_items.append(item.item_code)
 
-		self.assertEqual(
-			sorted(scrap_items), sorted(["Test Final Scrap Item 1", "Test Final Scrap Item 2"])
-		)
+		self.assertEqual(sorted(scrap_items), sorted(["Test Final Scrap Item 1", "Test Final Scrap Item 2"]))
 		for row in se_doc.additional_costs:
 			self.assertEqual(row.amount, 3000)
 
-		frappe.db.set_single_value(
-			"Manufacturing Settings", "set_op_cost_and_scrape_from_sub_assemblies", 0
-		)
+		frappe.db.set_single_value("Manufacturing Settings", "set_op_cost_and_scrape_from_sub_assemblies", 0)
 
 	@change_settings(
 		"Manufacturing Settings", {"material_consumption": 1, "get_rm_cost_from_consumption_entry": 1}
@@ -1979,9 +1959,7 @@
 
 		wo_order = make_wo_order_test_record(item=fg_item, qty=10)
 
-		stock_entry = frappe.get_doc(
-			make_stock_entry(wo_order.name, "Material Transfer for Manufacture", 10)
-		)
+		stock_entry = frappe.get_doc(make_stock_entry(wo_order.name, "Material Transfer for Manufacture", 10))
 		stock_entry.submit()
 		stock_entry.reload()
 
diff --git a/erpnext/manufacturing/doctype/work_order/work_order.py b/erpnext/manufacturing/doctype/work_order/work_order.py
index f897a91..0813961 100644
--- a/erpnext/manufacturing/doctype/work_order/work_order.py
+++ b/erpnext/manufacturing/doctype/work_order/work_order.py
@@ -224,9 +224,7 @@
 
 	def set_default_warehouse(self):
 		if not self.wip_warehouse and not self.skip_transfer:
-			self.wip_warehouse = frappe.db.get_single_value(
-				"Manufacturing Settings", "default_wip_warehouse"
-			)
+			self.wip_warehouse = frappe.db.get_single_value("Manufacturing Settings", "default_wip_warehouse")
 		if not self.fg_warehouse:
 			self.fg_warehouse = frappe.db.get_single_value("Manufacturing Settings", "default_fg_warehouse")
 
@@ -286,9 +284,7 @@
 		so_qty = flt(so_item_qty) + flt(dnpi_qty)
 
 		allowance_percentage = flt(
-			frappe.db.get_single_value(
-				"Manufacturing Settings", "overproduction_percentage_for_sales_order"
-			)
+			frappe.db.get_single_value("Manufacturing Settings", "overproduction_percentage_for_sales_order")
 		)
 
 		if total_qty > so_qty + (allowance_percentage / 100 * so_qty):
@@ -424,9 +420,7 @@
 			produced_qty = total_qty[0][0] if total_qty else 0
 
 		self.update_status()
-		production_plan.run_method(
-			"update_produced_pending_qty", produced_qty, self.production_plan_item
-		)
+		production_plan.run_method("update_produced_pending_qty", produced_qty, self.production_plan_item)
 
 	def before_submit(self):
 		self.create_serial_no_batch_no()
@@ -650,9 +644,7 @@
 				get_datetime(self.operations[idx - 1].planned_end_time) + get_mins_between_operations()
 			)
 
-		row.planned_end_time = get_datetime(row.planned_start_time) + relativedelta(
-			minutes=row.time_in_mins
-		)
+		row.planned_end_time = get_datetime(row.planned_start_time) + relativedelta(minutes=row.time_in_mins)
 
 		if row.planned_start_time == row.planned_end_time:
 			frappe.throw(_("Capacity Planning Error, planned start time can not be same as end time"))
@@ -719,11 +711,7 @@
 		)
 
 	def update_ordered_qty(self):
-		if (
-			self.production_plan
-			and self.production_plan_item
-			and not self.production_plan_sub_assembly_item
-		):
+		if self.production_plan and self.production_plan_item and not self.production_plan_sub_assembly_item:
 			table = frappe.qb.DocType("Work Order")
 
 			query = (
@@ -763,11 +751,9 @@
 		cond = "product_bundle_item = %s" if self.product_bundle_item else "production_item = %s"
 
 		qty = frappe.db.sql(
-			""" select sum(qty) from
-			`tabWork Order` where sales_order = %s and docstatus = 1 and {0}
-			""".format(
-				cond
-			),
+			f""" select sum(qty) from
+			`tabWork Order` where sales_order = %s and docstatus = 1 and {cond}
+			""",
 			(self.sales_order, (self.product_bundle_item or self.production_item)),
 			as_list=1,
 		)
@@ -917,9 +903,7 @@
 
 	def set_actual_dates(self):
 		if self.get("operations"):
-			actual_start_dates = [
-				d.actual_start_time for d in self.get("operations") if d.actual_start_time
-			]
+			actual_start_dates = [d.actual_start_time for d in self.get("operations") if d.actual_start_time]
 			if actual_start_dates:
 				self.actual_start_date = min(actual_start_dates)
 
@@ -964,11 +948,7 @@
 		if self.qty <= 0:
 			frappe.throw(_("Quantity to Manufacture must be greater than 0."))
 
-		if (
-			self.production_plan
-			and self.production_plan_item
-			and not self.production_plan_sub_assembly_item
-		):
+		if self.production_plan and self.production_plan_item and not self.production_plan_sub_assembly_item:
 			qty_dict = frappe.db.get_value(
 				"Production Plan Item", self.production_plan_item, ["planned_qty", "ordered_qty"], as_dict=1
 			)
@@ -1104,7 +1084,7 @@
 		query = (
 			frappe.qb.from_(ste)
 			.inner_join(ste_child)
-			.on((ste_child.parent == ste.name))
+			.on(ste_child.parent == ste.name)
 			.select(
 				ste_child.item_code,
 				ste_child.original_item,
@@ -1134,7 +1114,7 @@
 		query = (
 			frappe.qb.from_(ste)
 			.inner_join(ste_child)
-			.on((ste_child.parent == ste.name))
+			.on(ste_child.parent == ste.name)
 			.select(
 				ste_child.item_code,
 				ste_child.original_item,
@@ -1384,9 +1364,7 @@
 	)
 
 	if work_order.bom_no:
-		stock_entry.inspection_required = frappe.db.get_value(
-			"BOM", work_order.bom_no, "inspection_required"
-		)
+		stock_entry.inspection_required = frappe.db.get_value("BOM", work_order.bom_no, "inspection_required")
 
 	if purpose == "Material Transfer for Manufacture":
 		stock_entry.to_warehouse = wip_warehouse
@@ -1492,9 +1470,7 @@
 
 
 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")
-	):
+	if not cint(frappe.db.get_value("Operation", row.operation, "create_job_card_based_on_batch_size")):
 		row.batch_size = row.get("qty") or wo_doc.qty
 
 	row.job_card_qty = row.batch_size
@@ -1589,9 +1565,7 @@
 			doc.schedule_time_logs(row)
 
 		doc.insert()
-		frappe.msgprint(
-			_("Job card {0} created").format(get_link_to_form("Job Card", doc.name)), alert=True
-		)
+		frappe.msgprint(_("Job card {0} created").format(get_link_to_form("Job Card", doc.name)), alert=True)
 
 	if enable_capacity_planning:
 		# automatically added scheduling rows shouldn't change status to WIP
@@ -1654,7 +1628,7 @@
 def get_reserved_qty_for_production(
 	item_code: str,
 	warehouse: str,
-	non_completed_production_plans: list = None,
+	non_completed_production_plans: list | None = None,
 	check_production_plan: bool = False,
 ) -> float:
 	"""Get total reserved quantity for any item in specified warehouse"""
diff --git a/erpnext/manufacturing/doctype/workstation/workstation.py b/erpnext/manufacturing/doctype/workstation/workstation.py
index 3d40a2d..47cb742 100644
--- a/erpnext/manufacturing/doctype/workstation/workstation.py
+++ b/erpnext/manufacturing/doctype/workstation/workstation.py
@@ -134,7 +134,8 @@
 
 			if existing:
 				frappe.throw(
-					_("Row #{0}: Timings conflicts with row {1}").format(d.idx, comma_and(existing)), OverlapError
+					_("Row #{0}: Timings conflicts with row {1}").format(d.idx, comma_and(existing)),
+					OverlapError,
 				)
 
 	def update_bom_operation(self):
@@ -352,7 +353,9 @@
 
 		if applicable_holidays:
 			frappe.throw(
-				_("Workstation is closed on the following dates as per Holiday List: {0}").format(holiday_list)
+				_("Workstation is closed on the following dates as per Holiday List: {0}").format(
+					holiday_list
+				)
 				+ "\n"
 				+ "\n".join(applicable_holidays),
 				WorkstationHolidayError,
diff --git a/erpnext/manufacturing/report/bom_stock_calculated/bom_stock_calculated.py b/erpnext/manufacturing/report/bom_stock_calculated/bom_stock_calculated.py
index 550445c..6bc05a4 100644
--- a/erpnext/manufacturing/report/bom_stock_calculated/bom_stock_calculated.py
+++ b/erpnext/manufacturing/report/bom_stock_calculated/bom_stock_calculated.py
@@ -33,9 +33,7 @@
 		row.item_code,
 		row.description,
 		comma_and(manufacture_details.get(row.item_code, {}).get("manufacturer", []), add_quotes=False),
-		comma_and(
-			manufacture_details.get(row.item_code, {}).get("manufacturer_part", []), add_quotes=False
-		),
+		comma_and(manufacture_details.get(row.item_code, {}).get("manufacturer_part", []), add_quotes=False),
 		qty_per_unit,
 		row.actual_qty,
 		required_qty,
diff --git a/erpnext/manufacturing/report/bom_stock_report/bom_stock_report.py b/erpnext/manufacturing/report/bom_stock_report/bom_stock_report.py
index 3573a3a..48ffbac 100644
--- a/erpnext/manufacturing/report/bom_stock_report/bom_stock_report.py
+++ b/erpnext/manufacturing/report/bom_stock_report/bom_stock_report.py
@@ -44,9 +44,7 @@
 	else:
 		bom_item_table = "BOM Item"
 
-	warehouse_details = frappe.db.get_value(
-		"Warehouse", filters.get("warehouse"), ["lft", "rgt"], as_dict=1
-	)
+	warehouse_details = frappe.db.get_value("Warehouse", filters.get("warehouse"), ["lft", "rgt"], as_dict=1)
 
 	BOM = frappe.qb.DocType("BOM")
 	BOM_ITEM = frappe.qb.DocType(bom_item_table)
diff --git a/erpnext/manufacturing/report/cost_of_poor_quality_report/cost_of_poor_quality_report.py b/erpnext/manufacturing/report/cost_of_poor_quality_report/cost_of_poor_quality_report.py
index 481fe51..a86df31 100644
--- a/erpnext/manufacturing/report/cost_of_poor_quality_report/cost_of_poor_quality_report.py
+++ b/erpnext/manufacturing/report/cost_of_poor_quality_report/cost_of_poor_quality_report.py
@@ -20,9 +20,7 @@
 
 		job_card = frappe.qb.DocType("Job Card")
 
-		operating_cost = ((job_card.hour_rate) * (job_card.total_time_in_mins) / 60.0).as_(
-			"operating_cost"
-		)
+		operating_cost = ((job_card.hour_rate) * (job_card.total_time_in_mins) / 60.0).as_("operating_cost")
 		item_code = (job_card.production_item).as_("item_code")
 
 		query = (
@@ -64,7 +62,7 @@
 	):
 		if report_filters.get(field):
 			if field == "serial_no":
-				query = query.where(job_card[field].like("%{}%".format(report_filters.get(field))))
+				query = query.where(job_card[field].like(f"%{report_filters.get(field)}%"))
 			elif field == "operation":
 				query = query.where(job_card[field].isin(operations))
 			else:
diff --git a/erpnext/manufacturing/report/exponential_smoothing_forecasting/exponential_smoothing_forecasting.py b/erpnext/manufacturing/report/exponential_smoothing_forecasting/exponential_smoothing_forecasting.py
index daef7f6..6d91246 100644
--- a/erpnext/manufacturing/report/exponential_smoothing_forecasting/exponential_smoothing_forecasting.py
+++ b/erpnext/manufacturing/report/exponential_smoothing_forecasting/exponential_smoothing_forecasting.py
@@ -15,9 +15,9 @@
 	return ForecastingReport(filters).execute_report()
 
 
-class ExponentialSmoothingForecast(object):
+class ExponentialSmoothingForecast:
 	def forecast_future_data(self):
-		for key, value in self.period_wise_data.items():
+		for _key, value in self.period_wise_data.items():
 			forecast_data = []
 			for period in self.period_list:
 				forecast_key = "forecast_" + period.key
@@ -185,7 +185,6 @@
 				"Half-Yearly",
 				"Quarterly",
 			] or period.from_date >= getdate(self.filters.from_date):
-
 				forecast_key = period.key
 				label = _(period.label)
 				if period.from_date >= getdate(self.filters.from_date):
diff --git a/erpnext/manufacturing/report/process_loss_report/process_loss_report.py b/erpnext/manufacturing/report/process_loss_report/process_loss_report.py
index c3dd9cf..51efc6e 100644
--- a/erpnext/manufacturing/report/process_loss_report/process_loss_report.py
+++ b/erpnext/manufacturing/report/process_loss_report/process_loss_report.py
@@ -1,7 +1,6 @@
 # Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
 # For license information, please see license.txt
 
-from typing import Dict, List, Tuple
 
 import frappe
 from frappe import _
@@ -9,12 +8,12 @@
 
 Filters = frappe._dict
 Row = frappe._dict
-Data = List[Row]
-Columns = List[Dict[str, str]]
-QueryArgs = Dict[str, str]
+Data = list[Row]
+Columns = list[dict[str, str]]
+QueryArgs = dict[str, str]
 
 
-def execute(filters: Filters) -> Tuple[Columns, Data]:
+def execute(filters: Filters) -> tuple[Columns, Data]:
 	filters = frappe._dict(filters or {})
 	columns = get_columns()
 	data = get_data(filters)
diff --git a/erpnext/manufacturing/report/production_analytics/production_analytics.py b/erpnext/manufacturing/report/production_analytics/production_analytics.py
index 12b5d19..c02c1e6 100644
--- a/erpnext/manufacturing/report/production_analytics/production_analytics.py
+++ b/erpnext/manufacturing/report/production_analytics/production_analytics.py
@@ -20,13 +20,10 @@
 
 	ranges = get_period_date_ranges(filters)
 
-	for dummy, end_date in ranges:
-
+	for _dummy, end_date in ranges:
 		period = get_period(end_date, filters)
 
-		columns.append(
-			{"label": _(period), "fieldname": scrub(period), "fieldtype": "Float", "width": 120}
-		)
+		columns.append({"label": _(period), "fieldname": scrub(period), "fieldtype": "Float", "width": 120})
 
 	return columns
 
@@ -110,7 +107,7 @@
 	for label in labels:
 		work = {}
 		work["Status"] = label
-		for dummy, end_date in ranges:
+		for _dummy, end_date in ranges:
 			period = get_period(end_date, filters)
 			if periodic_data.get(label).get(period):
 				work[scrub(period)] = periodic_data.get(label).get(period)
diff --git a/erpnext/manufacturing/report/production_plan_summary/production_plan_summary.py b/erpnext/manufacturing/report/production_plan_summary/production_plan_summary.py
index 076690f..5bc9236 100644
--- a/erpnext/manufacturing/report/production_plan_summary/production_plan_summary.py
+++ b/erpnext/manufacturing/report/production_plan_summary/production_plan_summary.py
@@ -56,14 +56,10 @@
 			}
 		)
 
-		get_production_plan_sub_assembly_item_details(
-			filters, row, production_plan_doc, data, order_details
-		)
+		get_production_plan_sub_assembly_item_details(filters, row, production_plan_doc, data, order_details)
 
 
-def get_production_plan_sub_assembly_item_details(
-	filters, row, production_plan_doc, data, order_details
-):
+def get_production_plan_sub_assembly_item_details(filters, row, production_plan_doc, data, order_details):
 	for item in production_plan_doc.sub_assembly_items:
 		if row.name == item.production_plan_item:
 			subcontracted_item = item.type_of_manufacturing == "Subcontract"
@@ -76,7 +72,9 @@
 				)
 			else:
 				docname = frappe.get_value(
-					"Work Order", {"production_plan_sub_assembly_item": item.name, "docstatus": ("<", 2)}, "name"
+					"Work Order",
+					{"production_plan_sub_assembly_item": item.name, "docstatus": ("<", 2)},
+					"name",
 				)
 
 			data.append(
@@ -88,7 +86,9 @@
 					"document_type": "Work Order" if not subcontracted_item else "Purchase Order",
 					"document_name": docname or "",
 					"bom_level": item.bom_level,
-					"produced_qty": order_details.get((docname, item.production_item), {}).get("produced_qty", 0),
+					"produced_qty": order_details.get((docname, item.production_item), {}).get(
+						"produced_qty", 0
+					),
 					"pending_qty": flt(item.qty)
 					- flt(order_details.get((docname, item.production_item), {}).get("produced_qty", 0)),
 				}
diff --git a/erpnext/manufacturing/report/production_planning_report/production_planning_report.py b/erpnext/manufacturing/report/production_planning_report/production_planning_report.py
index 109d9ab..63af3e5 100644
--- a/erpnext/manufacturing/report/production_planning_report/production_planning_report.py
+++ b/erpnext/manufacturing/report/production_planning_report/production_planning_report.py
@@ -13,7 +13,7 @@
 	return ProductionPlanReport(filters).execute_report()
 
 
-class ProductionPlanReport(object):
+class ProductionPlanReport:
 	def __init__(self, filters=None):
 		self.filters = frappe._dict(filters or {})
 		self.raw_materials_dict = {}
@@ -79,7 +79,10 @@
 				query = query.where(child.parent.isin(self.filters.docnames))
 
 			if doctype == "Sales Order":
-				query = query.select(child.delivery_date, parent.base_grand_total,).where(
+				query = query.select(
+					child.delivery_date,
+					parent.base_grand_total,
+				).where(
 					(child.stock_qty > child.produced_qty)
 					& (parent.per_delivered < 100.0)
 					& (parent.status.notin(["Completed", "Closed"]))
@@ -91,7 +94,9 @@
 					query = query.orderby(parent.base_grand_total, order=Order.desc)
 
 			elif doctype == "Material Request":
-				query = query.select(child.schedule_date,).where(
+				query = query.select(
+					child.schedule_date,
+				).where(
 					(parent.per_ordered < 100)
 					& (parent.material_request_type == "Manufacture")
 					& (parent.status != "Stopped")
@@ -280,9 +285,7 @@
 			d.remaining_qty = d.required_qty
 			self.pick_materials_from_warehouses(d, data, warehouses)
 
-			if (
-				d.remaining_qty and self.filters.raw_material_warehouse and d.remaining_qty != d.required_qty
-			):
+			if d.remaining_qty and self.filters.raw_material_warehouse and d.remaining_qty != d.required_qty:
 				row = self.get_args()
 				d.warehouse = self.filters.raw_material_warehouse
 				d.required_qty = d.remaining_qty
diff --git a/erpnext/manufacturing/report/test_reports.py b/erpnext/manufacturing/report/test_reports.py
index e436fdc..3e20f31 100644
--- a/erpnext/manufacturing/report/test_reports.py
+++ b/erpnext/manufacturing/report/test_reports.py
@@ -1,5 +1,4 @@
 import unittest
-from typing import List, Tuple
 
 import frappe
 
@@ -13,7 +12,7 @@
 }
 
 
-REPORT_FILTER_TEST_CASES: List[Tuple[ReportName, ReportFilters]] = [
+REPORT_FILTER_TEST_CASES: list[tuple[ReportName, ReportFilters]] = [
 	("BOM Explorer", {"bom": frappe.get_last_doc("BOM").name}),
 	("BOM Operations Time", {}),
 	("BOM Stock Calculated", {"bom": frappe.get_last_doc("BOM").name, "qty_to_make": 2}),
diff --git a/erpnext/manufacturing/report/work_order_consumed_materials/work_order_consumed_materials.py b/erpnext/manufacturing/report/work_order_consumed_materials/work_order_consumed_materials.py
index 14e97d3..64363e2 100644
--- a/erpnext/manufacturing/report/work_order_consumed_materials/work_order_consumed_materials.py
+++ b/erpnext/manufacturing/report/work_order_consumed_materials/work_order_consumed_materials.py
@@ -22,7 +22,7 @@
 	wo_items = {}
 
 	work_orders = frappe.get_all("Work Order", filters=filters, fields=fields)
-	returned_materials = get_returned_materials(work_orders)
+	get_returned_materials(work_orders)
 
 	for d in work_orders:
 		d.extra_consumed_qty = 0.0
@@ -33,7 +33,7 @@
 			wo_items.setdefault((d.name, d.production_item), []).append(d)
 
 	data = []
-	for key, wo_data in wo_items.items():
+	for _key, wo_data in wo_items.items():
 		for index, row in enumerate(wo_data):
 			if index != 0:
 				# If one work order has multiple raw materials then show parent data in the first row only
diff --git a/erpnext/patches/v10_0/item_barcode_childtable_migrate.py b/erpnext/patches/v10_0/item_barcode_childtable_migrate.py
index e2d0943..b98e7ab 100644
--- a/erpnext/patches/v10_0/item_barcode_childtable_migrate.py
+++ b/erpnext/patches/v10_0/item_barcode_childtable_migrate.py
@@ -12,9 +12,7 @@
 	if "barcode" not in frappe.db.get_table_columns("Item"):
 		return
 
-	items_barcode = frappe.db.sql(
-		"select name, barcode from tabItem where barcode is not null", as_dict=True
-	)
+	items_barcode = frappe.db.sql("select name, barcode from tabItem where barcode is not null", as_dict=True)
 	frappe.reload_doc("stock", "doctype", "item")
 
 	for item in items_barcode:
diff --git a/erpnext/patches/v10_0/set_currency_in_pricing_rule.py b/erpnext/patches/v10_0/set_currency_in_pricing_rule.py
index d68148e..08f5ed1 100644
--- a/erpnext/patches/v10_0/set_currency_in_pricing_rule.py
+++ b/erpnext/patches/v10_0/set_currency_in_pricing_rule.py
@@ -9,6 +9,4 @@
 		if doc.company:
 			currency = frappe.get_cached_value("Company", doc.company, "default_currency")
 
-		frappe.db.sql(
-			"""update `tabPricing Rule` set currency = %s where name = %s""", (currency, doc.name)
-		)
+		frappe.db.sql("""update `tabPricing Rule` set currency = %s where name = %s""", (currency, doc.name))
diff --git a/erpnext/patches/v10_1/transfer_subscription_to_auto_repeat.py b/erpnext/patches/v10_1/transfer_subscription_to_auto_repeat.py
index 87151c1..375c010 100644
--- a/erpnext/patches/v10_1/transfer_subscription_to_auto_repeat.py
+++ b/erpnext/patches/v10_1/transfer_subscription_to_auto_repeat.py
@@ -52,7 +52,6 @@
 		"status",
 		"amended_from",
 	]:
-
 		if field in frappe.db.get_table_columns("Subscription"):
 			fields_to_drop["Subscription"].append(field)
 
diff --git a/erpnext/patches/v11_0/create_department_records_for_each_company.py b/erpnext/patches/v11_0/create_department_records_for_each_company.py
index 7a0641d..fb077af 100644
--- a/erpnext/patches/v11_0/create_department_records_for_each_company.py
+++ b/erpnext/patches/v11_0/create_department_records_for_each_company.py
@@ -53,11 +53,10 @@
 
 		for department in records:
 			when_then.append(
-				"""
-				WHEN company = "%s" and department = "%s"
-				THEN "%s"
+				f"""
+				WHEN company = "{company}" and department = "{department}"
+				THEN "{records[department]}"
 			"""
-				% (company, department, records[department])
 			)
 
 	if not when_then:
@@ -66,11 +65,10 @@
 	frappe.db.sql(
 		"""
 		update
-			`tab%s`
+			`tab{}`
 		set
-			department = CASE %s END
-	"""
-		% (doctype, " ".join(when_then))
+			department = CASE {} END
+	""".format(doctype, " ".join(when_then))
 	)
 
 
@@ -83,11 +81,10 @@
 
 		for department in records:
 			when_then.append(
-				"""
-				WHEN employee = "%s" and department = "%s"
-				THEN "%s"
+				f"""
+				WHEN employee = "{employee.name}" and department = "{department}"
+				THEN "{records[department]}"
 			"""
-				% (employee.name, department, records[department])
 			)
 
 	if not when_then:
diff --git a/erpnext/patches/v11_0/make_italian_localization_fields.py b/erpnext/patches/v11_0/make_italian_localization_fields.py
index 1b9793d..05c7b8a 100644
--- a/erpnext/patches/v11_0/make_italian_localization_fields.py
+++ b/erpnext/patches/v11_0/make_italian_localization_fields.py
@@ -20,19 +20,17 @@
 	# Set state codes
 	condition = ""
 	for state, code in state_codes.items():
-		condition += " when {0} then {1}".format(frappe.db.escape(state), frappe.db.escape(code))
+		condition += f" when {frappe.db.escape(state)} then {frappe.db.escape(code)}"
 
 	if condition:
-		condition = "state_code = (case state {0} end),".format(condition)
+		condition = f"state_code = (case state {condition} end),"
 
 	frappe.db.sql(
-		"""
+		f"""
 		UPDATE tabAddress set {condition} country_code = UPPER(ifnull((select code
 			from `tabCountry` where name = `tabAddress`.country), ''))
 			where country_code is null and state_code is null
-	""".format(
-			condition=condition
-		)
+	"""
 	)
 
 	frappe.db.sql(
diff --git a/erpnext/patches/v11_0/merge_land_unit_with_location.py b/erpnext/patches/v11_0/merge_land_unit_with_location.py
index c1afef6..92d0bc9 100644
--- a/erpnext/patches/v11_0/merge_land_unit_with_location.py
+++ b/erpnext/patches/v11_0/merge_land_unit_with_location.py
@@ -29,9 +29,9 @@
 		rename_field("Linked Location", "land_unit", "location")
 
 	if not frappe.db.exists("Location", "All Land Units"):
-		frappe.get_doc(
-			{"doctype": "Location", "is_group": True, "location_name": "All Land Units"}
-		).insert(ignore_permissions=True)
+		frappe.get_doc({"doctype": "Location", "is_group": True, "location_name": "All Land Units"}).insert(
+			ignore_permissions=True
+		)
 
 	if frappe.db.table_exists("Land Unit"):
 		land_units = frappe.get_all("Land Unit", fields=["*"], order_by="lft")
diff --git a/erpnext/patches/v11_0/move_item_defaults_to_child_table_for_multicompany.py b/erpnext/patches/v11_0/move_item_defaults_to_child_table_for_multicompany.py
index 37c0779..418bb13 100644
--- a/erpnext/patches/v11_0/move_item_defaults_to_child_table_for_multicompany.py
+++ b/erpnext/patches/v11_0/move_item_defaults_to_child_table_for_multicompany.py
@@ -106,8 +106,6 @@
 					`expense_account`, `income_account`, `buying_cost_center`, `selling_cost_center`
 				)
 				VALUES {}
-			""".format(
-					", ".join(["%s"] * len(to_insert_data))
-				),
+			""".format(", ".join(["%s"] * len(to_insert_data))),
 				tuple(to_insert_data),
 			)
diff --git a/erpnext/patches/v11_0/refactor_naming_series.py b/erpnext/patches/v11_0/refactor_naming_series.py
index 9cfb082..53c293c 100644
--- a/erpnext/patches/v11_0/refactor_naming_series.py
+++ b/erpnext/patches/v11_0/refactor_naming_series.py
@@ -124,9 +124,7 @@
 
 def get_series_to_preserve(doctype):
 	series_to_preserve = frappe.db.sql_list(
-		"""select distinct naming_series from `tab{doctype}` where ifnull(naming_series, '') != ''""".format(
-			doctype=doctype
-		)
+		f"""select distinct naming_series from `tab{doctype}` where ifnull(naming_series, '') != ''"""
 	)
 	series_to_preserve.sort()
 	return series_to_preserve
diff --git a/erpnext/patches/v11_0/rename_asset_adjustment_doctype.py b/erpnext/patches/v11_0/rename_asset_adjustment_doctype.py
index c444c16..206e7f5 100644
--- a/erpnext/patches/v11_0/rename_asset_adjustment_doctype.py
+++ b/erpnext/patches/v11_0/rename_asset_adjustment_doctype.py
@@ -6,8 +6,6 @@
 
 
 def execute():
-	if frappe.db.table_exists("Asset Adjustment") and not frappe.db.table_exists(
-		"Asset Value Adjustment"
-	):
+	if frappe.db.table_exists("Asset Adjustment") and not frappe.db.table_exists("Asset Value Adjustment"):
 		frappe.rename_doc("DocType", "Asset Adjustment", "Asset Value Adjustment", force=True)
 		frappe.reload_doc("assets", "doctype", "asset_value_adjustment")
diff --git a/erpnext/patches/v11_0/rename_bom_wo_fields.py b/erpnext/patches/v11_0/rename_bom_wo_fields.py
index fb25eeb..2132ff3 100644
--- a/erpnext/patches/v11_0/rename_bom_wo_fields.py
+++ b/erpnext/patches/v11_0/rename_bom_wo_fields.py
@@ -9,9 +9,7 @@
 def execute():
 	# updating column value to handle field change from Data to Currency
 	changed_field = "base_scrap_material_cost"
-	frappe.db.sql(
-		f"update `tabBOM` set {changed_field} = '0' where trim(coalesce({changed_field}, ''))= ''"
-	)
+	frappe.db.sql(f"update `tabBOM` set {changed_field} = '0' where trim(coalesce({changed_field}, ''))= ''")
 
 	for doctype in ["BOM Explosion Item", "BOM Item", "Work Order Item", "Item"]:
 		if frappe.db.has_column(doctype, "allow_transfer_for_manufacture"):
diff --git a/erpnext/patches/v11_0/rename_production_order_to_work_order.py b/erpnext/patches/v11_0/rename_production_order_to_work_order.py
index b58ac4e..31a9c88 100644
--- a/erpnext/patches/v11_0/rename_production_order_to_work_order.py
+++ b/erpnext/patches/v11_0/rename_production_order_to_work_order.py
@@ -21,14 +21,10 @@
 	rename_field("Timesheet", "production_order", "work_order")
 	rename_field("Stock Entry", "production_order", "work_order")
 
-	frappe.rename_doc(
-		"Report", "Production Orders in Progress", "Work Orders in Progress", force=True
-	)
+	frappe.rename_doc("Report", "Production Orders in Progress", "Work Orders in Progress", force=True)
 	frappe.rename_doc("Report", "Completed Production Orders", "Completed Work Orders", force=True)
 	frappe.rename_doc("Report", "Open Production Orders", "Open Work Orders", force=True)
 	frappe.rename_doc(
 		"Report", "Issued Items Against Production Order", "Issued Items Against Work Order", force=True
 	)
-	frappe.rename_doc(
-		"Report", "Production Order Stock Report", "Work Order Stock Report", force=True
-	)
+	frappe.rename_doc("Report", "Production Order Stock Report", "Work Order Stock Report", force=True)
diff --git a/erpnext/patches/v11_0/rename_supplier_type_to_supplier_group.py b/erpnext/patches/v11_0/rename_supplier_type_to_supplier_group.py
index 67eb915..1a07c56 100644
--- a/erpnext/patches/v11_0/rename_supplier_type_to_supplier_group.py
+++ b/erpnext/patches/v11_0/rename_supplier_type_to_supplier_group.py
@@ -25,10 +25,8 @@
 
 def build_tree():
 	frappe.db.sql(
-		"""update `tabSupplier Group` set parent_supplier_group = '{0}'
-		where is_group = 0""".format(
-			_("All Supplier Groups")
-		)
+		"""update `tabSupplier Group` set parent_supplier_group = '{}'
+		where is_group = 0""".format(_("All Supplier Groups"))
 	)
 
 	if not frappe.db.exists("Supplier Group", _("All Supplier Groups")):
diff --git a/erpnext/patches/v11_0/set_department_for_doctypes.py b/erpnext/patches/v11_0/set_department_for_doctypes.py
index b784772..70e9c8c 100644
--- a/erpnext/patches/v11_0/set_department_for_doctypes.py
+++ b/erpnext/patches/v11_0/set_department_for_doctypes.py
@@ -4,7 +4,6 @@
 
 
 def execute():
-
 	doctypes_to_update = {
 		"projects": ["Activity Cost", "Timesheet"],
 		"setup": ["Sales Person"],
diff --git a/erpnext/patches/v11_0/set_update_field_and_value_in_workflow_state.py b/erpnext/patches/v11_0/set_update_field_and_value_in_workflow_state.py
index 548a7cb..b6fc1a6 100644
--- a/erpnext/patches/v11_0/set_update_field_and_value_in_workflow_state.py
+++ b/erpnext/patches/v11_0/set_update_field_and_value_in_workflow_state.py
@@ -4,7 +4,6 @@
 
 def execute():
 	for doctype in ["Expense Claim", "Leave Application"]:
-
 		active_workflow = get_workflow_name(doctype)
 		if not active_workflow:
 			continue
diff --git a/erpnext/patches/v11_0/update_allow_transfer_for_manufacture.py b/erpnext/patches/v11_0/update_allow_transfer_for_manufacture.py
index a7351d2..3f59747 100644
--- a/erpnext/patches/v11_0/update_allow_transfer_for_manufacture.py
+++ b/erpnext/patches/v11_0/update_allow_transfer_for_manufacture.py
@@ -16,12 +16,10 @@
 		frappe.reload_doc("manufacturing", "doctype", frappe.scrub(doctype))
 
 		frappe.db.sql(
-			""" update `tab{0}` child, tabItem item
+			f""" update `tab{doctype}` child, tabItem item
 			set
 				child.include_item_in_manufacturing = 1
 			where
 				child.item_code = item.name and ifnull(item.is_stock_item, 0) = 1
-		""".format(
-				doctype
-			)
+		"""
 		)
diff --git a/erpnext/patches/v11_0/update_backflush_subcontract_rm_based_on_bom.py b/erpnext/patches/v11_0/update_backflush_subcontract_rm_based_on_bom.py
index 037dda5..57be8a7 100644
--- a/erpnext/patches/v11_0/update_backflush_subcontract_rm_based_on_bom.py
+++ b/erpnext/patches/v11_0/update_backflush_subcontract_rm_based_on_bom.py
@@ -7,9 +7,7 @@
 
 def execute():
 	frappe.reload_doc("buying", "doctype", "buying_settings")
-	frappe.db.set_single_value(
-		"Buying Settings", "backflush_raw_materials_of_subcontract_based_on", "BOM"
-	)
+	frappe.db.set_single_value("Buying Settings", "backflush_raw_materials_of_subcontract_based_on", "BOM")
 
 	frappe.reload_doc("stock", "doctype", "stock_entry_detail")
 	frappe.db.sql(
diff --git a/erpnext/patches/v11_0/update_department_lft_rgt.py b/erpnext/patches/v11_0/update_department_lft_rgt.py
index 380ca4d..ad66b0c 100644
--- a/erpnext/patches/v11_0/update_department_lft_rgt.py
+++ b/erpnext/patches/v11_0/update_department_lft_rgt.py
@@ -12,10 +12,8 @@
 		).insert(ignore_permissions=True, ignore_mandatory=True)
 
 	frappe.db.sql(
-		"""update `tabDepartment` set parent_department = '{0}'
-		where is_group = 0""".format(
-			_("All Departments")
-		)
+		"""update `tabDepartment` set parent_department = '{}'
+		where is_group = 0""".format(_("All Departments"))
 	)
 
 	rebuild_tree("Department")
diff --git a/erpnext/patches/v11_0/update_sales_partner_type.py b/erpnext/patches/v11_0/update_sales_partner_type.py
index 72fd424..ced77d9 100644
--- a/erpnext/patches/v11_0/update_sales_partner_type.py
+++ b/erpnext/patches/v11_0/update_sales_partner_type.py
@@ -16,7 +16,7 @@
 	# get partner type in existing forms (customized)
 	# and create a document if not created
 	for d in ["Sales Partner"]:
-		partner_type = frappe.db.sql_list("select distinct partner_type from `tab{0}`".format(d))
+		partner_type = frappe.db.sql_list(f"select distinct partner_type from `tab{d}`")
 		for s in partner_type:
 			if s and s not in default_sales_partner_type:
 				insert_sales_partner_type(s)
diff --git a/erpnext/patches/v11_0/update_total_qty_field.py b/erpnext/patches/v11_0/update_total_qty_field.py
index 09fcdb8..3ed7c83 100644
--- a/erpnext/patches/v11_0/update_total_qty_field.py
+++ b/erpnext/patches/v11_0/update_total_qty_field.py
@@ -24,16 +24,14 @@
 
 	for doctype in doctypes:
 		total_qty = frappe.db.sql(
-			"""
+			f"""
 			SELECT
 				parent, SUM(qty) as qty
 			FROM
-				`tab{0} Item`
-			where parenttype = '{0}'
+				`tab{doctype} Item`
+			where parenttype = '{doctype}'
 			GROUP BY parent
-		""".format(
-				doctype
-			),
+		""",
 			as_dict=True,
 		)
 
@@ -53,13 +51,11 @@
 			# This is probably never used anywhere else as of now, but should be
 			values = []
 			for d in batch_transactions:
-				values.append("({0}, {1})".format(frappe.db.escape(d.parent), d.qty))
+				values.append(f"({frappe.db.escape(d.parent)}, {d.qty})")
 			conditions = ",".join(values)
 			frappe.db.sql(
-				"""
-				INSERT INTO `tab{}` (name, total_qty) VALUES {}
+				f"""
+				INSERT INTO `tab{doctype}` (name, total_qty) VALUES {conditions}
 				ON DUPLICATE KEY UPDATE name = VALUES(name), total_qty = VALUES(total_qty)
-			""".format(
-					doctype, conditions
-				)
+			"""
 			)
diff --git a/erpnext/patches/v11_1/make_job_card_time_logs.py b/erpnext/patches/v11_1/make_job_card_time_logs.py
index beb2c4e..14bc4ee 100644
--- a/erpnext/patches/v11_1/make_job_card_time_logs.py
+++ b/erpnext/patches/v11_1/make_job_card_time_logs.py
@@ -8,9 +8,7 @@
 def execute():
 	frappe.reload_doc("manufacturing", "doctype", "job_card_time_log")
 
-	if frappe.db.table_exists("Job Card") and frappe.get_meta("Job Card").has_field(
-		"actual_start_date"
-	):
+	if frappe.db.table_exists("Job Card") and frappe.get_meta("Job Card").has_field("actual_start_date"):
 		time_logs = []
 		for d in frappe.get_all(
 			"Job Card",
@@ -37,9 +35,7 @@
                 `tabJob Card Time Log`
                     (from_time, to_time, time_in_mins, completed_qty, parent, parenttype, parentfield, name)
                 values {values}
-            """.format(
-					values=",".join(["%s"] * len(time_logs))
-				),
+            """.format(values=",".join(["%s"] * len(time_logs))),
 				tuple(time_logs),
 			)
 
diff --git a/erpnext/patches/v11_1/move_customer_lead_to_dynamic_column.py b/erpnext/patches/v11_1/move_customer_lead_to_dynamic_column.py
index b681f25..b4095ee 100644
--- a/erpnext/patches/v11_1/move_customer_lead_to_dynamic_column.py
+++ b/erpnext/patches/v11_1/move_customer_lead_to_dynamic_column.py
@@ -8,14 +8,10 @@
 def execute():
 	frappe.reload_doctype("Quotation")
 	frappe.db.sql(""" UPDATE `tabQuotation` set party_name = lead WHERE quotation_to = 'Lead' """)
-	frappe.db.sql(
-		""" UPDATE `tabQuotation` set party_name = customer WHERE quotation_to = 'Customer' """
-	)
+	frappe.db.sql(""" UPDATE `tabQuotation` set party_name = customer WHERE quotation_to = 'Customer' """)
 
 	frappe.reload_doctype("Opportunity")
-	frappe.db.sql(
-		""" UPDATE `tabOpportunity` set party_name = lead WHERE opportunity_from = 'Lead' """
-	)
+	frappe.db.sql(""" UPDATE `tabOpportunity` set party_name = lead WHERE opportunity_from = 'Lead' """)
 	frappe.db.sql(
 		""" UPDATE `tabOpportunity` set party_name = customer WHERE opportunity_from = 'Customer' """
 	)
diff --git a/erpnext/patches/v11_1/set_missing_opportunity_from.py b/erpnext/patches/v11_1/set_missing_opportunity_from.py
index ae5f620..fd3bf7e 100644
--- a/erpnext/patches/v11_1/set_missing_opportunity_from.py
+++ b/erpnext/patches/v11_1/set_missing_opportunity_from.py
@@ -2,7 +2,6 @@
 
 
 def execute():
-
 	frappe.reload_doctype("Opportunity")
 	if frappe.db.has_column("Opportunity", "enquiry_from"):
 		frappe.db.sql(
@@ -10,9 +9,7 @@
 			where ifnull(opportunity_from, '') = '' and ifnull(enquiry_from, '') != ''"""
 		)
 
-	if frappe.db.has_column("Opportunity", "lead") and frappe.db.has_column(
-		"Opportunity", "enquiry_from"
-	):
+	if frappe.db.has_column("Opportunity", "lead") and frappe.db.has_column("Opportunity", "enquiry_from"):
 		frappe.db.sql(
 			""" UPDATE `tabOpportunity` set party_name = lead
 			where enquiry_from = 'Lead' and ifnull(party_name, '') = '' and ifnull(lead, '') != ''"""
diff --git a/erpnext/patches/v12_0/add_default_buying_selling_terms_in_company.py b/erpnext/patches/v12_0/add_default_buying_selling_terms_in_company.py
index 284b616..0029074 100644
--- a/erpnext/patches/v12_0/add_default_buying_selling_terms_in_company.py
+++ b/erpnext/patches/v12_0/add_default_buying_selling_terms_in_company.py
@@ -11,9 +11,7 @@
 	if frappe.db.has_column("Company", "default_terms"):
 		rename_field("Company", "default_terms", "default_selling_terms")
 
-		for company in frappe.get_all(
-			"Company", ["name", "default_selling_terms", "default_buying_terms"]
-		):
+		for company in frappe.get_all("Company", ["name", "default_selling_terms", "default_buying_terms"]):
 			if company.default_selling_terms and not company.default_buying_terms:
 				frappe.db.set_value(
 					"Company", company.name, "default_buying_terms", company.default_selling_terms
diff --git a/erpnext/patches/v12_0/create_accounting_dimensions_in_missing_doctypes.py b/erpnext/patches/v12_0/create_accounting_dimensions_in_missing_doctypes.py
index 744ea1c..c3bf4a0 100644
--- a/erpnext/patches/v12_0/create_accounting_dimensions_in_missing_doctypes.py
+++ b/erpnext/patches/v12_0/create_accounting_dimensions_in_missing_doctypes.py
@@ -3,7 +3,6 @@
 
 
 def execute():
-
 	frappe.reload_doc("accounts", "doctype", "accounting_dimension")
 
 	accounting_dimensions = frappe.db.sql(
@@ -17,7 +16,6 @@
 
 	count = 1
 	for d in accounting_dimensions:
-
 		if count % 2 == 0:
 			insert_after_field = "dimension_col_break"
 		else:
@@ -31,7 +29,6 @@
 			"Expense Claim Detail",
 			"Expense Taxes and Charges",
 		]:
-
 			field = frappe.db.get_value("Custom Field", {"dt": doctype, "fieldname": d.fieldname})
 
 			if field:
diff --git a/erpnext/patches/v12_0/create_irs_1099_field_united_states.py b/erpnext/patches/v12_0/create_irs_1099_field_united_states.py
index 80e9047..8c7f6bd 100644
--- a/erpnext/patches/v12_0/create_irs_1099_field_united_states.py
+++ b/erpnext/patches/v12_0/create_irs_1099_field_united_states.py
@@ -4,7 +4,6 @@
 
 
 def execute():
-
 	frappe.reload_doc("accounts", "doctype", "allowed_to_transact_with", force=True)
 	frappe.reload_doc("accounts", "doctype", "pricing_rule_detail", force=True)
 	frappe.reload_doc("crm", "doctype", "lost_reason_detail", force=True)
diff --git a/erpnext/patches/v12_0/fix_quotation_expired_status.py b/erpnext/patches/v12_0/fix_quotation_expired_status.py
index 285183b..5d9c810 100644
--- a/erpnext/patches/v12_0/fix_quotation_expired_status.py
+++ b/erpnext/patches/v12_0/fix_quotation_expired_status.py
@@ -16,9 +16,7 @@
 			and qo.valid_till < so.transaction_date"""  # check if SO was created after quotation expired
 
 	frappe.db.sql(
-		"""UPDATE `tabQuotation` qo SET qo.status = 'Expired' WHERE {cond} and exists({invalid_so_against_quo})""".format(
-			cond=cond, invalid_so_against_quo=invalid_so_against_quo
-		)
+		f"""UPDATE `tabQuotation` qo SET qo.status = 'Expired' WHERE {cond} and exists({invalid_so_against_quo})"""
 	)
 
 	valid_so_against_quo = """
@@ -31,7 +29,5 @@
 			and qo.valid_till >= so.transaction_date"""  # check if SO was created before quotation expired
 
 	frappe.db.sql(
-		"""UPDATE `tabQuotation` qo SET qo.status = 'Closed' WHERE {cond} and exists({valid_so_against_quo})""".format(
-			cond=cond, valid_so_against_quo=valid_so_against_quo
-		)
+		f"""UPDATE `tabQuotation` qo SET qo.status = 'Closed' WHERE {cond} and exists({valid_so_against_quo})"""
 	)
diff --git a/erpnext/patches/v12_0/make_item_manufacturer.py b/erpnext/patches/v12_0/make_item_manufacturer.py
index 3f23365..67d6f97 100644
--- a/erpnext/patches/v12_0/make_item_manufacturer.py
+++ b/erpnext/patches/v12_0/make_item_manufacturer.py
@@ -30,8 +30,6 @@
 			"""
 			INSERT INTO `tabItem Manufacturer`
 			(`name`, `item_code`, `manufacturer`, `manufacturer_part_no`, `creation`, `owner`)
-			VALUES {}""".format(
-				", ".join(["%s"] * len(item_manufacturer))
-			),
+			VALUES {}""".format(", ".join(["%s"] * len(item_manufacturer))),
 			tuple(item_manufacturer),
 		)
diff --git a/erpnext/patches/v12_0/move_bank_account_swift_number_to_bank.py b/erpnext/patches/v12_0/move_bank_account_swift_number_to_bank.py
index 671dfd1..e6f522b 100644
--- a/erpnext/patches/v12_0/move_bank_account_swift_number_to_bank.py
+++ b/erpnext/patches/v12_0/move_bank_account_swift_number_to_bank.py
@@ -16,7 +16,7 @@
 				SET b.swift_number = ba.swift_number WHERE b.name = ba.bank
 			"""
 			)
-		except Exception as e:
+		except Exception:
 			frappe.log_error("Bank to Bank Account patch migration failed")
 
 	frappe.reload_doc("accounts", "doctype", "bank_account")
diff --git a/erpnext/patches/v12_0/move_credit_limit_to_customer_credit_limit.py b/erpnext/patches/v12_0/move_credit_limit_to_customer_credit_limit.py
index 17c1966..67fe5db 100644
--- a/erpnext/patches/v12_0/move_credit_limit_to_customer_credit_limit.py
+++ b/erpnext/patches/v12_0/move_credit_limit_to_customer_credit_limit.py
@@ -29,12 +29,10 @@
 			fields = ", bypass_credit_limit_check_at_sales_order"
 
 		credit_limit_records = frappe.db.sql(
-			"""
-			SELECT name, credit_limit {0}
-			FROM `tab{1}` where credit_limit > 0
-		""".format(
-				fields, doctype
-			),
+			f"""
+			SELECT name, credit_limit {fields}
+			FROM `tab{doctype}` where credit_limit > 0
+		""",
 			as_dict=1,
 		)  # nosec
 
diff --git a/erpnext/patches/v12_0/move_item_tax_to_item_tax_template.py b/erpnext/patches/v12_0/move_item_tax_to_item_tax_template.py
index c4c3b69..8ac1991 100644
--- a/erpnext/patches/v12_0/move_item_tax_to_item_tax_template.py
+++ b/erpnext/patches/v12_0/move_item_tax_to_item_tax_template.py
@@ -80,11 +80,9 @@
 
 	for dt in doctypes:
 		for d in frappe.db.sql(
-			"""select name, parenttype, parent, item_code, item_tax_rate from `tab{0} Item`
+			f"""select name, parenttype, parent, item_code, item_tax_rate from `tab{dt} Item`
 								where ifnull(item_tax_rate, '') not in ('', '{{}}')
-								and item_tax_template is NULL""".format(
-				dt
-			),
+								and item_tax_template is NULL""",
 			as_dict=1,
 		):
 			item_tax_map = json.loads(d.item_tax_rate)
@@ -145,13 +143,23 @@
 				if not parent_account:
 					parent_account = frappe.db.get_value(
 						"Account",
-						filters={"account_type": "Tax", "root_type": "Liability", "is_group": 0, "company": company},
+						filters={
+							"account_type": "Tax",
+							"root_type": "Liability",
+							"is_group": 0,
+							"company": company,
+						},
 						fieldname="parent_account",
 					)
 				if not parent_account:
 					parent_account = frappe.db.get_value(
 						"Account",
-						filters={"account_type": "Tax", "root_type": "Liability", "is_group": 1, "company": company},
+						filters={
+							"account_type": "Tax",
+							"root_type": "Liability",
+							"is_group": 1,
+							"company": company,
+						},
 					)
 				filters = {
 					"account_name": account_name,
diff --git a/erpnext/patches/v12_0/move_target_distribution_from_parent_to_child.py b/erpnext/patches/v12_0/move_target_distribution_from_parent_to_child.py
index 7192610..ffd8ddc 100644
--- a/erpnext/patches/v12_0/move_target_distribution_from_parent_to_child.py
+++ b/erpnext/patches/v12_0/move_target_distribution_from_parent_to_child.py
@@ -18,9 +18,7 @@
             WHERE
                 `tab{child_doc}`.parent = `tab{parent_doc}`.name
                 and `tab{parent_doc}`.distribution_id is not null and `tab{parent_doc}`.distribution_id != ''
-        """.format(
-				parent_doc=d, child_doc="Target Detail"
-			)
+        """.format(parent_doc=d, child_doc="Target Detail")
 		)
 
 	frappe.delete_doc("Report", "Sales Partner-wise Transaction Summary")
diff --git a/erpnext/patches/v12_0/purchase_receipt_status.py b/erpnext/patches/v12_0/purchase_receipt_status.py
index 3b828d6..2869e2b 100644
--- a/erpnext/patches/v12_0/purchase_receipt_status.py
+++ b/erpnext/patches/v12_0/purchase_receipt_status.py
@@ -17,16 +17,14 @@
 	if not affected_purchase_receipts:
 		return
 
-	logger.info(
-		"purchase_receipt_status: begin patch, PR count: {}".format(len(affected_purchase_receipts))
-	)
+	logger.info(f"purchase_receipt_status: begin patch, PR count: {len(affected_purchase_receipts)}")
 
 	frappe.reload_doc("stock", "doctype", "Purchase Receipt")
 	frappe.reload_doc("stock", "doctype", "Purchase Receipt Item")
 
 	for pr in affected_purchase_receipts:
 		pr_name = pr[0]
-		logger.info("purchase_receipt_status: patching PR - {}".format(pr_name))
+		logger.info(f"purchase_receipt_status: patching PR - {pr_name}")
 
 		pr_doc = frappe.get_doc("Purchase Receipt", pr_name)
 
diff --git a/erpnext/patches/v12_0/rename_bank_reconciliation_fields.py b/erpnext/patches/v12_0/rename_bank_reconciliation_fields.py
index e2a3887..dfc2366 100644
--- a/erpnext/patches/v12_0/rename_bank_reconciliation_fields.py
+++ b/erpnext/patches/v12_0/rename_bank_reconciliation_fields.py
@@ -6,12 +6,8 @@
 
 def _rename_single_field(**kwargs):
 	count = frappe.db.sql(
-		"SELECT COUNT(*) FROM tabSingles WHERE doctype='{doctype}' AND field='{new_name}';".format(
-			**kwargs
-		)
-	)[0][
-		0
-	]  # nosec
+		"SELECT COUNT(*) FROM tabSingles WHERE doctype='{doctype}' AND field='{new_name}';".format(**kwargs)
+	)[0][0]  # nosec
 	if count == 0:
 		frappe.db.sql(
 			"UPDATE tabSingles SET field='{new_name}' WHERE doctype='{doctype}' AND field='{old_name}';".format(
@@ -22,7 +18,5 @@
 
 def execute():
 	_rename_single_field(doctype="Bank Clearance", old_name="bank_account", new_name="account")
-	_rename_single_field(
-		doctype="Bank Clearance", old_name="bank_account_no", new_name="bank_account"
-	)
+	_rename_single_field(doctype="Bank Clearance", old_name="bank_account_no", new_name="bank_account")
 	frappe.reload_doc("Accounts", "doctype", "Bank Clearance")
diff --git a/erpnext/patches/v12_0/repost_stock_ledger_entries_for_target_warehouse.py b/erpnext/patches/v12_0/repost_stock_ledger_entries_for_target_warehouse.py
index a4a8587..69ddb60 100644
--- a/erpnext/patches/v12_0/repost_stock_ledger_entries_for_target_warehouse.py
+++ b/erpnext/patches/v12_0/repost_stock_ledger_entries_for_target_warehouse.py
@@ -41,35 +41,29 @@
 			cond = " AND parent_doc.update_stock = 1"
 
 		data = frappe.db.sql(
-			""" SELECT parent_doc.name as name, child_doc.name as child_name
+			f""" SELECT parent_doc.name as name, child_doc.name as child_name
 			FROM
 				`tab{doctype}` parent_doc, `tab{doctype} Item` child_doc
 			WHERE
 				parent_doc.name = child_doc.parent AND parent_doc.docstatus < 2
 				AND child_doc.target_warehouse is not null AND child_doc.target_warehouse != ''
 				AND child_doc.creation > '2020-04-16' {cond}
-		""".format(
-				doctype=doctype, cond=cond
-			),
+		""",
 			as_dict=1,
 		)
 
 		if data:
 			names = [d.child_name for d in data]
 			frappe.db.sql(
-				""" UPDATE `tab{0} Item` set target_warehouse = null
-				WHERE name in ({1}) """.format(
-					doctype, ",".join(["%s"] * len(names))
-				),
+				""" UPDATE `tab{} Item` set target_warehouse = null
+				WHERE name in ({}) """.format(doctype, ",".join(["%s"] * len(names))),
 				tuple(names),
 			)
 
 			frappe.db.sql(
 				""" UPDATE `tabPacked Item` set target_warehouse = null
-				WHERE parenttype = '{0}' and parent_detail_docname in ({1})
-			""".format(
-					doctype, ",".join(["%s"] * len(names))
-				),
+				WHERE parenttype = '{}' and parent_detail_docname in ({})
+			""".format(doctype, ",".join(["%s"] * len(names))),
 				tuple(names),
 			)
 
diff --git a/erpnext/patches/v12_0/set_against_blanket_order_in_sales_and_purchase_order.py b/erpnext/patches/v12_0/set_against_blanket_order_in_sales_and_purchase_order.py
index d88593b..5d1cb64 100644
--- a/erpnext/patches/v12_0/set_against_blanket_order_in_sales_and_purchase_order.py
+++ b/erpnext/patches/v12_0/set_against_blanket_order_in_sales_and_purchase_order.py
@@ -2,17 +2,14 @@
 
 
 def execute():
-
 	frappe.reload_doc("selling", "doctype", "sales_order_item", force=True)
 	frappe.reload_doc("buying", "doctype", "purchase_order_item", force=True)
 
 	for doctype in ("Sales Order Item", "Purchase Order Item"):
 		frappe.db.sql(
-			"""
-			UPDATE `tab{0}`
+			f"""
+			UPDATE `tab{doctype}`
 			SET against_blanket_order = 1
 			WHERE ifnull(blanket_order, '') != ''
-		""".format(
-				doctype
-			)
+		"""
 		)
diff --git a/erpnext/patches/v12_0/set_automatically_process_deferred_accounting_in_accounts_settings.py b/erpnext/patches/v12_0/set_automatically_process_deferred_accounting_in_accounts_settings.py
index 84dd1c7..fc54635 100644
--- a/erpnext/patches/v12_0/set_automatically_process_deferred_accounting_in_accounts_settings.py
+++ b/erpnext/patches/v12_0/set_automatically_process_deferred_accounting_in_accounts_settings.py
@@ -4,6 +4,4 @@
 def execute():
 	frappe.reload_doc("accounts", "doctype", "accounts_settings")
 
-	frappe.db.set_single_value(
-		"Accounts Settings", "automatically_process_deferred_accounting_entry", 1
-	)
+	frappe.db.set_single_value("Accounts Settings", "automatically_process_deferred_accounting_entry", 1)
diff --git a/erpnext/patches/v12_0/set_produced_qty_field_in_sales_order_for_work_order.py b/erpnext/patches/v12_0/set_produced_qty_field_in_sales_order_for_work_order.py
index 562ebed..a5b9f43 100644
--- a/erpnext/patches/v12_0/set_produced_qty_field_in_sales_order_for_work_order.py
+++ b/erpnext/patches/v12_0/set_produced_qty_field_in_sales_order_for_work_order.py
@@ -12,6 +12,5 @@
 		fields=["sales_order", "sales_order_item"],
 		filters={"sales_order": ("!=", ""), "sales_order_item": ("!=", "")},
 	):
-
 		# update produced qty in sales order
 		update_produced_qty_in_so_item(d.sales_order, d.sales_order_item)
diff --git a/erpnext/patches/v12_0/set_purchase_receipt_delivery_note_detail.py b/erpnext/patches/v12_0/set_purchase_receipt_delivery_note_detail.py
index 2edf0f5..e820731 100644
--- a/erpnext/patches/v12_0/set_purchase_receipt_delivery_note_detail.py
+++ b/erpnext/patches/v12_0/set_purchase_receipt_delivery_note_detail.py
@@ -4,7 +4,6 @@
 
 
 def execute():
-
 	frappe.reload_doc("stock", "doctype", "delivery_note_item", force=True)
 	frappe.reload_doc("stock", "doctype", "purchase_receipt_item", force=True)
 
@@ -50,14 +49,12 @@
 		Format => { 'document' : ['return_document_1','return_document_2'] }"""
 
 		return_against_documents = frappe.db.sql(
-			"""
+			f"""
 			SELECT
 				return_against as document, name as return_document
 			FROM `tab{doctype}`
 			WHERE
-				is_return = 1 and docstatus = 1""".format(
-				doctype=doctype
-			),
+				is_return = 1 and docstatus = 1""",
 			as_dict=1,
 		)  # nosec
 
@@ -72,7 +69,7 @@
 		return_document_map = defaultdict(list)
 		detail_field = "purchase_receipt_item" if doctype == "Purchase Receipt" else "dn_detail"
 
-		child_doc = frappe.scrub("{0} Item".format(doctype))
+		child_doc = frappe.scrub(f"{doctype} Item")
 		frappe.reload_doc("stock", "doctype", child_doc)
 
 		return_document_map = make_return_document_map(doctype, return_document_map)
@@ -89,7 +86,8 @@
 				for return_item in return_doc_items:
 					for doc_item in doc_items:
 						if (
-							row_is_mappable(doc_item, return_item, detail_field) and doc_item.get("name") not in mapped
+							row_is_mappable(doc_item, return_item, detail_field)
+							and doc_item.get("name") not in mapped
 						):
 							map_rows(doc_item, return_item, detail_field, doctype)
 							mapped.append(doc_item.get("name"))
diff --git a/erpnext/patches/v12_0/set_quotation_status.py b/erpnext/patches/v12_0/set_quotation_status.py
index bebedd3..edfb4a4 100644
--- a/erpnext/patches/v12_0/set_quotation_status.py
+++ b/erpnext/patches/v12_0/set_quotation_status.py
@@ -2,7 +2,6 @@
 
 
 def execute():
-
 	frappe.db.sql(
 		""" UPDATE `tabQuotation` set status = 'Open'
 		where docstatus = 1 and status = 'Submitted' """
diff --git a/erpnext/patches/v12_0/stock_entry_enhancements.py b/erpnext/patches/v12_0/stock_entry_enhancements.py
index db099a3..75749a4 100644
--- a/erpnext/patches/v12_0/stock_entry_enhancements.py
+++ b/erpnext/patches/v12_0/stock_entry_enhancements.py
@@ -28,7 +28,6 @@
 		"Repack",
 		"Send to Subcontractor",
 	]:
-
 		ste_type = frappe.get_doc({"doctype": "Stock Entry Type", "name": purpose, "purpose": purpose})
 
 		try:
diff --git a/erpnext/patches/v12_0/update_bom_in_so_mr.py b/erpnext/patches/v12_0/update_bom_in_so_mr.py
index d35b4bc..f9de6e8 100644
--- a/erpnext/patches/v12_0/update_bom_in_so_mr.py
+++ b/erpnext/patches/v12_0/update_bom_in_so_mr.py
@@ -6,21 +6,17 @@
 	frappe.reload_doc("selling", "doctype", "sales_order_item")
 
 	for doctype in ["Sales Order", "Material Request"]:
-		condition = (
-			" and child_doc.stock_qty > child_doc.produced_qty and ROUND(doc.per_delivered, 2) < 100"
-		)
+		condition = " and child_doc.stock_qty > child_doc.produced_qty and ROUND(doc.per_delivered, 2) < 100"
 		if doctype == "Material Request":
 			condition = " and doc.per_ordered < 100 and doc.material_request_type = 'Manufacture'"
 
 		frappe.db.sql(
-			""" UPDATE `tab{doc}` as doc, `tab{doc} Item` as child_doc, tabItem as item
+			f""" UPDATE `tab{doctype}` as doc, `tab{doctype} Item` as child_doc, tabItem as item
 			SET
 				child_doc.bom_no = item.default_bom
 			WHERE
 				child_doc.item_code = item.name and child_doc.docstatus < 2
 				and child_doc.parent = doc.name
-				and item.default_bom is not null and item.default_bom != '' {cond}
-		""".format(
-				doc=doctype, cond=condition
-			)
+				and item.default_bom is not null and item.default_bom != '' {condition}
+		"""
 		)
diff --git a/erpnext/patches/v12_0/update_is_cancelled_field.py b/erpnext/patches/v12_0/update_is_cancelled_field.py
index 398dd70..ea9a06b 100644
--- a/erpnext/patches/v12_0/update_is_cancelled_field.py
+++ b/erpnext/patches/v12_0/update_is_cancelled_field.py
@@ -17,20 +17,16 @@
 			continue
 
 		frappe.db.sql(
-			"""
+			f"""
 				UPDATE `tab{doctype}`
 				SET is_cancelled = 0
-				where is_cancelled in ('', 'No') or is_cancelled is NULL""".format(
-				doctype=doctype
-			)
+				where is_cancelled in ('', 'No') or is_cancelled is NULL"""
 		)
 		frappe.db.sql(
-			"""
+			f"""
 				UPDATE `tab{doctype}`
 				SET is_cancelled = 1
-				where is_cancelled = 'Yes'""".format(
-				doctype=doctype
-			)
+				where is_cancelled = 'Yes'"""
 		)
 
 		frappe.reload_doc(module, "doctype", frappe.scrub(doctype))
diff --git a/erpnext/patches/v12_0/update_owner_fields_in_acc_dimension_custom_fields.py b/erpnext/patches/v12_0/update_owner_fields_in_acc_dimension_custom_fields.py
index 7dc0af9..26db58d 100644
--- a/erpnext/patches/v12_0/update_owner_fields_in_acc_dimension_custom_fields.py
+++ b/erpnext/patches/v12_0/update_owner_fields_in_acc_dimension_custom_fields.py
@@ -19,8 +19,7 @@
 			"""
 			UPDATE `tabCustom Field`
 			SET owner = 'Administrator'
-			WHERE fieldname = %s
-			AND dt IN (%s)"""
-			% ("%s", ", ".join(["%s"] * len(doclist))),  # nosec
-			tuple([dimension.fieldname] + doclist),
+			WHERE fieldname = {}
+			AND dt IN ({})""".format("%s", ", ".join(["%s"] * len(doclist))),  # nosec
+			tuple([dimension.fieldname, *doclist]),
 		)
diff --git a/erpnext/patches/v12_0/update_pricing_rule_fields.py b/erpnext/patches/v12_0/update_pricing_rule_fields.py
index 8da06b0..f4eee85 100644
--- a/erpnext/patches/v12_0/update_pricing_rule_fields.py
+++ b/erpnext/patches/v12_0/update_pricing_rule_fields.py
@@ -8,7 +8,6 @@
 
 
 def execute():
-
 	if not frappe.get_all("Pricing Rule", limit=1):
 		return
 
@@ -33,20 +32,16 @@
 		child_doctype = doctype + " Item"
 
 		frappe.db.sql(
-			""" UPDATE `tab{child_doctype}` SET pricing_rules = pricing_rule
+			f""" UPDATE `tab{child_doctype}` SET pricing_rules = pricing_rule
 			WHERE docstatus < 2 and pricing_rule is not null and pricing_rule != ''
-		""".format(
-				child_doctype=child_doctype
-			)
+		"""
 		)
 
 		data = frappe.db.sql(
-			""" SELECT pricing_rule, name, parent,
+			f""" SELECT pricing_rule, name, parent,
 				parenttype, creation, modified, docstatus, modified_by, owner, name
-			FROM `tab{child_doc}` where docstatus < 2 and pricing_rule is not null
-			and pricing_rule != ''""".format(
-				child_doc=child_doctype
-			),
+			FROM `tab{child_doctype}` where docstatus < 2 and pricing_rule is not null
+			and pricing_rule != ''""",
 			as_dict=1,
 		)
 
@@ -73,9 +68,7 @@
 				""" INSERT INTO
 				`tabPricing Rule Detail` (`pricing_rule`, `child_docname`, `parent`, `parentfield`, `parenttype`,
 				`creation`, `modified`, `docstatus`, `modified_by`, `owner`, `name`)
-			VALUES {values} """.format(
-					values=", ".join(["%s"] * len(values))
-				),
+			VALUES {values} """.format(values=", ".join(["%s"] * len(values))),
 				tuple(values),
 			)
 
@@ -116,8 +109,6 @@
 				""" INSERT INTO
 				`tab{doctype}` ({field}, parent, parentfield, parenttype, creation, modified,
 					owner, modified_by, name)
-			VALUES {values} """.format(
-					doctype=doctype, field=field, values=", ".join(["%s"] * len(values))
-				),
+			VALUES {values} """.format(doctype=doctype, field=field, values=", ".join(["%s"] * len(values))),
 				tuple(values),
 			)
diff --git a/erpnext/patches/v13_0/add_bin_unique_constraint.py b/erpnext/patches/v13_0/add_bin_unique_constraint.py
index 7ad2bec..92fc702 100644
--- a/erpnext/patches/v13_0/add_bin_unique_constraint.py
+++ b/erpnext/patches/v13_0/add_bin_unique_constraint.py
@@ -21,7 +21,6 @@
 
 
 def delete_and_patch_duplicate_bins():
-
 	duplicate_bins = frappe.db.sql(
 		"""
 		SELECT
diff --git a/erpnext/patches/v13_0/add_missing_fg_item_for_stock_entry.py b/erpnext/patches/v13_0/add_missing_fg_item_for_stock_entry.py
index ed764f4..f80233b 100644
--- a/erpnext/patches/v13_0/add_missing_fg_item_for_stock_entry.py
+++ b/erpnext/patches/v13_0/add_missing_fg_item_for_stock_entry.py
@@ -13,9 +13,7 @@
 		return
 
 	frappe.reload_doc("manufacturing", "doctype", "manufacturing_settings")
-	if cint(
-		frappe.db.get_single_value("Manufacturing Settings", "make_serial_no_batch_from_work_order")
-	):
+	if cint(frappe.db.get_single_value("Manufacturing Settings", "make_serial_no_batch_from_work_order")):
 		return
 
 	frappe.reload_doc("manufacturing", "doctype", "work_order")
@@ -75,9 +73,7 @@
 def set_expense_account(doc):
 	for row in doc.items:
 		if row.is_finished_item and not row.expense_account:
-			row.expense_account = frappe.get_cached_value(
-				"Company", doc.company, "stock_adjustment_account"
-			)
+			row.expense_account = frappe.get_cached_value("Company", doc.company, "stock_adjustment_account")
 
 
 def repost_stock_entry(doc):
diff --git a/erpnext/patches/v13_0/add_po_to_global_search.py b/erpnext/patches/v13_0/add_po_to_global_search.py
index 514cd34..c07b6d9 100644
--- a/erpnext/patches/v13_0/add_po_to_global_search.py
+++ b/erpnext/patches/v13_0/add_po_to_global_search.py
@@ -4,9 +4,7 @@
 def execute():
 	global_search_settings = frappe.get_single("Global Search Settings")
 
-	if "Purchase Order" in (
-		dt.document_type for dt in global_search_settings.allowed_in_global_search
-	):
+	if "Purchase Order" in (dt.document_type for dt in global_search_settings.allowed_in_global_search):
 		return
 
 	global_search_settings.append("allowed_in_global_search", {"document_type": "Purchase Order"})
diff --git a/erpnext/patches/v13_0/agriculture_deprecation_warning.py b/erpnext/patches/v13_0/agriculture_deprecation_warning.py
index 512444e..053710b 100644
--- a/erpnext/patches/v13_0/agriculture_deprecation_warning.py
+++ b/erpnext/patches/v13_0/agriculture_deprecation_warning.py
@@ -2,7 +2,6 @@
 
 
 def execute():
-
 	click.secho(
 		"Agriculture Domain is moved to a separate app and will be removed from ERPNext in version-14.\n"
 		"Please install the app to continue using the Agriculture domain: https://github.com/frappe/agriculture",
diff --git a/erpnext/patches/v13_0/change_default_item_manufacturer_fieldtype.py b/erpnext/patches/v13_0/change_default_item_manufacturer_fieldtype.py
index 0b00188..5baec0c 100644
--- a/erpnext/patches/v13_0/change_default_item_manufacturer_fieldtype.py
+++ b/erpnext/patches/v13_0/change_default_item_manufacturer_fieldtype.py
@@ -2,7 +2,6 @@
 
 
 def execute():
-
 	# Erase all default item manufacturers that dont exist.
 	item = frappe.qb.DocType("Item")
 	manufacturer = frappe.qb.DocType("Manufacturer")
diff --git a/erpnext/patches/v13_0/convert_qi_parameter_to_link_field.py b/erpnext/patches/v13_0/convert_qi_parameter_to_link_field.py
index 08ddbbf..d0bde56 100644
--- a/erpnext/patches/v13_0/convert_qi_parameter_to_link_field.py
+++ b/erpnext/patches/v13_0/convert_qi_parameter_to_link_field.py
@@ -6,9 +6,7 @@
 	params = set()
 
 	# get all parameters from QI readings table
-	for (p,) in frappe.db.get_all(
-		"Quality Inspection Reading", fields=["specification"], as_list=True
-	):
+	for (p,) in frappe.db.get_all("Quality Inspection Reading", fields=["specification"], as_list=True):
 		params.add(p.strip())
 
 	# get all parameters from QI Template as some may be unused in QI
diff --git a/erpnext/patches/v13_0/create_accounting_dimensions_in_orders.py b/erpnext/patches/v13_0/create_accounting_dimensions_in_orders.py
index 8e6bce6..84b17a5 100644
--- a/erpnext/patches/v13_0/create_accounting_dimensions_in_orders.py
+++ b/erpnext/patches/v13_0/create_accounting_dimensions_in_orders.py
@@ -12,14 +12,12 @@
 
 	count = 1
 	for d in accounting_dimensions:
-
 		if count % 2 == 0:
 			insert_after_field = "dimension_col_break"
 		else:
 			insert_after_field = "accounting_dimensions_section"
 
 		for doctype in ["Purchase Order", "Purchase Receipt", "Sales Order"]:
-
 			field = frappe.db.get_value("Custom Field", {"dt": doctype, "fieldname": d.fieldname})
 
 			if field:
@@ -36,7 +34,7 @@
 			try:
 				create_custom_field(doctype, df, ignore_validate=True)
 				frappe.clear_cache(doctype=doctype)
-			except Exception as e:
+			except Exception:
 				pass
 
 		count += 1
diff --git a/erpnext/patches/v13_0/create_accounting_dimensions_in_pos_doctypes.py b/erpnext/patches/v13_0/create_accounting_dimensions_in_pos_doctypes.py
index 51ab0e8..b9e7033 100644
--- a/erpnext/patches/v13_0/create_accounting_dimensions_in_pos_doctypes.py
+++ b/erpnext/patches/v13_0/create_accounting_dimensions_in_pos_doctypes.py
@@ -15,14 +15,12 @@
 
 	count = 1
 	for d in accounting_dimensions:
-
 		if count % 2 == 0:
 			insert_after_field = "dimension_col_break"
 		else:
 			insert_after_field = "accounting_dimensions_section"
 
 		for doctype in ["POS Invoice", "POS Invoice Item"]:
-
 			field = frappe.db.get_value("Custom Field", {"dt": doctype, "fieldname": d.fieldname})
 
 			if field:
diff --git a/erpnext/patches/v13_0/create_uae_pos_invoice_fields.py b/erpnext/patches/v13_0/create_uae_pos_invoice_fields.py
index 66aae9a..d28f8c9 100644
--- a/erpnext/patches/v13_0/create_uae_pos_invoice_fields.py
+++ b/erpnext/patches/v13_0/create_uae_pos_invoice_fields.py
@@ -8,9 +8,7 @@
 
 
 def execute():
-	company = frappe.get_all(
-		"Company", filters={"country": ["in", ["Saudi Arabia", "United Arab Emirates"]]}
-	)
+	company = frappe.get_all("Company", filters={"country": ["in", ["Saudi Arabia", "United Arab Emirates"]]})
 	if not company:
 		return
 
diff --git a/erpnext/patches/v13_0/delete_bank_reconciliation_detail.py b/erpnext/patches/v13_0/delete_bank_reconciliation_detail.py
index c53eb79..46946a8 100644
--- a/erpnext/patches/v13_0/delete_bank_reconciliation_detail.py
+++ b/erpnext/patches/v13_0/delete_bank_reconciliation_detail.py
@@ -6,9 +6,7 @@
 
 
 def execute():
-
 	if frappe.db.exists("DocType", "Bank Reconciliation Detail") and frappe.db.exists(
 		"DocType", "Bank Clearance Detail"
 	):
-
 		frappe.delete_doc("DocType", "Bank Reconciliation Detail", force=1)
diff --git a/erpnext/patches/v13_0/enable_provisional_accounting.py b/erpnext/patches/v13_0/enable_provisional_accounting.py
index dd18167..6edb423 100644
--- a/erpnext/patches/v13_0/enable_provisional_accounting.py
+++ b/erpnext/patches/v13_0/enable_provisional_accounting.py
@@ -11,6 +11,4 @@
 		company.enable_perpetual_inventory_for_non_stock_items,
 	).set(company.default_provisional_account, company.service_received_but_not_billed).where(
 		company.enable_perpetual_inventory_for_non_stock_items == 1
-	).where(
-		company.service_received_but_not_billed.isnotnull()
-	).run()
+	).where(company.service_received_but_not_billed.isnotnull()).run()
diff --git a/erpnext/patches/v13_0/fix_additional_cost_in_mfg_stock_entry.py b/erpnext/patches/v13_0/fix_additional_cost_in_mfg_stock_entry.py
index aeb8d8e..e305b37 100644
--- a/erpnext/patches/v13_0/fix_additional_cost_in_mfg_stock_entry.py
+++ b/erpnext/patches/v13_0/fix_additional_cost_in_mfg_stock_entry.py
@@ -1,4 +1,4 @@
-from typing import List, NewType
+from typing import NewType
 
 import frappe
 
@@ -13,7 +13,7 @@
 		create_repost_item_valuation(patched_stock_entry)
 
 
-def find_broken_stock_entries() -> List[StockEntryCode]:
+def find_broken_stock_entries() -> list[StockEntryCode]:
 	period_closing_date = frappe.db.get_value(
 		"Period Closing Voucher", {"docstatus": 1}, "posting_date", order_by="posting_date desc"
 	)
diff --git a/erpnext/patches/v13_0/fix_invoice_statuses.py b/erpnext/patches/v13_0/fix_invoice_statuses.py
index 253b425..dc15a01 100644
--- a/erpnext/patches/v13_0/fix_invoice_statuses.py
+++ b/erpnext/patches/v13_0/fix_invoice_statuses.py
@@ -41,7 +41,7 @@
 					("Overdue", "Overdue and Discounted", "Partly Paid", "Partly Paid and Discounted"),
 				),
 				"outstanding_amount": (">", 0),
-				"modified": (">", "2021-01-01")
+				"modified": (">", "2021-01-01"),
 				# an assumption is being made that only invoices modified
 				# after 2021 got affected as incorrectly overdue.
 				# required for performance reasons.
diff --git a/erpnext/patches/v13_0/healthcare_deprecation_warning.py b/erpnext/patches/v13_0/healthcare_deprecation_warning.py
index c6fba59..3fff235 100644
--- a/erpnext/patches/v13_0/healthcare_deprecation_warning.py
+++ b/erpnext/patches/v13_0/healthcare_deprecation_warning.py
@@ -2,7 +2,6 @@
 
 
 def execute():
-
 	click.secho(
 		"Healthcare Module is moved to a separate app and will be removed from ERPNext in version-14.\n"
 		"Please install the app to continue using the module: https://github.com/frappe/healthcare",
diff --git a/erpnext/patches/v13_0/hospitality_deprecation_warning.py b/erpnext/patches/v13_0/hospitality_deprecation_warning.py
index 2708b2c..6416651 100644
--- a/erpnext/patches/v13_0/hospitality_deprecation_warning.py
+++ b/erpnext/patches/v13_0/hospitality_deprecation_warning.py
@@ -2,7 +2,6 @@
 
 
 def execute():
-
 	click.secho(
 		"Hospitality domain is moved to a separate app and will be removed from ERPNext in version-14.\n"
 		"When upgrading to ERPNext version-14, please install the app to continue using the Hospitality domain: https://github.com/frappe/hospitality",
diff --git a/erpnext/patches/v13_0/item_naming_series_not_mandatory.py b/erpnext/patches/v13_0/item_naming_series_not_mandatory.py
index 0235a62..d25da7a 100644
--- a/erpnext/patches/v13_0/item_naming_series_not_mandatory.py
+++ b/erpnext/patches/v13_0/item_naming_series_not_mandatory.py
@@ -4,7 +4,6 @@
 
 
 def execute():
-
 	stock_settings = frappe.get_doc("Stock Settings")
 
 	set_by_naming_series(
diff --git a/erpnext/patches/v13_0/move_branch_code_to_bank_account.py b/erpnext/patches/v13_0/move_branch_code_to_bank_account.py
index 2406127..79c79ff 100644
--- a/erpnext/patches/v13_0/move_branch_code_to_bank_account.py
+++ b/erpnext/patches/v13_0/move_branch_code_to_bank_account.py
@@ -6,13 +6,10 @@
 
 
 def execute():
-
 	frappe.reload_doc("accounts", "doctype", "bank_account")
 	frappe.reload_doc("accounts", "doctype", "bank")
 
-	if frappe.db.has_column("Bank", "branch_code") and frappe.db.has_column(
-		"Bank Account", "branch_code"
-	):
+	if frappe.db.has_column("Bank", "branch_code") and frappe.db.has_column("Bank Account", "branch_code"):
 		frappe.db.sql(
 			"""UPDATE `tabBank` b, `tabBank Account` ba
 			SET ba.branch_code = b.branch_code
diff --git a/erpnext/patches/v13_0/non_profit_deprecation_warning.py b/erpnext/patches/v13_0/non_profit_deprecation_warning.py
index 5b54b25..1736646 100644
--- a/erpnext/patches/v13_0/non_profit_deprecation_warning.py
+++ b/erpnext/patches/v13_0/non_profit_deprecation_warning.py
@@ -2,7 +2,6 @@
 
 
 def execute():
-
 	click.secho(
 		"Non Profit Domain is moved to a separate app and will be removed from ERPNext in version-14.\n"
 		"When upgrading to ERPNext version-14, please install the app to continue using the Non Profit domain: https://github.com/frappe/non_profit",
diff --git a/erpnext/patches/v13_0/rename_issue_doctype_fields.py b/erpnext/patches/v13_0/rename_issue_doctype_fields.py
index a9b6df7..dfa76a7 100644
--- a/erpnext/patches/v13_0/rename_issue_doctype_fields.py
+++ b/erpnext/patches/v13_0/rename_issue_doctype_fields.py
@@ -57,7 +57,11 @@
 		for entry in opportunities:
 			mins_to_first_response = convert_to_seconds(entry.mins_to_first_response, "Minutes")
 			frappe.db.set_value(
-				"Opportunity", entry.name, "first_response_time", mins_to_first_response, update_modified=False
+				"Opportunity",
+				entry.name,
+				"first_response_time",
+				mins_to_first_response,
+				update_modified=False,
 			)
 			# commit after every 100 updates
 			count += 1
diff --git a/erpnext/patches/v13_0/requeue_failed_reposts.py b/erpnext/patches/v13_0/requeue_failed_reposts.py
index 752490d..c7dfaa2 100644
--- a/erpnext/patches/v13_0/requeue_failed_reposts.py
+++ b/erpnext/patches/v13_0/requeue_failed_reposts.py
@@ -3,7 +3,6 @@
 
 
 def execute():
-
 	reposts = frappe.get_all(
 		"Repost Item Valuation",
 		{"status": "Failed", "modified": [">", "2021-10-05"]},
diff --git a/erpnext/patches/v13_0/set_per_billed_in_return_delivery_note.py b/erpnext/patches/v13_0/set_per_billed_in_return_delivery_note.py
index a4d7012..40df73e 100644
--- a/erpnext/patches/v13_0/set_per_billed_in_return_delivery_note.py
+++ b/erpnext/patches/v13_0/set_per_billed_in_return_delivery_note.py
@@ -20,9 +20,9 @@
 		.run(as_dict=True)
 	)
 
-	frappe.qb.update(dn_item).inner_join(dn).on(dn.name == dn_item.parent).set(
-		dn_item.returned_qty, 0
-	).where(dn.is_return == 1).where(dn_item.returned_qty > 0).run()
+	frappe.qb.update(dn_item).inner_join(dn).on(dn.name == dn_item.parent).set(dn_item.returned_qty, 0).where(
+		dn.is_return == 1
+	).where(dn_item.returned_qty > 0).run()
 
 	for d in dn_list:
 		dn_doc = frappe.get_doc("Delivery Note", d.get("name"))
diff --git a/erpnext/patches/v13_0/set_work_order_qty_in_so_from_mr.py b/erpnext/patches/v13_0/set_work_order_qty_in_so_from_mr.py
index 1adf0d8..be30fb1 100644
--- a/erpnext/patches/v13_0/set_work_order_qty_in_so_from_mr.py
+++ b/erpnext/patches/v13_0/set_work_order_qty_in_so_from_mr.py
@@ -28,9 +28,7 @@
 	results = query.run(as_dict=True)
 
 	for row in results:
-		so_item = frappe.get_value(
-			"Material Request Item", row.material_request_item, "sales_order_item"
-		)
+		so_item = frappe.get_value("Material Request Item", row.material_request_item, "sales_order_item")
 		frappe.db.set_value("Work Order", row.name, "sales_order_item", so_item)
 
 		if so_item:
diff --git a/erpnext/patches/v13_0/shopify_deprecation_warning.py b/erpnext/patches/v13_0/shopify_deprecation_warning.py
index 245d1a9..274c35f 100644
--- a/erpnext/patches/v13_0/shopify_deprecation_warning.py
+++ b/erpnext/patches/v13_0/shopify_deprecation_warning.py
@@ -2,7 +2,6 @@
 
 
 def execute():
-
 	click.secho(
 		"Shopify Integration is moved to a separate app and will be removed from ERPNext in version-14.\n"
 		"Please install the app to continue using the integration: https://github.com/frappe/ecommerce_integrations",
diff --git a/erpnext/patches/v13_0/trim_whitespace_from_serial_nos.py b/erpnext/patches/v13_0/trim_whitespace_from_serial_nos.py
index b69a408..182711a 100644
--- a/erpnext/patches/v13_0/trim_whitespace_from_serial_nos.py
+++ b/erpnext/patches/v13_0/trim_whitespace_from_serial_nos.py
@@ -38,9 +38,7 @@
 		if correct_sr_no == sle.serial_no:
 			continue
 
-		frappe.db.set_value(
-			"Stock Ledger Entry", sle.name, "serial_no", correct_sr_no, update_modified=False
-		)
+		frappe.db.set_value("Stock Ledger Entry", sle.name, "serial_no", correct_sr_no, update_modified=False)
 		broken_serial_nos.update(serial_no_list)
 
 	if not broken_serial_nos:
diff --git a/erpnext/patches/v13_0/update_actual_start_and_end_date_in_wo.py b/erpnext/patches/v13_0/update_actual_start_and_end_date_in_wo.py
index 3c6c5b5..2c41a29 100644
--- a/erpnext/patches/v13_0/update_actual_start_and_end_date_in_wo.py
+++ b/erpnext/patches/v13_0/update_actual_start_and_end_date_in_wo.py
@@ -29,7 +29,7 @@
 			)
 
 			if not doc.planned_end_date:
-				planned_end_date = add_to_date(doc.planned_start_date, minutes=doc.lead_time)
+				add_to_date(doc.planned_start_date, minutes=doc.lead_time)
 				doc.db_set("planned_end_date", doc.actual_start_date, update_modified=False)
 
 	frappe.db.sql(
diff --git a/erpnext/patches/v13_0/update_job_card_status.py b/erpnext/patches/v13_0/update_job_card_status.py
index f2d12da..0f54692 100644
--- a/erpnext/patches/v13_0/update_job_card_status.py
+++ b/erpnext/patches/v13_0/update_job_card_status.py
@@ -5,7 +5,6 @@
 
 
 def execute():
-
 	job_card = frappe.qb.DocType("Job Card")
 	(
 		frappe.qb.update(job_card)
diff --git a/erpnext/patches/v13_0/update_maintenance_schedule_field_in_visit.py b/erpnext/patches/v13_0/update_maintenance_schedule_field_in_visit.py
index 136d34e..183cd79 100644
--- a/erpnext/patches/v13_0/update_maintenance_schedule_field_in_visit.py
+++ b/erpnext/patches/v13_0/update_maintenance_schedule_field_in_visit.py
@@ -13,8 +13,6 @@
 
 	frappe.qb.update(mv).join(mvp).on(mvp.parent == mv.name).set(
 		mv.maintenance_schedule, Coalesce(mvp.prevdoc_docname, "")
-	).where(
-		(mv.maintenance_type == "Scheduled") & (mvp.prevdoc_docname.notnull()) & (mv.docstatus < 2)
-	).run(
+	).where((mv.maintenance_type == "Scheduled") & (mvp.prevdoc_docname.notnull()) & (mv.docstatus < 2)).run(
 		as_dict=1
 	)
diff --git a/erpnext/patches/v13_0/update_reserved_qty_closed_wo.py b/erpnext/patches/v13_0/update_reserved_qty_closed_wo.py
index 72e77fe..4bba7b9 100644
--- a/erpnext/patches/v13_0/update_reserved_qty_closed_wo.py
+++ b/erpnext/patches/v13_0/update_reserved_qty_closed_wo.py
@@ -4,7 +4,6 @@
 
 
 def execute():
-
 	wo = frappe.qb.DocType("Work Order")
 	wo_item = frappe.qb.DocType("Work Order Item")
 
diff --git a/erpnext/patches/v13_0/update_sane_transfer_against.py b/erpnext/patches/v13_0/update_sane_transfer_against.py
index 45691e2..0f58775 100644
--- a/erpnext/patches/v13_0/update_sane_transfer_against.py
+++ b/erpnext/patches/v13_0/update_sane_transfer_against.py
@@ -5,7 +5,5 @@
 	bom = frappe.qb.DocType("BOM")
 
 	(
-		frappe.qb.update(bom)
-		.set(bom.transfer_material_against, "Work Order")
-		.where(bom.with_operations == 0)
+		frappe.qb.update(bom).set(bom.transfer_material_against, "Work Order").where(bom.with_operations == 0)
 	).run()
diff --git a/erpnext/patches/v13_0/update_sla_enhancements.py b/erpnext/patches/v13_0/update_sla_enhancements.py
index cf9e185..8464fa8 100644
--- a/erpnext/patches/v13_0/update_sla_enhancements.py
+++ b/erpnext/patches/v13_0/update_sla_enhancements.py
@@ -39,7 +39,9 @@
 		for priority in priorities:
 			if priority.parenttype == "Service Level Agreement":
 				response_time = convert_to_seconds(priority.response_time, priority.response_time_period)
-				resolution_time = convert_to_seconds(priority.resolution_time, priority.resolution_time_period)
+				resolution_time = convert_to_seconds(
+					priority.resolution_time, priority.resolution_time_period
+				)
 				frappe.db.set_value(
 					"Service Level Priority",
 					priority.name,
@@ -86,7 +88,9 @@
 							{
 								"priority": priority.priority,
 								"default_priority": priority.default_priority,
-								"response_time": convert_to_seconds(priority.response_time, priority.response_time_period),
+								"response_time": convert_to_seconds(
+									priority.response_time, priority.response_time_period
+								),
 								"resolution_time": convert_to_seconds(
 									priority.resolution_time, priority.resolution_time_period
 								),
diff --git a/erpnext/patches/v13_0/update_subscription.py b/erpnext/patches/v13_0/update_subscription.py
index 66b3def..96bd146 100644
--- a/erpnext/patches/v13_0/update_subscription.py
+++ b/erpnext/patches/v13_0/update_subscription.py
@@ -6,7 +6,6 @@
 
 
 def execute():
-
 	frappe.reload_doc("accounts", "doctype", "subscription")
 	frappe.reload_doc("accounts", "doctype", "subscription_invoice")
 	frappe.reload_doc("accounts", "doctype", "subscription_plan")
diff --git a/erpnext/patches/v13_0/update_timesheet_changes.py b/erpnext/patches/v13_0/update_timesheet_changes.py
index 02654c1..c54b4cb 100644
--- a/erpnext/patches/v13_0/update_timesheet_changes.py
+++ b/erpnext/patches/v13_0/update_timesheet_changes.py
@@ -20,12 +20,10 @@
 	)
 
 	frappe.db.sql(
-		"""UPDATE `tabTimesheet`
-			SET currency = '{0}',
+		f"""UPDATE `tabTimesheet`
+			SET currency = '{base_currency}',
 			exchange_rate = 1.0,
 			base_total_billable_amount = total_billable_amount,
 			base_total_billed_amount = total_billed_amount,
-			base_total_costing_amount = total_costing_amount""".format(
-			base_currency
-		)
+			base_total_costing_amount = total_costing_amount"""
 	)
diff --git a/erpnext/patches/v13_0/wipe_serial_no_field_for_0_qty.py b/erpnext/patches/v13_0/wipe_serial_no_field_for_0_qty.py
index 693d06d..280635c 100644
--- a/erpnext/patches/v13_0/wipe_serial_no_field_for_0_qty.py
+++ b/erpnext/patches/v13_0/wipe_serial_no_field_for_0_qty.py
@@ -2,7 +2,6 @@
 
 
 def execute():
-
 	doctype = "Stock Reconciliation Item"
 
 	if not frappe.db.has_column(doctype, "current_serial_no"):
@@ -11,6 +10,4 @@
 
 	sr_item = frappe.qb.DocType(doctype)
 
-	(
-		frappe.qb.update(sr_item).set(sr_item.current_serial_no, None).where(sr_item.current_qty == 0)
-	).run()
+	(frappe.qb.update(sr_item).set(sr_item.current_serial_no, None).where(sr_item.current_qty == 0)).run()
diff --git a/erpnext/patches/v14_0/change_is_subcontracted_fieldtype.py b/erpnext/patches/v14_0/change_is_subcontracted_fieldtype.py
index 9b07ba8..a044bb0 100644
--- a/erpnext/patches/v14_0/change_is_subcontracted_fieldtype.py
+++ b/erpnext/patches/v14_0/change_is_subcontracted_fieldtype.py
@@ -7,20 +7,16 @@
 def execute():
 	for doctype in ["Purchase Order", "Purchase Receipt", "Purchase Invoice", "Supplier Quotation"]:
 		frappe.db.sql(
-			"""
+			f"""
 				UPDATE `tab{doctype}`
 				SET is_subcontracted = 0
-				where is_subcontracted in ('', 'No') or is_subcontracted is null""".format(
-				doctype=doctype
-			)
+				where is_subcontracted in ('', 'No') or is_subcontracted is null"""
 		)
 		frappe.db.sql(
-			"""
+			f"""
 				UPDATE `tab{doctype}`
 				SET is_subcontracted = 1
-				where is_subcontracted = 'Yes'""".format(
-				doctype=doctype
-			)
+				where is_subcontracted = 'Yes'"""
 		)
 
 		frappe.reload_doc(frappe.get_meta(doctype).module, "doctype", frappe.scrub(doctype))
diff --git a/erpnext/patches/v14_0/copy_is_subcontracted_value_to_is_old_subcontracting_flow.py b/erpnext/patches/v14_0/copy_is_subcontracted_value_to_is_old_subcontracting_flow.py
index 607ef695..40a408b 100644
--- a/erpnext/patches/v14_0/copy_is_subcontracted_value_to_is_old_subcontracting_flow.py
+++ b/erpnext/patches/v14_0/copy_is_subcontracted_value_to_is_old_subcontracting_flow.py
@@ -7,6 +7,4 @@
 def execute():
 	for doctype in ["Purchase Order", "Purchase Receipt", "Purchase Invoice"]:
 		tab = frappe.qb.DocType(doctype).as_("tab")
-		frappe.qb.update(tab).set(tab.is_old_subcontracting_flow, 1).where(
-			tab.is_subcontracted == 1
-		).run()
+		frappe.qb.update(tab).set(tab.is_old_subcontracting_flow, 1).where(tab.is_subcontracted == 1).run()
diff --git a/erpnext/patches/v14_0/create_accounting_dimensions_in_subcontracting_doctypes.py b/erpnext/patches/v14_0/create_accounting_dimensions_in_subcontracting_doctypes.py
index b349c07..aedf2f1 100644
--- a/erpnext/patches/v14_0/create_accounting_dimensions_in_subcontracting_doctypes.py
+++ b/erpnext/patches/v14_0/create_accounting_dimensions_in_subcontracting_doctypes.py
@@ -12,7 +12,6 @@
 
 	count = 1
 	for d in accounting_dimensions:
-
 		if count % 2 == 0:
 			insert_after_field = "dimension_col_break"
 		else:
@@ -24,7 +23,6 @@
 			"Subcontracting Receipt",
 			"Subcontracting Receipt Item",
 		]:
-
 			field = frappe.db.get_value("Custom Field", {"dt": doctype, "fieldname": d.fieldname})
 
 			if field:
diff --git a/erpnext/patches/v14_0/crm_ux_cleanup.py b/erpnext/patches/v14_0/crm_ux_cleanup.py
index b2df36f..186ccf8 100644
--- a/erpnext/patches/v14_0/crm_ux_cleanup.py
+++ b/erpnext/patches/v14_0/crm_ux_cleanup.py
@@ -45,7 +45,8 @@
 				"owner": d.lead_owner,
 				"subject": ("Contact " + cstr(d.lead_name)),
 				"description": (
-					("Contact " + cstr(d.lead_name)) + (("<br>By: " + cstr(d.contact_by)) if d.contact_by else "")
+					("Contact " + cstr(d.lead_name))
+					+ (("<br>By: " + cstr(d.contact_by)) if d.contact_by else "")
 				),
 				"starts_on": d.contact_date,
 				"ends_on": d.ends_on,
@@ -87,8 +88,6 @@
 			}
 		)
 
-		event.append(
-			"event_participants", {"reference_doctype": "Opportunity", "reference_docname": d.name}
-		)
+		event.append("event_participants", {"reference_doctype": "Opportunity", "reference_docname": d.name})
 
 		event.insert(ignore_permissions=True)
diff --git a/erpnext/patches/v14_0/delete_agriculture_doctypes.py b/erpnext/patches/v14_0/delete_agriculture_doctypes.py
index 8ec0c33..c8f9c93 100644
--- a/erpnext/patches/v14_0/delete_agriculture_doctypes.py
+++ b/erpnext/patches/v14_0/delete_agriculture_doctypes.py
@@ -13,9 +13,7 @@
 	for report in reports:
 		frappe.delete_doc("Report", report, ignore_missing=True, force=True)
 
-	dashboards = frappe.get_all(
-		"Dashboard", {"module": "agriculture", "is_standard": 1}, pluck="name"
-	)
+	dashboards = frappe.get_all("Dashboard", {"module": "agriculture", "is_standard": 1}, pluck="name")
 	for dashboard in dashboards:
 		frappe.delete_doc("Dashboard", dashboard, ignore_missing=True, force=True)
 
diff --git a/erpnext/patches/v14_0/delete_education_doctypes.py b/erpnext/patches/v14_0/delete_education_doctypes.py
index aeeda70..9b99f72 100644
--- a/erpnext/patches/v14_0/delete_education_doctypes.py
+++ b/erpnext/patches/v14_0/delete_education_doctypes.py
@@ -16,9 +16,7 @@
 	for report in reports:
 		frappe.delete_doc("Report", report, ignore_missing=True, force=True)
 
-	print_formats = frappe.get_all(
-		"Print Format", {"module": "education", "standard": "Yes"}, pluck="name"
-	)
+	print_formats = frappe.get_all("Print Format", {"module": "education", "standard": "Yes"}, pluck="name")
 	for print_format in print_formats:
 		frappe.delete_doc("Print Format", print_format, ignore_missing=True, force=True)
 
@@ -31,9 +29,7 @@
 	for dashboard in dashboards:
 		frappe.delete_doc("Dashboard", dashboard, ignore_missing=True, force=True)
 
-	dashboards = frappe.get_all(
-		"Dashboard Chart", {"module": "education", "is_standard": 1}, pluck="name"
-	)
+	dashboards = frappe.get_all("Dashboard Chart", {"module": "education", "is_standard": 1}, pluck="name")
 	for dashboard in dashboards:
 		frappe.delete_doc("Dashboard Chart", dashboard, ignore_missing=True, force=True)
 
diff --git a/erpnext/patches/v14_0/delete_healthcare_doctypes.py b/erpnext/patches/v14_0/delete_healthcare_doctypes.py
index 896a440..b4dde5b 100644
--- a/erpnext/patches/v14_0/delete_healthcare_doctypes.py
+++ b/erpnext/patches/v14_0/delete_healthcare_doctypes.py
@@ -15,9 +15,7 @@
 	for report in reports:
 		frappe.delete_doc("Report", report, ignore_missing=True, force=True)
 
-	print_formats = frappe.get_all(
-		"Print Format", {"module": "healthcare", "standard": "Yes"}, pluck="name"
-	)
+	print_formats = frappe.get_all("Print Format", {"module": "healthcare", "standard": "Yes"}, pluck="name")
 	for print_format in print_formats:
 		frappe.delete_doc("Print Format", print_format, ignore_missing=True, force=True)
 
@@ -30,9 +28,7 @@
 	for dashboard in dashboards:
 		frappe.delete_doc("Dashboard", dashboard, ignore_missing=True, force=True)
 
-	dashboards = frappe.get_all(
-		"Dashboard Chart", {"module": "healthcare", "is_standard": 1}, pluck="name"
-	)
+	dashboards = frappe.get_all("Dashboard Chart", {"module": "healthcare", "is_standard": 1}, pluck="name")
 	for dashboard in dashboards:
 		frappe.delete_doc("Dashboard Chart", dashboard, ignore_missing=True, force=True)
 
diff --git a/erpnext/patches/v14_0/delete_hub_doctypes.py b/erpnext/patches/v14_0/delete_hub_doctypes.py
index 08f4445..451880d 100644
--- a/erpnext/patches/v14_0/delete_hub_doctypes.py
+++ b/erpnext/patches/v14_0/delete_hub_doctypes.py
@@ -2,7 +2,6 @@
 
 
 def execute():
-
 	doctypes = frappe.get_all("DocType", {"module": "Hub Node", "custom": 0}, pluck="name")
 	for doctype in doctypes:
 		frappe.delete_doc("DocType", doctype, ignore_missing=True)
diff --git a/erpnext/patches/v14_0/delete_non_profit_doctypes.py b/erpnext/patches/v14_0/delete_non_profit_doctypes.py
index e9ea8b1..74a73fd 100644
--- a/erpnext/patches/v14_0/delete_non_profit_doctypes.py
+++ b/erpnext/patches/v14_0/delete_non_profit_doctypes.py
@@ -6,9 +6,7 @@
 
 	frappe.delete_doc("Workspace", "Non Profit", ignore_missing=True, force=True)
 
-	print_formats = frappe.get_all(
-		"Print Format", {"module": "Non Profit", "standard": "Yes"}, pluck="name"
-	)
+	print_formats = frappe.get_all("Print Format", {"module": "Non Profit", "standard": "Yes"}, pluck="name")
 	for print_format in print_formats:
 		frappe.delete_doc("Print Format", print_format, ignore_missing=True, force=True)
 
diff --git a/erpnext/patches/v14_0/fix_crm_no_of_employees.py b/erpnext/patches/v14_0/fix_crm_no_of_employees.py
index 268eb95..29c8b05 100644
--- a/erpnext/patches/v14_0/fix_crm_no_of_employees.py
+++ b/erpnext/patches/v14_0/fix_crm_no_of_employees.py
@@ -15,12 +15,10 @@
 		frappe.reload_doctype(doctype)
 		for key, value in options.items():
 			frappe.db.sql(
-				"""
+				f"""
                 update `tab{doctype}`
                 set no_of_employees = %s
                 where no_of_employees = %s
-            """.format(
-					doctype=doctype
-				),
+            """,
 				(value, key),
 			)
diff --git a/erpnext/patches/v14_0/migrate_cost_center_allocations.py b/erpnext/patches/v14_0/migrate_cost_center_allocations.py
index 48f4e6d..03e2b02 100644
--- a/erpnext/patches/v14_0/migrate_cost_center_allocations.py
+++ b/erpnext/patches/v14_0/migrate_cost_center_allocations.py
@@ -44,8 +44,6 @@
 
 	cc_allocations = frappe._dict()
 	for d in records:
-		cc_allocations.setdefault(d.name, frappe._dict()).setdefault(
-			d.cost_center, d.percentage_allocation
-		)
+		cc_allocations.setdefault(d.name, frappe._dict()).setdefault(d.cost_center, d.percentage_allocation)
 
 	return cc_allocations
diff --git a/erpnext/patches/v14_0/migrate_gl_to_payment_ledger.py b/erpnext/patches/v14_0/migrate_gl_to_payment_ledger.py
index 95b5bc5..de9a62e 100644
--- a/erpnext/patches/v14_0/migrate_gl_to_payment_ledger.py
+++ b/erpnext/patches/v14_0/migrate_gl_to_payment_ledger.py
@@ -152,7 +152,8 @@
 						gl.star,
 						ConstantColumn(1).as_("docstatus"),
 						IfNull(
-							ifelse(gl.against_voucher_type == "", None, gl.against_voucher_type), gl.voucher_type
+							ifelse(gl.against_voucher_type == "", None, gl.against_voucher_type),
+							gl.voucher_type,
 						).as_("against_voucher_type"),
 						IfNull(ifelse(gl.against_voucher == "", None, gl.against_voucher), gl.voucher_no).as_(
 							"against_voucher_no"
diff --git a/erpnext/patches/v14_0/remove_hr_and_payroll_modules.py b/erpnext/patches/v14_0/remove_hr_and_payroll_modules.py
index 4d01fcb..3d01f14 100644
--- a/erpnext/patches/v14_0/remove_hr_and_payroll_modules.py
+++ b/erpnext/patches/v14_0/remove_hr_and_payroll_modules.py
@@ -33,9 +33,7 @@
 	]:
 		frappe.delete_doc("Report", report, ignore_missing=True, force=True)
 
-	doctypes = frappe.get_all(
-		"DocType", {"module": ("in", ["HR", "Payroll"]), "custom": 0}, pluck="name"
-	)
+	doctypes = frappe.get_all("DocType", {"module": ("in", ["HR", "Payroll"]), "custom": 0}, pluck="name")
 	for doctype in doctypes:
 		frappe.delete_doc("DocType", doctype, ignore_missing=True, force=True)
 
@@ -51,9 +49,7 @@
 	frappe.delete_doc("User Type", "Employee Self Service", ignore_missing=True, force=True)
 
 	for dt in ["Web Form", "Dashboard", "Dashboard Chart", "Number Card"]:
-		records = frappe.get_all(
-			dt, {"module": ("in", ["HR", "Payroll"]), "is_standard": 1}, pluck="name"
-		)
+		records = frappe.get_all(dt, {"module": ("in", ["HR", "Payroll"]), "is_standard": 1}, pluck="name")
 		for record in records:
 			frappe.delete_doc(dt, record, ignore_missing=True, force=True)
 
diff --git a/erpnext/patches/v14_0/update_closing_balances.py b/erpnext/patches/v14_0/update_closing_balances.py
index 2c84281..cfc29c8 100644
--- a/erpnext/patches/v14_0/update_closing_balances.py
+++ b/erpnext/patches/v14_0/update_closing_balances.py
@@ -22,7 +22,6 @@
 			filters={"docstatus": 1, "company": company},
 			order_by="posting_date",
 		):
-
 			company_wise_order.setdefault(pcv.company, [])
 			if pcv.posting_date not in company_wise_order[pcv.company]:
 				pcv_doc = frappe.get_doc("Period Closing Voucher", pcv.name)
diff --git a/erpnext/patches/v14_0/update_flag_for_return_invoices.py b/erpnext/patches/v14_0/update_flag_for_return_invoices.py
index bea9957..ca1b296 100644
--- a/erpnext/patches/v14_0/update_flag_for_return_invoices.py
+++ b/erpnext/patches/v14_0/update_flag_for_return_invoices.py
@@ -22,7 +22,7 @@
 		.where(
 			(si.creation.gte(creation_date))
 			& (si.docstatus == 1)
-			& (si.is_return == True)
+			& (si.is_return is True)
 			& (si.return_against.notnull())
 		)
 		.run()
@@ -51,7 +51,7 @@
 		.where(
 			(pi.creation.gte(creation_date))
 			& (pi.docstatus == 1)
-			& (pi.is_return == True)
+			& (pi.is_return is True)
 			& (pi.return_against.notnull())
 		)
 		.run()
diff --git a/erpnext/patches/v14_0/update_partial_tds_fields.py b/erpnext/patches/v14_0/update_partial_tds_fields.py
index 5ccc2dc..9912013 100644
--- a/erpnext/patches/v14_0/update_partial_tds_fields.py
+++ b/erpnext/patches/v14_0/update_partial_tds_fields.py
@@ -14,32 +14,20 @@
 
 			frappe.qb.update(purchase_invoice).set(
 				purchase_invoice.tax_withholding_net_total, purchase_invoice.net_total
-			).set(
-				purchase_invoice.base_tax_withholding_net_total, purchase_invoice.base_net_total
-			).where(
+			).set(purchase_invoice.base_tax_withholding_net_total, purchase_invoice.base_net_total).where(
 				purchase_invoice.company == company.name
-			).where(
-				purchase_invoice.apply_tds == 1
-			).where(
+			).where(purchase_invoice.apply_tds == 1).where(
 				purchase_invoice.posting_date >= fiscal_year_details.year_start_date
-			).where(
-				purchase_invoice.docstatus == 1
-			).run()
+			).where(purchase_invoice.docstatus == 1).run()
 
 			purchase_order = frappe.qb.DocType("Purchase Order")
 
 			frappe.qb.update(purchase_order).set(
 				purchase_order.tax_withholding_net_total, purchase_order.net_total
-			).set(
-				purchase_order.base_tax_withholding_net_total, purchase_order.base_net_total
-			).where(
+			).set(purchase_order.base_tax_withholding_net_total, purchase_order.base_net_total).where(
 				purchase_order.company == company.name
-			).where(
-				purchase_order.apply_tds == 1
-			).where(
+			).where(purchase_order.apply_tds == 1).where(
 				purchase_order.transaction_date >= fiscal_year_details.year_start_date
-			).where(
-				purchase_order.docstatus == 1
-			).run()
+			).where(purchase_order.docstatus == 1).run()
 		except FiscalYearError:
 			pass
diff --git a/erpnext/patches/v15_0/correct_asset_value_if_je_with_workflow.py b/erpnext/patches/v15_0/correct_asset_value_if_je_with_workflow.py
index aededa2..dba27b4 100644
--- a/erpnext/patches/v15_0/correct_asset_value_if_je_with_workflow.py
+++ b/erpnext/patches/v15_0/correct_asset_value_if_je_with_workflow.py
@@ -39,9 +39,7 @@
 			asset.opening_accumulated_depreciation.as_("opening_accumulated_depreciation"),
 			Sum(gle.debit).as_("depr_amount"),
 		)
-		.where(
-			gle.account == IfNull(aca.depreciation_expense_account, company.depreciation_expense_account)
-		)
+		.where(gle.account == IfNull(aca.depreciation_expense_account, company.depreciation_expense_account))
 		.where(gle.debit != 0)
 		.where(gle.is_cancelled == 0)
 		.where(asset.docstatus == 1)
@@ -80,9 +78,7 @@
 			asset.opening_accumulated_depreciation.as_("opening_accumulated_depreciation"),
 			Sum(gle.debit).as_("depr_amount"),
 		)
-		.where(
-			gle.account == IfNull(aca.depreciation_expense_account, company.depreciation_expense_account)
-		)
+		.where(gle.account == IfNull(aca.depreciation_expense_account, company.depreciation_expense_account))
 		.where(gle.debit != 0)
 		.where(gle.is_cancelled == 0)
 		.where(asset.docstatus == 1)
diff --git a/erpnext/patches/v15_0/create_advance_payment_status.py b/erpnext/patches/v15_0/create_advance_payment_status.py
index 18ab9fa..0b7163c 100644
--- a/erpnext/patches/v15_0/create_advance_payment_status.py
+++ b/erpnext/patches/v15_0/create_advance_payment_status.py
@@ -9,16 +9,14 @@
 
 	if frappe.reload_doc("selling", "doctype", "Sales Order"):
 		so = frappe.qb.DocType("Sales Order")
-		frappe.qb.update(so).set(so.advance_payment_status, "Not Requested").where(
-			so.docstatus == 1
-		).where(so.advance_paid == 0.0).run()
-
-		frappe.qb.update(so).set(so.advance_payment_status, "Partially Paid").where(
-			so.docstatus == 1
-		).where(so.advance_payment_status.isnull()).where(
-			so.advance_paid < (so.rounded_total or so.grand_total)
+		frappe.qb.update(so).set(so.advance_payment_status, "Not Requested").where(so.docstatus == 1).where(
+			so.advance_paid == 0.0
 		).run()
 
+		frappe.qb.update(so).set(so.advance_payment_status, "Partially Paid").where(so.docstatus == 1).where(
+			so.advance_payment_status.isnull()
+		).where(so.advance_paid < (so.rounded_total or so.grand_total)).run()
+
 		frappe.qb.update(so).set(so.advance_payment_status, "Fully Paid").where(so.docstatus == 1).where(
 			so.advance_payment_status.isnull()
 		).where(so.advance_paid == (so.rounded_total or so.grand_total)).run()
@@ -32,16 +30,14 @@
 
 	if frappe.reload_doc("buying", "doctype", "Purchase Order"):
 		po = frappe.qb.DocType("Purchase Order")
-		frappe.qb.update(po).set(po.advance_payment_status, "Not Initiated").where(
-			po.docstatus == 1
-		).where(po.advance_paid == 0.0).run()
-
-		frappe.qb.update(po).set(po.advance_payment_status, "Partially Paid").where(
-			po.docstatus == 1
-		).where(po.advance_payment_status.isnull()).where(
-			po.advance_paid < (po.rounded_total or po.grand_total)
+		frappe.qb.update(po).set(po.advance_payment_status, "Not Initiated").where(po.docstatus == 1).where(
+			po.advance_paid == 0.0
 		).run()
 
+		frappe.qb.update(po).set(po.advance_payment_status, "Partially Paid").where(po.docstatus == 1).where(
+			po.advance_payment_status.isnull()
+		).where(po.advance_paid < (po.rounded_total or po.grand_total)).run()
+
 		frappe.qb.update(po).set(po.advance_payment_status, "Fully Paid").where(po.docstatus == 1).where(
 			po.advance_payment_status.isnull()
 		).where(po.advance_paid == (po.rounded_total or po.grand_total)).run()
diff --git a/erpnext/patches/v15_0/create_asset_depreciation_schedules_from_assets.py b/erpnext/patches/v15_0/create_asset_depreciation_schedules_from_assets.py
index ddce997..c31d754 100644
--- a/erpnext/patches/v15_0/create_asset_depreciation_schedules_from_assets.py
+++ b/erpnext/patches/v15_0/create_asset_depreciation_schedules_from_assets.py
@@ -57,7 +57,7 @@
 	grouped_dict = {}
 
 	for item in records:
-		key = list(item.keys())[0]
+		key = next(iter(item.keys()))
 		value = item[key]
 
 		if value not in grouped_dict:
diff --git a/erpnext/patches/v15_0/remove_loan_management_module.py b/erpnext/patches/v15_0/remove_loan_management_module.py
index 8242f9c..e18b092 100644
--- a/erpnext/patches/v15_0/remove_loan_management_module.py
+++ b/erpnext/patches/v15_0/remove_loan_management_module.py
@@ -15,9 +15,7 @@
 	for print_format in print_formats:
 		frappe.delete_doc("Print Format", print_format, ignore_missing=True, force=True)
 
-	reports = frappe.get_all(
-		"Report", {"module": "Loan Management", "is_standard": "Yes"}, pluck="name"
-	)
+	reports = frappe.get_all("Report", {"module": "Loan Management", "is_standard": "Yes"}, pluck="name")
 	for report in reports:
 		frappe.delete_doc("Report", report, ignore_missing=True, force=True)
 
diff --git a/erpnext/patches/v15_0/update_asset_value_for_manual_depr_entries.py b/erpnext/patches/v15_0/update_asset_value_for_manual_depr_entries.py
index 5d7b5cf..9bdcda0 100644
--- a/erpnext/patches/v15_0/update_asset_value_for_manual_depr_entries.py
+++ b/erpnext/patches/v15_0/update_asset_value_for_manual_depr_entries.py
@@ -17,9 +17,7 @@
 		.join(company)
 		.on(company.name == asset.company)
 		.select(Sum(gle.debit).as_("value"), asset.name.as_("asset_name"))
-		.where(
-			gle.account == IfNull(aca.depreciation_expense_account, company.depreciation_expense_account)
-		)
+		.where(gle.account == IfNull(aca.depreciation_expense_account, company.depreciation_expense_account))
 		.where(gle.debit != 0)
 		.where(gle.is_cancelled == 0)
 		.where(asset.docstatus == 1)
@@ -31,8 +29,4 @@
 		asset_total_depr_value_map.asset_name == asset.name
 	).set(
 		asset.value_after_depreciation, asset.value_after_depreciation - asset_total_depr_value_map.value
-	).where(
-		asset.docstatus == 1
-	).where(
-		asset.calculate_depreciation == 0
-	).run()
+	).where(asset.docstatus == 1).where(asset.calculate_depreciation == 0).run()
diff --git a/erpnext/patches/v15_0/update_sre_from_voucher_details.py b/erpnext/patches/v15_0/update_sre_from_voucher_details.py
index 06ba553..83d11cf 100644
--- a/erpnext/patches/v15_0/update_sre_from_voucher_details.py
+++ b/erpnext/patches/v15_0/update_sre_from_voucher_details.py
@@ -12,7 +12,5 @@
 			.set(sre.from_voucher_type, "Pick List")
 			.set(sre.from_voucher_no, sre.against_pick_list)
 			.set(sre.from_voucher_detail_no, sre.against_pick_list_item)
-			.where(
-				(IfNull(sre.against_pick_list, "") != "") & (IfNull(sre.against_pick_list_item, "") != "")
-			)
+			.where((IfNull(sre.against_pick_list, "") != "") & (IfNull(sre.against_pick_list_item, "") != ""))
 		).run()
diff --git a/erpnext/projects/doctype/project/project.py b/erpnext/projects/doctype/project/project.py
index 7600d0c..ff54fd0 100644
--- a/erpnext/projects/doctype/project/project.py
+++ b/erpnext/projects/doctype/project/project.py
@@ -38,9 +38,7 @@
 		cost_center: DF.Link | None
 		customer: DF.Link | None
 		daily_time_to_send: DF.Time | None
-		day_to_send: DF.Literal[
-			"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
-		]
+		day_to_send: DF.Literal["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
 		department: DF.Link | None
 		estimated_costing: DF.Currency
 		expected_end_date: DF.Date | None
@@ -107,7 +105,6 @@
 		Copy tasks from template
 		"""
 		if self.project_template and not frappe.db.get_all("Task", dict(project=self.name), limit=1):
-
 			# has a template, and no loaded tasks, so lets create
 			if not self.expected_start_date:
 				# project starts today
@@ -178,7 +175,9 @@
 			for child_task in template_task.get("depends_on"):
 				if project_template_map and project_template_map.get(child_task.task):
 					project_task.reload()  # reload, as it might have been updated in the previous iteration
-					project_task.append("depends_on", {"task": project_template_map.get(child_task.task).name})
+					project_task.append(
+						"depends_on", {"task": project_template_map.get(child_task.task).name}
+					)
 					project_task.save()
 
 	def check_for_parent_tasks(self, template_task, project_task, project_tasks):
@@ -332,7 +331,7 @@
 			frappe.db.set_value("Project", new_name, "copied_from", new_name)
 
 	def send_welcome_email(self):
-		url = get_url("/project/?name={0}".format(self.name))
+		url = get_url(f"/project/?name={self.name}")
 		messages = (
 			_("You have been invited to collaborate on the project: {0}").format(self.name),
 			url,
@@ -347,7 +346,9 @@
 		for user in self.users:
 			if user.welcome_email_sent == 0:
 				frappe.sendmail(
-					user.user, subject=_("Project Collaboration Invitation"), content=content.format(*messages)
+					user.user,
+					subject=_("Project Collaboration Invitation"),
+					content=content.format(*messages),
 				)
 				user.welcome_email_sent = 1
 
@@ -368,9 +369,7 @@
 	)
 
 
-def get_project_list(
-	doctype, txt, filters, limit_start, limit_page_length=20, order_by="creation"
-):
+def get_project_list(doctype, txt, filters, limit_start, limit_page_length=20, order_by="creation"):
 	customers, suppliers = get_customers_suppliers("Project", frappe.session.user)
 
 	ignore_permissions = False
@@ -671,9 +670,7 @@
 		return
 
 	# Else simply fallback to Daily
-	exists_query = (
-		"(SELECT 1 from `tab{doctype}` where docstatus = 1 and project = `tabProject`.name)"
-	)
+	exists_query = "(SELECT 1 from `tab{doctype}` where docstatus = 1 and project = `tabProject`.name)"
 	project_map = {}
 	for project_details in frappe.db.sql(
 		"""
@@ -736,9 +733,7 @@
 	holiday_list = frappe.get_cached_value("Company", company, "default_holiday_list")
 	if not holiday_list:
 		frappe.throw(
-			_("Please set a default Holiday List for Company {0}").format(
-				frappe.bold(get_default_company())
-			)
+			_("Please set a default Holiday List for Company {0}").format(frappe.bold(get_default_company()))
 		)
 	return holiday_list
 
diff --git a/erpnext/projects/doctype/project/test_project.py b/erpnext/projects/doctype/project/test_project.py
index b8340ff..1b7460f 100644
--- a/erpnext/projects/doctype/project/test_project.py
+++ b/erpnext/projects/doctype/project/test_project.py
@@ -30,9 +30,7 @@
 				priority="High",
 			)
 
-		template = make_project_template(
-			"Test Project Template - No Parent and Dependend Tasks", [task1]
-		)
+		template = make_project_template("Test Project Template - No Parent and Dependend Tasks", [task1])
 		project = get_project(project_name, template)
 		tasks = frappe.get_all(
 			"Task",
@@ -185,9 +183,7 @@
 			template_parent_task3,
 			template_task3,
 		]
-		project_template = make_project_template(
-			"Project template with common Task Subject", template_tasks
-		)
+		project_template = make_project_template("Project template with common Task Subject", template_tasks)
 
 		# Step - 4: Create Project against the Project Template
 		project = get_project("Project with common Task Subject", project_template)
@@ -196,7 +192,7 @@
 		)
 
 		# Test - 1: No. of Project Tasks should be equal to No. of Template Tasks
-		self.assertEquals(len(project_tasks), len(template_tasks))
+		self.assertEqual(len(project_tasks), len(template_tasks))
 
 		# Test - 2: All child Project Tasks should have Parent Task linked
 		for pt in project_tasks:
@@ -205,7 +201,6 @@
 
 
 def get_project(name, template):
-
 	project = frappe.get_doc(
 		dict(
 			doctype="Project",
diff --git a/erpnext/projects/doctype/project_template/test_project_template.py b/erpnext/projects/doctype/project_template/test_project_template.py
index 4fd24bf..382ffd5 100644
--- a/erpnext/projects/doctype/project_template/test_project_template.py
+++ b/erpnext/projects/doctype/project_template/test_project_template.py
@@ -12,7 +12,9 @@
 	pass
 
 
-def make_project_template(project_template_name, project_tasks=[]):
+def make_project_template(project_template_name, project_tasks=None):
+	if project_tasks is None:
+		project_tasks = []
 	if not frappe.db.exists("Project Template", project_template_name):
 		project_tasks = project_tasks or [
 			create_task(subject="_Test Template Task 1", is_template=1, begin=0, duration=3),
diff --git a/erpnext/projects/doctype/project_update/project_update.py b/erpnext/projects/doctype/project_update/project_update.py
index 53934d0..2153f1b 100644
--- a/erpnext/projects/doctype/project_update/project_update.py
+++ b/erpnext/projects/doctype/project_update/project_update.py
@@ -53,13 +53,8 @@
 		email_sending(project_name, frequency, date_start, date_end, progress, number_of_drafts, update)
 
 
-def email_sending(
-	project_name, frequency, date_start, date_end, progress, number_of_drafts, update
-):
-
-	holiday = frappe.db.sql(
-		"""SELECT holiday_date FROM `tabHoliday` where holiday_date = CURRENT_DATE;"""
-	)
+def email_sending(project_name, frequency, date_start, date_end, progress, number_of_drafts, update):
+	holiday = frappe.db.sql("""SELECT holiday_date FROM `tabHoliday` where holiday_date = CURRENT_DATE;""")
 	msg = (
 		"<p>Project Name: "
 		+ project_name
@@ -106,8 +101,6 @@
 	if len(holiday) == 0:
 		email = frappe.db.sql("""SELECT user from `tabProject User` WHERE parent = %s;""", project_name)
 		for emails in email:
-			frappe.sendmail(
-				recipients=emails, subject=frappe._(project_name + " " + "Summary"), message=msg
-			)
+			frappe.sendmail(recipients=emails, subject=frappe._(project_name + " " + "Summary"), message=msg)
 	else:
 		pass
diff --git a/erpnext/projects/doctype/task/task.py b/erpnext/projects/doctype/task/task.py
index 22df846..c03c99b 100755
--- a/erpnext/projects/doctype/task/task.py
+++ b/erpnext/projects/doctype/task/task.py
@@ -153,14 +153,14 @@
 	def validate_parent_template_task(self):
 		if self.parent_task:
 			if not frappe.db.get_value("Task", self.parent_task, "is_template"):
-				parent_task_format = """<a href="#Form/Task/{0}">{0}</a>""".format(self.parent_task)
+				parent_task_format = f"""<a href="#Form/Task/{self.parent_task}">{self.parent_task}</a>"""
 				frappe.throw(_("Parent Task {0} is not a Template Task").format(parent_task_format))
 
 	def validate_depends_on_tasks(self):
 		if self.depends_on:
 			for task in self.depends_on:
 				if not frappe.db.get_value("Task", task.task, "is_template"):
-					dependent_task_format = """<a href="#Form/Task/{0}">{0}</a>""".format(task.task)
+					dependent_task_format = f"""<a href="#Form/Task/{task.task}">{task.task}</a>"""
 					frappe.throw(_("Dependent Task {0} is not a Template Task").format(dependent_task_format))
 
 	def validate_completed_on(self):
@@ -219,7 +219,7 @@
 			task_list, count = [self.name], 0
 			while len(task_list) > count:
 				tasks = frappe.db.sql(
-					" select %s from `tabTask Depends On` where %s = %s " % (d[0], d[1], "%s"),
+					" select {} from `tabTask Depends On` where {} = {} ".format(d[0], d[1], "%s"),
 					cstr(task_list[count]),
 				)
 				count = count + 1
@@ -311,14 +311,12 @@
 	search_cond = " or " + " or ".join(field + " like %(txt)s" for field in searchfields)
 
 	return frappe.db.sql(
-		""" select name {search_columns} from `tabProject`
+		f""" select name {search_columns} from `tabProject`
 		where %(key)s like %(txt)s
 			%(mcond)s
-			{search_condition}
+			{search_cond}
 		order by name
-		limit %(page_len)s offset %(start)s""".format(
-			search_columns=search_columns, search_condition=search_cond
-		),
+		limit %(page_len)s offset %(start)s""",
 		{
 			"key": searchfield,
 			"txt": "%" + txt + "%",
@@ -379,7 +377,6 @@
 
 @frappe.whitelist()
 def get_children(doctype, parent, task=None, project=None, is_root=False):
-
 	filters = [["docstatus", "<", "2"]]
 
 	if task:
diff --git a/erpnext/projects/doctype/task/test_task.py b/erpnext/projects/doctype/task/test_task.py
index ea7d6ed..b0194b0 100644
--- a/erpnext/projects/doctype/task/test_task.py
+++ b/erpnext/projects/doctype/task/test_task.py
@@ -131,9 +131,7 @@
 		task.exp_start_date = start or nowdate()
 		task.exp_end_date = end or nowdate()
 		task.project = (
-			project or None
-			if is_template
-			else frappe.get_value("Project", {"project_name": "_Test Project"})
+			project or None if is_template else frappe.get_value("Project", {"project_name": "_Test Project"})
 		)
 		task.is_template = is_template
 		task.start = begin
diff --git a/erpnext/projects/doctype/timesheet/test_timesheet.py b/erpnext/projects/doctype/timesheet/test_timesheet.py
index 828a55e..da042f3 100644
--- a/erpnext/projects/doctype/timesheet/test_timesheet.py
+++ b/erpnext/projects/doctype/timesheet/test_timesheet.py
@@ -5,7 +5,7 @@
 import unittest
 
 import frappe
-from frappe.utils import add_months, add_to_date, now_datetime, nowdate
+from frappe.utils import add_to_date, now_datetime, nowdate
 
 from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice
 from erpnext.projects.doctype.timesheet.timesheet import OverlapError, make_sales_invoice
@@ -40,9 +40,7 @@
 		emp = make_employee("test_employee_6@salary.com")
 
 		timesheet = make_timesheet(emp, simulate=True, is_billable=1)
-		sales_invoice = make_sales_invoice(
-			timesheet.name, "_Test Item", "_Test Customer", currency="INR"
-		)
+		sales_invoice = make_sales_invoice(timesheet.name, "_Test Item", "_Test Customer", currency="INR")
 		sales_invoice.due_date = nowdate()
 		sales_invoice.submit()
 		timesheet = frappe.get_doc("Timesheet", timesheet.name)
@@ -211,9 +209,7 @@
 	timesheet_detail.activity_type = activity_type
 	timesheet_detail.from_time = now_datetime()
 	timesheet_detail.hours = 2
-	timesheet_detail.to_time = timesheet_detail.from_time + datetime.timedelta(
-		hours=timesheet_detail.hours
-	)
+	timesheet_detail.to_time = timesheet_detail.from_time + datetime.timedelta(hours=timesheet_detail.hours)
 	timesheet_detail.project = project
 	timesheet_detail.task = task
 
diff --git a/erpnext/projects/doctype/timesheet/timesheet.py b/erpnext/projects/doctype/timesheet/timesheet.py
index dcd289e..90f4368 100644
--- a/erpnext/projects/doctype/timesheet/timesheet.py
+++ b/erpnext/projects/doctype/timesheet/timesheet.py
@@ -309,12 +309,10 @@
 @frappe.whitelist()
 def get_timesheet_detail_rate(timelog, currency):
 	timelog_detail = frappe.db.sql(
-		"""SELECT tsd.billing_amount as billing_amount,
+		f"""SELECT tsd.billing_amount as billing_amount,
 		ts.currency as currency FROM `tabTimesheet Detail` tsd
 		INNER JOIN `tabTimesheet` ts ON ts.name=tsd.parent
-		WHERE tsd.name = '{0}'""".format(
-			timelog
-		),
+		WHERE tsd.name = '{timelog}'""",
 		as_dict=1,
 	)[0]
 
@@ -336,14 +334,12 @@
 		condition = "and tsd.project = %(project)s"
 
 	return frappe.db.sql(
-		"""select distinct tsd.parent from `tabTimesheet Detail` tsd,
+		f"""select distinct tsd.parent from `tabTimesheet Detail` tsd,
 			`tabTimesheet` ts where
 			ts.status in ('Submitted', 'Payslip') and tsd.parent = ts.name and
 			tsd.docstatus = 1 and ts.total_billable_amount > 0
 			and tsd.parent LIKE %(txt)s {condition}
-			order by tsd.parent limit %(page_len)s offset %(start)s""".format(
-			condition=condition
-		),
+			order by tsd.parent limit %(page_len)s offset %(start)s""",
 		{
 			"txt": "%" + txt + "%",
 			"start": start,
@@ -469,18 +465,14 @@
 		where `tabTimesheet Detail`.parent = `tabTimesheet`.name
 			and `tabTimesheet`.docstatus < 2
 			and (from_time <= %(end)s and to_time >= %(start)s) {conditions} {match_cond}
-		""".format(
-			conditions=conditions, match_cond=get_match_cond("Timesheet")
-		),
+		""".format(conditions=conditions, match_cond=get_match_cond("Timesheet")),
 		{"start": start, "end": end},
 		as_dict=True,
 		update={"allDay": 0},
 	)
 
 
-def get_timesheets_list(
-	doctype, txt, filters, limit_start, limit_page_length=20, order_by="creation"
-):
+def get_timesheets_list(doctype, txt, filters, limit_start, limit_page_length=20, order_by="creation"):
 	user = frappe.session.user
 	# find customer name from contact.
 	customer = ""
@@ -499,7 +491,7 @@
 		projects = [d.name for d in frappe.get_all("Project", filters={"customer": customer})]
 		# Return timesheet related data to web portal.
 		timesheets = frappe.db.sql(
-			"""
+			f"""
 			SELECT
 				ts.name, tsd.activity_type, ts.status, ts.total_billable_hours,
 				COALESCE(ts.sales_invoice, tsd.sales_invoice) AS sales_invoice, tsd.project
@@ -511,10 +503,8 @@
 					tsd.project IN %(projects)s
 				)
 			ORDER BY `end_date` ASC
-			LIMIT {1} offset {0}
-		""".format(
-				limit_start, limit_page_length
-			),
+			LIMIT {limit_page_length} offset {limit_start}
+		""",
 			dict(sales_invoices=sales_invoices, projects=projects),
 			as_dict=True,
 		)  # nosec
diff --git a/erpnext/projects/report/delayed_tasks_summary/test_delayed_tasks_summary.py b/erpnext/projects/report/delayed_tasks_summary/test_delayed_tasks_summary.py
index 91a0607..c288125 100644
--- a/erpnext/projects/report/delayed_tasks_summary/test_delayed_tasks_summary.py
+++ b/erpnext/projects/report/delayed_tasks_summary/test_delayed_tasks_summary.py
@@ -31,14 +31,14 @@
 			{"subject": "_Test Task 98", "status": "Completed", "priority": "Low", "delay": -1},
 		]
 		report = execute(filters)
-		data = list(filter(lambda x: x.subject == "_Test Task 99", report[1]))[0]
+		data = next(filter(lambda x: x.subject == "_Test Task 99", report[1]))
 
 		for key in ["subject", "status", "priority", "delay"]:
 			self.assertEqual(expected_data[0].get(key), data.get(key))
 
 		filters.status = "Completed"
 		report = execute(filters)
-		data = list(filter(lambda x: x.subject == "_Test Task 98", report[1]))[0]
+		data = next(filter(lambda x: x.subject == "_Test Task 98", report[1]))
 
 		for key in ["subject", "status", "priority", "delay"]:
 			self.assertEqual(expected_data[1].get(key), data.get(key))
diff --git a/erpnext/projects/utils.py b/erpnext/projects/utils.py
index 3cc4da4..5046d01 100644
--- a/erpnext/projects/utils.py
+++ b/erpnext/projects/utils.py
@@ -19,13 +19,14 @@
 
 	return frappe.db.sql(
 		"""select name, subject from `tabTask`
-		where (`%s` like %s or `subject` like %s) %s
+		where (`{}` like {} or `subject` like {}) {}
 		order by
-			case when `subject` like %s then 0 else 1 end,
-			case when `%s` like %s then 0 else 1 end,
-			`%s`,
+			case when `subject` like {} then 0 else 1 end,
+			case when `{}` like {} then 0 else 1 end,
+			`{}`,
 			subject
-		limit %s offset %s"""
-		% (searchfield, "%s", "%s", match_conditions, "%s", searchfield, "%s", searchfield, "%s", "%s"),
+		limit {} offset {}""".format(
+			searchfield, "%s", "%s", match_conditions, "%s", searchfield, "%s", searchfield, "%s", "%s"
+		),
 		(search_string, search_string, order_by_string, order_by_string, page_len, start),
 	)
diff --git a/erpnext/quality_management/doctype/quality_procedure/quality_procedure.py b/erpnext/quality_management/doctype/quality_procedure/quality_procedure.py
index 8a67d92..d65345e 100644
--- a/erpnext/quality_management/doctype/quality_procedure/quality_procedure.py
+++ b/erpnext/quality_management/doctype/quality_procedure/quality_procedure.py
@@ -77,7 +77,9 @@
 
 		for process in self.processes:
 			if process.procedure:
-				if not frappe.db.get_value("Quality Procedure", process.procedure, "parent_quality_procedure"):
+				if not frappe.db.get_value(
+					"Quality Procedure", process.procedure, "parent_quality_procedure"
+				):
 					frappe.db.set_value(
 						"Quality Procedure", process.procedure, "parent_quality_procedure", self.name
 					)
@@ -89,9 +91,13 @@
 			if old_child_procedures := set([d.procedure for d in old_doc.processes if d.procedure]):
 				current_child_procedures = set([d.procedure for d in self.processes if d.procedure])
 
-				if removed_child_procedures := list(old_child_procedures.difference(current_child_procedures)):
+				if removed_child_procedures := list(
+					old_child_procedures.difference(current_child_procedures)
+				):
 					for child_procedure in removed_child_procedures:
-						frappe.db.set_value("Quality Procedure", child_procedure, "parent_quality_procedure", None)
+						frappe.db.set_value(
+							"Quality Procedure", child_procedure, "parent_quality_procedure", None
+						)
 
 	def add_child_to_parent(self):
 		"""Add `Child Procedure` to `Parent Procedure`"""
@@ -125,7 +131,8 @@
 		# return the list in order
 		return [
 			dict(
-				value=d.procedure, expandable=frappe.db.get_value("Quality Procedure", d.procedure, "is_group")
+				value=d.procedure,
+				expandable=frappe.db.get_value("Quality Procedure", d.procedure, "is_group"),
 			)
 			for d in parent_procedure.processes
 			if d.procedure
diff --git a/erpnext/quality_management/doctype/quality_review/quality_review.py b/erpnext/quality_management/doctype/quality_review/quality_review.py
index bf4a403..fa5448d 100644
--- a/erpnext/quality_management/doctype/quality_review/quality_review.py
+++ b/erpnext/quality_management/doctype/quality_review/quality_review.py
@@ -67,9 +67,7 @@
 def create_review(goal):
 	goal = frappe.get_doc("Quality Goal", goal)
 
-	review = frappe.get_doc(
-		{"doctype": "Quality Review", "goal": goal.name, "date": frappe.utils.getdate()}
-	)
+	review = frappe.get_doc({"doctype": "Quality Review", "goal": goal.name, "date": frappe.utils.getdate()})
 
 	review.insert(ignore_permissions=True)
 
diff --git a/erpnext/regional/address_template/setup.py b/erpnext/regional/address_template/setup.py
index fd1dfa7..684c766 100644
--- a/erpnext/regional/address_template/setup.py
+++ b/erpnext/regional/address_template/setup.py
@@ -1,5 +1,6 @@
 """Import Address Templates from ./templates directory."""
 import os
+
 import frappe
 
 
@@ -26,7 +27,7 @@
 	def get_file_content(file_name):
 		"""Convert 'united_states.html' to '/path/to/united_states.html'."""
 		full_path = os.path.join(template_dir, file_name)
-		with open(full_path, "r") as f:
+		with open(full_path) as f:
 			content = f.read()
 		return content
 
@@ -41,7 +42,7 @@
 def update_address_template(country, html, is_default=0):
 	"""Update existing Address Template or create a new one."""
 	if not frappe.db.exists("Country", country):
-		frappe.log_error("Country {} for regional Address Template does not exist.".format(country))
+		frappe.log_error(f"Country {country} for regional Address Template does not exist.")
 		return
 
 	if frappe.db.exists("Address Template", country):
diff --git a/erpnext/regional/address_template/test_regional_address_template.py b/erpnext/regional/address_template/test_regional_address_template.py
index 523653b..952748b 100644
--- a/erpnext/regional/address_template/test_regional_address_template.py
+++ b/erpnext/regional/address_template/test_regional_address_template.py
@@ -32,7 +32,7 @@
 		"""Update an existing Address Template."""
 		country = ensure_country("Germany")
 		if not frappe.db.exists("Address Template", country.name):
-			template = frappe.get_doc(
+			frappe.get_doc(
 				{"doctype": "Address Template", "country": country.name, "template": "EXISTING"}
 			).insert()
 
diff --git a/erpnext/regional/doctype/import_supplier_invoice/import_supplier_invoice.py b/erpnext/regional/doctype/import_supplier_invoice/import_supplier_invoice.py
index bf338d6..fc2dc96 100644
--- a/erpnext/regional/doctype/import_supplier_invoice/import_supplier_invoice.py
+++ b/erpnext/regional/doctype/import_supplier_invoice/import_supplier_invoice.py
@@ -95,13 +95,13 @@
 			invoices_args["terms"] = get_payment_terms_from_file(file_content)
 
 			supplier_name = create_supplier(self.supplier_group, supp_dict)
-			address = create_address(supplier_name, supp_dict)
+			create_address(supplier_name, supp_dict)
 			pi_name = create_purchase_invoice(supplier_name, file_name, invoices_args, self.name)
 
 			self.file_count += 1
 			if pi_name:
 				self.purchase_invoices_count += 1
-				file_save = save_file(
+				save_file(
 					file_name,
 					encoded_content,
 					"Purchase Invoice",
@@ -179,7 +179,7 @@
 	except UnicodeDecodeError:
 		try:
 			content = encoded_content.decode("utf-16")
-		except UnicodeDecodeError as e:
+		except UnicodeDecodeError:
 			frappe.log_error("UTF-16 encoding error for File Name: " + file_name)
 
 	return content
@@ -297,7 +297,6 @@
 
 		return existing_supplier_name
 	else:
-
 		new_supplier = frappe.new_doc("Supplier")
 		new_supplier.supplier_name = re.sub("&amp", "&", args.supplier)
 		new_supplier.supplier_group = supplier_group
@@ -408,7 +407,7 @@
 		pi.imported_grand_total = calc_total
 		pi.save()
 		return pi.name
-	except Exception as e:
+	except Exception:
 		frappe.db.set_value("Import Supplier Invoice", name, "status", "Error")
 		pi.log_error("Unable to create Puchase Invoice")
 		return None
diff --git a/erpnext/regional/italy/setup.py b/erpnext/regional/italy/setup.py
index 1f66b36..23406ea 100644
--- a/erpnext/regional/italy/setup.py
+++ b/erpnext/regional/italy/setup.py
@@ -7,10 +7,11 @@
 from frappe import _
 from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
 from frappe.permissions import add_permission, update_permission_property
+
 from erpnext.regional.italy import (
 	fiscal_regimes,
-	tax_exemption_reasons,
 	mode_of_payment_codes,
+	tax_exemption_reasons,
 	vat_collectability_options,
 )
 
diff --git a/erpnext/regional/italy/utils.py b/erpnext/regional/italy/utils.py
index 9106d09..371390b 100644
--- a/erpnext/regional/italy/utils.py
+++ b/erpnext/regional/italy/utils.py
@@ -39,7 +39,7 @@
 
 	attachments = get_e_invoice_attachments(invoices)
 
-	zip_filename = "{0}-einvoices.zip".format(frappe.utils.get_datetime().strftime("%Y%m%d_%H%M%S"))
+	zip_filename = "{}-einvoices.zip".format(frappe.utils.get_datetime().strftime("%Y%m%d_%H%M%S"))
 
 	download_zip(attachments, zip_filename)
 
@@ -307,7 +307,9 @@
 		for row in doc.taxes:
 			if row.rate == 0 and row.tax_amount == 0 and not row.tax_exemption_reason:
 				frappe.throw(
-					_("Row {0}: Please set at Tax Exemption Reason in Sales Taxes and Charges").format(row.idx),
+					_("Row {0}: Please set at Tax Exemption Reason in Sales Taxes and Charges").format(
+						row.idx
+					),
 					title=_("E-Invoicing Information Missing"),
 				)
 
@@ -338,9 +340,7 @@
 					_("Row {0}: Please set the Mode of Payment in Payment Schedule").format(schedule.idx),
 					title=_("E-Invoicing Information Missing"),
 				)
-			elif not frappe.db.get_value(
-				"Mode of Payment", schedule.mode_of_payment, "mode_of_payment_code"
-			):
+			elif not frappe.db.get_value("Mode of Payment", schedule.mode_of_payment, "mode_of_payment_code"):
 				frappe.throw(
 					_("Row {0}: Please set the correct code on Mode of Payment {1}").format(
 						schedule.idx, schedule.mode_of_payment
@@ -473,9 +473,7 @@
 			filename = attachment.file_name.split(".xml")[0]
 			return filename, filename.split("_")[1]
 
-	company_tax_id = (
-		doc.company_tax_id if doc.company_tax_id.startswith("IT") else "IT" + doc.company_tax_id
-	)
+	company_tax_id = doc.company_tax_id if doc.company_tax_id.startswith("IT") else "IT" + doc.company_tax_id
 	progressive_name = frappe.model.naming.make_autoname(company_tax_id + "_.#####")
 	progressive_number = progressive_name.split("_")[1]
 
diff --git a/erpnext/regional/report/irs_1099/irs_1099.py b/erpnext/regional/report/irs_1099/irs_1099.py
index c5d8112..41e3761 100644
--- a/erpnext/regional/report/irs_1099/irs_1099.py
+++ b/erpnext/regional/report/irs_1099/irs_1099.py
@@ -34,7 +34,7 @@
 		conditions += "AND s.supplier_group = %s" % frappe.db.escape(filters.get("supplier_group"))
 
 	data = frappe.db.sql(
-		"""
+		f"""
 		SELECT
 			s.supplier_group as "supplier_group",
 			gl.party AS "supplier",
@@ -55,9 +55,7 @@
 			gl.party
 
 		ORDER BY
-			gl.party DESC""".format(
-			conditions=conditions
-		),
+			gl.party DESC""",
 		{"fiscal_year": filters.fiscal_year, "company": filters.company},
 		as_dict=True,
 	)
@@ -117,7 +115,7 @@
 			"Supplier", row.supplier
 		)
 		row["payments"] = fmt_money(row["payments"], precision=0, currency="USD")
-		pdf = get_pdf(render_template(template, row), output=output if output else None)
+		get_pdf(render_template(template, row), output=output if output else None)
 
 	frappe.local.response.filename = (
 		f"{filters.fiscal_year} {filters.company} IRS 1099 Forms{IRS_1099_FORMS_FILE_EXTENSION}"
diff --git a/erpnext/regional/report/uae_vat_201/uae_vat_201.py b/erpnext/regional/report/uae_vat_201/uae_vat_201.py
index 6ef21e5..1b77b3c 100644
--- a/erpnext/regional/report/uae_vat_201/uae_vat_201.py
+++ b/erpnext/regional/report/uae_vat_201/uae_vat_201.py
@@ -62,13 +62,9 @@
 		frappe.format(get_reverse_charge_tax(filters), "Currency"),
 	)
 
-	append_data(
-		data, "4", _("Zero Rated"), frappe.format(get_zero_rated_total(filters), "Currency"), "-"
-	)
+	append_data(data, "4", _("Zero Rated"), frappe.format(get_zero_rated_total(filters), "Currency"), "-")
 
-	append_data(
-		data, "5", _("Exempt Supplies"), frappe.format(get_exempt_total(filters), "Currency"), "-"
-	)
+	append_data(data, "5", _("Exempt Supplies"), frappe.format(get_exempt_total(filters), "Currency"), "-")
 
 	append_data(data, "", "", "", "")
 
@@ -139,7 +135,7 @@
 	conditions = get_conditions(filters)
 	try:
 		return frappe.db.sql(
-			"""
+			f"""
 			select
 				s.vat_emirate as emirate, sum(i.base_net_amount) as total, sum(i.tax_amount)
 			from
@@ -148,12 +144,10 @@
 				i.parent = s.name
 			where
 				s.docstatus = 1 and  i.is_exempt != 1 and i.is_zero_rated != 1
-				{where_conditions}
+				{conditions}
 			group by
 				s.vat_emirate;
-			""".format(
-				where_conditions=conditions
-			),
+			""",
 			filters,
 		)
 	except (IndexError, TypeError):
@@ -198,7 +192,7 @@
 	conditions = get_conditions_join(filters)
 	return (
 		frappe.db.sql(
-			"""
+			f"""
 		select sum(debit)  from
 			`tabPurchase Invoice` p inner join `tabGL Entry` gl
 		on
@@ -208,10 +202,8 @@
 			and p.docstatus = 1
 			and gl.docstatus = 1
 			and account in (select account from `tabUAE VAT Account` where  parent=%(company)s)
-			{where_conditions} ;
-		""".format(
-				where_conditions=conditions
-			),
+			{conditions} ;
+		""",
 			filters,
 		)[0][0]
 		or 0
@@ -240,7 +232,7 @@
 	conditions = get_conditions_join(filters)
 	return (
 		frappe.db.sql(
-			"""
+			f"""
 		select
 			sum(debit * p.recoverable_reverse_charge / 100)
 		from
@@ -253,10 +245,8 @@
 			and p.recoverable_reverse_charge > 0
 			and gl.docstatus = 1
 			and account in (select account from `tabUAE VAT Account` where  parent=%(company)s)
-			{where_conditions} ;
-		""".format(
-				where_conditions=conditions
-			),
+			{conditions} ;
+		""",
 			filters,
 		)[0][0]
 		or 0
@@ -354,7 +344,7 @@
 	try:
 		return (
 			frappe.db.sql(
-				"""
+				f"""
 			select
 				sum(i.base_net_amount) as total
 			from
@@ -363,10 +353,8 @@
 				i.parent = s.name
 			where
 				s.docstatus = 1 and  i.is_zero_rated = 1
-				{where_conditions} ;
-			""".format(
-					where_conditions=conditions
-				),
+				{conditions} ;
+			""",
 				filters,
 			)[0][0]
 			or 0
@@ -381,7 +369,7 @@
 	try:
 		return (
 			frappe.db.sql(
-				"""
+				f"""
 			select
 				sum(i.base_net_amount) as total
 			from
@@ -390,10 +378,8 @@
 				i.parent = s.name
 			where
 				s.docstatus = 1 and  i.is_exempt = 1
-				{where_conditions} ;
-			""".format(
-					where_conditions=conditions
-				),
+				{conditions} ;
+			""",
 				filters,
 			)[0][0]
 			or 0
diff --git a/erpnext/regional/report/vat_audit_report/vat_audit_report.py b/erpnext/regional/report/vat_audit_report/vat_audit_report.py
index 3d486ce..718b6c0 100644
--- a/erpnext/regional/report/vat_audit_report/vat_audit_report.py
+++ b/erpnext/regional/report/vat_audit_report/vat_audit_report.py
@@ -13,7 +13,7 @@
 	return VATAuditReport(filters).run()
 
 
-class VATAuditReport(object):
+class VATAuditReport:
 	def __init__(self, filters=None):
 		self.filters = frappe._dict(filters or {})
 		self.columns = []
@@ -58,19 +58,17 @@
 		self.invoices = frappe._dict()
 
 		invoice_data = frappe.db.sql(
-			"""
+			f"""
 			SELECT
-				{select_columns}
+				{self.select_columns}
 			FROM
 				`tab{doctype}`
 			WHERE
-				docstatus = 1 {where_conditions}
+				docstatus = 1 {conditions}
 				and is_opening = 'No'
 			ORDER BY
 				posting_date DESC
-			""".format(
-				select_columns=self.select_columns, doctype=doctype, where_conditions=conditions
-			),
+			""",
 			self.filters,
 			as_dict=1,
 		)
@@ -86,11 +84,10 @@
 			SELECT
 				item_code, parent, base_net_amount, is_zero_rated
 			FROM
-				`tab%s Item`
+				`tab{} Item`
 			WHERE
-				parent in (%s)
-			"""
-			% (doctype, ", ".join(["%s"] * len(self.invoices))),
+				parent in ({})
+			""".format(doctype, ", ".join(["%s"] * len(self.invoices))),
 			tuple(self.invoices),
 			as_dict=1,
 		)
@@ -111,15 +108,14 @@
 			SELECT
 				parent, account_head, item_wise_tax_detail
 			FROM
-				`tab%s`
+				`tab{}`
 			WHERE
-				parenttype = %s and docstatus = 1
-				and parent in (%s)
+				parenttype = {} and docstatus = 1
+				and parent in ({})
 			ORDER BY
 				account_head
-			"""
-			% (self.tax_doctype, "%s", ", ".join(["%s"] * len(self.invoices.keys()))),
-			tuple([doctype] + list(self.invoices.keys())),
+			""".format(self.tax_doctype, "%s", ", ".join(["%s"] * len(self.invoices.keys()))),
+			tuple([doctype, *list(self.invoices.keys())]),
 		)
 
 		for parent, account, item_wise_tax_detail in self.tax_details:
diff --git a/erpnext/regional/united_arab_emirates/utils.py b/erpnext/regional/united_arab_emirates/utils.py
index 634a152..d71b87b 100644
--- a/erpnext/regional/united_arab_emirates/utils.py
+++ b/erpnext/regional/united_arab_emirates/utils.py
@@ -55,14 +55,12 @@
 def get_tax_accounts(company):
 	"""Get the list of tax accounts for a specific company."""
 	tax_accounts_dict = frappe._dict()
-	tax_accounts_list = frappe.get_all(
-		"UAE VAT Account", filters={"parent": company}, fields=["Account"]
-	)
+	tax_accounts_list = frappe.get_all("UAE VAT Account", filters={"parent": company}, fields=["Account"])
 
 	if not tax_accounts_list and not frappe.flags.in_test:
 		frappe.throw(_('Please set Vat Accounts for Company: "{0}" in UAE VAT Settings').format(company))
 	for tax_account in tax_accounts_list:
-		for account, name in tax_account.items():
+		for _account, name in tax_account.items():
 			tax_accounts_dict[name] = name
 
 	return tax_accounts_dict
@@ -106,7 +104,6 @@
 	doc.grand_total -= vat_tax
 
 	if doc.meta.get_field("rounded_total"):
-
 		if doc.is_rounded_total_disabled():
 			doc.outstanding_amount = doc.grand_total
 
@@ -120,9 +117,7 @@
 			doc.outstanding_amount = doc.rounded_total or doc.grand_total
 
 	doc.in_words = money_in_words(doc.grand_total, doc.currency)
-	doc.base_in_words = money_in_words(
-		doc.base_grand_total, erpnext.get_company_currency(doc.company)
-	)
+	doc.base_in_words = money_in_words(doc.base_grand_total, erpnext.get_company_currency(doc.company))
 	doc.set_payment_schedule()
 
 
diff --git a/erpnext/regional/united_states/test_united_states.py b/erpnext/regional/united_states/test_united_states.py
index 83ba6ed..e54552b 100644
--- a/erpnext/regional/united_states/test_united_states.py
+++ b/erpnext/regional/united_states/test_united_states.py
@@ -10,7 +10,6 @@
 
 class TestUnitedStates(unittest.TestCase):
 	def test_irs_1099_custom_field(self):
-
 		if not frappe.db.exists("Supplier", "_US 1099 Test Supplier"):
 			doc = frappe.new_doc("Supplier")
 			doc.supplier_name = "_US 1099 Test Supplier"
@@ -38,7 +37,6 @@
 
 
 def make_payment_entry_to_irs_1099_supplier():
-
 	frappe.db.sql("delete from `tabGL Entry` where party='_US 1099 Test Supplier'")
 	frappe.db.sql("delete from `tabGL Entry` where against='_US 1099 Test Supplier'")
 	frappe.db.sql("delete from `tabPayment Entry` where party='_US 1099 Test Supplier'")
diff --git a/erpnext/selling/doctype/customer/customer.py b/erpnext/selling/doctype/customer/customer.py
index 3744922..bb6481c 100644
--- a/erpnext/selling/doctype/customer/customer.py
+++ b/erpnext/selling/doctype/customer/customer.py
@@ -17,7 +17,7 @@
 from frappe.utils import cint, cstr, flt, get_formatted_email, today
 from frappe.utils.user import get_users_with_role
 
-from erpnext.accounts.party import get_dashboard_info, validate_party_accounts  # noqa
+from erpnext.accounts.party import get_dashboard_info, validate_party_accounts
 from erpnext.controllers.website_list_for_contact import add_role_for_portal_user
 from erpnext.utilities.transaction_base import TransactionBase
 
@@ -106,17 +106,16 @@
 			self.name = set_name_from_naming_options(frappe.get_meta(self.doctype).autoname, self)
 
 	def get_customer_name(self):
-
 		if frappe.db.get_value("Customer", self.customer_name) and not frappe.flags.in_import:
 			count = frappe.db.sql(
 				"""select ifnull(MAX(CAST(SUBSTRING_INDEX(name, ' ', -1) AS UNSIGNED)), 0) from tabCustomer
 				 where name like %s""",
-				"%{0} - %".format(self.customer_name),
+				f"%{self.customer_name} - %",
 				as_list=1,
 			)[0][0]
 			count = cint(count) + 1
 
-			new_customer_name = "{0} - {1}".format(self.customer_name, cstr(count))
+			new_customer_name = f"{self.customer_name} - {cstr(count)}"
 
 			msgprint(
 				_("Changed customer name to '{}' as '{}' already exists.").format(
@@ -326,9 +325,7 @@
 			)
 		]
 
-		current_credit_limits = [
-			d.credit_limit for d in sorted(self.credit_limits, key=lambda k: k.company)
-		]
+		current_credit_limits = [d.credit_limit for d in sorted(self.credit_limits, key=lambda k: k.company)]
 
 		if past_credit_limits == current_credit_limits:
 			return
@@ -492,9 +489,7 @@
 		) and (
 			not loyalty_program.customer_territory
 			or doc.territory
-			in get_nested_links(
-				"Territory", loyalty_program.customer_territory, doc.flags.ignore_permissions
-			)
+			in get_nested_links("Territory", loyalty_program.customer_territory, doc.flags.ignore_permissions)
 		):
 			lp_details.append(loyalty_program.name)
 
@@ -540,12 +535,12 @@
 			]
 			if not credit_controller_users_formatted:
 				frappe.throw(
-					_("Please contact your administrator to extend the credit limits for {0}.").format(customer)
+					_("Please contact your administrator to extend the credit limits for {0}.").format(
+						customer
+					)
 				)
 
-			user_list = "<br><br><ul><li>{0}</li></ul>".format(
-				"<li>".join(credit_controller_users_formatted)
-			)
+			user_list = "<br><br><ul><li>{}</li></ul>".format("<li>".join(credit_controller_users_formatted))
 
 			message += _(
 				"Please contact any of the following users to extend the credit limits for {0}: {1}"
@@ -582,27 +577,21 @@
 	frappe.sendmail(recipients=credit_controller_users_list, subject=subject, message=message)
 
 
-def get_customer_outstanding(
-	customer, company, ignore_outstanding_sales_order=False, cost_center=None
-):
+def get_customer_outstanding(customer, company, ignore_outstanding_sales_order=False, cost_center=None):
 	# Outstanding based on GL Entries
 	cond = ""
 	if cost_center:
 		lft, rgt = frappe.get_cached_value("Cost Center", cost_center, ["lft", "rgt"])
 
-		cond = """ and cost_center in (select name from `tabCost Center` where
-			lft >= {0} and rgt <= {1})""".format(
-			lft, rgt
-		)
+		cond = f""" and cost_center in (select name from `tabCost Center` where
+			lft >= {lft} and rgt <= {rgt})"""
 
 	outstanding_based_on_gle = frappe.db.sql(
-		"""
+		f"""
 		select sum(debit) - sum(credit)
 		from `tabGL Entry` where party_type = 'Customer'
 		and is_cancelled = 0 and party = %s
-		and company=%s {0}""".format(
-			cond
-		),
+		and company=%s {cond}""",
 		(customer, company),
 	)
 
@@ -750,7 +739,7 @@
 	if reqd_fields:
 		msg = _("Following fields are mandatory to create address:")
 		frappe.throw(
-			"{0} <br><br> <ul>{1}</ul>".format(msg, "\n".join(reqd_fields)),
+			"{} <br><br> <ul>{}</ul>".format(msg, "\n".join(reqd_fields)),
 			title=_("Missing Values Required"),
 		)
 
diff --git a/erpnext/selling/doctype/customer/test_customer.py b/erpnext/selling/doctype/customer/test_customer.py
index 7e6d6de..de2172d 100644
--- a/erpnext/selling/doctype/customer/test_customer.py
+++ b/erpnext/selling/doctype/customer/test_customer.py
@@ -3,7 +3,6 @@
 
 
 import frappe
-from frappe.custom.doctype.property_setter.property_setter import make_property_setter
 from frappe.test_runner import make_test_records
 from frappe.tests.utils import FrappeTestCase
 from frappe.utils import flt
@@ -268,7 +267,6 @@
 
 	def test_customer_credit_limit(self):
 		from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice
-		from erpnext.selling.doctype.sales_order.sales_order import make_sales_invoice
 		from erpnext.selling.doctype.sales_order.test_sales_order import make_sales_order
 		from erpnext.stock.doctype.delivery_note.test_delivery_note import create_delivery_note
 
@@ -412,17 +410,13 @@
 		customer.credit_limits[-1].db_insert()
 
 
-def create_internal_customer(
-	customer_name=None, represents_company=None, allowed_to_interact_with=None
-):
+def create_internal_customer(customer_name=None, represents_company=None, allowed_to_interact_with=None):
 	if not customer_name:
 		customer_name = represents_company
 	if not allowed_to_interact_with:
 		allowed_to_interact_with = represents_company
 
-	existing_representative = frappe.db.get_value(
-		"Customer", {"represents_company": represents_company}
-	)
+	existing_representative = frappe.db.get_value("Customer", {"represents_company": represents_company})
 	if existing_representative:
 		return existing_representative
 
diff --git a/erpnext/selling/doctype/installation_note/installation_note.py b/erpnext/selling/doctype/installation_note/installation_note.py
index ac7cd60..b7dd578 100644
--- a/erpnext/selling/doctype/installation_note/installation_note.py
+++ b/erpnext/selling/doctype/installation_note/installation_note.py
@@ -45,7 +45,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(InstallationNote, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 		self.status_updater = [
 			{
 				"source_dt": "Installation Note Item",
diff --git a/erpnext/selling/doctype/product_bundle/product_bundle.py b/erpnext/selling/doctype/product_bundle/product_bundle.py
index 6632742..464cff0 100644
--- a/erpnext/selling/doctype/product_bundle/product_bundle.py
+++ b/erpnext/selling/doctype/product_bundle/product_bundle.py
@@ -65,7 +65,7 @@
 
 		if len(invoice_links):
 			frappe.throw(
-				"This Product Bundle is linked with {0}. You will have to cancel these documents in order to delete this Product Bundle".format(
+				"This Product Bundle is linked with {}. You will have to cancel these documents in order to delete this Product Bundle".format(
 					", ".join(invoice_links)
 				),
 				title=_("Not Allowed"),
@@ -97,9 +97,7 @@
 	query = (
 		frappe.qb.from_(item)
 		.select(item.item_code, item.item_name)
-		.where(
-			(item.is_stock_item == 0) & (item.is_fixed_asset == 0) & (item[searchfield].like(f"%{txt}%"))
-		)
+		.where((item.is_stock_item == 0) & (item.is_fixed_asset == 0) & (item[searchfield].like(f"%{txt}%")))
 		.limit(page_len)
 		.offset(start)
 	)
diff --git a/erpnext/selling/doctype/quotation/quotation.py b/erpnext/selling/doctype/quotation/quotation.py
index 6977f06..17fc2b7 100644
--- a/erpnext/selling/doctype/quotation/quotation.py
+++ b/erpnext/selling/doctype/quotation/quotation.py
@@ -125,7 +125,7 @@
 			self.indicator_title = "Expired"
 
 	def validate(self):
-		super(Quotation, self).validate()
+		super().validate()
 		self.set_status()
 		self.validate_uom_is_integer("stock_uom", "stock_qty")
 		self.validate_uom_is_integer("uom", "qty")
@@ -188,7 +188,8 @@
 		def is_in_sales_order(row):
 			in_sales_order = bool(
 				frappe.db.exists(
-					"Sales Order Item", {"quotation_item": row.name, "item_code": row.item_code, "docstatus": 1}
+					"Sales Order Item",
+					{"quotation_item": row.name, "item_code": row.item_code, "docstatus": 1},
 				)
 			)
 			return in_sales_order
@@ -278,7 +279,7 @@
 	def on_cancel(self):
 		if self.lost_reasons:
 			self.lost_reasons = []
-		super(Quotation, self).on_cancel()
+		super().on_cancel()
 
 		# update enquiry status
 		self.set_status(update=True)
@@ -453,12 +454,8 @@
 	# if not exists any SO, set status as Expired
 	frappe.db.multisql(
 		{
-			"mariadb": """UPDATE `tabQuotation`  SET `tabQuotation`.status = 'Expired' WHERE {cond} and not exists({so_against_quo})""".format(
-				cond=cond, so_against_quo=so_against_quo
-			),
-			"postgres": """UPDATE `tabQuotation` SET status = 'Expired' FROM `tabSales Order`, `tabSales Order Item` WHERE {cond} and not exists({so_against_quo})""".format(
-				cond=cond, so_against_quo=so_against_quo
-			),
+			"mariadb": f"""UPDATE `tabQuotation`  SET `tabQuotation`.status = 'Expired' WHERE {cond} and not exists({so_against_quo})""",
+			"postgres": f"""UPDATE `tabQuotation` SET status = 'Expired' FROM `tabSales Order`, `tabSales Order Item` WHERE {cond} and not exists({so_against_quo})""",
 		},
 		(nowdate()),
 	)
@@ -547,9 +544,7 @@
 	mandatory_fields = [customer.meta.get_label(field.strip()) for field in mandatory_fields]
 
 	frappe.local.message_log = []
-	message = (
-		_("Could not auto create Customer due to the following missing mandatory field(s):") + "<br>"
-	)
+	message = _("Could not auto create Customer due to the following missing mandatory field(s):") + "<br>"
 	message += "<br><ul><li>" + "</li><li>".join(mandatory_fields) + "</li></ul>"
 	message += _("Please create Customer from Lead {0}.").format(get_link_to_form("Lead", lead_name))
 
diff --git a/erpnext/selling/doctype/quotation/test_quotation.py b/erpnext/selling/doctype/quotation/test_quotation.py
index a525942..57c14db 100644
--- a/erpnext/selling/doctype/quotation/test_quotation.py
+++ b/erpnext/selling/doctype/quotation/test_quotation.py
@@ -152,9 +152,7 @@
 		self.assertEqual(quotation.payment_schedule[0].payment_amount, 8906.00)
 		self.assertEqual(quotation.payment_schedule[0].due_date, quotation.transaction_date)
 		self.assertEqual(quotation.payment_schedule[1].payment_amount, 8906.00)
-		self.assertEqual(
-			quotation.payment_schedule[1].due_date, add_days(quotation.transaction_date, 30)
-		)
+		self.assertEqual(quotation.payment_schedule[1].due_date, add_days(quotation.transaction_date, 30))
 
 		sales_order = make_sales_order(quotation.name)
 
@@ -187,9 +185,7 @@
 	def test_so_from_expired_quotation(self):
 		from erpnext.selling.doctype.quotation.quotation import make_sales_order
 
-		frappe.db.set_single_value(
-			"Selling Settings", "allow_sales_order_creation_for_expired_quotation", 0
-		)
+		frappe.db.set_single_value("Selling Settings", "allow_sales_order_creation_for_expired_quotation", 0)
 
 		quotation = frappe.copy_doc(test_records[0])
 		quotation.valid_till = add_days(nowdate(), -1)
@@ -198,9 +194,7 @@
 
 		self.assertRaises(frappe.ValidationError, make_sales_order, quotation.name)
 
-		frappe.db.set_single_value(
-			"Selling Settings", "allow_sales_order_creation_for_expired_quotation", 1
-		)
+		frappe.db.set_single_value("Selling Settings", "allow_sales_order_creation_for_expired_quotation", 1)
 
 		make_sales_order(quotation.name)
 
@@ -658,7 +652,7 @@
 			).insert()
 
 		if not frappe.db.exists("Item Tax Template", "Vat Template - _TC"):
-			doc = frappe.get_doc(
+			frappe.get_doc(
 				{
 					"doctype": "Item Tax Template",
 					"name": "Vat Template",
@@ -680,9 +674,7 @@
 			item_doc.append("taxes", {"item_tax_template": "Vat Template - _TC"})
 			item_doc.save()
 
-		quotation = make_quotation(
-			item_code="_Test Item Tax Template QTN", qty=1, rate=100, do_not_submit=1
-		)
+		quotation = make_quotation(item_code="_Test Item Tax Template QTN", qty=1, rate=100, do_not_submit=1)
 		self.assertFalse(quotation.taxes)
 
 		quotation.append_taxes_from_item_tax_template()
diff --git a/erpnext/selling/doctype/sales_order/sales_order.py b/erpnext/selling/doctype/sales_order/sales_order.py
index 826ba1e..6afd4ac 100755
--- a/erpnext/selling/doctype/sales_order/sales_order.py
+++ b/erpnext/selling/doctype/sales_order/sales_order.py
@@ -182,7 +182,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(SalesOrder, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 
 	def onload(self) -> None:
 		if frappe.db.get_single_value("Stock Settings", "enable_stock_reservation"):
@@ -193,7 +193,7 @@
 			self.set_onload("has_reserved_stock", True)
 
 	def validate(self):
-		super(SalesOrder, self).validate()
+		super().validate()
 		self.validate_delivery_date()
 		self.validate_proj_cust()
 		self.validate_po()
@@ -236,7 +236,9 @@
 			for d in self.get("items"):
 				if d.delivery_date and getdate(self.po_date) > getdate(d.delivery_date):
 					frappe.throw(
-						_("Row #{0}: Expected Delivery Date cannot be before Purchase Order Date").format(d.idx)
+						_("Row #{0}: Expected Delivery Date cannot be before Purchase Order Date").format(
+							d.idx
+						)
 					)
 
 		if self.po_no and self.customer and not self.skip_delivery_note:
@@ -251,9 +253,9 @@
 					frappe.db.get_single_value("Selling Settings", "allow_against_multiple_purchase_orders")
 				):
 					frappe.msgprint(
-						_("Warning: Sales Order {0} already exists against Customer's Purchase Order {1}").format(
-							frappe.bold(so[0][0]), frappe.bold(self.po_no)
-						),
+						_(
+							"Warning: Sales Order {0} already exists against Customer's Purchase Order {1}"
+						).format(frappe.bold(so[0][0]), frappe.bold(self.po_no)),
 						alert=True,
 					)
 				else:
@@ -263,14 +265,15 @@
 						).format(
 							frappe.bold(so[0][0]),
 							frappe.bold(self.po_no),
-							frappe.bold(_("'Allow Multiple Sales Orders Against a Customer's Purchase Order'")),
+							frappe.bold(
+								_("'Allow Multiple Sales Orders Against a Customer's Purchase Order'")
+							),
 							get_link_to_form("Selling Settings", "Selling Settings"),
 						)
 					)
 
 	def validate_for_items(self):
 		for d in self.get("items"):
-
 			# used for production plan
 			d.transaction_date = self.transaction_date
 
@@ -300,7 +303,9 @@
 					(d.prevdoc_docname, self.order_type),
 				)
 				if not res:
-					frappe.msgprint(_("Quotation {0} not of type {1}").format(d.prevdoc_docname, self.order_type))
+					frappe.msgprint(
+						_("Quotation {0} not of type {1}").format(d.prevdoc_docname, self.order_type)
+					)
 
 	def validate_delivery_date(self):
 		if self.order_type == "Sales" and not self.skip_delivery_note:
@@ -339,13 +344,16 @@
 				)
 
 	def validate_warehouse(self):
-		super(SalesOrder, self).validate_warehouse()
+		super().validate_warehouse()
 
 		for d in self.get("items"):
 			if (
 				(
 					frappe.get_cached_value("Item", d.item_code, "is_stock_item") == 1
-					or (self.has_product_bundle(d.item_code) and self.product_bundle_has_stock_item(d.item_code))
+					or (
+						self.has_product_bundle(d.item_code)
+						and self.product_bundle_has_stock_item(d.item_code)
+					)
 				)
 				and not d.warehouse
 				and not cint(d.delivered_by_supplier)
@@ -355,7 +363,7 @@
 				)
 
 	def validate_with_previous_doc(self):
-		super(SalesOrder, self).validate_with_previous_doc(
+		super().validate_with_previous_doc(
 			{
 				"Quotation": {"ref_dn_field": "prevdoc_docname", "compare_fields": [["company", "="]]},
 				"Quotation Item": {
@@ -416,7 +424,7 @@
 
 	def on_cancel(self):
 		self.ignore_linked_doctypes = ("GL Entry", "Stock Ledger Entry", "Payment Ledger Entry")
-		super(SalesOrder, self).on_cancel()
+		super().on_cancel()
 
 		# Cannot cancel closed SO
 		if self.status == "Closed":
@@ -439,9 +447,7 @@
 			update_coupon_code_count(self.coupon_code, "cancelled")
 
 	def update_project(self):
-		if (
-			frappe.db.get_single_value("Selling Settings", "sales_update_frequency") != "Each Transaction"
-		):
+		if frappe.db.get_single_value("Selling Settings", "sales_update_frequency") != "Each Transaction":
 			return
 
 		if self.project:
@@ -479,7 +485,7 @@
 
 	def check_modified_date(self):
 		mod_db = frappe.db.get_value("Sales Order", self.name, "modified")
-		date_diff = frappe.db.sql("select TIMEDIFF('%s', '%s')" % (mod_db, cstr(self.modified)))
+		date_diff = frappe.db.sql(f"select TIMEDIFF('{mod_db}', '{cstr(self.modified)}')")
 		if date_diff and date_diff[0][0]:
 			frappe.throw(_("{0} {1} has been modified. Please refresh.").format(self.doctype, self.name))
 
@@ -654,9 +660,9 @@
 						)
 					if not frappe.db.exists("BOM", {"item": item.item_code, "is_active": 1}):
 						frappe.throw(
-							_("No active BOM found for item {0}. Delivery by Serial No cannot be ensured").format(
-								item.item_code
-							)
+							_(
+								"No active BOM found for item {0}. Delivery by Serial No cannot be ensured"
+							).format(item.item_code)
 						)
 				reserved_items.append(item.item_code)
 			else:
@@ -672,9 +678,7 @@
 	def validate_reserved_stock(self):
 		"""Clean reserved stock flag for non-stock Item"""
 
-		enable_stock_reservation = frappe.db.get_single_value(
-			"Stock Settings", "enable_stock_reservation"
-		)
+		enable_stock_reservation = frappe.db.get_single_value("Stock Settings", "enable_stock_reservation")
 
 		for item in self.items:
 			if item.reserve_stock and (not enable_stock_reservation or not cint(item.is_stock_item)):
@@ -698,7 +702,7 @@
 	@frappe.whitelist()
 	def create_stock_reservation_entries(
 		self,
-		items_details: list[dict] = None,
+		items_details: list[dict] | None = None,
 		from_voucher_type: Literal["Pick List", "Purchase Receipt"] = None,
 		notify=True,
 	) -> None:
@@ -732,11 +736,7 @@
 	"""Returns the unreserved quantity for the Sales Order Item."""
 
 	existing_reserved_qty = reserved_qty_details.get(item.name, 0)
-	return (
-		item.stock_qty
-		- flt(item.delivered_qty) * item.get("conversion_factor", 1)
-		- existing_reserved_qty
-	)
+	return item.stock_qty - flt(item.delivered_qty) * item.get("conversion_factor", 1) - existing_reserved_qty
 
 
 def get_list_context(context=None):
@@ -757,9 +757,7 @@
 
 @frappe.whitelist()
 def is_enable_cutoff_date_on_bulk_delivery_note_creation():
-	return frappe.db.get_single_value(
-		"Selling Settings", "enable_cutoff_date_on_bulk_delivery_note_creation"
-	)
+	return frappe.db.get_single_value("Selling Settings", "enable_cutoff_date_on_bulk_delivery_note_creation")
 
 
 @frappe.whitelist()
@@ -1190,7 +1188,7 @@
 	conditions = get_event_conditions("Sales Order", filters)
 
 	data = frappe.db.sql(
-		"""
+		f"""
 		select
 			distinct `tabSales Order`.name, `tabSales Order`.customer_name, `tabSales Order`.status,
 			`tabSales Order`.delivery_status, `tabSales Order`.billing_status,
@@ -1203,9 +1201,7 @@
 			and (`tabSales Order Item`.delivery_date between %(start)s and %(end)s)
 			and `tabSales Order`.docstatus < 2
 			{conditions}
-		""".format(
-			conditions=conditions
-		),
+		""",
 		{"start": start, "end": end},
 		as_dict=True,
 		update={"allDay": 0},
@@ -1279,9 +1275,7 @@
 	items_to_map = list(set(items_to_map))
 
 	if not suppliers:
-		frappe.throw(
-			_("Please set a Supplier against the Items to be considered in the Purchase Order.")
-		)
+		frappe.throw(_("Please set a Supplier against the Items to be considered in the Purchase Order."))
 
 	purchase_orders = []
 	for supplier in suppliers:
@@ -1347,9 +1341,7 @@
 		selected_items = json.loads(selected_items)
 
 	items_to_map = [
-		item.get("item_code")
-		for item in selected_items
-		if item.get("item_code") and item.get("item_code")
+		item.get("item_code") for item in selected_items if item.get("item_code") and item.get("item_code")
 	]
 	items_to_map = list(set(items_to_map))
 
@@ -1532,17 +1524,13 @@
 	for item in items.get("items"):
 		item["include_exploded_items"] = items.get("include_exploded_items")
 		item["ignore_existing_ordered_qty"] = items.get("ignore_existing_ordered_qty")
-		item["include_raw_materials_from_sales_order"] = items.get(
-			"include_raw_materials_from_sales_order"
-		)
+		item["include_raw_materials_from_sales_order"] = items.get("include_raw_materials_from_sales_order")
 
 	items.update({"company": company, "sales_order": sales_order})
 
 	raw_materials = get_items_for_material_requests(items)
 	if not raw_materials:
-		frappe.msgprint(
-			_("Material Request not created, as quantity for Raw Materials already available.")
-		)
+		frappe.msgprint(_("Material Request not created, as quantity for Raw Materials already available."))
 		return
 
 	material_request = frappe.new_doc("Material Request")
diff --git a/erpnext/selling/doctype/sales_order/test_sales_order.py b/erpnext/selling/doctype/sales_order/test_sales_order.py
index 7327fde..2c9e887 100644
--- a/erpnext/selling/doctype/sales_order/test_sales_order.py
+++ b/erpnext/selling/doctype/sales_order/test_sales_order.py
@@ -36,9 +36,7 @@
 	def setUpClass(cls):
 		super().setUpClass()
 		cls.unlink_setting = int(
-			frappe.db.get_single_value(
-				"Accounts Settings", "unlink_advance_payment_on_cancelation_of_order"
-			)
+			frappe.db.get_single_value("Accounts Settings", "unlink_advance_payment_on_cancelation_of_order")
 		)
 
 	@classmethod
@@ -329,9 +327,7 @@
 
 	def test_reserved_qty_for_partial_delivery_with_packing_list(self):
 		make_stock_entry(target="_Test Warehouse - _TC", qty=10, rate=100)
-		make_stock_entry(
-			item="_Test Item Home Desktop 100", target="_Test Warehouse - _TC", qty=10, rate=100
-		)
+		make_stock_entry(item="_Test Item Home Desktop 100", target="_Test Warehouse - _TC", qty=10, rate=100)
 
 		existing_reserved_qty_item1 = get_reserved_qty("_Test Item")
 		existing_reserved_qty_item2 = get_reserved_qty("_Test Item Home Desktop 100")
@@ -339,16 +335,12 @@
 		so = make_sales_order(item_code="_Test Product Bundle Item")
 
 		self.assertEqual(get_reserved_qty("_Test Item"), existing_reserved_qty_item1 + 50)
-		self.assertEqual(
-			get_reserved_qty("_Test Item Home Desktop 100"), existing_reserved_qty_item2 + 20
-		)
+		self.assertEqual(get_reserved_qty("_Test Item Home Desktop 100"), existing_reserved_qty_item2 + 20)
 
 		dn = create_dn_against_so(so.name)
 
 		self.assertEqual(get_reserved_qty("_Test Item"), existing_reserved_qty_item1 + 25)
-		self.assertEqual(
-			get_reserved_qty("_Test Item Home Desktop 100"), existing_reserved_qty_item2 + 10
-		)
+		self.assertEqual(get_reserved_qty("_Test Item Home Desktop 100"), existing_reserved_qty_item2 + 10)
 
 		# close so
 		so.load_from_db()
@@ -362,15 +354,11 @@
 		so.update_status("Draft")
 
 		self.assertEqual(get_reserved_qty("_Test Item"), existing_reserved_qty_item1 + 25)
-		self.assertEqual(
-			get_reserved_qty("_Test Item Home Desktop 100"), existing_reserved_qty_item2 + 10
-		)
+		self.assertEqual(get_reserved_qty("_Test Item Home Desktop 100"), existing_reserved_qty_item2 + 10)
 
 		dn.cancel()
 		self.assertEqual(get_reserved_qty("_Test Item"), existing_reserved_qty_item1 + 50)
-		self.assertEqual(
-			get_reserved_qty("_Test Item Home Desktop 100"), existing_reserved_qty_item2 + 20
-		)
+		self.assertEqual(get_reserved_qty("_Test Item Home Desktop 100"), existing_reserved_qty_item2 + 20)
 
 		so.load_from_db()
 		so.cancel()
@@ -386,9 +374,7 @@
 
 	def test_reserved_qty_for_over_delivery_with_packing_list(self):
 		make_stock_entry(target="_Test Warehouse - _TC", qty=10, rate=100)
-		make_stock_entry(
-			item="_Test Item Home Desktop 100", target="_Test Warehouse - _TC", qty=10, rate=100
-		)
+		make_stock_entry(item="_Test Item Home Desktop 100", target="_Test Warehouse - _TC", qty=10, rate=100)
 
 		# set over-delivery allowance
 		frappe.db.set_value("Item", "_Test Product Bundle Item", "over_delivery_receipt_allowance", 50)
@@ -399,9 +385,7 @@
 		so = make_sales_order(item_code="_Test Product Bundle Item")
 
 		self.assertEqual(get_reserved_qty("_Test Item"), existing_reserved_qty_item1 + 50)
-		self.assertEqual(
-			get_reserved_qty("_Test Item Home Desktop 100"), existing_reserved_qty_item2 + 20
-		)
+		self.assertEqual(get_reserved_qty("_Test Item Home Desktop 100"), existing_reserved_qty_item2 + 20)
 
 		dn = create_dn_against_so(so.name, 15)
 
@@ -410,9 +394,7 @@
 
 		dn.cancel()
 		self.assertEqual(get_reserved_qty("_Test Item"), existing_reserved_qty_item1 + 50)
-		self.assertEqual(
-			get_reserved_qty("_Test Item Home Desktop 100"), existing_reserved_qty_item2 + 20
-		)
+		self.assertEqual(get_reserved_qty("_Test Item Home Desktop 100"), existing_reserved_qty_item2 + 20)
 
 	def test_update_child_adding_new_item(self):
 		so = make_sales_order(item_code="_Test Item", qty=4)
@@ -482,9 +464,7 @@
 		trans_item = json.dumps(
 			[{"item_code": "_Test Item 2", "qty": 2, "rate": 500, "docname": so.get("items")[1].name}]
 		)
-		self.assertRaises(
-			frappe.ValidationError, update_child_qty_rate, "Sales Order", trans_item, so.name
-		)
+		self.assertRaises(frappe.ValidationError, update_child_qty_rate, "Sales Order", trans_item, so.name)
 
 		# remove last added item
 		trans_item = json.dumps(
@@ -523,9 +503,7 @@
 		trans_item = json.dumps(
 			[{"item_code": "_Test Item", "rate": 200, "qty": 2, "docname": so.items[0].name}]
 		)
-		self.assertRaises(
-			frappe.ValidationError, update_child_qty_rate, "Sales Order", trans_item, so.name
-		)
+		self.assertRaises(frappe.ValidationError, update_child_qty_rate, "Sales Order", trans_item, so.name)
 
 	def test_update_child_with_precision(self):
 		from frappe.custom.doctype.property_setter.property_setter import make_property_setter
@@ -555,15 +533,11 @@
 		trans_item = json.dumps(
 			[{"item_code": "_Test Item", "rate": 200, "qty": 7, "docname": so.items[0].name}]
 		)
-		self.assertRaises(
-			frappe.ValidationError, update_child_qty_rate, "Sales Order", trans_item, so.name
-		)
+		self.assertRaises(frappe.ValidationError, update_child_qty_rate, "Sales Order", trans_item, so.name)
 
 		# add new item
 		trans_item = json.dumps([{"item_code": "_Test Item", "rate": 100, "qty": 2}])
-		self.assertRaises(
-			frappe.ValidationError, update_child_qty_rate, "Sales Order", trans_item, so.name
-		)
+		self.assertRaises(frappe.ValidationError, update_child_qty_rate, "Sales Order", trans_item, so.name)
 
 	def test_update_child_qty_rate_with_workflow(self):
 		from frappe.model.workflow import apply_workflow
@@ -581,9 +555,7 @@
 		trans_item = json.dumps(
 			[{"item_code": "_Test Item", "rate": 150, "qty": 2, "docname": so.items[0].name}]
 		)
-		self.assertRaises(
-			frappe.ValidationError, update_child_qty_rate, "Sales Order", trans_item, so.name
-		)
+		self.assertRaises(frappe.ValidationError, update_child_qty_rate, "Sales Order", trans_item, so.name)
 
 		frappe.set_user("Administrator")
 		user2 = "test2@example.com"
@@ -841,9 +813,7 @@
 
 		frappe.set_user("Administrator")
 		frappe.permissions.remove_user_permission("Warehouse", "_Test Warehouse 1 - _TC", test_user.name)
-		frappe.permissions.remove_user_permission(
-			"Warehouse", "_Test Warehouse 2 - _TC1", test_user_2.name
-		)
+		frappe.permissions.remove_user_permission("Warehouse", "_Test Warehouse 2 - _TC1", test_user_2.name)
 		frappe.permissions.remove_user_permission("Company", "_Test Company 1", test_user_2.name)
 
 	def test_block_delivery_note_against_cancelled_sales_order(self):
@@ -962,9 +932,7 @@
 		from erpnext.selling.doctype.sales_order.sales_order import update_status as so_update_status
 
 		# make items
-		po_item = make_item(
-			"_Test Item for Drop Shipping", {"is_stock_item": 1, "delivered_by_supplier": 1}
-		)
+		po_item = make_item("_Test Item for Drop Shipping", {"is_stock_item": 1, "delivered_by_supplier": 1})
 		dn_item = make_item("_Test Regular Item", {"is_stock_item": 1})
 
 		so_items = [
@@ -1247,17 +1215,13 @@
 		new_so = frappe.copy_doc(so)
 		new_so.save(ignore_permissions=True)
 
-		self.assertEqual(
-			new_so.get("items")[0].rate, flt((price_list_rate * 25) / 100 + price_list_rate)
-		)
+		self.assertEqual(new_so.get("items")[0].rate, flt((price_list_rate * 25) / 100 + price_list_rate))
 		new_so.items[0].margin_rate_or_amount = 25
 		new_so.payment_schedule = []
 		new_so.save()
 		new_so.submit()
 
-		self.assertEqual(
-			new_so.get("items")[0].rate, flt((price_list_rate * 25) / 100 + price_list_rate)
-		)
+		self.assertEqual(new_so.get("items")[0].rate, flt((price_list_rate * 25) / 100 + price_list_rate))
 
 	def test_terms_auto_added(self):
 		so = make_sales_order(do_not_save=1)
@@ -1327,9 +1291,7 @@
 	def test_advance_payment_entry_unlink_against_sales_order(self):
 		from erpnext.accounts.doctype.payment_entry.test_payment_entry import get_payment_entry
 
-		frappe.db.set_single_value(
-			"Accounts Settings", "unlink_advance_payment_on_cancelation_of_order", 0
-		)
+		frappe.db.set_single_value("Accounts Settings", "unlink_advance_payment_on_cancelation_of_order", 0)
 
 		so = make_sales_order()
 
@@ -1382,9 +1344,7 @@
 		so = make_sales_order()
 
 		# disable unlinking of payment entry
-		frappe.db.set_single_value(
-			"Accounts Settings", "unlink_advance_payment_on_cancelation_of_order", 0
-		)
+		frappe.db.set_single_value("Accounts Settings", "unlink_advance_payment_on_cancelation_of_order", 0)
 
 		# create a payment entry against sales order
 		pe = get_payment_entry("Sales Order", so.name, bank_account="_Test Bank - _TC")
@@ -1515,7 +1475,7 @@
 		Second Sales Order should not add on to Blanket Orders Ordered Quantity.
 		"""
 
-		bo = make_blanket_order(blanket_order_type="Selling", quantity=10, rate=10)
+		make_blanket_order(blanket_order_type="Selling", quantity=10, rate=10)
 
 		so = make_sales_order(item_code="_Test Item", qty=5, against_blanket_order=1)
 		so_doc = frappe.get_doc("Sales Order", so.get("name"))
@@ -1736,7 +1696,10 @@
 
 		wo.submit()
 		make_stock_entry(
-			item_code="_Test Item", target="Work In Progress - _TC", qty=4, basic_rate=100  # Stock RM
+			item_code="_Test Item",
+			target="Work In Progress - _TC",
+			qty=4,
+			basic_rate=100,  # Stock RM
 		)
 		make_stock_entry(
 			item_code="_Test Item Home Desktop 100",  # Stock RM
@@ -1844,10 +1807,6 @@
 
 	def test_delivered_item_material_request(self):
 		"SO -> MR (Manufacture) -> WO. Test if WO Qty is updated in SO."
-		from erpnext.manufacturing.doctype.work_order.work_order import (
-			make_stock_entry as make_se_from_wo,
-		)
-		from erpnext.stock.doctype.material_request.material_request import raise_work_orders
 
 		so = make_sales_order(
 			item_list=[
@@ -1855,9 +1814,7 @@
 			]
 		)
 
-		make_stock_entry(
-			item_code="_Test FG Item", target="Work In Progress - _TC", qty=4, basic_rate=100
-		)
+		make_stock_entry(item_code="_Test FG Item", target="Work In Progress - _TC", qty=4, basic_rate=100)
 
 		dn = make_delivery_note(so.name)
 		dn.items[0].qty = 4
@@ -1882,7 +1839,8 @@
 			if not frappe.db.exists("Item", product_bundle):
 				bundle_item = make_item(product_bundle, {"is_stock_item": 0})
 				bundle_item.append(
-					"item_defaults", {"company": "_Test Company", "default_warehouse": "_Test Warehouse - _TC"}
+					"item_defaults",
+					{"company": "_Test Company", "default_warehouse": "_Test Warehouse - _TC"},
 				)
 				bundle_item.save(ignore_permissions=True)
 
@@ -1952,7 +1910,8 @@
 			if not frappe.db.exists("Item", product_bundle):
 				bundle_item = make_item(product_bundle, {"is_stock_item": 0})
 				bundle_item.append(
-					"item_defaults", {"company": "_Test Company", "default_warehouse": "_Test Warehouse - _TC"}
+					"item_defaults",
+					{"company": "_Test Company", "default_warehouse": "_Test Warehouse - _TC"},
 				)
 				bundle_item.save(ignore_permissions=True)
 
@@ -2002,17 +1961,13 @@
 		from erpnext.accounts.doctype.payment_request.payment_request import make_payment_request
 
 		so = make_sales_order(qty=1, rate=100)
-		self.assertEqual(
-			frappe.db.get_value(so.doctype, so.name, "advance_payment_status"), "Not Requested"
-		)
+		self.assertEqual(frappe.db.get_value(so.doctype, so.name, "advance_payment_status"), "Not Requested")
 
 		pr = make_payment_request(dt=so.doctype, dn=so.name, submit_doc=True, return_doc=True)
 		self.assertEqual(frappe.db.get_value(so.doctype, so.name, "advance_payment_status"), "Requested")
 
 		pe = get_payment_entry(so.doctype, so.name).save().submit()
-		self.assertEqual(
-			frappe.db.get_value(so.doctype, so.name, "advance_payment_status"), "Fully Paid"
-		)
+		self.assertEqual(frappe.db.get_value(so.doctype, so.name, "advance_payment_status"), "Fully Paid")
 
 		pe.reload()
 		pe.cancel()
@@ -2020,9 +1975,7 @@
 
 		pr.reload()
 		pr.cancel()
-		self.assertEqual(
-			frappe.db.get_value(so.doctype, so.name, "advance_payment_status"), "Not Requested"
-		)
+		self.assertEqual(frappe.db.get_value(so.doctype, so.name, "advance_payment_status"), "Not Requested")
 
 	def test_pick_list_without_rejected_materials(self):
 		serial_and_batch_item = make_item(
@@ -2252,9 +2205,7 @@
 
 
 def get_reserved_qty(item_code="_Test Item", warehouse="_Test Warehouse - _TC"):
-	return flt(
-		frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse}, "reserved_qty")
-	)
+	return flt(frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse}, "reserved_qty"))
 
 
 test_dependencies = ["Currency Exchange"]
@@ -2267,9 +2218,7 @@
 		doc.save()
 		return doc
 
-	frappe.get_doc(dict(doctype="Role", role_name="Test Junior Approver")).insert(
-		ignore_if_duplicate=True
-	)
+	frappe.get_doc(dict(doctype="Role", role_name="Test Junior Approver")).insert(ignore_if_duplicate=True)
 	frappe.get_doc(dict(doctype="Role", role_name="Test Approver")).insert(ignore_if_duplicate=True)
 	frappe.cache().hdel("roles", frappe.session.user)
 
diff --git a/erpnext/selling/page/point_of_sale/point_of_sale.py b/erpnext/selling/page/point_of_sale/point_of_sale.py
index fd23381..2bb61a6 100644
--- a/erpnext/selling/page/point_of_sale/point_of_sale.py
+++ b/erpnext/selling/page/point_of_sale/point_of_sale.py
@@ -3,7 +3,6 @@
 
 
 import json
-from typing import Dict, Optional
 
 import frappe
 from frappe.utils import cint
@@ -198,16 +197,14 @@
 
 
 @frappe.whitelist()
-def search_for_serial_or_batch_or_barcode_number(search_value: str) -> Dict[str, Optional[str]]:
+def search_for_serial_or_batch_or_barcode_number(search_value: str) -> dict[str, str | None]:
 	return scan_barcode(search_value)
 
 
 def get_conditions(search_term):
 	condition = "("
 	condition += """item.name like {search_term}
-		or item.item_name like {search_term}""".format(
-		search_term=frappe.db.escape("%" + search_term + "%")
-	)
+		or item.item_name like {search_term}""".format(search_term=frappe.db.escape("%" + search_term + "%"))
 	condition += add_search_fields_condition(search_term)
 	condition += ")"
 
@@ -219,7 +216,7 @@
 	search_fields = frappe.get_all("POS Search Fields", fields=["fieldname"])
 	if search_fields:
 		for field in search_fields:
-			condition += " or item.`{0}` like {1}".format(
+			condition += " or item.`{}` like {}".format(
 				field["fieldname"], frappe.db.escape("%" + search_term + "%")
 			)
 	return condition
@@ -249,10 +246,8 @@
 			cond = cond % tuple(item_groups)
 
 	return frappe.db.sql(
-		""" select distinct name from `tabItem Group`
-			where {condition} and (name like %(txt)s) limit {page_len} offset {start}""".format(
-			condition=cond, start=start, page_len=page_len
-		),
+		f""" select distinct name from `tabItem Group`
+			where {cond} and (name like %(txt)s) limit {page_len} offset {start}""",
 		{"txt": "%%%s%%" % txt},
 	)
 
@@ -297,13 +292,13 @@
 	if search_term and status:
 		invoices_by_customer = frappe.db.get_all(
 			"POS Invoice",
-			filters={"customer": ["like", "%{}%".format(search_term)], "status": status},
+			filters={"customer": ["like", f"%{search_term}%"], "status": status},
 			fields=fields,
 			page_length=limit,
 		)
 		invoices_by_name = frappe.db.get_all(
 			"POS Invoice",
-			filters={"name": ["like", "%{}%".format(search_term)], "status": status},
+			filters={"name": ["like", f"%{search_term}%"], "status": status},
 			fields=fields,
 			page_length=limit,
 		)
diff --git a/erpnext/selling/page/sales_funnel/sales_funnel.py b/erpnext/selling/page/sales_funnel/sales_funnel.py
index 6b33a71..155d21e 100644
--- a/erpnext/selling/page/sales_funnel/sales_funnel.py
+++ b/erpnext/selling/page/sales_funnel/sales_funnel.py
@@ -85,7 +85,7 @@
 						* x["probability"]
 						/ 100
 					)
-				}
+				},
 			)
 			for x in opportunities
 		]
@@ -137,7 +137,7 @@
 						* x["probability"]
 						/ 100
 					)
-				}
+				},
 			)
 			for x in opportunities
 		]
diff --git a/erpnext/selling/report/address_and_contacts/address_and_contacts.py b/erpnext/selling/report/address_and_contacts/address_and_contacts.py
index 0a29d43..a165b9f 100644
--- a/erpnext/selling/report/address_and_contacts/address_and_contacts.py
+++ b/erpnext/selling/report/address_and_contacts/address_and_contacts.py
@@ -27,8 +27,8 @@
 	party_type = filters.get("party_type")
 	party_type_value = get_party_group(party_type)
 	columns = [
-		"{party_type}:Link/{party_type}".format(party_type=party_type),
-		"{party_value_type}::150".format(party_value_type=frappe.unscrub(str(party_type_value))),
+		f"{party_type}:Link/{party_type}",
+		f"{frappe.unscrub(str(party_type_value))}::150",
 		"Address Line 1",
 		"Address Line 2",
 		"City",
@@ -127,7 +127,7 @@
 		["Dynamic Link", "link_doctype", "=", party_type],
 		["Dynamic Link", "link_name", "in", party_list],
 	]
-	fields = ["`tabDynamic Link`.link_name"] + field_map.get(doctype, [])
+	fields = ["`tabDynamic Link`.link_name", *field_map.get(doctype, [])]
 
 	records = frappe.get_list(doctype, filters=filters, fields=fields, as_list=True)
 	for d in records:
diff --git a/erpnext/selling/report/customer_acquisition_and_loyalty/customer_acquisition_and_loyalty.py b/erpnext/selling/report/customer_acquisition_and_loyalty/customer_acquisition_and_loyalty.py
index 3e4bfb2..dcdd252 100644
--- a/erpnext/selling/report/customer_acquisition_and_loyalty/customer_acquisition_and_loyalty.py
+++ b/erpnext/selling/report/customer_acquisition_and_loyalty/customer_acquisition_and_loyalty.py
@@ -77,10 +77,8 @@
 
 	out = []
 	for year in range(from_year, to_year + 1):
-		for month in range(
-			from_month if year == from_year else 1, (to_month + 1) if year == to_year else 13
-		):
-			key = "{year}-{month:02d}".format(year=year, month=month)
+		for month in range(from_month if year == from_year else 1, (to_month + 1) if year == to_year else 13):
+			key = f"{year}-{month:02d}"
 			data = customers_in.get(key)
 			new = data["new"] if data else [0, 0.0]
 			repeat = data["repeat"] if data else [0, 0.0]
@@ -147,7 +145,7 @@
 
 	for ld in loop_data:
 		if ld["parent_territory"]:
-			parent_data = [x for x in data if x["territory"] == ld["parent_territory"]][0]
+			parent_data = next(x for x in data if x["territory"] == ld["parent_territory"])
 			for key in parent_data.keys():
 				if key not in ["indent", "territory", "parent_territory", "bold"]:
 					parent_data[key] += ld[key]
@@ -165,15 +163,12 @@
 	customers_in = {}
 
 	for si in frappe.db.sql(
-		"""select territory, posting_date, customer, base_grand_total from `tabSales Invoice`
+		f"""select territory, posting_date, customer, base_grand_total from `tabSales Invoice`
 		where docstatus=1 and posting_date <= %(to_date)s
-		{company_condition} order by posting_date""".format(
-			company_condition=company_condition
-		),
+		{company_condition} order by posting_date""",
 		filters,
 		as_dict=1,
 	):
-
 		key = si.territory if tree_view else si.posting_date.strftime("%Y-%m")
 		new_or_repeat = "new" if si.customer not in customers else "repeat"
 		customers_in.setdefault(key, {"new": [0, 0.0], "repeat": [0, 0.0]})
diff --git a/erpnext/selling/report/customer_credit_balance/customer_credit_balance.py b/erpnext/selling/report/customer_credit_balance/customer_credit_balance.py
index a584d3a..d64c89c 100644
--- a/erpnext/selling/report/customer_credit_balance/customer_credit_balance.py
+++ b/erpnext/selling/report/customer_credit_balance/customer_credit_balance.py
@@ -77,7 +77,6 @@
 
 
 def get_details(filters):
-
 	sql_query = """SELECT
 						c.name, c.customer_name,
 						ccl.bypass_credit_limit_check,
diff --git a/erpnext/selling/report/customer_wise_item_price/customer_wise_item_price.py b/erpnext/selling/report/customer_wise_item_price/customer_wise_item_price.py
index 40aa9ac..6acc060 100644
--- a/erpnext/selling/report/customer_wise_item_price/customer_wise_item_price.py
+++ b/erpnext/selling/report/customer_wise_item_price/customer_wise_item_price.py
@@ -51,7 +51,10 @@
 
 
 def fetch_item_prices(
-	customer: str = None, price_list: str = None, selling_price_list: str = None, items: list = None
+	customer: str | None = None,
+	price_list: str | None = None,
+	selling_price_list: str | None = None,
+	items: list | None = None,
 ):
 	price_list_map = frappe._dict()
 	ip = qb.DocType("Item Price")
@@ -59,10 +62,10 @@
 	or_conditions = []
 	if items:
 		and_conditions.append(ip.item_code.isin([x.item_code for x in items]))
-		and_conditions.append(ip.selling == True)
+		and_conditions.append(ip.selling is True)
 
-		or_conditions.append(ip.customer == None)
-		or_conditions.append(ip.price_list == None)
+		or_conditions.append(ip.customer is None)
+		or_conditions.append(ip.price_list is None)
 
 		if customer:
 			or_conditions.append(ip.customer == customer)
diff --git a/erpnext/selling/report/inactive_customers/inactive_customers.py b/erpnext/selling/report/inactive_customers/inactive_customers.py
index a166085..7e4ddc1 100644
--- a/erpnext/selling/report/inactive_customers/inactive_customers.py
+++ b/erpnext/selling/report/inactive_customers/inactive_customers.py
@@ -40,19 +40,17 @@
 			DATEDIFF(CURRENT_DATE, max(so.transaction_date)) as 'days_since_last_order'"""
 
 	return frappe.db.sql(
-		"""select
+		f"""select
 			cust.name,
 			cust.customer_name,
 			cust.territory,
 			cust.customer_group,
 			count(distinct(so.name)) as 'num_of_order',
-			sum(base_net_total) as 'total_order_value', {0}
-		from `tabCustomer` cust, `tab{1}` so
+			sum(base_net_total) as 'total_order_value', {cond}
+		from `tabCustomer` cust, `tab{doctype}` so
 		where cust.name = so.customer and so.docstatus = 1
 		group by cust.name
-		order by 'days_since_last_order' desc """.format(
-			cond, doctype
-		),
+		order by 'days_since_last_order' desc """,
 		as_list=1,
 	)
 
@@ -62,11 +60,9 @@
 	if doctype == "Sales Order":
 		cond = "transaction_date"
 	res = frappe.db.sql(
-		"""select base_net_total from `tab{0}`
-		where customer = %s and docstatus = 1 order by {1} desc
-		limit 1""".format(
-			doctype, cond
-		),
+		f"""select base_net_total from `tab{doctype}`
+		where customer = %s and docstatus = 1 order by {cond} desc
+		limit 1""",
 		customer,
 	)
 
diff --git a/erpnext/selling/report/item_wise_sales_history/item_wise_sales_history.py b/erpnext/selling/report/item_wise_sales_history/item_wise_sales_history.py
index cd45e7d..9cdb14c 100644
--- a/erpnext/selling/report/item_wise_sales_history/item_wise_sales_history.py
+++ b/erpnext/selling/report/item_wise_sales_history/item_wise_sales_history.py
@@ -128,7 +128,6 @@
 
 
 def get_data(filters):
-
 	data = []
 
 	company_list = get_descendants_of("Company", filters.get("company"))
@@ -181,9 +180,7 @@
 	details = frappe.db.get_all("Item", fields=["name", "item_name", "item_group"])
 	item_details = {}
 	for d in details:
-		item_details.setdefault(
-			d.name, frappe._dict({"item_name": d.item_name, "item_group": d.item_group})
-		)
+		item_details.setdefault(d.name, frappe._dict({"item_name": d.item_name, "item_group": d.item_group}))
 	return item_details
 
 
@@ -246,8 +243,7 @@
 		item_wise_sales_map[item_key] = flt(item_wise_sales_map[item_key]) + flt(row.get("amount"))
 
 	item_wise_sales_map = {
-		item: value
-		for item, value in (sorted(item_wise_sales_map.items(), key=lambda i: i[1], reverse=True))
+		item: value for item, value in (sorted(item_wise_sales_map.items(), key=lambda i: i[1], reverse=True))
 	}
 
 	for key in item_wise_sales_map:
diff --git a/erpnext/selling/report/lost_quotations/lost_quotations.py b/erpnext/selling/report/lost_quotations/lost_quotations.py
index 7c0bfbd..a48e945 100644
--- a/erpnext/selling/report/lost_quotations/lost_quotations.py
+++ b/erpnext/selling/report/lost_quotations/lost_quotations.py
@@ -53,9 +53,7 @@
 	]
 
 
-def get_data(
-	company: str, from_date: str, to_date: str, group_by: Literal["Lost Reason", "Competitor"]
-):
+def get_data(company: str, from_date: str, to_date: str, group_by: Literal["Lost Reason", "Competitor"]):
 	"""Return quotation value grouped by lost reason or competitor"""
 	if group_by == "Lost Reason":
 		fieldname = "lost_reason"
diff --git a/erpnext/selling/report/payment_terms_status_for_sales_order/payment_terms_status_for_sales_order.py b/erpnext/selling/report/payment_terms_status_for_sales_order/payment_terms_status_for_sales_order.py
index 72b7fa2..79e0764 100644
--- a/erpnext/selling/report/payment_terms_status_for_sales_order/payment_terms_status_for_sales_order.py
+++ b/erpnext/selling/report/payment_terms_status_for_sales_order/payment_terms_status_for_sales_order.py
@@ -82,9 +82,7 @@
 	).run()[0]
 
 	# get all children of group node
-	query = (
-		qb.from_(group_doc).select(group_doc.name).where((group_doc.lft >= lft) & (group_doc.rgt <= rgt))
-	)
+	query = qb.from_(group_doc).select(group_doc.name).where((group_doc.lft >= lft) & (group_doc.rgt <= rgt))
 
 	child_nodes = []
 	for x in query.run():
@@ -108,7 +106,9 @@
 					)
 			elif item[0] == "Item Group":
 				if item[3] != "":
-					filter_list.append([doctype, "item_group", "in", get_descendants_of("Item Group", item[3])])
+					filter_list.append(
+						[doctype, "item_group", "in", get_descendants_of("Item Group", item[3])]
+					)
 
 	if searchfield and txt:
 		filter_list.append([doctype, searchfield, "like", "%%%s%%" % txt])
@@ -132,9 +132,7 @@
 
 	conditions.company = filters.company or frappe.defaults.get_user_default("company")
 	conditions.end_date = filters.period_end_date or frappe.utils.today()
-	conditions.start_date = filters.period_start_date or frappe.utils.add_months(
-		conditions.end_date, -1
-	)
+	conditions.start_date = filters.period_start_date or frappe.utils.add_months(conditions.end_date, -1)
 
 	return conditions
 
diff --git a/erpnext/selling/report/pending_so_items_for_purchase_request/pending_so_items_for_purchase_request.py b/erpnext/selling/report/pending_so_items_for_purchase_request/pending_so_items_for_purchase_request.py
index 928ed80..7f9f3fb 100644
--- a/erpnext/selling/report/pending_so_items_for_purchase_request/pending_so_items_for_purchase_request.py
+++ b/erpnext/selling/report/pending_so_items_for_purchase_request/pending_so_items_for_purchase_request.py
@@ -81,9 +81,7 @@
 
 	bundled_item_map = get_packed_items(sales_orders)
 
-	item_with_product_bundle = get_items_with_product_bundle(
-		[row.item_code for row in sales_order_entry]
-	)
+	item_with_product_bundle = get_items_with_product_bundle([row.item_code for row in sales_order_entry])
 
 	materials_request_dict = {}
 
@@ -129,7 +127,9 @@
 						"description": item.description,
 						"sales_order_no": so.name,
 						"date": so.transaction_date,
-						"material_request": ",".join(material_requests_against_so.get("material_requests", [])),
+						"material_request": ",".join(
+							material_requests_against_so.get("material_requests", [])
+						),
 						"customer": so.customer,
 						"territory": so.territory,
 						"so_qty": item.qty,
diff --git a/erpnext/selling/report/quotation_trends/quotation_trends.py b/erpnext/selling/report/quotation_trends/quotation_trends.py
index 4d71ce7..bcb8fe9 100644
--- a/erpnext/selling/report/quotation_trends/quotation_trends.py
+++ b/erpnext/selling/report/quotation_trends/quotation_trends.py
@@ -48,9 +48,7 @@
 	return {
 		"data": {
 			"labels": labels,
-			"datasets": [
-				{"name": _(filters.get("period")) + " " + _("Quoted Amount"), "values": datapoints}
-			],
+			"datasets": [{"name": _(filters.get("period")) + " " + _("Quoted Amount"), "values": datapoints}],
 		},
 		"type": "line",
 		"lineOptions": {"regionFill": 1},
diff --git a/erpnext/selling/report/sales_analytics/sales_analytics.py b/erpnext/selling/report/sales_analytics/sales_analytics.py
index 605d2fa..27d2e6e 100644
--- a/erpnext/selling/report/sales_analytics/sales_analytics.py
+++ b/erpnext/selling/report/sales_analytics/sales_analytics.py
@@ -13,7 +13,7 @@
 	return Analytics(filters).run()
 
 
-class Analytics(object):
+class Analytics:
 	def __init__(self, filters=None):
 		self.filters = frappe._dict(filters or {})
 		self.date_field = (
@@ -87,9 +87,7 @@
 				{"label": _(period), "fieldname": scrub(period), "fieldtype": "Float", "width": 120}
 			)
 
-		self.columns.append(
-			{"label": _("Total"), "fieldname": "total", "fieldtype": "Float", "width": 120}
-		)
+		self.columns.append({"label": _("Total"), "fieldname": "total", "fieldtype": "Float", "width": 120})
 
 	def get_data(self):
 		if self.filters.tree_type in ["Customer", "Supplier"]:
@@ -129,9 +127,7 @@
 			""" select s.order_type as entity, s.{value_field} as value_field, s.{date_field}
 			from `tab{doctype}` s where s.docstatus = 1 and s.company = %s and s.{date_field} between %s and %s
 			and ifnull(s.order_type, '') != '' order by s.order_type
-		""".format(
-				date_field=self.date_field, value_field=value_field, doctype=self.filters.doc_type
-			),
+		""".format(date_field=self.date_field, value_field=value_field, doctype=self.filters.doc_type),
 			(self.filters.company, self.filters.from_date, self.filters.to_date),
 			as_dict=1,
 		)
@@ -166,7 +162,6 @@
 			self.entity_names.setdefault(d.entity, d.entity_name)
 
 	def get_sales_transactions_based_on_items(self):
-
 		if self.filters["value_quantity"] == "Value":
 			value_field = "base_net_amount"
 		else:
@@ -178,9 +173,7 @@
 			from `tab{doctype} Item` i , `tab{doctype}` s
 			where s.name = i.parent and i.docstatus = 1 and s.company = %s
 			and s.{date_field} between %s and %s
-		""".format(
-				date_field=self.date_field, value_field=value_field, doctype=self.filters.doc_type
-			),
+		""".format(date_field=self.date_field, value_field=value_field, doctype=self.filters.doc_type),
 			(self.filters.company, self.filters.from_date, self.filters.to_date),
 			as_dict=1,
 		)
@@ -221,14 +214,12 @@
 			value_field = "qty"
 
 		self.entries = frappe.db.sql(
-			"""
-			select i.item_group as entity, i.{value_field} as value_field, s.{date_field}
-			from `tab{doctype} Item` i , `tab{doctype}` s
+			f"""
+			select i.item_group as entity, i.{value_field} as value_field, s.{self.date_field}
+			from `tab{self.filters.doc_type} Item` i , `tab{self.filters.doc_type}` s
 			where s.name = i.parent and i.docstatus = 1 and s.company = %s
-			and s.{date_field} between %s and %s
-		""".format(
-				date_field=self.date_field, value_field=value_field, doctype=self.filters.doc_type
-			),
+			and s.{self.date_field} between %s and %s
+		""",
 			(self.filters.company, self.filters.from_date, self.filters.to_date),
 			as_dict=1,
 		)
@@ -294,7 +285,7 @@
 				total += amount
 
 			row["total"] = total
-			out = [row] + out
+			out = [row, *out]
 
 		self.data = out
 
@@ -330,9 +321,7 @@
 
 		from_date, to_date = getdate(self.filters.from_date), getdate(self.filters.to_date)
 
-		increment = {"Monthly": 1, "Quarterly": 3, "Half-Yearly": 6, "Yearly": 12}.get(
-			self.filters.range, 1
-		)
+		increment = {"Monthly": 1, "Quarterly": 3, "Half-Yearly": 6, "Yearly": 12}.get(self.filters.range, 1)
 
 		if self.filters.range in ["Monthly", "Quarterly"]:
 			from_date = from_date.replace(day=1)
@@ -342,7 +331,7 @@
 			from_date = from_date + relativedelta(from_date, weekday=MO(-1))
 
 		self.periodic_daterange = []
-		for dummy in range(1, 53):
+		for _dummy in range(1, 53):
 			if self.filters.range == "Weekly":
 				period_end_date = add_days(from_date, 6)
 			else:
@@ -370,10 +359,8 @@
 		self.depth_map = frappe._dict()
 
 		self.group_entries = frappe.db.sql(
-			"""select name, lft, rgt , {parent} as parent
-			from `tab{tree}` order by lft""".format(
-				tree=self.filters.tree_type, parent=parent
-			),
+			f"""select name, lft, rgt , {parent} as parent
+			from `tab{self.filters.tree_type}` order by lft""",
 			as_dict=1,
 		)
 
@@ -387,12 +374,10 @@
 		self.depth_map = frappe._dict()
 
 		self.group_entries = frappe.db.sql(
-			""" select * from (select "Order Types" as name, 0 as lft,
+			f""" select * from (select "Order Types" as name, 0 as lft,
 			2 as rgt, '' as parent union select distinct order_type as name, 1 as lft, 1 as rgt, "Order Types" as parent
-			from `tab{doctype}` where ifnull(order_type, '') != '') as b order by lft, name
-		""".format(
-				doctype=self.filters.doc_type
-			),
+			from `tab{self.filters.doc_type}` where ifnull(order_type, '') != '') as b order by lft, name
+		""",
 			as_dict=1,
 		)
 
diff --git a/erpnext/selling/report/sales_order_analysis/sales_order_analysis.py b/erpnext/selling/report/sales_order_analysis/sales_order_analysis.py
index 1e1d0c0..70b021a 100644
--- a/erpnext/selling/report/sales_order_analysis/sales_order_analysis.py
+++ b/erpnext/selling/report/sales_order_analysis/sales_order_analysis.py
@@ -61,7 +61,7 @@
 
 def get_data(conditions, filters):
 	data = frappe.db.sql(
-		"""
+		f"""
 		SELECT
 			so.transaction_date as date,
 			soi.delivery_date as delivery_date,
@@ -91,9 +91,7 @@
 			{conditions}
 		GROUP BY soi.name
 		ORDER BY so.transaction_date ASC, soi.item_code ASC
-	""".format(
-			conditions=conditions
-		),
+	""",
 		filters,
 		as_dict=1,
 	)
@@ -176,7 +174,9 @@
 				so_row = sales_order_map[so_name]
 				so_row["required_date"] = max(getdate(so_row["delivery_date"]), getdate(row["delivery_date"]))
 				so_row["delay"] = (
-					min(so_row["delay"], row["delay"]) if row["delay"] and so_row["delay"] else so_row["delay"]
+					min(so_row["delay"], row["delay"])
+					if row["delay"] and so_row["delay"]
+					else so_row["delay"]
 				)
 
 				# sum numeric columns
diff --git a/erpnext/selling/report/sales_partner_commission_summary/sales_partner_commission_summary.py b/erpnext/selling/report/sales_partner_commission_summary/sales_partner_commission_summary.py
index cf9ea21..844aa86 100644
--- a/erpnext/selling/report/sales_partner_commission_summary/sales_partner_commission_summary.py
+++ b/erpnext/selling/report/sales_partner_commission_summary/sales_partner_commission_summary.py
@@ -75,16 +75,14 @@
 	entries = frappe.db.sql(
 		"""
 		SELECT
-			name, customer, territory, {0} as posting_date, base_net_total as amount,
+			name, customer, territory, {} as posting_date, base_net_total as amount,
 			sales_partner, commission_rate, total_commission
 		FROM
-			`tab{1}`
+			`tab{}`
 		WHERE
-			{2} and docstatus = 1 and sales_partner is not null
+			{} and docstatus = 1 and sales_partner is not null
 			and sales_partner != '' order by name desc, sales_partner
-		""".format(
-			date_field, filters.get("doctype"), conditions
-		),
+		""".format(date_field, filters.get("doctype"), conditions),
 		filters,
 		as_dict=1,
 	)
@@ -97,15 +95,15 @@
 
 	for field in ["company", "customer", "territory"]:
 		if filters.get(field):
-			conditions += " and {0} = %({1})s".format(field, field)
+			conditions += f" and {field} = %({field})s"
 
 	if filters.get("sales_partner"):
 		conditions += " and sales_partner = %(sales_partner)s"
 
 	if filters.get("from_date"):
-		conditions += " and {0} >= %(from_date)s".format(date_field)
+		conditions += f" and {date_field} >= %(from_date)s"
 
 	if filters.get("to_date"):
-		conditions += " and {0} <= %(to_date)s".format(date_field)
+		conditions += f" and {date_field} <= %(to_date)s"
 
 	return conditions
diff --git a/erpnext/selling/report/sales_partner_target_variance_based_on_item_group/item_group_wise_sales_target_variance.py b/erpnext/selling/report/sales_partner_target_variance_based_on_item_group/item_group_wise_sales_target_variance.py
index 42bdf57..5046ec5 100644
--- a/erpnext/selling/report/sales_partner_target_variance_based_on_item_group/item_group_wise_sales_target_variance.py
+++ b/erpnext/selling/report/sales_partner_target_variance_based_on_item_group/item_group_wise_sales_target_variance.py
@@ -94,8 +94,8 @@
 	]
 
 	for period in period_list:
-		target_key = "target_{}".format(period.key)
-		variance_key = "variance_{}".format(period.key)
+		target_key = f"target_{period.key}"
+		variance_key = f"variance_{period.key}"
 
 		columns.extend(
 			[
@@ -169,9 +169,7 @@
 
 	for d in sales_users_data:
 		key = (d.parent, d.item_group)
-		dist_data = get_periodwise_distribution_data(
-			d.distribution_id, period_list, filters.get("period")
-		)
+		dist_data = get_periodwise_distribution_data(d.distribution_id, period_list, filters.get("period"))
 
 		if key not in rows:
 			rows.setdefault(key, {"total_target": 0, "total_achieved": 0, "total_variance": 0})
@@ -182,8 +180,8 @@
 			if p_key not in details:
 				details[p_key] = 0
 
-			target_key = "target_{}".format(p_key)
-			variance_key = "variance_{}".format(p_key)
+			target_key = f"target_{p_key}"
+			variance_key = f"variance_{p_key}"
 			details[target_key] = (d.get(target_qty_amt_field) * dist_data.get(p_key)) / 100
 			details[variance_key] = 0
 			details["total_target"] += details[target_key]
diff --git a/erpnext/selling/report/sales_partner_target_variance_based_on_item_group/sales_partner_target_variance_based_on_item_group.py b/erpnext/selling/report/sales_partner_target_variance_based_on_item_group/sales_partner_target_variance_based_on_item_group.py
index f2b6a54..bad6c94 100644
--- a/erpnext/selling/report/sales_partner_target_variance_based_on_item_group/sales_partner_target_variance_based_on_item_group.py
+++ b/erpnext/selling/report/sales_partner_target_variance_based_on_item_group/sales_partner_target_variance_based_on_item_group.py
@@ -8,6 +8,4 @@
 
 
 def execute(filters=None):
-	data = []
-
 	return get_data_column(filters, "Sales Partner")
diff --git a/erpnext/selling/report/sales_partner_transaction_summary/sales_partner_transaction_summary.py b/erpnext/selling/report/sales_partner_transaction_summary/sales_partner_transaction_summary.py
index 2049520..216adde 100644
--- a/erpnext/selling/report/sales_partner_transaction_summary/sales_partner_transaction_summary.py
+++ b/erpnext/selling/report/sales_partner_transaction_summary/sales_partner_transaction_summary.py
@@ -110,9 +110,7 @@
 			{cond} and dt.name = dt_item.parent and dt.docstatus = 1
 			and dt.sales_partner is not null and dt.sales_partner != ''
 			order by dt.name desc, dt.sales_partner
-		""".format(
-			date_field=date_field, doctype=filters.get("doctype"), cond=conditions
-		),
+		""".format(date_field=date_field, doctype=filters.get("doctype"), cond=conditions),
 		filters,
 		as_dict=1,
 	)
@@ -125,13 +123,13 @@
 
 	for field in ["company", "customer", "territory", "sales_partner"]:
 		if filters.get(field):
-			conditions += " and dt.{0} = %({1})s".format(field, field)
+			conditions += f" and dt.{field} = %({field})s"
 
 	if filters.get("from_date"):
-		conditions += " and dt.{0} >= %(from_date)s".format(date_field)
+		conditions += f" and dt.{date_field} >= %(from_date)s"
 
 	if filters.get("to_date"):
-		conditions += " and dt.{0} <= %(to_date)s".format(date_field)
+		conditions += f" and dt.{date_field} <= %(to_date)s"
 
 	if not filters.get("show_return_entries"):
 		conditions += " and dt_item.qty > 0.0"
@@ -142,10 +140,7 @@
 	if filters.get("item_group"):
 		lft, rgt = frappe.get_cached_value("Item Group", filters.get("item_group"), ["lft", "rgt"])
 
-		conditions += """ and dt_item.item_group in (select name from
-			`tabItem Group` where lft >= %s and rgt <= %s)""" % (
-			lft,
-			rgt,
-		)
+		conditions += f""" and dt_item.item_group in (select name from
+			`tabItem Group` where lft >= {lft} and rgt <= {rgt})"""
 
 	return conditions
diff --git a/erpnext/selling/report/sales_person_commission_summary/sales_person_commission_summary.py b/erpnext/selling/report/sales_person_commission_summary/sales_person_commission_summary.py
index a8df530..16b2d49 100644
--- a/erpnext/selling/report/sales_person_commission_summary/sales_person_commission_summary.py
+++ b/erpnext/selling/report/sales_person_commission_summary/sales_person_commission_summary.py
@@ -103,16 +103,15 @@
 	entries = frappe.db.sql(
 		"""
 		select
-			dt.name, dt.customer, dt.territory, dt.%s as posting_date,dt.base_net_total as base_net_amount,
+			dt.name, dt.customer, dt.territory, dt.{} as posting_date,dt.base_net_total as base_net_amount,
 			st.commission_rate,st.sales_person, st.allocated_percentage, st.allocated_amount, st.incentives
 		from
-			`tab%s` dt, `tabSales Team` st
+			`tab{}` dt, `tabSales Team` st
 		where
-			st.parent = dt.name and st.parenttype = %s
-			and dt.docstatus = 1 %s order by dt.name desc,st.sales_person
-		"""
-		% (date_field, filters["doc_type"], "%s", conditions),
-		tuple([filters["doc_type"]] + values),
+			st.parent = dt.name and st.parenttype = {}
+			and dt.docstatus = 1 {} order by dt.name desc,st.sales_person
+		""".format(date_field, filters["doc_type"], "%s", conditions),
+		tuple([filters["doc_type"], *values]),
 		as_dict=1,
 	)
 
@@ -125,18 +124,18 @@
 
 	for field in ["company", "customer", "territory"]:
 		if filters.get(field):
-			conditions.append("dt.{0}=%s".format(field))
+			conditions.append(f"dt.{field}=%s")
 			values.append(filters[field])
 
 	if filters.get("sales_person"):
-		conditions.append("st.sales_person = '{0}'".format(filters.get("sales_person")))
+		conditions.append("st.sales_person = '{}'".format(filters.get("sales_person")))
 
 	if filters.get("from_date"):
-		conditions.append("dt.{0}>=%s".format(date_field))
+		conditions.append(f"dt.{date_field}>=%s")
 		values.append(filters["from_date"])
 
 	if filters.get("to_date"):
-		conditions.append("dt.{0}<=%s".format(date_field))
+		conditions.append(f"dt.{date_field}<=%s")
 		values.append(filters["to_date"])
 
 	return " and ".join(conditions), values
diff --git a/erpnext/selling/report/sales_person_wise_transaction_summary/sales_person_wise_transaction_summary.py b/erpnext/selling/report/sales_person_wise_transaction_summary/sales_person_wise_transaction_summary.py
index 847488f..f8cde14 100644
--- a/erpnext/selling/report/sales_person_wise_transaction_summary/sales_person_wise_transaction_summary.py
+++ b/erpnext/selling/report/sales_person_wise_transaction_summary/sales_person_wise_transaction_summary.py
@@ -156,27 +156,26 @@
 	entries = frappe.db.sql(
 		"""
 		SELECT
-			dt.name, dt.customer, dt.territory, dt.%s as posting_date, dt_item.item_code,
+			dt.name, dt.customer, dt.territory, dt.{} as posting_date, dt_item.item_code,
 			st.sales_person, st.allocated_percentage, dt_item.warehouse,
 		CASE
-			WHEN dt.status = "Closed" THEN dt_item.%s * dt_item.conversion_factor
+			WHEN dt.status = "Closed" THEN dt_item.{} * dt_item.conversion_factor
 			ELSE dt_item.stock_qty
 		END as stock_qty,
 		CASE
-			WHEN dt.status = "Closed" THEN (dt_item.base_net_rate * dt_item.%s * dt_item.conversion_factor)
+			WHEN dt.status = "Closed" THEN (dt_item.base_net_rate * dt_item.{} * dt_item.conversion_factor)
 			ELSE dt_item.base_net_amount
 		END as base_net_amount,
 		CASE
-			WHEN dt.status = "Closed" THEN ((dt_item.base_net_rate * dt_item.%s * dt_item.conversion_factor) * st.allocated_percentage/100)
+			WHEN dt.status = "Closed" THEN ((dt_item.base_net_rate * dt_item.{} * dt_item.conversion_factor) * st.allocated_percentage/100)
 			ELSE dt_item.base_net_amount * st.allocated_percentage/100
 		END as contribution_amt
 		FROM
-			`tab%s` dt, `tab%s Item` dt_item, `tabSales Team` st
+			`tab{}` dt, `tab{} Item` dt_item, `tabSales Team` st
 		WHERE
-			st.parent = dt.name and dt.name = dt_item.parent and st.parenttype = %s
-			and dt.docstatus = 1 %s order by st.sales_person, dt.name desc
-		"""
-		% (
+			st.parent = dt.name and dt.name = dt_item.parent and st.parenttype = {}
+			and dt.docstatus = 1 {} order by st.sales_person, dt.name desc
+		""".format(
 			date_field,
 			qty_field,
 			qty_field,
@@ -186,7 +185,7 @@
 			"%s",
 			conditions,
 		),
-		tuple([filters["doc_type"]] + values),
+		tuple([filters["doc_type"], *values]),
 		as_dict=1,
 	)
 
@@ -199,23 +198,21 @@
 
 	for field in ["company", "customer", "territory"]:
 		if filters.get(field):
-			conditions.append("dt.{0}=%s".format(field))
+			conditions.append(f"dt.{field}=%s")
 			values.append(filters[field])
 
 	if filters.get("sales_person"):
 		lft, rgt = frappe.get_value("Sales Person", filters.get("sales_person"), ["lft", "rgt"])
 		conditions.append(
-			"exists(select name from `tabSales Person` where lft >= {0} and rgt <= {1} and name=st.sales_person)".format(
-				lft, rgt
-			)
+			f"exists(select name from `tabSales Person` where lft >= {lft} and rgt <= {rgt} and name=st.sales_person)"
 		)
 
 	if filters.get("from_date"):
-		conditions.append("dt.{0}>=%s".format(date_field))
+		conditions.append(f"dt.{date_field}>=%s")
 		values.append(filters["from_date"])
 
 	if filters.get("to_date"):
-		conditions.append("dt.{0}<=%s".format(date_field))
+		conditions.append(f"dt.{date_field}<=%s")
 		values.append(filters["to_date"])
 
 	items = get_items(filters)
diff --git a/erpnext/selling/report/territory_target_variance_based_on_item_group/territory_target_variance_based_on_item_group.py b/erpnext/selling/report/territory_target_variance_based_on_item_group/territory_target_variance_based_on_item_group.py
index eee2d42..527e60e 100644
--- a/erpnext/selling/report/territory_target_variance_based_on_item_group/territory_target_variance_based_on_item_group.py
+++ b/erpnext/selling/report/territory_target_variance_based_on_item_group/territory_target_variance_based_on_item_group.py
@@ -8,6 +8,4 @@
 
 
 def execute(filters=None):
-	data = []
-
 	return get_data_column(filters, "Territory")
diff --git a/erpnext/selling/report/territory_wise_sales/territory_wise_sales.py b/erpnext/selling/report/territory_wise_sales/territory_wise_sales.py
index ecb63d8..e31b259 100644
--- a/erpnext/selling/report/territory_wise_sales/territory_wise_sales.py
+++ b/erpnext/selling/report/territory_wise_sales/territory_wise_sales.py
@@ -107,7 +107,7 @@
 	conditions = ""
 
 	if filters.get("transaction_date"):
-		conditions = " WHERE transaction_date between {0} and {1}".format(
+		conditions = " WHERE transaction_date between {} and {}".format(
 			frappe.db.escape(filters["transaction_date"][0]),
 			frappe.db.escape(filters["transaction_date"][1]),
 		)
@@ -120,12 +120,10 @@
 		conditions += " company = %(company)s"
 
 	return frappe.db.sql(
-		"""
+		f"""
 		SELECT name, territory, opportunity_amount
-		FROM `tabOpportunity` {0}
-	""".format(
-			conditions
-		),
+		FROM `tabOpportunity` {conditions}
+	""",
 		filters,
 		as_dict=1,
 	)  # nosec
@@ -141,10 +139,8 @@
 		"""
 		SELECT `name`,`base_grand_total`, `opportunity`
 		FROM `tabQuotation`
-		WHERE docstatus=1 AND opportunity in ({0})
-	""".format(
-			", ".join(["%s"] * len(opportunity_names))
-		),
+		WHERE docstatus=1 AND opportunity in ({})
+	""".format(", ".join(["%s"] * len(opportunity_names))),
 		tuple(opportunity_names),
 		as_dict=1,
 	)  # nosec
@@ -160,10 +156,8 @@
 		"""
 	SELECT so.`name`, so.`base_grand_total`, soi.prevdoc_docname as quotation
 	FROM `tabSales Order` so, `tabSales Order Item` soi
-	WHERE so.docstatus=1 AND so.name = soi.parent AND soi.prevdoc_docname in ({0})
-	""".format(
-			", ".join(["%s"] * len(quotation_names))
-		),
+	WHERE so.docstatus=1 AND so.name = soi.parent AND soi.prevdoc_docname in ({})
+	""".format(", ".join(["%s"] * len(quotation_names))),
 		tuple(quotation_names),
 		as_dict=1,
 	)  # nosec
@@ -179,10 +173,8 @@
 		"""
 	SELECT si.name, si.base_grand_total, sii.sales_order
 	FROM `tabSales Invoice` si, `tabSales Invoice Item` sii
-	WHERE si.docstatus=1 AND si.name = sii.parent AND sii.sales_order in ({0})
-	""".format(
-			", ".join(["%s"] * len(so_names))
-		),
+	WHERE si.docstatus=1 AND si.name = sii.parent AND sii.sales_order in ({})
+	""".format(", ".join(["%s"] * len(so_names))),
 		tuple(so_names),
 		as_dict=1,
 	)  # nosec
diff --git a/erpnext/setup/demo.py b/erpnext/setup/demo.py
index f48402e..f025352 100644
--- a/erpnext/setup/demo.py
+++ b/erpnext/setup/demo.py
@@ -150,7 +150,6 @@
 				document, filters={"docstatus": 1}, fields=["name", "transaction_date"], limit=6
 			)
 		):
-
 			if document == "Purchase Order":
 				invoice = make_purchase_invoice(order.name)
 			elif document == "Sales Order":
@@ -217,7 +216,7 @@
 
 def read_data_file_using_hooks(doctype):
 	path = os.path.join(os.path.dirname(__file__), "demo_data")
-	with open(os.path.join(path, doctype + ".json"), "r") as f:
+	with open(os.path.join(path, doctype + ".json")) as f:
 		data = f.read()
 
 	return data
diff --git a/erpnext/setup/doctype/authorization_control/authorization_control.py b/erpnext/setup/doctype/authorization_control/authorization_control.py
index 27313ae..ef703de 100644
--- a/erpnext/setup/doctype/authorization_control/authorization_control.py
+++ b/erpnext/setup/doctype/authorization_control/authorization_control.py
@@ -22,7 +22,7 @@
 
 	def get_appr_user_role(self, det, doctype_name, total, based_on, condition, master_name, company):
 		amt_list, appr_users, appr_roles = [], [], []
-		users, roles = "", ""
+		_users, _roles = "", ""
 		if det:
 			for x in det:
 				amt_list.append(flt(x[0]))
@@ -30,18 +30,20 @@
 
 			app_dtl = frappe.db.sql(
 				"""select approving_user, approving_role from `tabAuthorization Rule`
-				where transaction = %s and (value = %s or value > %s)
-				and docstatus != 2 and based_on = %s and company = %s %s"""
-				% ("%s", "%s", "%s", "%s", "%s", condition),
+				where transaction = {} and (value = {} or value > {})
+				and docstatus != 2 and based_on = {} and company = {} {}""".format(
+					"%s", "%s", "%s", "%s", "%s", condition
+				),
 				(doctype_name, flt(max_amount), total, based_on, company),
 			)
 
 			if not app_dtl:
 				app_dtl = frappe.db.sql(
 					"""select approving_user, approving_role from `tabAuthorization Rule`
-					where transaction = %s and (value = %s or value > %s) and docstatus != 2
-					and based_on = %s and ifnull(company,'') = '' %s"""
-					% ("%s", "%s", "%s", "%s", condition),
+					where transaction = {} and (value = {} or value > {}) and docstatus != 2
+					and based_on = {} and ifnull(company,'') = '' {}""".format(
+						"%s", "%s", "%s", "%s", condition
+					),
 					(doctype_name, flt(max_amount), total, based_on),
 				)
 
@@ -64,18 +66,20 @@
 			add_cond1 += " and master_name = " + frappe.db.escape(cstr(master_name))
 			itemwise_exists = frappe.db.sql(
 				"""select value from `tabAuthorization Rule`
-				where transaction = %s and value <= %s
-				and based_on = %s and company = %s and docstatus != 2 %s %s"""
-				% ("%s", "%s", "%s", "%s", cond, add_cond1),
+				where transaction = {} and value <= {}
+				and based_on = {} and company = {} and docstatus != 2 {} {}""".format(
+					"%s", "%s", "%s", "%s", cond, add_cond1
+				),
 				(doctype_name, total, based_on, company),
 			)
 
 			if not itemwise_exists:
 				itemwise_exists = frappe.db.sql(
 					"""select value from `tabAuthorization Rule`
-					where transaction = %s and value <= %s and based_on = %s
-					and ifnull(company,'') = ''	and docstatus != 2 %s %s"""
-					% ("%s", "%s", "%s", cond, add_cond1),
+					where transaction = {} and value <= {} and based_on = {}
+					and ifnull(company,'') = ''	and docstatus != 2 {} {}""".format(
+						"%s", "%s", "%s", cond, add_cond1
+					),
 					(doctype_name, total, based_on),
 				)
 
@@ -90,18 +94,18 @@
 
 			appr = frappe.db.sql(
 				"""select value from `tabAuthorization Rule`
-				where transaction = %s and value <= %s and based_on = %s
-				and company = %s and docstatus != 2 %s %s"""
-				% ("%s", "%s", "%s", "%s", cond, add_cond2),
+				where transaction = {} and value <= {} and based_on = {}
+				and company = {} and docstatus != 2 {} {}""".format("%s", "%s", "%s", "%s", cond, add_cond2),
 				(doctype_name, total, based_on, company),
 			)
 
 			if not appr:
 				appr = frappe.db.sql(
 					"""select value from `tabAuthorization Rule`
-					where transaction = %s and value <= %s and based_on = %s
-					and ifnull(company,'') = '' and docstatus != 2 %s %s"""
-					% ("%s", "%s", "%s", cond, add_cond2),
+					where transaction = {} and value <= {} and based_on = {}
+					and ifnull(company,'') = '' and docstatus != 2 {} {}""".format(
+						"%s", "%s", "%s", cond, add_cond2
+					),
 					(doctype_name, total, based_on),
 				)
 
@@ -128,7 +132,7 @@
 					customer = doc_obj.customer
 				else:
 					customer = doc_obj.customer_name
-				add_cond = " and master_name = {}".format(frappe.db.escape(customer))
+				add_cond = f" and master_name = {frappe.db.escape(customer)}"
 		if based_on == "Itemwise Discount":
 			if doc_obj:
 				for t in doc_obj.get("items"):
@@ -197,11 +201,10 @@
 			for x in frappe.db.sql(
 				"""select based_on
 			from `tabAuthorization Rule`
-			where transaction = %s and system_role IN (%s) and based_on IN (%s)
-			and (company = %s or ifnull(company,'')='')
+			where transaction = {} and system_role IN ({}) and based_on IN ({})
+			and (company = {} or ifnull(company,'')='')
 			and docstatus != 2
-		"""
-				% (
+		""".format(
 					"%s",
 					"'" + "','".join(frappe.get_roles()) + "'",
 					"'" + "','".join(final_based_on) + "'",
diff --git a/erpnext/setup/doctype/authorization_rule/authorization_rule.py b/erpnext/setup/doctype/authorization_rule/authorization_rule.py
index b65a327..a52a32a 100644
--- a/erpnext/setup/doctype/authorization_rule/authorization_rule.py
+++ b/erpnext/setup/doctype/authorization_rule/authorization_rule.py
@@ -88,9 +88,7 @@
 			"Itemwise Discount",
 			"Item Group wise Discount",
 		]:
-			frappe.throw(
-				_("Cannot set authorization on basis of Discount for {0}").format(self.transaction)
-			)
+			frappe.throw(_("Cannot set authorization on basis of Discount for {0}").format(self.transaction))
 		elif self.based_on == "Average Discount" and flt(self.value) > 100.00:
 			frappe.throw(_("Discount must be less than 100"))
 		elif self.based_on == "Customerwise Discount" and not self.master_name:
diff --git a/erpnext/setup/doctype/company/company.py b/erpnext/setup/doctype/company/company.py
index 3ca14e6..ad2280c 100644
--- a/erpnext/setup/doctype/company/company.py
+++ b/erpnext/setup/doctype/company/company.py
@@ -122,9 +122,8 @@
 			"Supplier Quotation",
 		]:
 			if frappe.db.sql(
-				"""select name from `tab%s` where company=%s and docstatus=1
-					limit 1"""
-				% (doctype, "%s"),
+				"""select name from `tab{}` where company={} and docstatus=1
+					limit 1""".format(doctype, "%s"),
 				self.name,
 			):
 				exists = True
@@ -157,9 +156,7 @@
 		if not self.abbr.strip():
 			frappe.throw(_("Abbreviation is mandatory"))
 
-		if frappe.db.sql(
-			"select abbr from tabCompany where name!=%s and abbr=%s", (self.name, self.abbr)
-		):
+		if frappe.db.sql("select abbr from tabCompany where name!=%s and abbr=%s", (self.name, self.abbr)):
 			frappe.throw(_("Abbreviation already used for another company"))
 
 	@frappe.whitelist()
@@ -183,7 +180,9 @@
 				for_company = frappe.db.get_value("Account", self.get(account[1]), "company")
 				if for_company != self.name:
 					frappe.throw(
-						_("Account {0} does not belong to company: {1}").format(self.get(account[1]), self.name)
+						_("Account {0} does not belong to company: {1}").format(
+							self.get(account[1]), self.name
+						)
 					)
 
 				if get_account_currency(self.get(account[1])) != self.default_currency:
@@ -195,9 +194,7 @@
 	def validate_currency(self):
 		if self.is_new():
 			return
-		self.previous_default_currency = frappe.get_cached_value(
-			"Company", self.name, "default_currency"
-		)
+		self.previous_default_currency = frappe.get_cached_value("Company", self.name, "default_currency")
 		if (
 			self.default_currency
 			and self.previous_default_currency
@@ -261,17 +258,14 @@
 			{"warehouse_name": _("Finished Goods"), "is_group": 0},
 			{"warehouse_name": _("Goods In Transit"), "is_group": 0, "warehouse_type": "Transit"},
 		]:
-
-			if not frappe.db.exists(
-				"Warehouse", "{0} - {1}".format(wh_detail["warehouse_name"], self.abbr)
-			):
+			if not frappe.db.exists("Warehouse", "{} - {}".format(wh_detail["warehouse_name"], self.abbr)):
 				warehouse = frappe.get_doc(
 					{
 						"doctype": "Warehouse",
 						"warehouse_name": wh_detail["warehouse_name"],
 						"is_group": wh_detail["is_group"],
 						"company": self.name,
-						"parent_warehouse": "{0} - {1}".format(_("All Warehouses"), self.abbr)
+						"parent_warehouse": "{} - {}".format(_("All Warehouses"), self.abbr)
 						if not wh_detail["is_group"]
 						else "",
 						"warehouse_type": wh_detail.get("warehouse_type"),
@@ -296,9 +290,7 @@
 
 		self.db_set(
 			"default_payable_account",
-			frappe.db.get_value(
-				"Account", {"company": self.name, "account_type": "Payable", "is_group": 0}
-			),
+			frappe.db.get_value("Account", {"company": self.name, "account_type": "Payable", "is_group": 0}),
 		)
 
 	def create_default_departments(self):
@@ -425,7 +417,9 @@
 				and not self.default_provisional_account
 			):
 				frappe.throw(
-					_("Set default {0} account for non stock items").format(frappe.bold("Provisional Account"))
+					_("Set default {0} account for non stock items").format(
+						frappe.bold("Provisional Account")
+					)
 				)
 
 			make_property_setter(
@@ -440,9 +434,7 @@
 	def check_country_change(self):
 		frappe.flags.country_change = False
 
-		if not self.is_new() and self.country != frappe.get_cached_value(
-			"Company", self.name, "country"
-		):
+		if not self.is_new() and self.country != frappe.get_cached_value("Company", self.name, "country"):
 			frappe.flags.country_change = True
 
 	def set_chart_of_accounts(self):
@@ -609,14 +601,14 @@
 			)
 
 			for doctype in ["Account", "Cost Center", "Budget", "Party Account"]:
-				frappe.db.sql("delete from `tab{0}` where company = %s".format(doctype), self.name)
+				frappe.db.sql(f"delete from `tab{doctype}` where company = %s", self.name)
 
 		if not frappe.db.get_value("Stock Ledger Entry", {"company": self.name}):
 			frappe.db.sql("""delete from `tabWarehouse` where company=%s""", self.name)
 
 		frappe.defaults.clear_default("company", value=self.name)
 		for doctype in ["Mode of Payment Account", "Item Default"]:
-			frappe.db.sql("delete from `tab{0}` where company = %s".format(doctype), self.name)
+			frappe.db.sql(f"delete from `tab{doctype}` where company = %s", self.name)
 
 		# clear default accounts, warehouses from item
 		warehouses = frappe.db.sql_list("select name from tabWarehouse where company=%s", self.name)
@@ -649,7 +641,7 @@
 			frappe.db.sql("delete from tabBOM where company=%s", self.name)
 			for dt in ("BOM Operation", "BOM Item", "BOM Scrap Item", "BOM Explosion Item"):
 				frappe.db.sql(
-					"delete from `tab%s` where parent in (%s)" "" % (dt, ", ".join(["%s"] * len(boms))),
+					"delete from `tab{}` where parent in ({})" "".format(dt, ", ".join(["%s"] * len(boms))),
 					tuple(boms),
 				)
 
@@ -705,7 +697,7 @@
 	current_month_year = formatdate(today(), "MM-yyyy")
 
 	results = frappe.db.sql(
-		"""
+		f"""
 		SELECT
 			SUM(base_grand_total) AS total,
 			DATE_FORMAT(`posting_date`, '%m-%Y') AS month_year
@@ -714,12 +706,10 @@
 		WHERE
 			DATE_FORMAT(`posting_date`, '%m-%Y') = '{current_month_year}'
 			AND docstatus = 1
-			AND company = {company}
+			AND company = {frappe.db.escape(company)}
 		GROUP BY
 			month_year
-	""".format(
-			current_month_year=current_month_year, company=frappe.db.escape(company)
-		),
+	""",
 		as_dict=True,
 	)
 
@@ -734,9 +724,7 @@
 
 	from frappe.utils.goal import get_monthly_results
 
-	filter_str = "company = {0} and status != 'Draft' and docstatus=1".format(
-		frappe.db.escape(company)
-	)
+	filter_str = f"company = {frappe.db.escape(company)} and status != 'Draft' and docstatus=1"
 	month_to_value_dict = get_monthly_results(
 		"Sales Invoice", "base_grand_total", "posting_date", filter_str, "sum"
 	)
@@ -746,9 +734,7 @@
 
 def update_transactions_annual_history(company, commit=False):
 	transactions_history = get_all_transactions_annual_history(company)
-	frappe.db.set_value(
-		"Company", company, "transactions_annual_history", json.dumps(transactions_history)
-	)
+	frappe.db.set_value("Company", company, "transactions_annual_history", json.dumps(transactions_history))
 
 	if commit:
 		frappe.db.commit()
@@ -764,21 +750,19 @@
 
 @frappe.whitelist()
 def get_children(doctype, parent=None, company=None, is_root=False):
-	if parent == None or parent == "All Companies":
+	if parent is None or parent == "All Companies":
 		parent = ""
 
 	return frappe.db.sql(
-		"""
+		f"""
 		select
 			name as value,
 			is_group as expandable
 		from
 			`tabCompany` comp
 		where
-			ifnull(parent_company, "")={parent}
-		""".format(
-			parent=frappe.db.escape(parent)
-		),
+			ifnull(parent_company, "")={frappe.db.escape(parent)}
+		""",
 		as_dict=1,
 	)
 
@@ -854,7 +838,6 @@
 
 def get_timeline_data(doctype, name):
 	"""returns timeline data based on linked records in dashboard"""
-	out = {}
 	date_to_value_dict = {}
 
 	history = frappe.get_cached_value("Company", name, "transactions_annual_history")
@@ -879,14 +862,13 @@
 
 	out = frappe.db.sql(
 		""" SELECT
-			addr.name, addr.%s
+			addr.name, addr.{}
 		FROM
 			`tabAddress` addr, `tabDynamic Link` dl
 		WHERE
 			dl.parent = addr.name and dl.link_doctype = 'Company' and
-			dl.link_name = %s and ifnull(addr.disabled, 0) = 0
-		"""
-		% (sort_key, "%s"),
+			dl.link_name = {} and ifnull(addr.disabled, 0) = 0
+		""".format(sort_key, "%s"),
 		(name),
 	)  # nosec
 
diff --git a/erpnext/setup/doctype/currency_exchange/currency_exchange.py b/erpnext/setup/doctype/currency_exchange/currency_exchange.py
index 735734b..dab3564 100644
--- a/erpnext/setup/doctype/currency_exchange/currency_exchange.py
+++ b/erpnext/setup/doctype/currency_exchange/currency_exchange.py
@@ -38,7 +38,7 @@
 		if cint(self.for_buying) == 1 and cint(self.for_selling) == 0:
 			purpose = "Buying"
 
-		self.name = "{0}-{1}-{2}{3}".format(
+		self.name = "{}-{}-{}{}".format(
 			formatdate(get_datetime_str(self.date), "yyyy-MM-dd"),
 			self.from_currency,
 			self.to_currency,
diff --git a/erpnext/setup/doctype/currency_exchange/test_currency_exchange.py b/erpnext/setup/doctype/currency_exchange/test_currency_exchange.py
index 8477984..3249c93 100644
--- a/erpnext/setup/doctype/currency_exchange/test_currency_exchange.py
+++ b/erpnext/setup/doctype/currency_exchange/test_currency_exchange.py
@@ -49,6 +49,7 @@
 
 test_exchange_values = {"2015-12-15": "66.999", "2016-01-15": "65.1"}
 
+
 # Removing API call from get_exchange_rate
 def patched_requests_get(*args, **kwargs):
 	class PatchResponse:
@@ -83,7 +84,7 @@
 	def clear_cache(self):
 		cache = frappe.cache()
 		for date in test_exchange_values.keys():
-			key = "currency_exchange_rate_{0}:{1}:{2}".format(date, "USD", "INR")
+			key = "currency_exchange_rate_{}:{}:{}".format(date, "USD", "INR")
 			cache.delete(key)
 
 	def tearDown(self):
diff --git a/erpnext/setup/doctype/customer_group/customer_group.py b/erpnext/setup/doctype/customer_group/customer_group.py
index 89b89ad..0b783c0 100644
--- a/erpnext/setup/doctype/customer_group/customer_group.py
+++ b/erpnext/setup/doctype/customer_group/customer_group.py
@@ -41,7 +41,7 @@
 
 	def on_update(self):
 		self.validate_name_with_customer()
-		super(CustomerGroup, self).on_update()
+		super().on_update()
 		self.validate_one_root()
 
 	def validate_name_with_customer(self):
diff --git a/erpnext/setup/doctype/department/department.py b/erpnext/setup/doctype/department/department.py
index b36f032..d40cf6b 100644
--- a/erpnext/setup/doctype/department/department.py
+++ b/erpnext/setup/doctype/department/department.py
@@ -51,10 +51,10 @@
 
 	def on_update(self):
 		if not (frappe.local.flags.ignore_update_nsm or frappe.flags.in_setup_wizard):
-			super(Department, self).on_update()
+			super().on_update()
 
 	def on_trash(self):
-		super(Department, self).on_trash()
+		super().on_trash()
 		delete_events(self.doctype, self.name)
 
 
@@ -64,7 +64,7 @@
 
 def get_abbreviated_name(name, company):
 	abbr = frappe.get_cached_value("Company", company, "abbr")
-	new_name = "{0} - {1}".format(name, abbr)
+	new_name = f"{name} - {abbr}"
 	return new_name
 
 
diff --git a/erpnext/setup/doctype/email_digest/email_digest.py b/erpnext/setup/doctype/email_digest/email_digest.py
index 7ac7086..3a5933e 100644
--- a/erpnext/setup/doctype/email_digest/email_digest.py
+++ b/erpnext/setup/doctype/email_digest/email_digest.py
@@ -75,7 +75,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(EmailDigest, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 
 		self.from_date, self.to_date = self.get_from_to_date()
 		self.set_dates()
@@ -90,9 +90,7 @@
 			select name, enabled from tabUser
 			where name not in ({})
 			and user_type != "Website User"
-			order by enabled desc, name asc""".format(
-				", ".join(["%s"] * len(STANDARD_USERS))
-			),
+			order by enabled desc, name asc""".format(", ".join(["%s"] * len(STANDARD_USERS))),
 			STANDARD_USERS,
 			as_dict=1,
 		)
@@ -195,15 +193,11 @@
 		context.text_color = "#36414C"
 		context.h1 = "margin-bottom: 30px; margin-top: 40px; font-weight: 400; font-size: 30px;"
 		context.h2 = "margin-bottom: 30px; margin-top: -20px; font-weight: 400; font-size: 20px;"
-		context.label_css = """display: inline-block; color: {text_muted};
-			padding: 3px 7px; margin-right: 7px;""".format(
-			text_muted=context.text_muted
-		)
+		context.label_css = f"""display: inline-block; color: {context.text_muted};
+			padding: 3px 7px; margin-right: 7px;"""
 		context.section_head = "margin-top: 60px; font-size: 16px;"
 		context.line_item = "padding: 5px 0px; margin: 0; border-bottom: 1px solid #d1d8dd;"
-		context.link_css = "color: {text_color}; text-decoration: none;".format(
-			text_color=context.text_color
-		)
+		context.link_css = f"color: {context.text_color}; text-decoration: none;"
 
 	def get_notifications(self):
 		"""Get notifications for user"""
@@ -226,7 +220,7 @@
 		events = get_events(from_date, to_date)
 
 		event_count = 0
-		for i, e in enumerate(events):
+		for _i, e in enumerate(events):
 			e.starts_on_label = format_time(e.starts_on)
 			e.ends_on_label = format_time(e.ends_on) if e.ends_on else None
 			e.date = formatdate(e.starts)
@@ -342,11 +336,8 @@
 			"new_quotations",
 			"pending_quotations",
 		):
-
 			if self.get(key):
-				cache_key = "email_digest:card:{0}:{1}:{2}:{3}".format(
-					self.company, self.frequency, key, self.from_date
-				)
+				cache_key = f"email_digest:card:{self.company}:{self.frequency}:{key}:{self.from_date}"
 				card = cache.get(cache_key)
 
 				if card:
@@ -465,9 +456,7 @@
 		return self.get_type_balance("invoiced_amount", "Receivable")
 
 	def get_expenses_booked(self):
-		expenses, past_expenses, count = self.get_period_amounts(
-			self.get_roots("expense"), "expenses_booked"
-		)
+		expenses, past_expenses, count = self.get_period_amounts(self.get_roots("expense"), "expenses_booked")
 
 		expense_account = frappe.db.get_all(
 			"Account",
@@ -603,7 +592,6 @@
 		return {"label": label, "value": value, "count": count}
 
 	def get_type_balance(self, fieldname, account_type, root_type=None):
-
 		if root_type:
 			accounts = [
 				d.name
@@ -693,53 +681,43 @@
 			self._accounts[root_type] = [
 				d.name
 				for d in frappe.db.get_all(
-					"Account", filters={"root_type": root_type.title(), "company": self.company, "is_group": 0}
+					"Account",
+					filters={"root_type": root_type.title(), "company": self.company, "is_group": 0},
 				)
 			]
 		return self._accounts[root_type]
 
 	def get_purchase_order(self):
-
 		return self.get_summary_of_doc("Purchase Order", "purchase_order")
 
 	def get_sales_order(self):
-
 		return self.get_summary_of_doc("Sales Order", "sales_order")
 
 	def get_pending_purchase_orders(self):
-
 		return self.get_summary_of_pending("Purchase Order", "pending_purchase_orders", "per_received")
 
 	def get_pending_sales_orders(self):
-
 		return self.get_summary_of_pending("Sales Order", "pending_sales_orders", "per_delivered")
 
 	def get_sales_invoice(self):
-
 		return self.get_summary_of_doc("Sales Invoice", "sales_invoice")
 
 	def get_purchase_invoice(self):
-
 		return self.get_summary_of_doc("Purchase Invoice", "purchase_invoice")
 
 	def get_new_quotations(self):
-
 		return self.get_summary_of_doc("Quotation", "new_quotations")
 
 	def get_pending_quotations(self):
-
 		return self.get_summary_of_pending_quotations("pending_quotations")
 
 	def get_summary_of_pending(self, doc_type, fieldname, getfield):
-
 		value, count, billed_value, delivered_value = frappe.db.sql(
 			"""select ifnull(sum(grand_total),0), count(*),
-			ifnull(sum(grand_total*per_billed/100),0), ifnull(sum(grand_total*{0}/100),0)  from `tab{1}`
+			ifnull(sum(grand_total*per_billed/100),0), ifnull(sum(grand_total*{}/100),0)  from `tab{}`
 			where (transaction_date <= %(to_date)s)
 			and status not in ('Closed','Cancelled', 'Completed')
-			and company = %(company)s """.format(
-				getfield, doc_type
-			),
+			and company = %(company)s """.format(getfield, doc_type),
 			{"to_date": self.future_to_date, "company": self.company},
 		)[0]
 
@@ -752,7 +730,6 @@
 		}
 
 	def get_summary_of_pending_quotations(self, fieldname):
-
 		value, count = frappe.db.sql(
 			"""select ifnull(sum(grand_total),0), count(*) from `tabQuotation`
 			where (transaction_date <= %(to_date)s)
@@ -785,19 +762,14 @@
 		return {"label": label, "value": value, "last_value": last_value, "count": count}
 
 	def get_summary_of_doc(self, doc_type, fieldname):
-
 		date_field = (
 			"posting_date" if doc_type in ["Sales Invoice", "Purchase Invoice"] else "transaction_date"
 		)
 
-		value = flt(
-			self.get_total_on(doc_type, self.future_from_date, self.future_to_date)[0].grand_total
-		)
+		value = flt(self.get_total_on(doc_type, self.future_from_date, self.future_to_date)[0].grand_total)
 		count = self.get_total_on(doc_type, self.future_from_date, self.future_to_date)[0].count
 
-		last_value = flt(
-			self.get_total_on(doc_type, self.past_from_date, self.past_to_date)[0].grand_total
-		)
+		last_value = flt(self.get_total_on(doc_type, self.past_from_date, self.past_to_date)[0].grand_total)
 
 		filters = {
 			date_field: [[">=", self.future_from_date], ["<=", self.future_to_date]],
@@ -816,7 +788,6 @@
 		return {"label": label, "value": value, "last_value": last_value, "count": count}
 
 	def get_total_on(self, doc_type, from_date, to_date):
-
 		date_field = (
 			"posting_date" if doc_type in ["Sales Invoice", "Purchase Invoice"] else "transaction_date"
 		)
@@ -897,20 +868,16 @@
 			"received_qty, qty - received_qty as missing_qty, rate, amount"
 		)
 
-		sql_po = """select {fields} from `tabPurchase Order Item`
+		sql_po = f"""select {fields_po} from `tabPurchase Order Item`
 			left join `tabPurchase Order` on `tabPurchase Order`.name = `tabPurchase Order Item`.parent
 			where status<>'Closed' and `tabPurchase Order Item`.docstatus=1 and CURRENT_DATE > `tabPurchase Order Item`.schedule_date
 			and received_qty < qty order by `tabPurchase Order Item`.parent DESC,
-			`tabPurchase Order Item`.schedule_date DESC""".format(
-			fields=fields_po
-		)
+			`tabPurchase Order Item`.schedule_date DESC"""
 
-		sql_poi = """select {fields} from `tabPurchase Order Item`
+		sql_poi = f"""select {fields_poi} from `tabPurchase Order Item`
 			left join `tabPurchase Order` on `tabPurchase Order`.name = `tabPurchase Order Item`.parent
 			where status<>'Closed' and `tabPurchase Order Item`.docstatus=1 and CURRENT_DATE > `tabPurchase Order Item`.schedule_date
-			and received_qty < qty order by `tabPurchase Order Item`.idx""".format(
-			fields=fields_poi
-		)
+			and received_qty < qty order by `tabPurchase Order Item`.idx"""
 		purchase_order_list = frappe.db.sql(sql_po, as_dict=True)
 		purchase_order_items_overdue_list = frappe.db.sql(sql_poi, as_dict=True)
 
diff --git a/erpnext/setup/doctype/employee/employee.py b/erpnext/setup/doctype/employee/employee.py
index 5237f5a..8f3ba87 100755
--- a/erpnext/setup/doctype/employee/employee.py
+++ b/erpnext/setup/doctype/employee/employee.py
@@ -241,16 +241,12 @@
 
 	user_roles = [d.role for d in doc.get("roles")]
 	if "Employee" in user_roles:
-		frappe.msgprint(
-			_("User {0}: Removed Employee role as there is no mapped employee.").format(doc.name)
-		)
+		frappe.msgprint(_("User {0}: Removed Employee role as there is no mapped employee.").format(doc.name))
 		doc.get("roles").remove(doc.get("roles", {"role": "Employee"})[0])
 
 	if "Employee Self Service" in user_roles:
 		frappe.msgprint(
-			_("User {0}: Removed Employee Self Service role as there is no mapped employee.").format(
-				doc.name
-			)
+			_("User {0}: Removed Employee Self Service role as there is no mapped employee.").format(doc.name)
 		)
 		doc.get("roles").remove(doc.get("roles", {"role": "Employee Self Service"})[0])
 
@@ -266,17 +262,13 @@
 
 def get_employee_email(employee_doc):
 	return (
-		employee_doc.get("user_id")
-		or employee_doc.get("personal_email")
-		or employee_doc.get("company_email")
+		employee_doc.get("user_id") or employee_doc.get("personal_email") or employee_doc.get("company_email")
 	)
 
 
 def get_holiday_list_for_employee(employee, raise_exception=True):
 	if employee:
-		holiday_list, company = frappe.get_cached_value(
-			"Employee", employee, ["holiday_list", "company"]
-		)
+		holiday_list, company = frappe.get_cached_value("Employee", employee, ["holiday_list", "company"])
 	else:
 		holiday_list = ""
 		company = frappe.db.get_single_value("Global Defaults", "default_company")
@@ -292,9 +284,7 @@
 	return holiday_list
 
 
-def is_holiday(
-	employee, date=None, raise_exception=True, only_non_weekly=False, with_description=False
-):
+def is_holiday(employee, date=None, raise_exception=True, only_non_weekly=False, with_description=False):
 	"""
 	Returns True if given Employee has an holiday on the given date
 	        :param employee: Employee `name`
@@ -404,7 +394,6 @@
 
 @frappe.whitelist()
 def get_children(doctype, parent=None, company=None, is_root=False, is_tree=False):
-
 	filters = [["status", "=", "Active"]]
 	if company and company != "All Companies":
 		filters.append(["company", "=", company])
diff --git a/erpnext/setup/doctype/holiday_list/holiday_list.py b/erpnext/setup/doctype/holiday_list/holiday_list.py
index 6381234..9d854c7 100644
--- a/erpnext/setup/doctype/holiday_list/holiday_list.py
+++ b/erpnext/setup/doctype/holiday_list/holiday_list.py
@@ -193,9 +193,7 @@
 	if date is None:
 		date = today()
 	if holiday_list:
-		return bool(
-			frappe.db.exists("Holiday", {"parent": holiday_list, "holiday_date": date}, cache=True)
-		)
+		return bool(frappe.db.exists("Holiday", {"parent": holiday_list, "holiday_date": date}, cache=True))
 	else:
 		return False
 
diff --git a/erpnext/setup/doctype/holiday_list/test_holiday_list.py b/erpnext/setup/doctype/holiday_list/test_holiday_list.py
index c0e71f5..21dacc6 100644
--- a/erpnext/setup/doctype/holiday_list/test_holiday_list.py
+++ b/erpnext/setup/doctype/holiday_list/test_holiday_list.py
@@ -112,9 +112,7 @@
 		frappe.local.lang = lang
 
 
-def make_holiday_list(
-	name, from_date=getdate() - timedelta(days=10), to_date=getdate(), holiday_dates=None
-):
+def make_holiday_list(name, from_date=getdate() - timedelta(days=10), to_date=getdate(), holiday_dates=None):
 	frappe.delete_doc_if_exists("Holiday List", name, force=1)
 	doc = frappe.get_doc(
 		{
diff --git a/erpnext/setup/doctype/incoterm/incoterm.py b/erpnext/setup/doctype/incoterm/incoterm.py
index 17305e9..3b4579d 100644
--- a/erpnext/setup/doctype/incoterm/incoterm.py
+++ b/erpnext/setup/doctype/incoterm/incoterm.py
@@ -27,7 +27,7 @@
 	import os
 	from csv import DictReader
 
-	with open(os.path.join(os.path.dirname(__file__), "incoterms.csv"), "r") as f:
+	with open(os.path.join(os.path.dirname(__file__), "incoterms.csv")) as f:
 		for incoterm in DictReader(f):
 			if frappe.db.exists("Incoterm", incoterm["code"]):
 				continue
diff --git a/erpnext/setup/doctype/item_group/item_group.py b/erpnext/setup/doctype/item_group/item_group.py
index fd65ab6..54f57e7 100644
--- a/erpnext/setup/doctype/item_group/item_group.py
+++ b/erpnext/setup/doctype/item_group/item_group.py
@@ -47,7 +47,7 @@
 					frappe.throw(
 						_("{0} entered twice {1} in Item Taxes").format(
 							frappe.bold(d.item_tax_template),
-							"for tax category {0}".format(frappe.bold(d.tax_category)) if d.tax_category else "",
+							f"for tax category {frappe.bold(d.tax_category)}" if d.tax_category else "",
 						)
 					)
 				else:
diff --git a/erpnext/setup/doctype/item_group/test_item_group.py b/erpnext/setup/doctype/item_group/test_item_group.py
index d95199d..34d7a68 100644
--- a/erpnext/setup/doctype/item_group/test_item_group.py
+++ b/erpnext/setup/doctype/item_group/test_item_group.py
@@ -124,9 +124,7 @@
 	def print_tree(self):
 		import json
 
-		print(
-			json.dumps(frappe.db.sql("select name, lft, rgt from `tabItem Group` order by lft"), indent=1)
-		)
+		print(json.dumps(frappe.db.sql("select name, lft, rgt from `tabItem Group` order by lft"), indent=1))
 
 	def test_move_leaf_into_another_group(self):
 		# before move
@@ -156,17 +154,13 @@
 
 	def test_delete_leaf(self):
 		# for checking later
-		parent_item_group = frappe.db.get_value(
-			"Item Group", "_Test Item Group B - 3", "parent_item_group"
-		)
-		rgt = frappe.db.get_value("Item Group", parent_item_group, "rgt")
+		parent_item_group = frappe.db.get_value("Item Group", "_Test Item Group B - 3", "parent_item_group")
+		frappe.db.get_value("Item Group", parent_item_group, "rgt")
 
 		ancestors = get_ancestors_of("Item Group", "_Test Item Group B - 3")
 		ancestors = frappe.db.sql(
 			"""select name, rgt from `tabItem Group`
-			where name in ({})""".format(
-				", ".join(["%s"] * len(ancestors))
-			),
+			where name in ({})""".format(", ".join(["%s"] * len(ancestors))),
 			tuple(ancestors),
 			as_dict=True,
 		)
@@ -188,9 +182,7 @@
 
 	def test_delete_group(self):
 		# cannot delete group with child, but can delete leaf
-		self.assertRaises(
-			NestedSetChildExistsError, frappe.delete_doc, "Item Group", "_Test Item Group B"
-		)
+		self.assertRaises(NestedSetChildExistsError, frappe.delete_doc, "Item Group", "_Test Item Group B")
 
 	def test_merge_groups(self):
 		frappe.rename_doc("Item Group", "_Test Item Group B", "_Test Item Group C", merge=True)
@@ -207,7 +199,6 @@
 			"""select name from `tabItem Group`
 			where parent_item_group='_Test Item Group C'"""
 		):
-
 			doc = frappe.get_doc("Item Group", name)
 			doc.parent_item_group = "_Test Item Group B"
 			doc.save()
diff --git a/erpnext/setup/doctype/party_type/party_type.py b/erpnext/setup/doctype/party_type/party_type.py
index 76b985b..be8652f 100644
--- a/erpnext/setup/doctype/party_type/party_type.py
+++ b/erpnext/setup/doctype/party_type/party_type.py
@@ -31,10 +31,8 @@
 		cond = "and account_type = '%s'" % account_type
 
 	return frappe.db.sql(
-		"""select name from `tabParty Type`
-			where `{key}` LIKE %(txt)s {cond}
-			order by name limit %(page_len)s offset %(start)s""".format(
-			key=searchfield, cond=cond
-		),
+		f"""select name from `tabParty Type`
+			where `{searchfield}` LIKE %(txt)s {cond}
+			order by name limit %(page_len)s offset %(start)s""",
 		{"txt": "%" + txt + "%", "start": start, "page_len": page_len},
 	)
diff --git a/erpnext/setup/doctype/sales_partner/sales_partner.py b/erpnext/setup/doctype/sales_partner/sales_partner.py
index a8a965d..754e263 100644
--- a/erpnext/setup/doctype/sales_partner/sales_partner.py
+++ b/erpnext/setup/doctype/sales_partner/sales_partner.py
@@ -49,7 +49,7 @@
 	def validate(self):
 		if not self.route:
 			self.route = "partners/" + self.scrub(self.partner_name)
-		super(SalesPartner, self).validate()
+		super().validate()
 		if self.partner_website and not self.partner_website.startswith("http"):
 			self.partner_website = "http://" + self.partner_website
 
diff --git a/erpnext/setup/doctype/sales_person/sales_person.py b/erpnext/setup/doctype/sales_person/sales_person.py
index c2615d3..b0e42de 100644
--- a/erpnext/setup/doctype/sales_person/sales_person.py
+++ b/erpnext/setup/doctype/sales_person/sales_person.py
@@ -80,7 +80,7 @@
 		self.set_onload("dashboard_info", info)
 
 	def on_update(self):
-		super(SalesPerson, self).on_update()
+		super().on_update()
 		self.validate_one_root()
 
 	def get_email_id(self):
diff --git a/erpnext/setup/doctype/terms_and_conditions/terms_and_conditions.py b/erpnext/setup/doctype/terms_and_conditions/terms_and_conditions.py
index 73b5919..40c905b 100644
--- a/erpnext/setup/doctype/terms_and_conditions/terms_and_conditions.py
+++ b/erpnext/setup/doctype/terms_and_conditions/terms_and_conditions.py
@@ -30,12 +30,7 @@
 	def validate(self):
 		if self.terms:
 			validate_template(self.terms)
-		if (
-			not cint(self.buying)
-			and not cint(self.selling)
-			and not cint(self.hr)
-			and not cint(self.disabled)
-		):
+		if not cint(self.buying) and not cint(self.selling) and not cint(self.hr) and not cint(self.disabled):
 			throw(_("At least one of the Applicable Modules should be selected"))
 
 
diff --git a/erpnext/setup/doctype/territory/territory.py b/erpnext/setup/doctype/territory/territory.py
index 1cc3f62..119bfe6 100644
--- a/erpnext/setup/doctype/territory/territory.py
+++ b/erpnext/setup/doctype/territory/territory.py
@@ -40,7 +40,7 @@
 				frappe.throw(_("Either target qty or target amount is mandatory"))
 
 	def on_update(self):
-		super(Territory, self).on_update()
+		super().on_update()
 		self.validate_one_root()
 
 
diff --git a/erpnext/setup/doctype/transaction_deletion_record/test_transaction_deletion_record.py b/erpnext/setup/doctype/transaction_deletion_record/test_transaction_deletion_record.py
index 432438b..68d856e 100644
--- a/erpnext/setup/doctype/transaction_deletion_record/test_transaction_deletion_record.py
+++ b/erpnext/setup/doctype/transaction_deletion_record/test_transaction_deletion_record.py
@@ -1,7 +1,6 @@
 # Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors
 # See license.txt
 
-import unittest
 
 import frappe
 from frappe.tests.utils import FrappeTestCase
@@ -26,7 +25,7 @@
 			self.assertTrue(contains_company)
 
 	def test_no_of_docs_is_correct(self):
-		for i in range(5):
+		for _i in range(5):
 			create_task("Dunder Mifflin Paper Co")
 		tdr = create_transaction_deletion_doc("Dunder Mifflin Paper Co")
 		tdr.reload()
@@ -52,9 +51,7 @@
 
 
 def create_company(company_name):
-	company = frappe.get_doc(
-		{"doctype": "Company", "company_name": company_name, "default_currency": "INR"}
-	)
+	company = frappe.get_doc({"doctype": "Company", "company_name": company_name, "default_currency": "INR"})
 	company.insert(ignore_if_duplicate=True)
 
 
diff --git a/erpnext/setup/doctype/transaction_deletion_record/transaction_deletion_record.py b/erpnext/setup/doctype/transaction_deletion_record/transaction_deletion_record.py
index 00fad5f..9fce0fe 100644
--- a/erpnext/setup/doctype/transaction_deletion_record/transaction_deletion_record.py
+++ b/erpnext/setup/doctype/transaction_deletion_record/transaction_deletion_record.py
@@ -43,7 +43,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(TransactionDeletionRecord, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 		self.batch_size = 5000
 		# Tasks are listed by their execution order
 		self.task_to_internal_method_map = OrderedDict(
@@ -157,7 +157,7 @@
 			if task := getattr(self, method, None):
 				try:
 					task()
-				except Exception as err:
+				except Exception:
 					frappe.db.rollback()
 					traceback = frappe.get_traceback(with_context=True)
 					if traceback:
@@ -177,7 +177,7 @@
 		for doctype in doctypes_to_be_ignored_list:
 			self.append("doctypes_to_be_ignored", {"doctype_name": doctype})
 
-	def validate_running_task_for_doc(self, job_names: list = None):
+	def validate_running_task_for_doc(self, job_names: list | None = None):
 		# at most only one task should be runnning
 		running_tasks = []
 		for x in job_names:
@@ -226,9 +226,7 @@
 			if leads:
 				addresses = frappe.db.sql_list(
 					"""select parent from `tabDynamic Link` where link_name
-					in ({leads})""".format(
-						leads=",".join(leads)
-					)
+					in ({leads})""".format(leads=",".join(leads))
 				)
 
 				if addresses:
@@ -238,16 +236,12 @@
 						"""delete from `tabAddress` where name in ({addresses}) and
 						name not in (select distinct dl1.parent from `tabDynamic Link` dl1
 						inner join `tabDynamic Link` dl2 on dl1.parent=dl2.parent
-						and dl1.link_doctype<>dl2.link_doctype)""".format(
-							addresses=",".join(addresses)
-						)
+						and dl1.link_doctype<>dl2.link_doctype)""".format(addresses=",".join(addresses))
 					)
 
 					frappe.db.sql(
 						"""delete from `tabDynamic Link` where link_doctype='Lead'
-						and parenttype='Address' and link_name in ({leads})""".format(
-							leads=",".join(leads)
-						)
+						and parenttype='Address' and link_name in ({leads})""".format(leads=",".join(leads))
 					)
 
 				frappe.db.sql(
@@ -289,9 +283,9 @@
 		self.validate_doc_status()
 		if not self.delete_transactions:
 			doctypes_to_be_ignored_list = self.get_doctypes_to_be_ignored_list()
-			docfields = self.get_doctypes_with_company_field(doctypes_to_be_ignored_list)
+			self.get_doctypes_with_company_field(doctypes_to_be_ignored_list)
 
-			tables = self.get_all_child_doctypes()
+			self.get_all_child_doctypes()
 			for docfield in self.doctypes:
 				if docfield.doctype_name != self.doctype and not docfield.done:
 					no_of_docs = self.get_number_of_docs_linked_with_specified_company(
@@ -299,7 +293,9 @@
 					)
 					if no_of_docs > 0:
 						reference_docs = frappe.get_all(
-							docfield.doctype_name, filters={docfield.docfield_name: self.company}, limit=self.batch_size
+							docfield.doctype_name,
+							filters={docfield.docfield_name: self.company},
+							limit=self.batch_size,
 						)
 						reference_doc_names = [r.name for r in reference_docs]
 
@@ -308,7 +304,9 @@
 						self.delete_comments(docfield.doctype_name, reference_doc_names)
 						self.unlink_attachments(docfield.doctype_name, reference_doc_names)
 						self.delete_child_tables(docfield.doctype_name, reference_doc_names)
-						self.delete_docs_linked_with_specified_company(docfield.doctype_name, reference_doc_names)
+						self.delete_docs_linked_with_specified_company(
+							docfield.doctype_name, reference_doc_names
+						)
 						processed = int(docfield.no_of_docs) + len(reference_doc_names)
 						frappe.db.set_value(docfield.doctype, docfield.name, "no_of_docs", processed)
 					else:
@@ -385,10 +383,8 @@
 		else:
 			prefix, hashes = naming_series.rsplit("{", 1)
 		last = frappe.db.sql(
-			"""select max(name) from `tab{0}`
-						where name like %s""".format(
-				doctype_name
-			),
+			f"""select max(name) from `tab{doctype_name}`
+						where name like %s""",
 			prefix + "%",
 		)
 		if last and last[0][0]:
diff --git a/erpnext/setup/install.py b/erpnext/setup/install.py
index 474296d..ca065be 100644
--- a/erpnext/setup/install.py
+++ b/erpnext/setup/install.py
@@ -122,7 +122,6 @@
 
 
 def create_default_energy_point_rules():
-
 	for rule in get_default_energy_point_rules():
 		# check if any rule for ref. doctype exists
 		rule_exists = frappe.db.exists(
diff --git a/erpnext/setup/setup_wizard/operations/company_setup.py b/erpnext/setup/setup_wizard/operations/company_setup.py
index d4aac5e..034f4ef 100644
--- a/erpnext/setup/setup_wizard/operations/company_setup.py
+++ b/erpnext/setup/setup_wizard/operations/company_setup.py
@@ -2,7 +2,6 @@
 # License: GNU General Public License v3. See license.txt
 
 import frappe
-from frappe import _
 from frappe.utils import cstr, getdate
 
 
diff --git a/erpnext/setup/setup_wizard/operations/defaults_setup.py b/erpnext/setup/setup_wizard/operations/defaults_setup.py
index 29314a2..b81d744 100644
--- a/erpnext/setup/setup_wizard/operations/defaults_setup.py
+++ b/erpnext/setup/setup_wizard/operations/defaults_setup.py
@@ -30,9 +30,7 @@
 	stock_settings = frappe.get_doc("Stock Settings")
 	stock_settings.item_naming_by = "Item Code"
 	stock_settings.valuation_method = "FIFO"
-	stock_settings.default_warehouse = frappe.db.get_value(
-		"Warehouse", {"warehouse_name": _("Stores")}
-	)
+	stock_settings.default_warehouse = frappe.db.get_value("Warehouse", {"warehouse_name": _("Stores")})
 	stock_settings.stock_uom = "Nos"
 	stock_settings.auto_indent = 1
 	stock_settings.auto_insert_price_list_rate_if_missing = 1
diff --git a/erpnext/setup/setup_wizard/operations/install_fixtures.py b/erpnext/setup/setup_wizard/operations/install_fixtures.py
index 8f11424..1d2530c 100644
--- a/erpnext/setup/setup_wizard/operations/install_fixtures.py
+++ b/erpnext/setup/setup_wizard/operations/install_fixtures.py
@@ -276,9 +276,7 @@
 		records += [{"doctype": doctype, title_field: title} for title in read_lines(filename)]
 
 	base_path = frappe.get_app_path("erpnext", "stock", "doctype")
-	response = frappe.read_file(
-		os.path.join(base_path, "delivery_trip/dispatch_notification_template.html")
-	)
+	response = frappe.read_file(os.path.join(base_path, "delivery_trip/dispatch_notification_template.html"))
 
 	records += [
 		{
@@ -471,9 +469,8 @@
 	stock_settings = frappe.get_doc("Stock Settings")
 	stock_settings.item_naming_by = "Item Code"
 	stock_settings.valuation_method = "FIFO"
-	stock_settings.default_warehouse = frappe.db.get_value(
-		"Warehouse", {"warehouse_name": _("Stores")}
-	)
+	stock_settings.default_warehouse = frappe.db.get_value("Warehouse", {"warehouse_name": _("Stores")})
+	stock_settings.stock_uom = _("Nos")
 	stock_settings.stock_uom = "Nos"
 	stock_settings.auto_indent = 1
 	stock_settings.auto_insert_price_list_rate_if_missing = 1
diff --git a/erpnext/setup/setup_wizard/operations/taxes_setup.py b/erpnext/setup/setup_wizard/operations/taxes_setup.py
index 32d92f6..689af2c 100644
--- a/erpnext/setup/setup_wizard/operations/taxes_setup.py
+++ b/erpnext/setup/setup_wizard/operations/taxes_setup.py
@@ -14,7 +14,7 @@
 		frappe.throw(_("Company {} does not exist yet. Taxes setup aborted.").format(company_name))
 
 	file_path = os.path.join(os.path.dirname(__file__), "..", "data", "country_wise_tax.json")
-	with open(file_path, "r") as json_file:
+	with open(file_path) as json_file:
 		tax_data = json.load(json_file)
 
 	country_wise_tax = tax_data.get(country)
@@ -54,7 +54,12 @@
 					{
 						"title": title,
 						"taxes": [
-							{"tax_type": {"account_name": data.get("account_name"), "tax_rate": data.get("tax_rate")}}
+							{
+								"tax_type": {
+									"account_name": data.get("account_name"),
+									"tax_rate": data.get("tax_rate"),
+								}
+							}
 						],
 					}
 					for title, data in templates.items()
@@ -110,9 +115,7 @@
 	path = frappe.get_app_path("erpnext", "regional", frappe.scrub(country))
 	if os.path.exists(path.encode("utf-8")):
 		try:
-			module_name = "erpnext.regional.{0}.setup.update_regional_tax_settings".format(
-				frappe.scrub(country)
-			)
+			module_name = f"erpnext.regional.{frappe.scrub(country)}.setup.update_regional_tax_settings"
 			frappe.get_attr(module_name)(country, company)
 		except (ImportError, AttributeError):
 			pass
@@ -141,7 +144,7 @@
 
 		# if account_head is a dict, search or create the account and get it's name
 		if isinstance(account_data, dict):
-			tax_row_defaults["description"] = "{0} @ {1}".format(
+			tax_row_defaults["description"] = "{} @ {}".format(
 				account_data.get("account_name"), account_data.get("tax_rate")
 			)
 			tax_row_defaults["rate"] = account_data.get("tax_rate")
diff --git a/erpnext/setup/utils.py b/erpnext/setup/utils.py
index bab57fe..705fb1f 100644
--- a/erpnext/setup/utils.py
+++ b/erpnext/setup/utils.py
@@ -5,7 +5,7 @@
 from frappe import _
 from frappe.utils import add_days, flt, get_datetime_str, nowdate
 from frappe.utils.data import now_datetime
-from frappe.utils.nestedset import get_ancestors_of, get_root_of  # noqa
+from frappe.utils.nestedset import get_root_of
 
 from erpnext import get_default_company
 
@@ -81,14 +81,12 @@
 	if entries:
 		return flt(entries[0].exchange_rate)
 
-	if frappe.get_cached_value(
-		"Currency Exchange Settings", "Currency Exchange Settings", "disabled"
-	):
+	if frappe.get_cached_value("Currency Exchange Settings", "Currency Exchange Settings", "disabled"):
 		return 0.00
 
 	try:
 		cache = frappe.cache()
-		key = "currency_exchange_rate_{0}:{1}:{2}".format(transaction_date, from_currency, to_currency)
+		key = f"currency_exchange_rate_{transaction_date}:{from_currency}:{to_currency}"
 		value = cache.get(key)
 
 		if not value:
diff --git a/erpnext/startup/boot.py b/erpnext/startup/boot.py
index d2be1a0..3de2be3 100644
--- a/erpnext/startup/boot.py
+++ b/erpnext/startup/boot.py
@@ -13,9 +13,7 @@
 		update_page_info(bootinfo)
 
 		bootinfo.sysdefaults.territory = frappe.db.get_single_value("Selling Settings", "territory")
-		bootinfo.sysdefaults.customer_group = frappe.db.get_single_value(
-			"Selling Settings", "customer_group"
-		)
+		bootinfo.sysdefaults.customer_group = frappe.db.get_single_value("Selling Settings", "customer_group")
 		bootinfo.sysdefaults.allow_stale = cint(
 			frappe.db.get_single_value("Accounts Settings", "allow_stale")
 		)
@@ -28,9 +26,7 @@
 		)
 
 		bootinfo.sysdefaults.allow_sales_order_creation_for_expired_quotation = cint(
-			frappe.db.get_single_value(
-				"Selling Settings", "allow_sales_order_creation_for_expired_quotation"
-			)
+			frappe.db.get_single_value("Selling Settings", "allow_sales_order_creation_for_expired_quotation")
 		)
 
 		# if no company, show a dialog box to create a new company
@@ -54,9 +50,7 @@
 			update={"doctype": ":Company"},
 		)
 
-		party_account_types = frappe.db.sql(
-			""" select name, ifnull(account_type, '') from `tabParty Type`"""
-		)
+		party_account_types = frappe.db.sql(""" select name, ifnull(account_type, '') from `tabParty Type`""")
 		bootinfo.party_account_types = frappe._dict(party_account_types)
 
 		bootinfo.sysdefaults.demo_company = frappe.db.get_single_value("Global Defaults", "demo_company")
diff --git a/erpnext/startup/leaderboard.py b/erpnext/startup/leaderboard.py
index 5a60d2f..06f61fd 100644
--- a/erpnext/startup/leaderboard.py
+++ b/erpnext/startup/leaderboard.py
@@ -93,7 +93,7 @@
 		select_field = "sum(actual_qty)" if field == "available_stock_qty" else "sum(stock_value)"
 		results = frappe.db.get_all(
 			"Bin",
-			fields=["item_code as name", "{0} as value".format(select_field)],
+			fields=["item_code as name", f"{select_field} as value"],
 			group_by="item_code",
 			order_by="value desc",
 			limit=limit,
@@ -224,9 +224,7 @@
 	if date_range:
 		date_range = frappe.parse_json(date_range)
 		from_date, to_date = date_range
-		date_condition = "and {0} between {1} and {2}".format(
-			field, frappe.db.escape(from_date), frappe.db.escape(to_date)
-		)
+		date_condition = f"and {field} between {frappe.db.escape(from_date)} and {frappe.db.escape(to_date)}"
 	return date_condition
 
 
diff --git a/erpnext/stock/__init__.py b/erpnext/stock/__init__.py
index bd16d69..7b58cbb 100644
--- a/erpnext/stock/__init__.py
+++ b/erpnext/stock/__init__.py
@@ -17,9 +17,9 @@
 
 
 def get_warehouse_account_map(company=None):
-	company_warehouse_account_map = company and frappe.flags.setdefault(
-		"warehouse_account_map", {}
-	).get(company)
+	company_warehouse_account_map = company and frappe.flags.setdefault("warehouse_account_map", {}).get(
+		company
+	)
 	warehouse_account_map = frappe.flags.warehouse_account_map
 
 	if not warehouse_account_map or not company_warehouse_account_map or frappe.flags.in_test:
diff --git a/erpnext/stock/dashboard_chart_source/warehouse_wise_stock_value/warehouse_wise_stock_value.py b/erpnext/stock/dashboard_chart_source/warehouse_wise_stock_value/warehouse_wise_stock_value.py
index d488150..cbc4fc7 100644
--- a/erpnext/stock/dashboard_chart_source/warehouse_wise_stock_value/warehouse_wise_stock_value.py
+++ b/erpnext/stock/dashboard_chart_source/warehouse_wise_stock_value/warehouse_wise_stock_value.py
@@ -27,9 +27,7 @@
 	if filters and filters.get("company"):
 		warehouse_filters.append(["company", "=", filters.get("company")])
 
-	warehouses = frappe.get_list(
-		"Warehouse", pluck="name", filters=warehouse_filters, order_by="name"
-	)
+	warehouses = frappe.get_list("Warehouse", pluck="name", filters=warehouse_filters, order_by="name")
 
 	warehouses = frappe.get_list(
 		"Bin",
diff --git a/erpnext/stock/deprecated_serial_batch.py b/erpnext/stock/deprecated_serial_batch.py
index 6e32cc2..bc53878 100644
--- a/erpnext/stock/deprecated_serial_batch.py
+++ b/erpnext/stock/deprecated_serial_batch.py
@@ -139,9 +139,7 @@
 			if not self.non_batchwise_balance_qty:
 				continue
 
-			self.batch_avg_rate[batch_no] = (
-				self.non_batchwise_balance_value / self.non_batchwise_balance_qty
-			)
+			self.batch_avg_rate[batch_no] = self.non_batchwise_balance_value / self.non_batchwise_balance_qty
 
 			stock_value_change = self.batch_avg_rate[batch_no] * ledger.qty
 			self.stock_value_change += stock_value_change
@@ -208,9 +206,9 @@
 		bundle_child = frappe.qb.DocType("Serial and Batch Entry")
 		batch = frappe.qb.DocType("Batch")
 
-		timestamp_condition = CombineDatetime(
-			bundle.posting_date, bundle.posting_time
-		) < CombineDatetime(self.sle.posting_date, self.sle.posting_time)
+		timestamp_condition = CombineDatetime(bundle.posting_date, bundle.posting_time) < CombineDatetime(
+			self.sle.posting_date, self.sle.posting_time
+		)
 
 		if self.sle.creation:
 			timestamp_condition |= (
diff --git a/erpnext/stock/doctype/batch/batch.py b/erpnext/stock/doctype/batch/batch.py
index e8e94fd..8726642 100644
--- a/erpnext/stock/doctype/batch/batch.py
+++ b/erpnext/stock/doctype/batch/batch.py
@@ -240,17 +240,13 @@
 def get_batches_by_oldest(item_code, warehouse):
 	"""Returns the oldest batch and qty for the given item_code and warehouse"""
 	batches = get_batch_qty(item_code=item_code, warehouse=warehouse)
-	batches_dates = [
-		[batch, frappe.get_value("Batch", batch.batch_no, "expiry_date")] for batch in batches
-	]
+	batches_dates = [[batch, frappe.get_value("Batch", batch.batch_no, "expiry_date")] for batch in batches]
 	batches_dates.sort(key=lambda tup: tup[1])
 	return batches_dates
 
 
 @frappe.whitelist()
-def split_batch(
-	batch_no: str, item_code: str, warehouse: str, qty: float, new_batch_id: str | None = None
-):
+def split_batch(batch_no: str, item_code: str, warehouse: str, qty: float, new_batch_id: str | None = None):
 	"""Split the batch into a new batch"""
 	batch = frappe.get_doc(dict(doctype="Batch", item=item_code, batch_id=new_batch_id)).insert()
 	qty = flt(qty)
@@ -282,7 +278,10 @@
 			company=company,
 			items=[
 				dict(
-					item_code=item_code, qty=qty, s_warehouse=warehouse, serial_and_batch_bundle=from_bundle_id
+					item_code=item_code,
+					qty=qty,
+					s_warehouse=warehouse,
+					serial_and_batch_bundle=from_bundle_id,
 				),
 				dict(
 					item_code=item_code, qty=qty, t_warehouse=warehouse, serial_and_batch_bundle=to_bundle_id
diff --git a/erpnext/stock/doctype/batch/test_batch.py b/erpnext/stock/doctype/batch/test_batch.py
index 7fb672c..1adffae 100644
--- a/erpnext/stock/doctype/batch/test_batch.py
+++ b/erpnext/stock/doctype/batch/test_batch.py
@@ -156,9 +156,7 @@
 
 		bundle = stock_entry.items[0].serial_and_batch_bundle
 		self.assertTrue(bundle)
-		self.assertEqual(
-			get_batch_qty(get_batch_from_bundle(bundle), stock_entry.items[0].t_warehouse), 90
-		)
+		self.assertEqual(get_batch_qty(get_batch_from_bundle(bundle), stock_entry.items[0].t_warehouse), 90)
 
 	def test_delivery_note(self):
 		"""Test automatic batch selection for outgoing items"""
@@ -543,9 +541,7 @@
 			get_batch_from_bundle(pr_2.items[0].serial_and_batch_bundle),
 		)
 
-		self.assertEqual(
-			"BATCHEXISTING002", get_batch_from_bundle(pr_2.items[0].serial_and_batch_bundle)
-		)
+		self.assertEqual("BATCHEXISTING002", get_batch_from_bundle(pr_2.items[0].serial_and_batch_bundle))
 
 
 def create_batch(item_code, rate, create_item_price_for_batch):
diff --git a/erpnext/stock/doctype/bin/bin.py b/erpnext/stock/doctype/bin/bin.py
index 9310985..e3a155b 100644
--- a/erpnext/stock/doctype/bin/bin.py
+++ b/erpnext/stock/doctype/bin/bin.py
@@ -83,9 +83,7 @@
 			get_reserved_qty_for_sub_assembly,
 		)
 
-		reserved_qty_for_production_plan = get_reserved_qty_for_sub_assembly(
-			self.item_code, self.warehouse
-		)
+		reserved_qty_for_production_plan = get_reserved_qty_for_sub_assembly(self.item_code, self.warehouse)
 
 		if reserved_qty_for_production_plan is None and not self.reserved_qty_for_production_plan:
 			return
@@ -106,9 +104,7 @@
 		in open work orders"""
 		from erpnext.manufacturing.doctype.work_order.work_order import get_reserved_qty_for_production
 
-		self.reserved_qty_for_production = get_reserved_qty_for_production(
-			self.item_code, self.warehouse
-		)
+		self.reserved_qty_for_production = get_reserved_qty_for_production(self.item_code, self.warehouse)
 
 		self.db_set(
 			"reserved_qty_for_production", flt(self.reserved_qty_for_production), update_modified=True
@@ -156,9 +152,7 @@
 		se_item = frappe.qb.DocType("Stock Entry Detail")
 
 		if frappe.db.field_exists("Stock Entry", "is_return"):
-			qty_field = (
-				Case().when(se.is_return == 1, se_item.transfer_qty * -1).else_(se_item.transfer_qty)
-			)
+			qty_field = Case().when(se.is_return == 1, se_item.transfer_qty * -1).else_(se_item.transfer_qty)
 		else:
 			qty_field = se_item.transfer_qty
 
diff --git a/erpnext/stock/doctype/bin/test_bin.py b/erpnext/stock/doctype/bin/test_bin.py
index b79dee8..e4f5565 100644
--- a/erpnext/stock/doctype/bin/test_bin.py
+++ b/erpnext/stock/doctype/bin/test_bin.py
@@ -31,4 +31,4 @@
 	def test_index_exists(self):
 		indexes = frappe.db.sql("show index from tabBin where Non_unique = 0", as_dict=1)
 		if not any(index.get("Key_name") == "unique_item_warehouse" for index in indexes):
-			self.fail(f"Expected unique index on item-warehouse")
+			self.fail("Expected unique index on item-warehouse")
diff --git a/erpnext/stock/doctype/closing_stock_balance/closing_stock_balance.py b/erpnext/stock/doctype/closing_stock_balance/closing_stock_balance.py
index e99a0b1..1cb6305 100644
--- a/erpnext/stock/doctype/closing_stock_balance/closing_stock_balance.py
+++ b/erpnext/stock/doctype/closing_stock_balance/closing_stock_balance.py
@@ -149,6 +149,6 @@
 	try:
 		doc.create_closing_stock_balance_entries()
 		doc.db_set("status", "Completed")
-	except Exception as e:
+	except Exception:
 		doc.db_set("status", "Failed")
 		doc.log_error(title="Closing Stock Balance Failed")
diff --git a/erpnext/stock/doctype/delivery_note/delivery_note.py b/erpnext/stock/doctype/delivery_note/delivery_note.py
index f13353e..c3148d6 100644
--- a/erpnext/stock/doctype/delivery_note/delivery_note.py
+++ b/erpnext/stock/doctype/delivery_note/delivery_note.py
@@ -141,7 +141,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(DeliveryNote, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 		self.status_updater = [
 			{
 				"source_dt": "Delivery Note Item",
@@ -229,7 +229,7 @@
 			for f in fieldname:
 				toggle_print_hide(self.meta if key == "parent" else item_meta, f)
 
-		super(DeliveryNote, self).before_print(settings)
+		super().before_print(settings)
 
 	def set_actual_qty(self):
 		for d in self.get("items"):
@@ -250,7 +250,7 @@
 
 	def validate(self):
 		self.validate_posting_time()
-		super(DeliveryNote, self).validate()
+		super().validate()
 		self.validate_references()
 		self.set_status()
 		self.so_required()
@@ -274,11 +274,16 @@
 		self.reset_default_field_value("set_warehouse", "items", "warehouse")
 
 	def validate_with_previous_doc(self):
-		super(DeliveryNote, self).validate_with_previous_doc(
+		super().validate_with_previous_doc(
 			{
 				"Sales Order": {
 					"ref_dn_field": "against_sales_order",
-					"compare_fields": [["customer", "="], ["company", "="], ["project", "="], ["currency", "="]],
+					"compare_fields": [
+						["customer", "="],
+						["company", "="],
+						["project", "="],
+						["currency", "="],
+					],
 				},
 				"Sales Order Item": {
 					"ref_dn_field": "so_detail",
@@ -288,7 +293,12 @@
 				},
 				"Sales Invoice": {
 					"ref_dn_field": "against_sales_invoice",
-					"compare_fields": [["customer", "="], ["company", "="], ["project", "="], ["currency", "="]],
+					"compare_fields": [
+						["customer", "="],
+						["company", "="],
+						["project", "="],
+						["currency", "="],
+					],
 				},
 				"Sales Invoice Item": {
 					"ref_dn_field": "si_detail",
@@ -409,7 +419,7 @@
 				)
 
 	def validate_warehouse(self):
-		super(DeliveryNote, self).validate_warehouse()
+		super().validate_warehouse()
 
 		for d in self.get_item_list():
 			if not d["warehouse"] and frappe.get_cached_value("Item", d["item_code"], "is_stock_item") == 1:
@@ -466,7 +476,7 @@
 		self.repost_future_sle_and_gle()
 
 	def on_cancel(self):
-		super(DeliveryNote, self).on_cancel()
+		super().on_cancel()
 
 		self.check_sales_order_on_hold_or_close("against_sales_order")
 		self.check_next_docstatus()
@@ -555,7 +565,9 @@
 									delivered_batch_qty[entry.batch_no] -= delivered_qty
 					else:
 						# `Delivered Qty` should be less than or equal to `Reserved Qty`.
-						qty_can_be_deliver = min((sre_doc.reserved_qty - sre_doc.delivered_qty), qty_to_deliver)
+						qty_can_be_deliver = min(
+							(sre_doc.reserved_qty - sre_doc.delivered_qty), qty_to_deliver
+						)
 
 					sre_doc.delivered_qty += qty_can_be_deliver
 					sre_doc.db_update()
@@ -613,7 +625,9 @@
 							batch_qty_to_undelivered = {d.batch_no: -1 * d.qty for d in sbb.entries}
 							for entry in sre_doc.sb_entries:
 								if entry.batch_no in batch_qty_to_undelivered:
-									undelivered_qty = min(entry.delivered_qty, batch_qty_to_undelivered[entry.batch_no])
+									undelivered_qty = min(
+										entry.delivered_qty, batch_qty_to_undelivered[entry.batch_no]
+									)
 									entry.delivered_qty -= undelivered_qty
 									entry.db_update()
 									qty_can_be_undelivered += undelivered_qty
@@ -669,7 +683,8 @@
 						frappe.bold(reserved_warehouses[0])
 						if len(reserved_warehouses) == 1
 						else _("{0} and {1}").format(
-							frappe.bold(", ".join(reserved_warehouses[:-1])), frappe.bold(reserved_warehouses[-1])
+							frappe.bold(", ".join(reserved_warehouses[:-1])),
+							frappe.bold(reserved_warehouses[-1]),
 						),
 					)
 					frappe.throw(msg, title=_("Stock Reservation Warehouse Mismatch"))
@@ -1166,7 +1181,7 @@
 			"User", frappe.session.user, ["email", "full_name", "phone", "mobile_no"], as_dict=1
 		)
 		target.pickup_contact_email = user.email
-		pickup_contact_display = "{}".format(user.full_name)
+		pickup_contact_display = f"{user.full_name}"
 		if user:
 			if user.email:
 				pickup_contact_display += "<br>" + user.email
@@ -1182,7 +1197,7 @@
 		contact = frappe.db.get_value(
 			"Contact", source.contact_person, ["email_id", "phone", "mobile_no"], as_dict=1
 		)
-		delivery_contact_display = "{}".format(source.contact_display)
+		delivery_contact_display = f"{source.contact_display}"
 		if contact:
 			if contact.email_id:
 				delivery_contact_display += "<br>" + contact.email_id
@@ -1351,8 +1366,7 @@
 				"postprocess": update_details,
 				"field_no_map": ["taxes_and_charges", "set_warehouse"],
 			},
-			doctype
-			+ " Item": {
+			doctype + " Item": {
 				"doctype": target_doctype + " Item",
 				"field_map": {
 					source_document_warehouse_field: target_document_warehouse_field,
diff --git a/erpnext/stock/doctype/delivery_note/test_delivery_note.py b/erpnext/stock/doctype/delivery_note/test_delivery_note.py
index 905287d..6f47c26 100644
--- a/erpnext/stock/doctype/delivery_note/test_delivery_note.py
+++ b/erpnext/stock/doctype/delivery_note/test_delivery_note.py
@@ -68,7 +68,7 @@
 		self.assertRaises(frappe.ValidationError, frappe.get_doc(si).insert)
 
 	def test_delivery_note_no_gl_entry(self):
-		company = frappe.db.get_value("Warehouse", "_Test Warehouse - _TC", "company")
+		frappe.db.get_value("Warehouse", "_Test Warehouse - _TC", "company")
 		make_stock_entry(target="_Test Warehouse - _TC", qty=5, basic_rate=100)
 
 		stock_queue = json.loads(
@@ -85,16 +85,14 @@
 
 		dn = create_delivery_note()
 
-		sle = frappe.get_doc(
-			"Stock Ledger Entry", {"voucher_type": "Delivery Note", "voucher_no": dn.name}
-		)
+		sle = frappe.get_doc("Stock Ledger Entry", {"voucher_type": "Delivery Note", "voucher_no": dn.name})
 
 		self.assertEqual(sle.stock_value_difference, flt(-1 * stock_queue[0][1], 2))
 
 		self.assertFalse(get_gl_entries("Delivery Note", dn.name))
 
 	def test_delivery_note_gl_entry_packing_item(self):
-		company = frappe.db.get_value("Warehouse", "Stores - TCP1", "company")
+		frappe.db.get_value("Warehouse", "Stores - TCP1", "company")
 
 		make_stock_entry(item_code="_Test Item", target="Stores - TCP1", qty=10, basic_rate=100)
 		make_stock_entry(
@@ -141,7 +139,7 @@
 			stock_in_hand_account: [0.0, stock_value_diff],
 			"Cost of Goods Sold - TCP1": [stock_value_diff, 0.0],
 		}
-		for i, gle in enumerate(gl_entries):
+		for _i, gle in enumerate(gl_entries):
 			self.assertEqual([gle.debit, gle.credit], expected_values.get(gle.account))
 
 		# check stock in hand balance
@@ -795,7 +793,7 @@
 			"Stock In Hand - TCP1": [0.0, stock_value_difference],
 			target_warehouse: [stock_value_difference, 0.0],
 		}
-		for i, gle in enumerate(gl_entries):
+		for _i, gle in enumerate(gl_entries):
 			self.assertEqual([gle.debit, gle.credit], expected_values.get(gle.account))
 
 		# tear down
@@ -1003,7 +1001,7 @@
 			"Cost of Goods Sold - TCP1": {"cost_center": cost_center},
 			stock_in_hand_account: {"cost_center": cost_center},
 		}
-		for i, gle in enumerate(gl_entries):
+		for _i, gle in enumerate(gl_entries):
 			self.assertEqual(expected_values[gle.account]["cost_center"], gle.cost_center)
 
 	def test_delivery_note_cost_center_with_balance_sheet_account(self):
@@ -1032,7 +1030,7 @@
 			"Cost of Goods Sold - TCP1": {"cost_center": cost_center},
 			stock_in_hand_account: {"cost_center": cost_center},
 		}
-		for i, gle in enumerate(gl_entries):
+		for _i, gle in enumerate(gl_entries):
 			self.assertEqual(expected_values[gle.account]["cost_center"], gle.cost_center)
 
 	def test_make_sales_invoice_from_dn_for_returned_qty(self):
@@ -1100,9 +1098,7 @@
 			},
 		)
 		make_product_bundle(parent=batched_bundle.name, items=[batched_item.name])
-		make_stock_entry(
-			item_code=batched_item.name, target="_Test Warehouse - _TC", qty=10, basic_rate=42
-		)
+		make_stock_entry(item_code=batched_item.name, target="_Test Warehouse - _TC", qty=10, basic_rate=42)
 
 		dn = create_delivery_note(item_code=batched_bundle.name, qty=1)
 		dn.load_from_db()
@@ -1125,9 +1121,7 @@
 		dn.reload()
 		dn.delete()
 
-		bundle = frappe.db.get_value(
-			"Serial and Batch Bundle", {"voucher_detail_no": packed_name}, "name"
-		)
+		bundle = frappe.db.get_value("Serial and Batch Bundle", {"voucher_detail_no": packed_name}, "name")
 		self.assertFalse(bundle)
 
 		frappe.db.set_single_value("Stock Settings", "use_serial_batch_fields", 1)
@@ -1306,9 +1300,7 @@
 			warehouse=warehouse,
 			target_warehouse=target,
 		)
-		self.assertFalse(
-			frappe.db.exists("GL Entry", {"voucher_no": dn.name, "voucher_type": dn.doctype})
-		)
+		self.assertFalse(frappe.db.exists("GL Entry", {"voucher_no": dn.name, "voucher_type": dn.doctype}))
 
 	def test_batch_expiry_for_delivery_note(self):
 		from erpnext.controllers.sales_and_purchase_return import make_return_doc
@@ -1435,9 +1427,7 @@
 			basic_rate=100.0,
 			posting_date=add_days(nowdate(), -5),
 		)
-		dn = create_delivery_note(
-			item_code=item_code, qty=5, rate=500, posting_date=add_days(nowdate(), -4)
-		)
+		dn = create_delivery_note(item_code=item_code, qty=5, rate=500, posting_date=add_days(nowdate(), -4))
 		self.assertEqual(dn.items[0].incoming_rate, 100.0)
 
 		make_stock_entry(
@@ -1527,9 +1517,7 @@
 		self.assertAlmostEqual(returned_dn.items[0].incoming_rate, 200.0)
 
 	def test_batch_with_non_stock_uom(self):
-		frappe.db.set_single_value(
-			"Stock Settings", "auto_create_serial_and_batch_bundle_for_outward", 1
-		)
+		frappe.db.set_single_value("Stock Settings", "auto_create_serial_and_batch_bundle_for_outward", 1)
 
 		item = make_item(
 			properties={
@@ -1562,9 +1550,7 @@
 		)
 		self.assertEqual(abs(delivered_batch_qty), 5.0)
 
-		frappe.db.set_single_value(
-			"Stock Settings", "auto_create_serial_and_batch_bundle_for_outward", 0
-		)
+		frappe.db.set_single_value("Stock Settings", "auto_create_serial_and_batch_bundle_for_outward", 0)
 
 	def test_internal_transfer_for_non_stock_item(self):
 		from erpnext.selling.doctype.customer.test_customer import create_internal_customer
@@ -1604,9 +1590,7 @@
 
 		item_details = {}
 		for item in [serial_item, batch_item]:
-			se = make_stock_entry(
-				item_code=item.name, target="_Test Warehouse - _TC", qty=5, basic_rate=100
-			)
+			se = make_stock_entry(item_code=item.name, target="_Test Warehouse - _TC", qty=5, basic_rate=100)
 			item_details[item.name] = se.items[0].serial_and_batch_bundle
 
 		dn = create_delivery_note(item_code=bundle_item.name, qty=1, do_not_submit=True)
diff --git a/erpnext/stock/doctype/delivery_trip/delivery_trip.py b/erpnext/stock/doctype/delivery_trip/delivery_trip.py
index cb9fc5b..58f393d 100644
--- a/erpnext/stock/doctype/delivery_trip/delivery_trip.py
+++ b/erpnext/stock/doctype/delivery_trip/delivery_trip.py
@@ -40,7 +40,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(DeliveryTrip, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 
 		# Google Maps returns distances in meters by default
 		self.default_distance_uom = (
@@ -94,9 +94,7 @@
 		        delete (bool, optional): Defaults to `False`. `True` if driver details need to be emptied, else `False`.
 		"""
 
-		delivery_notes = list(
-			set(stop.delivery_note for stop in self.delivery_stops if stop.delivery_note)
-		)
+		delivery_notes = list(set(stop.delivery_note for stop in self.delivery_stops if stop.delivery_note))
 
 		update_fields = {
 			"driver": self.driver,
@@ -342,14 +340,11 @@
 		"Contact", contact, ["first_name", "last_name", "phone", "mobile_no"], as_dict=1
 	)
 
-	contact_info.html = (
-		""" <b>%(first_name)s %(last_name)s</b> <br> %(phone)s <br> %(mobile_no)s"""
-		% {
-			"first_name": contact_info.first_name,
-			"last_name": contact_info.last_name or "",
-			"phone": contact_info.phone or "",
-			"mobile_no": contact_info.mobile_no or "",
-		}
+	contact_info.html = """ <b>{first_name} {last_name}</b> <br> {phone} <br> {mobile_no}""".format(
+		first_name=contact_info.first_name,
+		last_name=contact_info.last_name or "",
+		phone=contact_info.phone or "",
+		mobile_no=contact_info.mobile_no or "",
 	)
 
 	return contact_info.html
diff --git a/erpnext/stock/doctype/delivery_trip/test_delivery_trip.py b/erpnext/stock/doctype/delivery_trip/test_delivery_trip.py
index 9b8b46e..09f5b2c 100644
--- a/erpnext/stock/doctype/delivery_trip/test_delivery_trip.py
+++ b/erpnext/stock/doctype/delivery_trip/test_delivery_trip.py
@@ -1,7 +1,6 @@
 # Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
 # See license.txt
 
-import unittest
 
 import frappe
 from frappe.tests.utils import FrappeTestCase
diff --git a/erpnext/stock/doctype/inventory_dimension/inventory_dimension.py b/erpnext/stock/doctype/inventory_dimension/inventory_dimension.py
index d5eef5a..103d8a1 100644
--- a/erpnext/stock/doctype/inventory_dimension/inventory_dimension.py
+++ b/erpnext/stock/doctype/inventory_dimension/inventory_dimension.py
@@ -384,9 +384,7 @@
 
 @frappe.whitelist()
 def get_parent_fields(child_doctype, dimension_name):
-	parent_doctypes = frappe.get_all(
-		"DocField", fields=["parent"], filters={"options": child_doctype}
-	)
+	parent_doctypes = frappe.get_all("DocField", fields=["parent"], filters={"options": child_doctype})
 
 	fields = []
 
diff --git a/erpnext/stock/doctype/inventory_dimension/test_inventory_dimension.py b/erpnext/stock/doctype/inventory_dimension/test_inventory_dimension.py
index 361c2f8..8ce954d 100644
--- a/erpnext/stock/doctype/inventory_dimension/test_inventory_dimension.py
+++ b/erpnext/stock/doctype/inventory_dimension/test_inventory_dimension.py
@@ -210,9 +210,7 @@
 		)
 
 		self.assertFalse(
-			frappe.db.get_value(
-				"Custom Field", {"fieldname": "project", "dt": "Stock Ledger Entry"}, "name"
-			)
+			frappe.db.get_value("Custom Field", {"fieldname": "project", "dt": "Stock Ledger Entry"}, "name")
 		)
 
 	def test_check_mandatory_dimensions(self):
@@ -296,9 +294,7 @@
 		se_doc.save()
 		se_doc.submit()
 
-		entries = get_voucher_sl_entries(
-			se_doc.name, ["warehouse", "store", "incoming_rate", "actual_qty"]
-		)
+		entries = get_voucher_sl_entries(se_doc.name, ["warehouse", "store", "incoming_rate", "actual_qty"])
 
 		for entry in entries:
 			self.assertEqual(entry.warehouse, warehouse)
@@ -488,7 +484,14 @@
 				"autoname": "field:store_name",
 				"fields": [{"label": "Store Name", "fieldname": "store_name", "fieldtype": "Data"}],
 				"permissions": [
-					{"role": "System Manager", "permlevel": 0, "read": 1, "write": 1, "create": 1, "delete": 1}
+					{
+						"role": "System Manager",
+						"permlevel": 0,
+						"read": 1,
+						"write": 1,
+						"create": 1,
+						"delete": 1,
+					}
 				],
 			}
 		).insert(ignore_permissions=True)
@@ -510,7 +513,14 @@
 				"autoname": "field:shelf_name",
 				"fields": [{"label": "Shelf Name", "fieldname": "shelf_name", "fieldtype": "Data"}],
 				"permissions": [
-					{"role": "System Manager", "permlevel": 0, "read": 1, "write": 1, "create": 1, "delete": 1}
+					{
+						"role": "System Manager",
+						"permlevel": 0,
+						"read": 1,
+						"write": 1,
+						"create": 1,
+						"delete": 1,
+					}
 				],
 			}
 		).insert(ignore_permissions=True)
@@ -532,7 +542,14 @@
 				"autoname": "field:rack_name",
 				"fields": [{"label": "Rack Name", "fieldname": "rack_name", "fieldtype": "Data"}],
 				"permissions": [
-					{"role": "System Manager", "permlevel": 0, "read": 1, "write": 1, "create": 1, "delete": 1}
+					{
+						"role": "System Manager",
+						"permlevel": 0,
+						"read": 1,
+						"write": 1,
+						"create": 1,
+						"delete": 1,
+					}
 				],
 			}
 		).insert(ignore_permissions=True)
@@ -554,7 +571,14 @@
 				"autoname": "field:pallet_name",
 				"fields": [{"label": "Pallet Name", "fieldname": "pallet_name", "fieldtype": "Data"}],
 				"permissions": [
-					{"role": "System Manager", "permlevel": 0, "read": 1, "write": 1, "create": 1, "delete": 1}
+					{
+						"role": "System Manager",
+						"permlevel": 0,
+						"read": 1,
+						"write": 1,
+						"create": 1,
+						"delete": 1,
+					}
 				],
 			}
 		).insert(ignore_permissions=True)
@@ -570,7 +594,14 @@
 				"autoname": "field:site_name",
 				"fields": [{"label": "Site Name", "fieldname": "site_name", "fieldtype": "Data"}],
 				"permissions": [
-					{"role": "System Manager", "permlevel": 0, "read": 1, "write": 1, "create": 1, "delete": 1}
+					{
+						"role": "System Manager",
+						"permlevel": 0,
+						"read": 1,
+						"write": 1,
+						"create": 1,
+						"delete": 1,
+					}
 				],
 			}
 		).insert(ignore_permissions=True)
@@ -623,9 +654,7 @@
 
 	to_warehouse = create_warehouse("_Test Internal Warehouse GIT A", company=company)
 
-	pr_doc = make_purchase_receipt(
-		company=company, warehouse=warehouse, qty=10, rate=100, do_not_submit=True
-	)
+	pr_doc = make_purchase_receipt(company=company, warehouse=warehouse, qty=10, rate=100, do_not_submit=True)
 	pr_doc.items[0].store = "Inter Transfer Store 1"
 	pr_doc.submit()
 
@@ -651,9 +680,7 @@
 
 	expene_account = frappe.db.get_value(
 		"Company", company, "stock_adjustment_account"
-	) or frappe.db.get_value(
-		"Account", {"company": company, "account_type": "Expense Account"}, "name"
-	)
+	) or frappe.db.get_value("Account", {"company": company, "account_type": "Expense Account"}, "name")
 
 	return frappe._dict(
 		{
diff --git a/erpnext/stock/doctype/item/item.py b/erpnext/stock/doctype/item/item.py
index 949c109..063b28d 100644
--- a/erpnext/stock/doctype/item/item.py
+++ b/erpnext/stock/doctype/item/item.py
@@ -3,7 +3,6 @@
 
 import copy
 import json
-from typing import Dict, List, Optional
 
 import frappe
 from frappe import _
@@ -375,9 +374,9 @@
 		for d in self.get("uoms"):
 			if cstr(d.uom) in check_list:
 				frappe.throw(
-					_("Unit of Measure {0} has been entered more than once in Conversion Factor Table").format(
-						d.uom
-					)
+					_(
+						"Unit of Measure {0} has been entered more than once in Conversion Factor Table"
+					).format(d.uom)
 				)
 			else:
 				check_list.append(cstr(d.uom))
@@ -429,7 +428,7 @@
 					frappe.throw(
 						_("{0} entered twice {1} in Item Taxes").format(
 							frappe.bold(d.item_tax_template),
-							"for tax category {0}".format(frappe.bold(d.tax_category)) if d.tax_category else "",
+							f"for tax category {frappe.bold(d.tax_category)}" if d.tax_category else "",
 						)
 					)
 				else:
@@ -448,7 +447,9 @@
 					)
 					if duplicate:
 						frappe.throw(
-							_("Barcode {0} already used in Item {1}").format(item_barcode.barcode, duplicate[0][0])
+							_("Barcode {0} already used in Item {1}").format(
+								item_barcode.barcode, duplicate[0][0]
+							)
 						)
 
 					item_barcode.barcode_type = (
@@ -477,9 +478,9 @@
 				warehouse_material_request_type += [(d.get("warehouse"), d.get("material_request_type"))]
 			else:
 				frappe.throw(
-					_("Row #{0}: A reorder entry already exists for warehouse {1} with reorder type {2}.").format(
-						d.idx, d.warehouse, d.material_request_type
-					),
+					_(
+						"Row #{0}: A reorder entry already exists for warehouse {1} with reorder type {2}."
+					).format(d.idx, d.warehouse, d.material_request_type),
 					DuplicateReorderRows,
 				)
 
@@ -547,20 +548,21 @@
 
 		for dt in ("Sales Taxes and Charges", "Purchase Taxes and Charges"):
 			for d in frappe.db.sql(
-				"""select name, item_wise_tax_detail from `tab{0}`
-					where ifnull(item_wise_tax_detail, '') != ''""".format(
-					dt
-				),
+				f"""select name, item_wise_tax_detail from `tab{dt}`
+					where ifnull(item_wise_tax_detail, '') != ''""",
 				as_dict=1,
 			):
-
 				item_wise_tax_detail = json.loads(d.item_wise_tax_detail)
 				if isinstance(item_wise_tax_detail, dict) and old_name in item_wise_tax_detail:
 					item_wise_tax_detail[new_name] = item_wise_tax_detail[old_name]
 					item_wise_tax_detail.pop(old_name)
 
 					frappe.db.set_value(
-						dt, d.name, "item_wise_tax_detail", json.dumps(item_wise_tax_detail), update_modified=False
+						dt,
+						d.name,
+						"item_wise_tax_detail",
+						json.dumps(item_wise_tax_detail),
+						update_modified=False,
 					)
 
 	def delete_old_bins(self, old_name):
@@ -587,9 +589,7 @@
 		)
 
 		msg += " <br>"
-		msg += (
-			", ".join([get_link_to_form("Stock Reconciliation", d.parent) for d in records]) + "<br><br>"
-		)
+		msg += ", ".join([get_link_to_form("Stock Reconciliation", d.parent) for d in records]) + "<br><br>"
 
 		msg += _(
 			"Note: To merge the items, create a separate Stock Reconciliation for the old item {0}"
@@ -612,12 +612,8 @@
 
 	def validate_duplicate_product_bundles_before_merge(self, old_name, new_name):
 		"Block merge if both old and new items have product bundles."
-		old_bundle = frappe.get_value(
-			"Product Bundle", filters={"new_item_code": old_name, "disabled": 0}
-		)
-		new_bundle = frappe.get_value(
-			"Product Bundle", filters={"new_item_code": new_name, "disabled": 0}
-		)
+		old_bundle = frappe.get_value("Product Bundle", filters={"new_item_code": old_name, "disabled": 0})
+		new_bundle = frappe.get_value("Product Bundle", filters={"new_item_code": new_name, "disabled": 0})
 
 		if old_bundle and new_bundle:
 			bundle_link = get_link_to_form("Product Bundle", old_bundle)
@@ -635,9 +631,7 @@
 	def recalculate_bin_qty(self, new_name):
 		from erpnext.stock.stock_balance import repost_stock
 
-		existing_allow_negative_stock = frappe.db.get_single_value(
-			"Stock Settings", "allow_negative_stock"
-		)
+		existing_allow_negative_stock = frappe.db.get_single_value("Stock Settings", "allow_negative_stock")
 		frappe.db.set_single_value("Stock Settings", "allow_negative_stock", 1)
 
 		repost_stock_for_warehouses = frappe.get_all(
@@ -654,9 +648,7 @@
 		for warehouse in repost_stock_for_warehouses:
 			repost_stock(new_name, warehouse)
 
-		frappe.db.set_single_value(
-			"Stock Settings", "allow_negative_stock", existing_allow_negative_stock
-		)
+		frappe.db.set_single_value("Stock Settings", "allow_negative_stock", existing_allow_negative_stock)
 
 	def update_bom_item_desc(self):
 		if self.is_new():
@@ -817,12 +809,10 @@
 			return "<br>".join(docnames)
 
 		def table_row(title, body):
-			return """<tr>
-				<td>{0}</td>
-				<td>{1}</td>
-			</tr>""".format(
-				title, body
-			)
+			return f"""<tr>
+				<td>{title}</td>
+				<td>{body}</td>
+			</tr>"""
 
 		rows = ""
 		for docname, attr_list in not_included.items():
@@ -834,17 +824,15 @@
 		)
 
 		message = """
-			<div>{0}</div><br>
+			<div>{}</div><br>
 			<table class="table">
 				<thead>
-					<td>{1}</td>
-					<td>{2}</td>
+					<td>{}</td>
+					<td>{}</td>
 				</thead>
-				{3}
+				{}
 			</table>
-		""".format(
-			error_description, _("Variant Items"), _("Attributes"), rows
-		)
+		""".format(error_description, _("Variant Items"), _("Attributes"), rows)
 
 		frappe.throw(message, title=_("Variant Attribute Error"), is_minimizable=True, wide=True)
 
@@ -974,7 +962,7 @@
 
 			frappe.throw(msg, title=_("Linked with submitted documents"))
 
-	def _get_linked_submitted_documents(self, changed_fields: List[str]) -> Optional[Dict[str, str]]:
+	def _get_linked_submitted_documents(self, changed_fields: list[str]) -> dict[str, str] | None:
 		linked_doctypes = [
 			"Delivery Note Item",
 			"Sales Invoice Item",
@@ -1163,17 +1151,13 @@
 		last_purchase_receipt and last_purchase_receipt[0].posting_date or "1900-01-01"
 	)
 
-	if last_purchase_order and (
-		purchase_order_date >= purchase_receipt_date or not last_purchase_receipt
-	):
+	if last_purchase_order and (purchase_order_date >= purchase_receipt_date or not last_purchase_receipt):
 		# use purchase order
 
 		last_purchase = last_purchase_order[0]
 		purchase_date = purchase_order_date
 
-	elif last_purchase_receipt and (
-		purchase_receipt_date > purchase_order_date or not last_purchase_order
-	):
+	elif last_purchase_receipt and (purchase_receipt_date > purchase_order_date or not last_purchase_order):
 		# use purchase receipt
 		last_purchase = last_purchase_receipt[0]
 		purchase_date = purchase_receipt_date
@@ -1349,7 +1333,7 @@
 			frappe.publish_progress(count / total * 100, title=_("Updating Variants..."))
 
 
-def validate_item_default_company_links(item_defaults: List[ItemDefault]) -> None:
+def validate_item_default_company_links(item_defaults: list[ItemDefault]) -> None:
 	for item_default in item_defaults:
 		for doctype, field in [
 			["Warehouse", "default_warehouse"],
diff --git a/erpnext/stock/doctype/item/test_item.py b/erpnext/stock/doctype/item/test_item.py
index b237f73..a0ed1f2 100644
--- a/erpnext/stock/doctype/item/test_item.py
+++ b/erpnext/stock/doctype/item/test_item.py
@@ -315,7 +315,6 @@
 			self.assertEqual(value, purchase_item_details.get(key))
 
 	def test_item_default_validations(self):
-
 		with self.assertRaises(frappe.ValidationError) as ve:
 			make_item(
 				"Bad Item defaults",
@@ -469,9 +468,7 @@
 
 		self.assertFalse(frappe.db.exists("Item", old))
 
-		self.assertTrue(
-			frappe.db.get_value("Bin", {"item_code": new, "warehouse": "_Test Warehouse - _TC"})
-		)
+		self.assertTrue(frappe.db.get_value("Bin", {"item_code": new, "warehouse": "_Test Warehouse - _TC"}))
 		self.assertTrue(
 			frappe.db.get_value("Bin", {"item_code": new, "warehouse": "_Test Warehouse 1 - _TC"})
 		)
@@ -729,9 +726,7 @@
 
 	@change_settings("Stock Settings", {"sample_retention_warehouse": "_Test Warehouse - _TC"})
 	def test_retain_sample(self):
-		item = make_item(
-			"_TestRetainSample", {"has_batch_no": 1, "retain_sample": 1, "sample_quantity": 1}
-		)
+		item = make_item("_TestRetainSample", {"has_batch_no": 1, "retain_sample": 1, "sample_quantity": 1})
 
 		self.assertEqual(item.has_batch_no, 1)
 		self.assertEqual(item.retain_sample, 1)
@@ -804,7 +799,7 @@
 	def test_customer_codes_length(self):
 		"""Check if item code with special characters are allowed."""
 		item = make_item(properties={"item_code": "Test Item Code With Special Characters"})
-		for row in range(3):
+		for _row in range(3):
 			item.append("customer_items", {"ref_code": frappe.generate_hash("", 120)})
 		item.save()
 		self.assertTrue(len(item.customer_code) > 140)
@@ -845,9 +840,7 @@
 		make_property_setter("Item", None, "search_fields", "item_name", "Data", for_doctype="Doctype")
 
 		item = make_item(properties={"item_name": "Test Item", "description": "Test Description"})
-		data = item_query(
-			"Item", "Test Item", "", 0, 20, filters={"item_name": "Test Item"}, as_dict=True
-		)
+		data = item_query("Item", "Test Item", "", 0, 20, filters={"item_name": "Test Item"}, as_dict=True)
 		self.assertEqual(data[0].name, item.name)
 		self.assertEqual(data[0].item_name, item.item_name)
 		self.assertTrue("description" not in data[0])
@@ -855,9 +848,7 @@
 		make_property_setter(
 			"Item", None, "search_fields", "item_name, description", "Data", for_doctype="Doctype"
 		)
-		data = item_query(
-			"Item", "Test Item", "", 0, 20, filters={"item_name": "Test Item"}, as_dict=True
-		)
+		data = item_query("Item", "Test Item", "", 0, 20, filters={"item_name": "Test Item"}, as_dict=True)
 		self.assertEqual(data[0].name, item.name)
 		self.assertEqual(data[0].item_name, item.item_name)
 		self.assertEqual(data[0].description, item.description)
diff --git a/erpnext/stock/doctype/item_alternative/item_alternative.py b/erpnext/stock/doctype/item_alternative/item_alternative.py
index 83bee9c..a73a82f 100644
--- a/erpnext/stock/doctype/item_alternative/item_alternative.py
+++ b/erpnext/stock/doctype/item_alternative/item_alternative.py
@@ -45,9 +45,7 @@
 			"allow_alternative_item",
 		]
 		item_data = frappe.db.get_value("Item", self.item_code, fields, as_dict=1)
-		alternative_item_data = frappe.db.get_value(
-			"Item", self.alternative_item_code, fields, as_dict=1
-		)
+		alternative_item_data = frappe.db.get_value("Item", self.alternative_item_code, fields, as_dict=1)
 
 		for field in fields:
 			if item_data.get(field) != alternative_item_data.get(field):
@@ -87,14 +85,12 @@
 @frappe.validate_and_sanitize_search_inputs
 def get_alternative_items(doctype, txt, searchfield, start, page_len, filters):
 	return frappe.db.sql(
-		""" (select alternative_item_code from `tabItem Alternative`
+		f""" (select alternative_item_code from `tabItem Alternative`
 			where item_code = %(item_code)s and alternative_item_code like %(txt)s)
 		union
 			(select item_code from `tabItem Alternative`
 			where alternative_item_code = %(item_code)s and item_code like %(txt)s
-			and two_way = 1) limit {1} offset {0}
-		""".format(
-			start, page_len
-		),
+			and two_way = 1) limit {page_len} offset {start}
+		""",
 		{"item_code": filters.get("item_code"), "txt": "%" + txt + "%"},
 	)
diff --git a/erpnext/stock/doctype/item_alternative/test_item_alternative.py b/erpnext/stock/doctype/item_alternative/test_item_alternative.py
index 1996418..11e45ee 100644
--- a/erpnext/stock/doctype/item_alternative/test_item_alternative.py
+++ b/erpnext/stock/doctype/item_alternative/test_item_alternative.py
@@ -54,9 +54,7 @@
 				"fg_item_qty": 5,
 			},
 		]
-		sco = get_subcontracting_order(
-			service_items=service_items, supplier_warehouse=supplier_warehouse
-		)
+		sco = get_subcontracting_order(service_items=service_items, supplier_warehouse=supplier_warehouse)
 		rm_items = [
 			{
 				"item_code": "Test Finished Goods - A",
@@ -106,9 +104,7 @@
 			"reserved_qty_for_sub_contract",
 		)
 
-		self.assertEqual(
-			after_transfer_reserved_qty_for_sub_contract, flt(reserved_qty_for_sub_contract - 5)
-		)
+		self.assertEqual(after_transfer_reserved_qty_for_sub_contract, flt(reserved_qty_for_sub_contract - 5))
 
 		scr = make_subcontracting_receipt(sco.name)
 		scr.save()
@@ -159,9 +155,7 @@
 			"reserved_qty_for_production",
 		)
 
-		self.assertEqual(
-			reserved_qty_for_production_after_transfer, flt(reserved_qty_for_production - 5)
-		)
+		self.assertEqual(reserved_qty_for_production_after_transfer, flt(reserved_qty_for_production - 5))
 		ste1 = frappe.get_doc(make_stock_entry(pro_order.name, "Manufacture", 5))
 
 		status = False
diff --git a/erpnext/stock/doctype/item_attribute/item_attribute.py b/erpnext/stock/doctype/item_attribute/item_attribute.py
index 7b341b2..04421d6 100644
--- a/erpnext/stock/doctype/item_attribute/item_attribute.py
+++ b/erpnext/stock/doctype/item_attribute/item_attribute.py
@@ -93,7 +93,9 @@
 		values, abbrs = [], []
 		for d in self.item_attribute_values:
 			if d.attribute_value.lower() in map(str.lower, values):
-				frappe.throw(_("Attribute value: {0} must appear only once").format(d.attribute_value.title()))
+				frappe.throw(
+					_("Attribute value: {0} must appear only once").format(d.attribute_value.title())
+				)
 			values.append(d.attribute_value)
 
 			if d.abbr.lower() in map(str.lower, abbrs):
diff --git a/erpnext/stock/doctype/item_manufacturer/item_manufacturer.py b/erpnext/stock/doctype/item_manufacturer/item_manufacturer.py
index ed004d5..715f09b 100644
--- a/erpnext/stock/doctype/item_manufacturer/item_manufacturer.py
+++ b/erpnext/stock/doctype/item_manufacturer/item_manufacturer.py
@@ -57,7 +57,9 @@
 			# if unchecked and default in Item master, clear it.
 			if default_manufacturer == self.manufacturer and default_part_no == self.manufacturer_part_no:
 				frappe.db.set_value(
-					"Item", item.name, {"default_item_manufacturer": None, "default_manufacturer_part_no": None}
+					"Item",
+					item.name,
+					{"default_item_manufacturer": None, "default_manufacturer_part_no": None},
 				)
 
 		elif self.is_default:
diff --git a/erpnext/stock/doctype/item_price/item_price.py b/erpnext/stock/doctype/item_price/item_price.py
index d64e321..ccdf1a0 100644
--- a/erpnext/stock/doctype/item_price/item_price.py
+++ b/erpnext/stock/doctype/item_price/item_price.py
@@ -68,7 +68,7 @@
 
 			if not price_list_details:
 				link = frappe.utils.get_link_to_form("Price List", self.price_list)
-				frappe.throw("The price list {0} does not exist or is disabled".format(link))
+				frappe.throw(f"The price list {link} does not exist or is disabled")
 
 			self.buying, self.selling, self.currency = price_list_details
 
@@ -85,7 +85,6 @@
 			frappe.throw(_(msg))
 
 	def check_duplicates(self):
-
 		item_price = frappe.qb.DocType("Item Price")
 
 		query = (
diff --git a/erpnext/stock/doctype/item_variant_settings/item_variant_settings.py b/erpnext/stock/doctype/item_variant_settings/item_variant_settings.py
index a4bdc0b..3ee46e4 100644
--- a/erpnext/stock/doctype/item_variant_settings/item_variant_settings.py
+++ b/erpnext/stock/doctype/item_variant_settings/item_variant_settings.py
@@ -64,4 +64,6 @@
 	def validate(self):
 		for d in self.fields:
 			if d.field_name in self.invalid_fields_for_copy_fields_in_variants:
-				frappe.throw(_("Cannot set the field <b>{0}</b> for copying in variants").format(d.field_name))
+				frappe.throw(
+					_("Cannot set the field <b>{0}</b> for copying in variants").format(d.field_name)
+				)
diff --git a/erpnext/stock/doctype/landed_cost_voucher/landed_cost_voucher.py b/erpnext/stock/doctype/landed_cost_voucher/landed_cost_voucher.py
index baff540..5e5efb5 100644
--- a/erpnext/stock/doctype/landed_cost_voucher/landed_cost_voucher.py
+++ b/erpnext/stock/doctype/landed_cost_voucher/landed_cost_voucher.py
@@ -103,13 +103,13 @@
 		for d in self.get("purchase_receipts"):
 			docstatus = frappe.db.get_value(d.receipt_document_type, d.receipt_document, "docstatus")
 			if docstatus != 1:
-				msg = (
-					f"Row {d.idx}: {d.receipt_document_type} {frappe.bold(d.receipt_document)} must be submitted"
-				)
+				msg = f"Row {d.idx}: {d.receipt_document_type} {frappe.bold(d.receipt_document)} must be submitted"
 				frappe.throw(_(msg), title=_("Invalid Document"))
 
 			if d.receipt_document_type == "Purchase Invoice":
-				update_stock = frappe.db.get_value(d.receipt_document_type, d.receipt_document, "update_stock")
+				update_stock = frappe.db.get_value(
+					d.receipt_document_type, d.receipt_document, "update_stock"
+				)
 				if not update_stock:
 					msg = _("Row {0}: Purchase Invoice {1} has no stock impact.").format(
 						d.idx, frappe.bold(d.receipt_document)
@@ -159,7 +159,8 @@
 					)
 
 				item.applicable_charges = flt(
-					flt(item.get(based_on_field)) * (flt(self.total_taxes_and_charges) / flt(total_item_cost)),
+					flt(item.get(based_on_field))
+					* (flt(self.total_taxes_and_charges) / flt(total_item_cost)),
 					item.precision("applicable_charges"),
 				)
 				total_charges += item.applicable_charges
@@ -257,7 +258,9 @@
 		for item in self.get("items"):
 			if item.is_fixed_asset:
 				receipt_document_type = (
-					"purchase_invoice" if item.receipt_document_type == "Purchase Invoice" else "purchase_receipt"
+					"purchase_invoice"
+					if item.receipt_document_type == "Purchase Invoice"
+					else "purchase_receipt"
 				)
 				docs = frappe.db.get_all(
 					"Asset",
@@ -280,9 +283,7 @@
 							frappe.throw(
 								_(
 									"{0} <b>{1}</b> has submitted Assets. Remove Item <b>{2}</b> from table to continue."
-								).format(
-									item.receipt_document_type, item.receipt_document, item.item_code
-								)
+								).format(item.receipt_document_type, item.receipt_document, item.item_code)
 							)
 
 	def update_rate_in_serial_no_for_non_asset_items(self, receipt_document):
@@ -291,10 +292,10 @@
 				serial_nos = get_serial_nos(item.serial_no)
 				if serial_nos:
 					frappe.db.sql(
-						"update `tabSerial No` set purchase_rate=%s where name in ({0})".format(
+						"update `tabSerial No` set purchase_rate=%s where name in ({})".format(
 							", ".join(["%s"] * len(serial_nos))
 						),
-						tuple([item.valuation_rate] + serial_nos),
+						tuple([item.valuation_rate, *serial_nos]),
 					)
 
 
diff --git a/erpnext/stock/doctype/landed_cost_voucher/test_landed_cost_voucher.py b/erpnext/stock/doctype/landed_cost_voucher/test_landed_cost_voucher.py
index 4058aa8..9ec2d69 100644
--- a/erpnext/stock/doctype/landed_cost_voucher/test_landed_cost_voucher.py
+++ b/erpnext/stock/doctype/landed_cost_voucher/test_landed_cost_voucher.py
@@ -16,9 +16,7 @@
 	make_purchase_receipt,
 )
 from erpnext.stock.doctype.serial_and_batch_bundle.test_serial_and_batch_bundle import (
-	get_batch_from_bundle,
 	get_serial_nos_from_bundle,
-	make_serial_batch_bundle,
 )
 from erpnext.stock.serial_batch_bundle import SerialNoValuation
 
@@ -68,9 +66,7 @@
 			as_dict=1,
 		)
 
-		self.assertEqual(
-			last_sle.qty_after_transaction, last_sle_after_landed_cost.qty_after_transaction
-		)
+		self.assertEqual(last_sle.qty_after_transaction, last_sle_after_landed_cost.qty_after_transaction)
 		self.assertEqual(last_sle_after_landed_cost.stock_value - last_sle.stock_value, 25.0)
 
 		# assert after submit
@@ -93,7 +89,6 @@
 		self.assertPurchaseReceiptLCVGLEntries(pr)
 
 	def assertPurchaseReceiptLCVGLEntries(self, pr):
-
 		gl_entries = get_gl_entries("Purchase Receipt", pr.name)
 
 		self.assertTrue(gl_entries)
@@ -176,9 +171,7 @@
 			as_dict=1,
 		)
 
-		self.assertEqual(
-			last_sle.qty_after_transaction, last_sle_after_landed_cost.qty_after_transaction
-		)
+		self.assertEqual(last_sle.qty_after_transaction, last_sle_after_landed_cost.qty_after_transaction)
 		self.assertEqual(last_sle_after_landed_cost.stock_value - last_sle.stock_value, 50.0)
 
 	def test_landed_cost_voucher_for_zero_purchase_rate(self):
@@ -235,7 +228,6 @@
 		)
 
 	def test_landed_cost_voucher_against_purchase_invoice(self):
-
 		pi = make_purchase_invoice(
 			update_stock=1,
 			posting_date=frappe.utils.nowdate(),
@@ -280,9 +272,7 @@
 			as_dict=1,
 		)
 
-		self.assertEqual(
-			last_sle.qty_after_transaction, last_sle_after_landed_cost.qty_after_transaction
-		)
+		self.assertEqual(last_sle.qty_after_transaction, last_sle_after_landed_cost.qty_after_transaction)
 
 		self.assertEqual(last_sle_after_landed_cost.stock_value - last_sle.stock_value, 50.0)
 
@@ -436,7 +426,7 @@
 			do_not_save=True,
 		)
 		pr.items[0].cost_center = "Main - TCP1"
-		for x in range(2):
+		for _x in range(2):
 			pr.append(
 				"items",
 				{
diff --git a/erpnext/stock/doctype/material_request/material_request.py b/erpnext/stock/doctype/material_request/material_request.py
index ace84f8..b52b169 100644
--- a/erpnext/stock/doctype/material_request/material_request.py
+++ b/erpnext/stock/doctype/material_request/material_request.py
@@ -107,13 +107,13 @@
 
 				if actual_so_qty and (flt(so_items[so_no][item]) + already_indented > actual_so_qty):
 					frappe.throw(
-						_("Material Request of maximum {0} can be made for Item {1} against Sales Order {2}").format(
-							actual_so_qty - already_indented, item, so_no
-						)
+						_(
+							"Material Request of maximum {0} can be made for Item {1} against Sales Order {2}"
+						).format(actual_so_qty - already_indented, item, so_no)
 					)
 
 	def validate(self):
-		super(MaterialRequest, self).validate()
+		super().validate()
 
 		self.validate_schedule_date()
 		self.check_for_on_hold_or_closed_status("Sales Order", "sales_order")
@@ -187,12 +187,8 @@
 		self.set_status(update=True, status="Cancelled")
 
 	def check_modified_date(self):
-		mod_db = frappe.db.sql(
-			"""select modified from `tabMaterial Request` where name = %s""", self.name
-		)
-		date_diff = frappe.db.sql(
-			"""select TIMEDIFF('%s', '%s')""" % (mod_db[0][0], cstr(self.modified))
-		)
+		mod_db = frappe.db.sql("""select modified from `tabMaterial Request` where name = %s""", self.name)
+		date_diff = frappe.db.sql(f"""select TIMEDIFF('{mod_db[0][0]}', '{cstr(self.modified)}')""")
 
 		if date_diff and date_diff[0][0]:
 			frappe.throw(_("{0} {1} has been modified. Please refresh.").format(_(self.doctype), self.name))
@@ -276,7 +272,9 @@
 					d.ordered_qty = flt(mr_items_ordered_qty.get(d.name))
 
 					if mr_qty_allowance:
-						allowed_qty = flt((d.qty + (d.qty * (mr_qty_allowance / 100))), d.precision("ordered_qty"))
+						allowed_qty = flt(
+							(d.qty + (d.qty * (mr_qty_allowance / 100))), d.precision("ordered_qty")
+						)
 
 						if d.ordered_qty and d.ordered_qty > allowed_qty:
 							frappe.throw(
@@ -371,9 +369,7 @@
 
 
 def set_missing_values(source, target_doc):
-	if target_doc.doctype == "Purchase Order" and getdate(target_doc.schedule_date) < getdate(
-		nowdate()
-	):
+	if target_doc.doctype == "Purchase Order" and getdate(target_doc.schedule_date) < getdate(nowdate()):
 		target_doc.schedule_date = None
 	target_doc.run_method("set_missing_values")
 	target_doc.run_method("calculate_taxes_and_totals")
@@ -503,9 +499,7 @@
 			target_doc.schedule_date = None
 		target_doc.set(
 			"items",
-			[
-				d for d in target_doc.get("items") if d.get("item_code") in supplier_items and d.get("qty") > 0
-			],
+			[d for d in target_doc.get("items") if d.get("item_code") in supplier_items and d.get("qty") > 0],
 		)
 
 		set_missing_values(source, target_doc)
@@ -557,7 +551,7 @@
 
 	if filters.get("transaction_date"):
 		date = filters.get("transaction_date")[1]
-		conditions += "and mr.transaction_date between '{0}' and '{1}' ".format(date[0], date[1])
+		conditions += f"and mr.transaction_date between '{date[0]}' and '{date[1]}' "
 
 	supplier = filters.get("supplier")
 	supplier_items = get_items_based_on_default_supplier(supplier)
@@ -569,18 +563,18 @@
 		"""select distinct mr.name, transaction_date,company
 		from `tabMaterial Request` mr, `tabMaterial Request Item` mr_item
 		where mr.name = mr_item.parent
-			and mr_item.item_code in ({0})
+			and mr_item.item_code in ({})
 			and mr.material_request_type = 'Purchase'
 			and mr.per_ordered < 99.99
 			and mr.docstatus = 1
 			and mr.status != 'Stopped'
 			and mr.company = %s
-			{1}
+			{}
 		order by mr_item.item_code ASC
-		limit {2} offset {3} """.format(
+		limit {} offset {} """.format(
 			", ".join(["%s"] * len(supplier_items)), conditions, cint(page_len), cint(start)
 		),
-		tuple(supplier_items) + (filters.get("company"),),
+		(*tuple(supplier_items), filters.get("company")),
 		as_dict=1,
 	)
 
@@ -708,7 +702,10 @@
 				"doctype": "Stock Entry",
 				"validation": {
 					"docstatus": ["=", 1],
-					"material_request_type": ["in", ["Material Transfer", "Material Issue", "Customer Provided"]],
+					"material_request_type": [
+						"in",
+						["Material Transfer", "Material Issue", "Customer Provided"],
+					],
 				},
 			},
 			"Material Request Item": {
@@ -738,9 +735,7 @@
 	mr = frappe.get_doc("Material Request", material_request)
 	errors = []
 	work_orders = []
-	default_wip_warehouse = frappe.db.get_single_value(
-		"Manufacturing Settings", "default_wip_warehouse"
-	)
+	default_wip_warehouse = frappe.db.get_single_value("Manufacturing Settings", "default_wip_warehouse")
 
 	for d in mr.items:
 		if (d.stock_qty - d.ordered_qty) > 0:
@@ -788,7 +783,9 @@
 			)
 		else:
 			msgprint(
-				_("The {0} {1} created successfully").format(frappe.bold(_("Work Order")), work_orders_list[0])
+				_("The {0} {1} created successfully").format(
+					frappe.bold(_("Work Order")), work_orders_list[0]
+				)
 			)
 
 	if errors:
diff --git a/erpnext/stock/doctype/material_request/test_material_request.py b/erpnext/stock/doctype/material_request/test_material_request.py
index 48397a3..b383078 100644
--- a/erpnext/stock/doctype/material_request/test_material_request.py
+++ b/erpnext/stock/doctype/material_request/test_material_request.py
@@ -756,9 +756,7 @@
 		self.assertEqual(mr.per_ordered, 100)
 
 	def test_customer_provided_parts_mr(self):
-		create_item(
-			"CUST-0987", is_customer_provided_item=1, customer="_Test Customer", is_purchase_item=0
-		)
+		create_item("CUST-0987", is_customer_provided_item=1, customer="_Test Customer", is_purchase_item=0)
 		existing_requested_qty = self._get_requested_qty("_Test Customer", "_Test Warehouse - _TC")
 
 		mr = make_material_request(item_code="CUST-0987", material_request_type="Customer Provided")
@@ -822,7 +820,7 @@
 		)
 		comapnywise_mr_list.setdefault(mr2.company, []).append(mr2.name)
 
-		for company, mr_list in comapnywise_mr_list.items():
+		for company, _mr_list in comapnywise_mr_list.items():
 			emails = get_email_list(company)
 
 			self.assertTrue(comapnywise_users[company] in emails)
@@ -840,9 +838,7 @@
 			}
 		).insert()
 
-	in_transit_warehouse = frappe.db.exists(
-		"Warehouse", {"warehouse_type": "Transit", "company": company}
-	)
+	in_transit_warehouse = frappe.db.exists("Warehouse", {"warehouse_type": "Transit", "company": company})
 
 	if not in_transit_warehouse:
 		in_transit_warehouse = (
diff --git a/erpnext/stock/doctype/packed_item/packed_item.py b/erpnext/stock/doctype/packed_item/packed_item.py
index d81ceaf..081d9c5 100644
--- a/erpnext/stock/doctype/packed_item/packed_item.py
+++ b/erpnext/stock/doctype/packed_item/packed_item.py
@@ -69,9 +69,7 @@
 		return
 
 	parent_items_price, reset = {}, False
-	set_price_from_children = frappe.db.get_single_value(
-		"Selling Settings", "editable_bundle_item_rates"
-	)
+	set_price_from_children = frappe.db.get_single_value("Selling Settings", "editable_bundle_item_rates")
 
 	stale_packed_items_table = get_indexed_packed_items_table(doc)
 
@@ -236,9 +234,7 @@
 	bin = get_packed_item_bin_qty(packing_item.item_code, pi_row.warehouse)
 	pi_row.actual_qty = flt(bin.get("actual_qty"))
 	pi_row.projected_qty = flt(bin.get("projected_qty"))
-	pi_row.use_serial_batch_fields = frappe.db.get_single_value(
-		"Stock Settings", "use_serial_batch_fields"
-	)
+	pi_row.use_serial_batch_fields = frappe.db.get_single_value("Stock Settings", "use_serial_batch_fields")
 
 
 def update_packed_item_price_data(pi_row, item_data, doc):
@@ -293,9 +289,7 @@
 def get_cancelled_doc_packed_item_details(old_packed_items):
 	prev_doc_packed_items_map = {}
 	for items in old_packed_items:
-		prev_doc_packed_items_map.setdefault((items.item_code, items.parent_item), []).append(
-			items.as_dict()
-		)
+		prev_doc_packed_items_map.setdefault((items.item_code, items.parent_item), []).append(items.as_dict())
 	return prev_doc_packed_items_map
 
 
diff --git a/erpnext/stock/doctype/packed_item/test_packed_item.py b/erpnext/stock/doctype/packed_item/test_packed_item.py
index ad06732..3f87ced 100644
--- a/erpnext/stock/doctype/packed_item/test_packed_item.py
+++ b/erpnext/stock/doctype/packed_item/test_packed_item.py
@@ -1,7 +1,6 @@
 # Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors
 # License: GNU General Public License v3. See license.txt
 
-from typing import List, Optional, Tuple
 
 import frappe
 from frappe.tests.utils import FrappeTestCase, change_settings
@@ -15,8 +14,8 @@
 
 
 def create_product_bundle(
-	quantities: Optional[List[int]] = None, warehouse: Optional[str] = None
-) -> Tuple[str, List[str]]:
+	quantities: list[int] | None = None, warehouse: str | None = None
+) -> tuple[str, list[str]]:
 	"""Get a new product_bundle for use in tests.
 
 	Create 10x required stock if warehouse is specified.
@@ -169,9 +168,7 @@
 
 		# backdated stock entry
 		for item in self.bundle_items:
-			make_stock_entry(
-				item_code=item, to_warehouse=warehouse, qty=10, rate=200, posting_date=yesterday
-			)
+			make_stock_entry(item_code=item, to_warehouse=warehouse, qty=10, rate=200, posting_date=yesterday)
 
 		# assert correct reposting
 		gles = get_gl_entries(dn.doctype, dn.name)
@@ -182,10 +179,11 @@
 	def assertReturns(self, original, returned):
 		self.assertEqual(len(original), len(returned))
 
-		sort_function = lambda p: (p.parent_item, p.item_code, p.qty)
+		def sort_function(p):
+			return p.parent_item, p.item_code, p.qty
 
 		for sent, returned in zip(
-			sorted(original, key=sort_function), sorted(returned, key=sort_function)
+			sorted(original, key=sort_function), sorted(returned, key=sort_function), strict=False
 		):
 			self.assertEqual(sent.item_code, returned.item_code)
 			self.assertEqual(sent.parent_item, returned.parent_item)
diff --git a/erpnext/stock/doctype/packing_slip/packing_slip.py b/erpnext/stock/doctype/packing_slip/packing_slip.py
index 88acfe8..8f8e8dc 100644
--- a/erpnext/stock/doctype/packing_slip/packing_slip.py
+++ b/erpnext/stock/doctype/packing_slip/packing_slip.py
@@ -34,7 +34,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs) -> None:
-		super(PackingSlip, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 		self.status_updater = [
 			{
 				"target_dt": "Delivery Note Item",
@@ -87,9 +87,7 @@
 		"""Validate if case nos overlap. If they do, recommend next case no."""
 
 		if cint(self.from_case_no) <= 0:
-			frappe.throw(
-				_("The 'From Package No.' field must neither be empty nor it's value less than 1.")
-			)
+			frappe.throw(_("The 'From Package No.' field must neither be empty nor it's value less than 1."))
 		elif not self.to_case_no:
 			self.to_case_no = self.from_case_no
 		elif cint(self.to_case_no) < cint(self.from_case_no):
@@ -212,9 +210,8 @@
 	return frappe.db.sql(
 		"""select name, item_name, description from `tabItem`
 				where name in ( select item_code FROM `tabDelivery Note Item`
-	 						where parent= %s)
-	 			and %s like "%s" %s
-	 			limit  %s offset %s """
-		% ("%s", searchfield, "%s", get_match_cond(doctype), "%s", "%s"),
+	 						where parent= {})
+	 			and {} like "{}" {}
+	 			limit  {} offset {} """.format("%s", searchfield, "%s", get_match_cond(doctype), "%s", "%s"),
 		((filters or {}).get("delivery_note"), "%%%s%%" % txt, page_len, start),
 	)
diff --git a/erpnext/stock/doctype/packing_slip/test_packing_slip.py b/erpnext/stock/doctype/packing_slip/test_packing_slip.py
index 96da23d..08c70bf 100644
--- a/erpnext/stock/doctype/packing_slip/test_packing_slip.py
+++ b/erpnext/stock/doctype/packing_slip/test_packing_slip.py
@@ -1,7 +1,6 @@
 # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
 # See license.txt
 
-import unittest
 
 import frappe
 from frappe.tests.utils import FrappeTestCase
diff --git a/erpnext/stock/doctype/pick_list/pick_list.py b/erpnext/stock/doctype/pick_list/pick_list.py
index 4eab7e8..56bdca5 100644
--- a/erpnext/stock/doctype/pick_list/pick_list.py
+++ b/erpnext/stock/doctype/pick_list/pick_list.py
@@ -4,7 +4,6 @@
 import json
 from collections import OrderedDict, defaultdict
 from itertools import groupby
-from typing import Dict, List
 
 import frappe
 from frappe import _
@@ -381,9 +380,7 @@
 				),
 			)
 
-			locations = get_items_with_location_and_quantity(
-				item_doc, self.item_location_map, self.docstatus
-			)
+			locations = get_items_with_location_and_quantity(item_doc, self.item_location_map, self.docstatus)
 
 			item_doc.idx = None
 			item_doc.name = None
@@ -437,12 +434,10 @@
 		item_map = OrderedDict()
 		for item in locations:
 			if not item.item_code:
-				frappe.throw("Row #{0}: Item Code is Mandatory".format(item.idx))
+				frappe.throw(f"Row #{item.idx}: Item Code is Mandatory")
 			if not cint(
 				frappe.get_cached_value("Item", item.item_code, "is_stock_item")
-			) and not frappe.db.exists(
-				"Product Bundle", {"new_item_code": item.item_code, "disabled": 0}
-			):
+			) and not frappe.db.exists("Product Bundle", {"new_item_code": item.item_code, "disabled": 0}):
 				continue
 			item_code = item.item_code
 			reference = item.sales_order_item or item.material_request_item
@@ -564,7 +559,7 @@
 
 		return picked_items
 
-	def _get_product_bundles(self) -> Dict[str, str]:
+	def _get_product_bundles(self) -> dict[str, str]:
 		# Dict[so_item_row: item_code]
 		product_bundles = {}
 		for item in self.locations:
@@ -577,13 +572,11 @@
 			)
 		return product_bundles
 
-	def _get_product_bundle_qty_map(self, bundles: List[str]) -> Dict[str, Dict[str, float]]:
+	def _get_product_bundle_qty_map(self, bundles: list[str]) -> dict[str, dict[str, float]]:
 		# bundle_item_code: Dict[component, qty]
 		product_bundle_qty_map = {}
 		for bundle_item_code in bundles:
-			bundle = frappe.get_last_doc(
-				"Product Bundle", {"new_item_code": bundle_item_code, "disabled": 0}
-			)
+			bundle = frappe.get_last_doc("Product Bundle", {"new_item_code": bundle_item_code, "disabled": 0})
 			product_bundle_qty_map[bundle_item_code] = {item.item_code: item.qty for item in bundle.items}
 		return product_bundle_qty_map
 
@@ -617,7 +610,11 @@
 	def has_reserved_stock(self):
 		if self.purpose == "Delivery":
 			for location in self.locations:
-				if location.sales_order and location.sales_order_item and flt(location.stock_reserved_qty) > 0:
+				if (
+					location.sales_order
+					and location.sales_order_item
+					and flt(location.stock_reserved_qty) > 0
+				):
 					return True
 
 		return False
@@ -629,7 +626,7 @@
 		doc.run_method("update_status")
 
 
-def get_picked_items_qty(items) -> List[Dict]:
+def get_picked_items_qty(items) -> list[dict]:
 	pi_item = frappe.qb.DocType("Pick List Item")
 	return (
 		frappe.qb.from_(pi_item)
@@ -659,17 +656,13 @@
 	locations = []
 
 	# if stock qty is zero on submitted entry, show positive remaining qty to recalculate in case of restock.
-	remaining_stock_qty = (
-		item_doc.qty if (docstatus == 1 and item_doc.stock_qty == 0) else item_doc.stock_qty
-	)
+	remaining_stock_qty = item_doc.qty if (docstatus == 1 and item_doc.stock_qty == 0) else item_doc.stock_qty
 
 	while flt(remaining_stock_qty) > 0 and available_locations:
 		item_location = available_locations.pop(0)
 		item_location = frappe._dict(item_location)
 
-		stock_qty = (
-			remaining_stock_qty if item_location.qty >= remaining_stock_qty else item_location.qty
-		)
+		stock_qty = remaining_stock_qty if item_location.qty >= remaining_stock_qty else item_location.qty
 		qty = stock_qty / (item_doc.conversion_factor or 1)
 
 		uom_must_be_whole_number = frappe.get_cached_value("UOM", item_doc.uom, "must_be_whole_number")
@@ -705,7 +698,7 @@
 			if item_location.serial_no:
 				# set remaining serial numbers
 				item_location.serial_no = item_location.serial_no[-int(qty_diff) :]
-			available_locations = [item_location] + available_locations
+			available_locations = [item_location, *available_locations]
 
 	# update available locations for the item
 	item_location_map[item_doc.item_code] = available_locations
@@ -920,9 +913,7 @@
 	rejected_warehouses = get_rejected_warehouses()
 
 	for d in data:
-		if (
-			not consider_rejected_warehouses and rejected_warehouses and d.warehouse in rejected_warehouses
-		):
+		if not consider_rejected_warehouses and rejected_warehouses and d.warehouse in rejected_warehouses:
 			continue
 
 		if d.warehouse not in warehouse_wise_batches:
@@ -1033,8 +1024,7 @@
 			"name": "so_detail",
 			"parent": "against_sales_order",
 		},
-		"condition": lambda doc: abs(doc.delivered_qty) < abs(doc.qty)
-		and doc.delivered_by_supplier != 1,
+		"condition": lambda doc: abs(doc.delivered_qty) < abs(doc.qty) and doc.delivered_by_supplier != 1,
 	}
 
 	for customer in sales_dict:
@@ -1056,7 +1046,6 @@
 
 
 def map_pl_locations(pick_list, item_mapper, delivery_note, sales_order=None):
-
 	for location in pick_list.locations:
 		if location.sales_order != sales_order or location.product_bundle_item:
 			continue
@@ -1087,9 +1076,7 @@
 	delivery_note.customer = frappe.get_value("Sales Order", sales_order, "customer")
 
 
-def add_product_bundles_to_delivery_note(
-	pick_list: "PickList", delivery_note, item_mapper
-) -> None:
+def add_product_bundles_to_delivery_note(pick_list: "PickList", delivery_note, item_mapper) -> None:
 	"""Add product bundles found in pick list to delivery note.
 
 	When mapping pick list items, the bundle item itself isn't part of the
@@ -1167,7 +1154,7 @@
 			& (wo.qty > wo.material_transferred_for_manufacturing)
 			& (wo.docstatus == 1)
 			& (wo.company == filters.get("company"))
-			& (wo.name.like("%{0}%".format(txt)))
+			& (wo.name.like(f"%{txt}%"))
 		)
 		.orderby(Case().when(Locate(txt, wo.name) > 0, Locate(txt, wo.name)).else_(99999))
 		.orderby(wo.name)
@@ -1234,9 +1221,7 @@
 	stock_entry.use_multi_level_bom = work_order.use_multi_level_bom
 	stock_entry.fg_completed_qty = pick_list.for_qty
 	if work_order.bom_no:
-		stock_entry.inspection_required = frappe.db.get_value(
-			"BOM", work_order.bom_no, "inspection_required"
-		)
+		stock_entry.inspection_required = frappe.db.get_value("BOM", work_order.bom_no, "inspection_required")
 
 	is_wip_warehouse_group = frappe.db.get_value("Warehouse", work_order.wip_warehouse, "is_group")
 	if not (is_wip_warehouse_group and work_order.skip_transfer):
diff --git a/erpnext/stock/doctype/pick_list/test_pick_list.py b/erpnext/stock/doctype/pick_list/test_pick_list.py
index cffd0d2..0fe869b 100644
--- a/erpnext/stock/doctype/pick_list/test_pick_list.py
+++ b/erpnext/stock/doctype/pick_list/test_pick_list.py
@@ -319,7 +319,6 @@
 		pr2.cancel()
 
 	def test_pick_list_for_items_from_multiple_sales_orders(self):
-
 		item_code = make_item().name
 		try:
 			frappe.get_doc(
@@ -463,9 +462,7 @@
 
 		self.assertEqual(pick_list.locations[0].qty, delivery_note.items[0].qty)
 		self.assertEqual(pick_list.locations[1].qty, delivery_note.items[1].qty)
-		self.assertEqual(
-			sales_order.items[0].conversion_factor, delivery_note.items[0].conversion_factor
-		)
+		self.assertEqual(sales_order.items[0].conversion_factor, delivery_note.items[0].conversion_factor)
 
 		pick_list.cancel()
 		sales_order.cancel()
@@ -514,7 +511,7 @@
 			_dict(item_code="A", warehouse="X", qty=8, picked_qty=3),
 			_dict(item_code="B", warehouse="Y", qty=6, picked_qty=4),
 		]
-		for expected_item, created_item in zip(expected_items, pl.locations):
+		for expected_item, created_item in zip(expected_items, pl.locations, strict=False):
 			_compare_dicts(expected_item, created_item)
 
 	def test_multiple_dn_creation(self):
@@ -624,9 +621,7 @@
 		pick_list_1.set_item_locations()
 		pick_list_1.submit()
 		create_delivery_note(pick_list_1.name)
-		for dn in frappe.get_all(
-			"Delivery Note", filters={"pick_list": pick_list_1.name}, fields={"name"}
-		):
+		for dn in frappe.get_all("Delivery Note", filters={"pick_list": pick_list_1.name}, fields={"name"}):
 			for dn_item in frappe.get_doc("Delivery Note", dn.name).get("items"):
 				if dn_item.item_code == "_Test Item":
 					self.assertEqual(dn_item.qty, 1)
@@ -728,7 +723,9 @@
 			self.assertTrue(loc.serial_and_batch_bundle)
 
 			data = frappe.get_all(
-				"Serial and Batch Entry", fields=["serial_no"], filters={"parent": loc.serial_and_batch_bundle}
+				"Serial and Batch Entry",
+				fields=["serial_no"],
+				filters={"parent": loc.serial_and_batch_bundle},
 			)
 
 			picked_serial_nos = [d.serial_no for d in data]
@@ -760,7 +757,7 @@
 
 		quantities = [5, 2]
 		bundle, components = create_product_bundle(quantities, warehouse=warehouse)
-		bundle_items = dict(zip(components, quantities))
+		bundle_items = dict(zip(components, quantities, strict=False))
 
 		so = make_sales_order(item_code=bundle, qty=3, rate=42)
 
diff --git a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
index e87e20d..0eb42b1 100644
--- a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
+++ b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
@@ -135,7 +135,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(PurchaseReceipt, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 		self.status_updater = [
 			{
 				"target_dt": "Purchase Order Item",
@@ -228,7 +228,7 @@
 
 	def validate(self):
 		self.validate_posting_time()
-		super(PurchaseReceipt, self).validate()
+		super().validate()
 
 		if self._action != "submit":
 			self.set_status()
@@ -258,15 +258,15 @@
 				# Improves UX by not giving messages of "Assets Created" before throwing error of not finding arbnb account
 				self.get_company_default("asset_received_but_not_billed")
 				get_asset_account(
-					"capital_work_in_progress_account", asset_category=item.asset_category, company=self.company
+					"capital_work_in_progress_account",
+					asset_category=item.asset_category,
+					company=self.company,
 				)
 				break
 
 	def validate_provisional_expense_account(self):
 		provisional_accounting_for_non_stock_items = cint(
-			frappe.db.get_value(
-				"Company", self.company, "enable_provisional_accounting_for_non_stock_items"
-			)
+			frappe.db.get_value("Company", self.company, "enable_provisional_accounting_for_non_stock_items")
 		)
 
 		if not provisional_accounting_for_non_stock_items:
@@ -278,7 +278,7 @@
 				item.provisional_expense_account = default_provisional_account
 
 	def validate_with_previous_doc(self):
-		super(PurchaseReceipt, self).validate_with_previous_doc(
+		super().validate_with_previous_doc(
 			{
 				"Purchase Order": {
 					"ref_dn_field": "purchase_order",
@@ -339,24 +339,20 @@
 		return qty and flt(qty[0][0]) or 0.0
 
 	def get_po_qty_and_warehouse(self, po_detail):
-		po_qty, po_warehouse = frappe.db.get_value(
-			"Purchase Order Item", po_detail, ["qty", "warehouse"]
-		)
+		po_qty, po_warehouse = frappe.db.get_value("Purchase Order Item", po_detail, ["qty", "warehouse"])
 		return po_qty, po_warehouse
 
 	# Check for Closed status
 	def check_on_hold_or_closed_status(self):
 		check_list = []
 		for d in self.get("items"):
-			if (
-				d.meta.get_field("purchase_order") and d.purchase_order and d.purchase_order not in check_list
-			):
+			if d.meta.get_field("purchase_order") and d.purchase_order and d.purchase_order not in check_list:
 				check_list.append(d.purchase_order)
 				check_on_hold_or_closed_status("Purchase Order", d.purchase_order)
 
 	# on submit
 	def on_submit(self):
-		super(PurchaseReceipt, self).on_submit()
+		super().on_submit()
 
 		# Check for Approving Authority
 		frappe.get_doc("Authorization Control").validate_approving_authority(
@@ -390,7 +386,7 @@
 			frappe.throw(_("Purchase Invoice {0} is already submitted").format(self.submit_rv[0][0]))
 
 	def on_cancel(self):
-		super(PurchaseReceipt, self).on_cancel()
+		super().on_cancel()
 
 		self.check_on_hold_or_closed_status()
 		# Check if Purchase Invoice has been submitted against current Purchase Order
@@ -437,9 +433,7 @@
 		)
 
 		provisional_accounting_for_non_stock_items = cint(
-			frappe.db.get_value(
-				"Company", self.company, "enable_provisional_accounting_for_non_stock_items"
-			)
+			frappe.db.get_value("Company", self.company, "enable_provisional_accounting_for_non_stock_items")
 		)
 
 		exchange_rate_map, net_rate_map = get_purchase_document_details(self)
@@ -508,7 +502,6 @@
 						and self.conversion_rate != exchange_rate_map[item.purchase_invoice]
 						and item.net_rate == net_rate_map[item.purchase_invoice_item]
 					):
-
 						discrepancy_caused_by_exchange_rate_difference = (item.qty * item.net_rate) * (
 							exchange_rate_map[item.purchase_invoice] - self.conversion_rate
 						)
@@ -691,10 +684,12 @@
 				elif warehouse_account.get(d.warehouse):
 					stock_value_diff = get_stock_value_difference(self.name, d.name, d.warehouse)
 					stock_asset_account_name = warehouse_account[d.warehouse]["account"]
-					supplier_warehouse_account = warehouse_account.get(self.supplier_warehouse, {}).get("account")
-					supplier_warehouse_account_currency = warehouse_account.get(self.supplier_warehouse, {}).get(
-						"account_currency"
+					supplier_warehouse_account = warehouse_account.get(self.supplier_warehouse, {}).get(
+						"account"
 					)
+					supplier_warehouse_account_currency = warehouse_account.get(
+						self.supplier_warehouse, {}
+					).get("account_currency")
 
 					# If PR is sub-contracted and fg item rate is zero
 					# in that case if account for source and target warehouse are same,
@@ -911,7 +906,7 @@
 				so_items_details_map.setdefault(item.sales_order, []).append(item_details)
 
 		if so_items_details_map:
-			if get_datetime("{} {}".format(self.posting_date, self.posting_time)) > get_datetime():
+			if get_datetime(f"{self.posting_date} {self.posting_time}") > get_datetime():
 				return frappe.msgprint(
 					_("Cannot create Stock Reservation Entries for future dated Purchase Receipts.")
 				)
@@ -1172,9 +1167,7 @@
 			frappe.throw(_("All items have already been Invoiced/Returned"))
 
 		doc = frappe.get_doc(target)
-		doc.payment_terms_template = get_payment_terms_template(
-			source.supplier, "Supplier", source.company
-		)
+		doc.payment_terms_template = get_payment_terms_template(source.supplier, "Supplier", source.company)
 		doc.run_method("onload")
 		doc.run_method("set_missing_values")
 
@@ -1186,9 +1179,7 @@
 
 	def update_item(source_doc, target_doc, source_parent):
 		target_doc.qty, returned_qty = get_pending_qty(source_doc)
-		if frappe.db.get_single_value(
-			"Buying Settings", "bill_for_rejected_quantity_in_purchase_invoice"
-		):
+		if frappe.db.get_single_value("Buying Settings", "bill_for_rejected_quantity_in_purchase_invoice"):
 			target_doc.rejected_qty = 0
 		target_doc.stock_qty = flt(target_doc.qty) * flt(
 			target_doc.conversion_factor, target_doc.precision("conversion_factor")
@@ -1197,9 +1188,7 @@
 
 	def get_pending_qty(item_row):
 		qty = item_row.qty
-		if frappe.db.get_single_value(
-			"Buying Settings", "bill_for_rejected_quantity_in_purchase_invoice"
-		):
+		if frappe.db.get_single_value("Buying Settings", "bill_for_rejected_quantity_in_purchase_invoice"):
 			qty = item_row.received_qty
 		pending_qty = qty - invoiced_qty_map.get(item_row.name, 0)
 		returned_qty = flt(returned_qty_map.get(item_row.name, 0))
@@ -1384,15 +1373,11 @@
 					if total_item_cost > 0:
 						item_account_wise_cost[(item.item_code, item.purchase_receipt_item)][
 							account.expense_account
-						]["amount"] += (
-							account.amount * item.get(based_on_field) / total_item_cost
-						)
+						]["amount"] += account.amount * item.get(based_on_field) / total_item_cost
 
 						item_account_wise_cost[(item.item_code, item.purchase_receipt_item)][
 							account.expense_account
-						]["base_amount"] += (
-							account.base_amount * item.get(based_on_field) / total_item_cost
-						)
+						]["base_amount"] += account.base_amount * item.get(based_on_field) / total_item_cost
 					else:
 						item_account_wise_cost[(item.item_code, item.purchase_receipt_item)][
 							account.expense_account
diff --git a/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py b/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py
index 5cf2080..705b0f9 100644
--- a/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py
+++ b/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py
@@ -63,7 +63,6 @@
 		pr.delete()
 
 	def test_reverse_purchase_receipt_sle(self):
-
 		pr = make_purchase_receipt(qty=0.5, item_code="_Test Item Home Desktop 200")
 
 		sl_entry = frappe.db.get_all(
@@ -150,9 +149,7 @@
 		pi.delete()  # draft PI
 		pr.cancel()
 		frappe.db.set_value("Supplier", "_Test Supplier", "payment_terms", old_template_in_supplier)
-		frappe.get_doc(
-			"Payment Terms Template", "_Test Payment Terms Template For Purchase Invoice"
-		).delete()
+		frappe.get_doc("Payment Terms Template", "_Test Payment Terms Template For Purchase Invoice").delete()
 
 	def test_purchase_receipt_no_gl_entry(self):
 		from erpnext.stock.doctype.stock_entry.test_stock_entry import make_stock_entry
@@ -220,7 +217,6 @@
 
 	def test_duplicate_serial_nos(self):
 		from erpnext.stock.doctype.delivery_note.test_delivery_note import create_delivery_note
-		from erpnext.stock.serial_batch_bundle import SerialBatchCreation
 
 		item = frappe.db.exists("Item", {"item_name": "Test Serialized Item 123"})
 		if not item:
@@ -243,7 +239,7 @@
 
 		serial_nos = get_serial_nos_from_bundle(bundle_id)
 
-		self.assertEquals(get_serial_nos_from_bundle(pr.items[0].serial_and_batch_bundle), serial_nos)
+		self.assertEqual(get_serial_nos_from_bundle(pr.items[0].serial_and_batch_bundle), serial_nos)
 
 		bundle_id = make_serial_batch_bundle(
 			frappe._dict(
@@ -266,7 +262,7 @@
 		# Then made delivery note to remove the serial nos from stock
 		dn = create_delivery_note(item_code=item.name, qty=2, rate=1500, serial_no=serial_nos)
 		dn.load_from_db()
-		self.assertEquals(get_serial_nos_from_bundle(dn.items[0].serial_and_batch_bundle), serial_nos)
+		self.assertEqual(get_serial_nos_from_bundle(dn.items[0].serial_and_batch_bundle), serial_nos)
 
 		posting_date = add_days(today(), -3)
 
@@ -393,13 +389,12 @@
 				frappe.db.get_value("Serial No", serial_no, "warehouse"), pr.get("items")[0].warehouse
 			)
 
-		rejected_serial_nos = get_serial_nos_from_bundle(
-			pr.get("items")[0].rejected_serial_and_batch_bundle
-		)
+		rejected_serial_nos = get_serial_nos_from_bundle(pr.get("items")[0].rejected_serial_and_batch_bundle)
 		self.assertEqual(len(rejected_serial_nos), 2)
 		for serial_no in rejected_serial_nos:
 			self.assertEqual(
-				frappe.db.get_value("Serial No", serial_no, "warehouse"), pr.get("items")[0].rejected_warehouse
+				frappe.db.get_value("Serial No", serial_no, "warehouse"),
+				pr.get("items")[0].rejected_warehouse,
 			)
 
 		pr.cancel()
@@ -614,8 +609,6 @@
 			for field, value in field_values.items():
 				self.assertEqual(cstr(serial_no.get(field)), value)
 
-		from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
-
 		pr = make_purchase_receipt(item_code="_Test Serialized Item With Series", qty=1)
 
 		serial_no = get_serial_nos_from_bundle(pr.get("items")[0].serial_and_batch_bundle)[0]
@@ -733,7 +726,6 @@
 		po.cancel()
 
 	def test_serial_no_against_purchase_receipt(self):
-
 		item_code = "Test Manual Created Serial No"
 		if not frappe.db.exists("Item", item_code):
 			make_item(item_code, dict(has_serial_no=1))
@@ -884,7 +876,7 @@
 			"Stock Received But Not Billed - TCP1": {"cost_center": cost_center},
 			stock_in_hand_account: {"cost_center": cost_center},
 		}
-		for i, gle in enumerate(gl_entries):
+		for _i, gle in enumerate(gl_entries):
 			self.assertEqual(expected_values[gle.account]["cost_center"], gle.cost_center)
 
 		pr.cancel()
@@ -909,7 +901,7 @@
 			"Stock Received But Not Billed - TCP1": {"cost_center": cost_center},
 			stock_in_hand_account: {"cost_center": cost_center},
 		}
-		for i, gle in enumerate(gl_entries):
+		for _i, gle in enumerate(gl_entries):
 			self.assertEqual(expected_values[gle.account]["cost_center"], gle.cost_center)
 
 		pr.cancel()
@@ -1190,9 +1182,7 @@
 		pr.submit()
 
 		# Get exchnage gain and loss account
-		exchange_gain_loss_account = frappe.db.get_value(
-			"Company", pr.company, "exchange_gain_loss_account"
-		)
+		exchange_gain_loss_account = frappe.db.get_value("Company", pr.company, "exchange_gain_loss_account")
 
 		# fetching the latest GL Entry with exchange gain and loss account account
 		amount = frappe.db.get_value(
@@ -1249,9 +1239,7 @@
 		account = "Stock Received But Not Billed - TCP1"
 
 		make_item(item_code)
-		se = make_stock_entry(
-			item_code=item_code, from_warehouse=warehouse, qty=50, do_not_save=True, rate=0
-		)
+		se = make_stock_entry(item_code=item_code, from_warehouse=warehouse, qty=50, do_not_save=True, rate=0)
 		se.items[0].allow_zero_valuation_rate = 1
 		se.save()
 		se.submit()
@@ -1697,7 +1685,6 @@
 		)
 
 		# Step 4: Create Internal Purchase Receipt
-		from erpnext.controllers.status_updater import OverAllowanceError
 		from erpnext.stock.doctype.delivery_note.delivery_note import make_inter_company_purchase_receipt
 
 		pr = make_inter_company_purchase_receipt(dn.name)
@@ -1847,7 +1834,6 @@
 		)
 
 		# Step 4: Create Internal Purchase Receipt
-		from erpnext.controllers.status_updater import OverAllowanceError
 		from erpnext.stock.doctype.delivery_note.delivery_note import make_inter_company_purchase_receipt
 
 		pr = make_inter_company_purchase_receipt(dn.name)
@@ -2200,9 +2186,9 @@
 		gl_entries = get_gl_entries(pr_return.doctype, pr_return.name)
 
 		# Test - 1: SLE Stock Value Difference should be equal to Qty * Average Rate
-		average_rate = (
-			(se.items[0].qty * se.items[0].basic_rate) + (pr.items[0].qty * pr.items[0].rate)
-		) / (se.items[0].qty + pr.items[0].qty)
+		average_rate = ((se.items[0].qty * se.items[0].basic_rate) + (pr.items[0].qty * pr.items[0].rate)) / (
+			se.items[0].qty + pr.items[0].qty
+		)
 		expected_stock_value_difference = pr_return.items[0].qty * average_rate
 		self.assertEqual(
 			flt(sl_entries[0].stock_value_difference, 2), flt(expected_stock_value_difference, 2)
@@ -2344,7 +2330,7 @@
 			do_not_save=1,
 		)
 
-		for i in range(9):
+		for _i in range(9):
 			pr.append(
 				"items",
 				{
@@ -2384,7 +2370,7 @@
 			do_not_save=1,
 		)
 
-		for i in range(9):
+		for _i in range(9):
 			pr.append(
 				"items",
 				{
@@ -2678,7 +2664,9 @@
 				self.assertEqual(row.rate, 250.0)
 				serial_nos = get_serial_nos_from_bundle(row.serial_and_batch_bundle)
 				for sn in serial_nos:
-					serial_no_details = frappe.db.get_value("Serial No", sn, ["status", "warehouse"], as_dict=1)
+					serial_no_details = frappe.db.get_value(
+						"Serial No", sn, ["status", "warehouse"], as_dict=1
+					)
 					self.assertTrue(serial_no_details.status == "Active")
 					self.assertEqual(serial_no_details.warehouse, "Work In Progress - TCP1")
 
@@ -2815,7 +2803,9 @@
 				self.assertEqual(row.rate, 250.0)
 				serial_nos = get_serial_nos_from_bundle(row.serial_and_batch_bundle)
 				for sn in serial_nos:
-					serial_no_details = frappe.db.get_value("Serial No", sn, ["status", "warehouse"], as_dict=1)
+					serial_no_details = frappe.db.get_value(
+						"Serial No", sn, ["status", "warehouse"], as_dict=1
+					)
 					self.assertTrue(serial_no_details.status == "Active")
 					self.assertEqual(serial_no_details.warehouse, "Work In Progress - TCP1")
 
@@ -2890,7 +2880,6 @@
 
 
 def get_taxes(**args):
-
 	args = frappe._dict(args)
 
 	return [
@@ -3035,14 +3024,13 @@
 			"rejected_warehouse": args.rejected_warehouse or "_Test Rejected Warehouse - _TC"
 			if rejected_qty != 0
 			else "",
-			"rate": args.rate if args.rate != None else 50,
+			"rate": args.rate if args.rate is not None else 50,
 			"conversion_factor": args.conversion_factor or 1.0,
 			"stock_qty": flt(qty) * (flt(args.conversion_factor) or 1.0),
 			"serial_and_batch_bundle": bundle_id,
 			"stock_uom": args.stock_uom or "_Test UOM",
 			"uom": uom,
-			"cost_center": args.cost_center
-			or frappe.get_cached_value("Company", pr.company, "cost_center"),
+			"cost_center": args.cost_center or frappe.get_cached_value("Company", pr.company, "cost_center"),
 			"asset_location": args.location or "Test Location",
 			"use_serial_batch_fields": args.use_serial_batch_fields or 0,
 			"serial_no": args.serial_no if args.use_serial_batch_fields else "",
diff --git a/erpnext/stock/doctype/putaway_rule/putaway_rule.py b/erpnext/stock/doctype/putaway_rule/putaway_rule.py
index 7ed6923..923c34e 100644
--- a/erpnext/stock/doctype/putaway_rule/putaway_rule.py
+++ b/erpnext/stock/doctype/putaway_rule/putaway_rule.py
@@ -128,9 +128,7 @@
 			updated_table = add_row(item, pending_qty, source_warehouse or item.warehouse, updated_table)
 			continue
 
-		at_capacity, rules = get_ordered_putaway_rules(
-			item_code, company, source_warehouse=source_warehouse
-		)
+		at_capacity, rules = get_ordered_putaway_rules(item_code, company, source_warehouse=source_warehouse)
 
 		if not rules:
 			warehouse = source_warehouse or item.get("warehouse")
@@ -221,7 +219,7 @@
 	new_sorted = sorted(new, key=sort_key)
 
 	# Once sorted by all relevant keys both tables should align if they are same.
-	for old_item, new_item in zip(old_sorted, new_sorted):
+	for old_item, new_item in zip(old_sorted, new_sorted, strict=False):
 		for key in compare_keys:
 			if old_item.get(key) != new_item.get(key):
 				return True
@@ -270,9 +268,7 @@
 
 	if item.doctype == "Stock Entry Detail":
 		new_updated_table_row.t_warehouse = warehouse
-		new_updated_table_row.transfer_qty = flt(to_allocate) * flt(
-			new_updated_table_row.conversion_factor
-		)
+		new_updated_table_row.transfer_qty = flt(to_allocate) * flt(new_updated_table_row.conversion_factor)
 	else:
 		new_updated_table_row.stock_qty = flt(to_allocate) * flt(new_updated_table_row.conversion_factor)
 		new_updated_table_row.warehouse = warehouse
@@ -294,23 +290,19 @@
 
 	for entry in items_not_accomodated:
 		item_link = frappe.utils.get_link_to_form("Item", entry[0])
-		formatted_item_rows += """
-			<td>{0}</td>
-			<td>{1}</td>
-		</tr>""".format(
-			item_link, frappe.bold(entry[1])
-		)
+		formatted_item_rows += f"""
+			<td>{item_link}</td>
+			<td>{frappe.bold(entry[1])}</td>
+		</tr>"""
 
 	msg += """
 		<table class="table">
 			<thead>
-				<td>{0}</td>
-				<td>{1}</td>
+				<td>{}</td>
+				<td>{}</td>
 			</thead>
-			{2}
+			{}
 		</table>
-	""".format(
-		_("Item"), _("Unassigned Qty"), formatted_item_rows
-	)
+	""".format(_("Item"), _("Unassigned Qty"), formatted_item_rows)
 
 	frappe.msgprint(msg, title=_("Insufficient Capacity"), is_minimizable=True, wide=True)
diff --git a/erpnext/stock/doctype/putaway_rule/test_putaway_rule.py b/erpnext/stock/doctype/putaway_rule/test_putaway_rule.py
index f5bad51..9f7fdec 100644
--- a/erpnext/stock/doctype/putaway_rule/test_putaway_rule.py
+++ b/erpnext/stock/doctype/putaway_rule/test_putaway_rule.py
@@ -10,7 +10,6 @@
 from erpnext.stock.doctype.serial_and_batch_bundle.test_serial_and_batch_bundle import (
 	get_batch_from_bundle,
 	get_serial_nos_from_bundle,
-	make_serial_batch_bundle,
 )
 from erpnext.stock.doctype.stock_entry.test_stock_entry import make_stock_entry
 from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse
@@ -51,9 +50,7 @@
 
 	def test_putaway_rules_priority(self):
 		"""Test if rule is applied by priority, irrespective of free space."""
-		rule_1 = create_putaway_rule(
-			item_code="_Rice", warehouse=self.warehouse_1, capacity=200, uom="Kg"
-		)
+		rule_1 = create_putaway_rule(item_code="_Rice", warehouse=self.warehouse_1, capacity=200, uom="Kg")
 		rule_2 = create_putaway_rule(
 			item_code="_Rice", warehouse=self.warehouse_2, capacity=300, uom="Kg", priority=2
 		)
@@ -74,17 +71,11 @@
 	def test_putaway_rules_with_same_priority(self):
 		"""Test if rule with more free space is applied,
 		among two rules with same priority and capacity."""
-		rule_1 = create_putaway_rule(
-			item_code="_Rice", warehouse=self.warehouse_1, capacity=500, uom="Kg"
-		)
-		rule_2 = create_putaway_rule(
-			item_code="_Rice", warehouse=self.warehouse_2, capacity=500, uom="Kg"
-		)
+		rule_1 = create_putaway_rule(item_code="_Rice", warehouse=self.warehouse_1, capacity=500, uom="Kg")
+		rule_2 = create_putaway_rule(item_code="_Rice", warehouse=self.warehouse_2, capacity=500, uom="Kg")
 
 		# out of 500 kg capacity, occupy 100 kg in warehouse_1
-		stock_receipt = make_stock_entry(
-			item_code="_Rice", target=self.warehouse_1, qty=100, basic_rate=50
-		)
+		stock_receipt = make_stock_entry(item_code="_Rice", target=self.warehouse_1, qty=100, basic_rate=50)
 
 		pr = make_purchase_receipt(item_code="_Rice", qty=700, apply_putaway_rule=1, do_not_submit=1)
 		self.assertEqual(len(pr.items), 2)
@@ -102,12 +93,8 @@
 
 	def test_putaway_rules_with_insufficient_capacity(self):
 		"""Test if qty exceeding capacity, is handled."""
-		rule_1 = create_putaway_rule(
-			item_code="_Rice", warehouse=self.warehouse_1, capacity=100, uom="Kg"
-		)
-		rule_2 = create_putaway_rule(
-			item_code="_Rice", warehouse=self.warehouse_2, capacity=200, uom="Kg"
-		)
+		rule_1 = create_putaway_rule(item_code="_Rice", warehouse=self.warehouse_1, capacity=100, uom="Kg")
+		rule_2 = create_putaway_rule(item_code="_Rice", warehouse=self.warehouse_2, capacity=200, uom="Kg")
 
 		pr = make_purchase_receipt(item_code="_Rice", qty=350, apply_putaway_rule=1, do_not_submit=1)
 		self.assertEqual(len(pr.items), 2)
@@ -128,19 +115,13 @@
 			item.append("uoms", {"uom": "Bag", "conversion_factor": 1000})
 			item.save()
 
-		rule_1 = create_putaway_rule(
-			item_code="_Rice", warehouse=self.warehouse_1, capacity=3, uom="Bag"
-		)
+		rule_1 = create_putaway_rule(item_code="_Rice", warehouse=self.warehouse_1, capacity=3, uom="Bag")
 		self.assertEqual(rule_1.stock_capacity, 3000)
-		rule_2 = create_putaway_rule(
-			item_code="_Rice", warehouse=self.warehouse_2, capacity=4, uom="Bag"
-		)
+		rule_2 = create_putaway_rule(item_code="_Rice", warehouse=self.warehouse_2, capacity=4, uom="Bag")
 		self.assertEqual(rule_2.stock_capacity, 4000)
 
 		# populate 'Rack 1' with 1 Bag, making the free space 2 Bags
-		stock_receipt = make_stock_entry(
-			item_code="_Rice", target=self.warehouse_1, qty=1000, basic_rate=50
-		)
+		stock_receipt = make_stock_entry(item_code="_Rice", target=self.warehouse_1, qty=1000, basic_rate=50)
 
 		pr = make_purchase_receipt(
 			item_code="_Rice",
@@ -172,9 +153,7 @@
 		frappe.db.set_value("UOM", "Bag", "must_be_whole_number", 1)
 
 		# Putaway Rule in different UOM
-		rule_1 = create_putaway_rule(
-			item_code="_Rice", warehouse=self.warehouse_1, capacity=1, uom="Bag"
-		)
+		rule_1 = create_putaway_rule(item_code="_Rice", warehouse=self.warehouse_1, capacity=1, uom="Bag")
 		self.assertEqual(rule_1.stock_capacity, 1000)
 		# Putaway Rule in Stock UOM
 		rule_2 = create_putaway_rule(item_code="_Rice", warehouse=self.warehouse_2, capacity=500)
@@ -204,9 +183,7 @@
 
 	def test_putaway_rules_with_reoccurring_item(self):
 		"""Test rules on same item entered multiple times with different rate."""
-		rule_1 = create_putaway_rule(
-			item_code="_Rice", warehouse=self.warehouse_1, capacity=200, uom="Kg"
-		)
+		rule_1 = create_putaway_rule(item_code="_Rice", warehouse=self.warehouse_1, capacity=200, uom="Kg")
 		# total capacity is 200 Kg
 
 		pr = make_purchase_receipt(item_code="_Rice", qty=100, apply_putaway_rule=1, do_not_submit=1)
@@ -242,9 +219,7 @@
 
 	def test_validate_over_receipt_in_warehouse(self):
 		"""Test if overreceipt is blocked in the presence of putaway rules."""
-		rule_1 = create_putaway_rule(
-			item_code="_Rice", warehouse=self.warehouse_1, capacity=200, uom="Kg"
-		)
+		rule_1 = create_putaway_rule(item_code="_Rice", warehouse=self.warehouse_1, capacity=200, uom="Kg")
 
 		pr = make_purchase_receipt(item_code="_Rice", qty=300, apply_putaway_rule=1, do_not_submit=1)
 		self.assertEqual(len(pr.items), 1)
@@ -296,9 +271,7 @@
 
 	def test_putaway_rule_on_stock_entry_material_transfer_reoccuring_item(self):
 		"""Test if reoccuring item is correctly considered."""
-		rule_1 = create_putaway_rule(
-			item_code="_Rice", warehouse=self.warehouse_1, capacity=300, uom="Kg"
-		)
+		rule_1 = create_putaway_rule(item_code="_Rice", warehouse=self.warehouse_1, capacity=300, uom="Kg")
 		rule_2 = create_putaway_rule(
 			item_code="_Rice", warehouse=self.warehouse_2, capacity=600, uom="Kg", priority=2
 		)
@@ -440,9 +413,7 @@
 		rule_1 = create_putaway_rule(
 			item_code="_Rice", warehouse=self.warehouse_1, capacity=200, uom="Kg"
 		)  # more capacity
-		rule_2 = create_putaway_rule(
-			item_code="_Rice", warehouse=self.warehouse_2, capacity=100, uom="Kg"
-		)
+		rule_2 = create_putaway_rule(item_code="_Rice", warehouse=self.warehouse_2, capacity=100, uom="Kg")
 
 		stock_entry = make_stock_entry(
 			item_code="_Rice",
@@ -492,9 +463,7 @@
 	putaway.capacity = args.capacity or 1
 	putaway.stock_uom = frappe.db.get_value("Item", putaway.item_code, "stock_uom")
 	putaway.uom = args.uom or putaway.stock_uom
-	putaway.conversion_factor = get_conversion_factor(putaway.item_code, putaway.uom)[
-		"conversion_factor"
-	]
+	putaway.conversion_factor = get_conversion_factor(putaway.item_code, putaway.uom)["conversion_factor"]
 
 	if not args.do_not_save:
 		putaway.save()
diff --git a/erpnext/stock/doctype/quality_inspection/quality_inspection.py b/erpnext/stock/doctype/quality_inspection/quality_inspection.py
index 8816341..536a88f 100644
--- a/erpnext/stock/doctype/quality_inspection/quality_inspection.py
+++ b/erpnext/stock/doctype/quality_inspection/quality_inspection.py
@@ -125,13 +125,11 @@
 		if self.reference_type == "Job Card":
 			if self.reference_name:
 				frappe.db.sql(
-					"""
-					UPDATE `tab{doctype}`
+					f"""
+					UPDATE `tab{self.reference_type}`
 					SET quality_inspection = %s, modified = %s
 					WHERE name = %s and production_item = %s
-				""".format(
-						doctype=self.reference_type
-					),
+				""",
 					(quality_inspection, self.modified, self.reference_name, self.item_code),
 				)
 
@@ -153,9 +151,9 @@
 					args.append(self.name)
 
 				frappe.db.sql(
-					"""
+					f"""
 					UPDATE
-						`tab{child_doc}` t1, `tab{parent_doc}` t2
+						`tab{doctype}` t1, `tab{self.reference_type}` t2
 					SET
 						t1.quality_inspection = %s, t2.modified = %s
 					WHERE
@@ -163,9 +161,7 @@
 						and t1.item_code = %s
 						and t1.parent = t2.name
 						{conditions}
-				""".format(
-						parent_doc=self.reference_type, child_doc=doctype, conditions=conditions
-					),
+				""",
 					args,
 				)
 
@@ -203,7 +199,9 @@
 			reading_value = reading.get("reading_" + str(i))
 			if reading_value is not None and reading_value.strip():
 				result = (
-					flt(reading.get("min_value")) <= parse_float(reading_value) <= flt(reading.get("max_value"))
+					flt(reading.get("min_value"))
+					<= parse_float(reading_value)
+					<= flt(reading.get("max_value"))
 				)
 				if not result:
 					return False
@@ -225,9 +223,9 @@
 		except NameError as e:
 			field = frappe.bold(e.args[0].split()[1])
 			frappe.throw(
-				_("Row #{0}: {1} is not a valid reading field. Please refer to the field description.").format(
-					reading.idx, field
-				),
+				_(
+					"Row #{0}: {1} is not a valid reading field. Please refer to the field description."
+				).format(reading.idx, field),
 				title=_("Invalid Formula"),
 			)
 		except Exception:
@@ -296,40 +294,26 @@
 			qi_condition = ""
 
 		return frappe.db.sql(
-			"""
+			f"""
 				SELECT item_code
-				FROM `tab{doc}`
+				FROM `tab{from_doctype}`
 				WHERE parent=%(parent)s and docstatus < 2 and item_code like %(txt)s
 				{qi_condition} {cond} {mcond}
-				ORDER BY item_code limit {page_len} offset {start}
-			""".format(
-				doc=from_doctype,
-				cond=cond,
-				mcond=mcond,
-				start=cint(start),
-				page_len=cint(page_len),
-				qi_condition=qi_condition,
-			),
+				ORDER BY item_code limit {cint(page_len)} offset {cint(start)}
+			""",
 			{"parent": filters.get("parent"), "txt": "%%%s%%" % txt},
 		)
 
 	elif filters.get("reference_name"):
 		return frappe.db.sql(
-			"""
+			f"""
 				SELECT production_item
-				FROM `tab{doc}`
+				FROM `tab{from_doctype}`
 				WHERE name = %(reference_name)s and docstatus < 2 and production_item like %(txt)s
 				{qi_condition} {cond} {mcond}
 				ORDER BY production_item
-				limit {page_len} offset {start}
-			""".format(
-				doc=from_doctype,
-				cond=cond,
-				mcond=mcond,
-				start=cint(start),
-				page_len=cint(page_len),
-				qi_condition=qi_condition,
-			),
+				limit {cint(page_len)} offset {cint(start)}
+			""",
 			{"reference_name": filters.get("reference_name"), "txt": "%%%s%%" % txt},
 		)
 
diff --git a/erpnext/stock/doctype/quality_inspection/test_quality_inspection.py b/erpnext/stock/doctype/quality_inspection/test_quality_inspection.py
index c423ca8..f59d7c3 100644
--- a/erpnext/stock/doctype/quality_inspection/test_quality_inspection.py
+++ b/erpnext/stock/doctype/quality_inspection/test_quality_inspection.py
@@ -159,9 +159,7 @@
 			do_not_submit=True,
 		)
 
-		readings = [
-			{"specification": "Iron Content", "min_value": 0.1, "max_value": 0.9, "reading_1": "1.0"}
-		]
+		readings = [{"specification": "Iron Content", "min_value": 0.1, "max_value": 0.9, "reading_1": "1.0"}]
 
 		qa = create_quality_inspection(
 			reference_type="Stock Entry", reference_name=se.name, readings=readings, status="Rejected"
diff --git a/erpnext/stock/doctype/quick_stock_balance/quick_stock_balance.py b/erpnext/stock/doctype/quick_stock_balance/quick_stock_balance.py
index 34fb68c..7b7bffe 100644
--- a/erpnext/stock/doctype/quick_stock_balance/quick_stock_balance.py
+++ b/erpnext/stock/doctype/quick_stock_balance/quick_stock_balance.py
@@ -35,17 +35,13 @@
 def get_stock_item_details(warehouse, date, item=None, barcode=None):
 	out = {}
 	if barcode:
-		out["item"] = frappe.db.get_value(
-			"Item Barcode", filters={"barcode": barcode}, fieldname=["parent"]
-		)
+		out["item"] = frappe.db.get_value("Item Barcode", filters={"barcode": barcode}, fieldname=["parent"])
 		if not out["item"]:
 			frappe.throw(_("Invalid Barcode. There is no Item attached to this barcode."))
 	else:
 		out["item"] = item
 
-	barcodes = frappe.db.get_values(
-		"Item Barcode", filters={"parent": out["item"]}, fieldname=["barcode"]
-	)
+	barcodes = frappe.db.get_values("Item Barcode", filters={"parent": out["item"]}, fieldname=["barcode"])
 
 	out["barcodes"] = [x[0] for x in barcodes]
 	out["qty"] = get_stock_balance(out["item"], warehouse, date)
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 4ad3237..73778e3 100644
--- a/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py
+++ b/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py
@@ -144,15 +144,12 @@
 		if not acc_settings.acc_frozen_upto:
 			return
 		if getdate(self.posting_date) <= getdate(acc_settings.acc_frozen_upto):
-			if (
+			if acc_settings.frozen_accounts_modifier and frappe.session.user in get_users_with_role(
 				acc_settings.frozen_accounts_modifier
-				and frappe.session.user in get_users_with_role(acc_settings.frozen_accounts_modifier)
 			):
 				frappe.msgprint(_("Caution: This might alter frozen accounts."))
 				return
-			frappe.throw(
-				_("You cannot repost item valuation before {}").format(acc_settings.acc_frozen_upto)
-			)
+			frappe.throw(_("You cannot repost item valuation before {}").format(acc_settings.acc_frozen_upto))
 
 	def reset_field_values(self):
 		if self.based_on == "Transaction":
diff --git a/erpnext/stock/doctype/repost_item_valuation/test_repost_item_valuation.py b/erpnext/stock/doctype/repost_item_valuation/test_repost_item_valuation.py
index 950b436..7aa2fc3 100644
--- a/erpnext/stock/doctype/repost_item_valuation/test_repost_item_valuation.py
+++ b/erpnext/stock/doctype/repost_item_valuation/test_repost_item_valuation.py
@@ -175,7 +175,6 @@
 		riv3.set_status("Skipped")
 
 	def test_stock_freeze_validation(self):
-
 		today = nowdate()
 
 		riv = frappe.get_doc(
diff --git a/erpnext/stock/doctype/serial_and_batch_bundle/serial_and_batch_bundle.py b/erpnext/stock/doctype/serial_and_batch_bundle/serial_and_batch_bundle.py
index 58971e8..1ae34d0 100644
--- a/erpnext/stock/doctype/serial_and_batch_bundle/serial_and_batch_bundle.py
+++ b/erpnext/stock/doctype/serial_and_batch_bundle/serial_and_batch_bundle.py
@@ -4,7 +4,6 @@
 import collections
 import csv
 from collections import Counter, defaultdict
-from typing import Dict, List
 
 import frappe
 from frappe import _, _dict, bold
@@ -149,9 +148,7 @@
 			serial_no_warehouse[data.serial_no] = data.warehouse
 
 		for serial_no in serial_nos:
-			if (
-				not serial_no_warehouse.get(serial_no) or serial_no_warehouse.get(serial_no) != self.warehouse
-			):
+			if not serial_no_warehouse.get(serial_no) or serial_no_warehouse.get(serial_no) != self.warehouse:
 				self.throw_error_message(
 					f"Serial No {bold(serial_no)} is not present in the warehouse {bold(self.warehouse)}.",
 					SerialNoWarehouseError,
@@ -229,9 +226,7 @@
 	def get_serial_nos(self):
 		return [d.serial_no for d in self.entries if d.serial_no]
 
-	def set_incoming_rate_for_outward_transaction(
-		self, row=None, save=False, allow_negative_stock=False
-	):
+	def set_incoming_rate_for_outward_transaction(self, row=None, save=False, allow_negative_stock=False):
 		sle = self.get_sle_for_outward_transaction()
 
 		if self.has_serial_no:
@@ -352,14 +347,10 @@
 		if not self.voucher_detail_no or self.voucher_detail_no != row.name:
 			values_to_set["voucher_detail_no"] = row.name
 
-		if parent.get("posting_date") and (
-			not self.posting_date or self.posting_date != parent.posting_date
-		):
+		if parent.get("posting_date") and (not self.posting_date or self.posting_date != parent.posting_date):
 			values_to_set["posting_date"] = parent.posting_date or today()
 
-		if parent.get("posting_time") and (
-			not self.posting_time or self.posting_time != parent.posting_time
-		):
+		if parent.get("posting_time") and (not self.posting_time or self.posting_time != parent.posting_time):
 			values_to_set["posting_time"] = parent.posting_time
 
 		if parent.doctype in [
@@ -441,9 +432,9 @@
 		parent = frappe.qb.DocType("Serial and Batch Bundle")
 		child = frappe.qb.DocType("Serial and Batch Entry")
 
-		timestamp_condition = CombineDatetime(
-			parent.posting_date, parent.posting_time
-		) > CombineDatetime(self.posting_date, self.posting_time)
+		timestamp_condition = CombineDatetime(parent.posting_date, parent.posting_time) > CombineDatetime(
+			self.posting_date, self.posting_time
+		)
 
 		future_entries = (
 			frappe.qb.from_(parent)
@@ -615,7 +606,6 @@
 				)
 
 	def validate_incorrect_serial_nos(self, serial_nos):
-
 		if self.voucher_type == "Stock Entry" and self.voucher_no:
 			if frappe.get_cached_value("Stock Entry", self.voucher_no, "purpose") == "Repack":
 				return
@@ -942,7 +932,7 @@
 	serial_nos = []
 	batch_nos = []
 
-	with open(file_path, "r") as f:
+	with open(file_path) as f:
 		reader = csv.reader(f)
 		serial_nos, batch_nos = parse_csv_file_to_get_serial_batch(reader)
 
@@ -1217,10 +1207,7 @@
 def create_serial_batch_no_ledgers(
 	entries, child_row, parent_doc, warehouse=None, do_not_save=False
 ) -> object:
-
-	warehouse = warehouse or (
-		child_row.rejected_warehouse if child_row.is_rejected else child_row.warehouse
-	)
+	warehouse = warehouse or (child_row.rejected_warehouse if child_row.is_rejected else child_row.warehouse)
 
 	type_of_transaction = get_type_of_transaction(parent_doc, child_row)
 	if parent_doc.get("doctype") == "Stock Entry":
@@ -1706,9 +1693,7 @@
 	reserved_batches_details = frappe._dict()
 	if data:
 		reserved_batches_details = frappe._dict(
-			{
-				(d.batch_no, d.warehouse): frappe._dict({"warehouse": d.warehouse, "qty": d.qty}) for d in data
-			}
+			{(d.batch_no, d.warehouse): frappe._dict({"warehouse": d.warehouse, "qty": d.qty}) for d in data}
 		)
 
 	return reserved_batches_details
@@ -1856,7 +1841,7 @@
 
 
 # For work order and subcontracting
-def get_voucher_wise_serial_batch_from_bundle(**kwargs) -> Dict[str, Dict]:
+def get_voucher_wise_serial_batch_from_bundle(**kwargs) -> dict[str, dict]:
 	data = get_ledgers_from_serial_batch_bundle(**kwargs)
 	if not data:
 		return {}
@@ -1984,7 +1969,7 @@
 	return [row.serial_no for row in data if row.serial_no]
 
 
-def get_ledgers_from_serial_batch_bundle(**kwargs) -> List[frappe._dict]:
+def get_ledgers_from_serial_batch_bundle(**kwargs) -> list[frappe._dict]:
 	bundle_table = frappe.qb.DocType("Serial and Batch Bundle")
 	serial_batch_table = frappe.qb.DocType("Serial and Batch Entry")
 
@@ -2045,7 +2030,7 @@
 			stock_ledger_entry.serial_no,
 			stock_ledger_entry.serial_and_batch_bundle,
 		)
-		.where((stock_ledger_entry.is_cancelled == 0))
+		.where(stock_ledger_entry.is_cancelled == 0)
 	)
 
 	if kwargs.get("posting_date"):
diff --git a/erpnext/stock/doctype/serial_and_batch_bundle/test_serial_and_batch_bundle.py b/erpnext/stock/doctype/serial_and_batch_bundle/test_serial_and_batch_bundle.py
index 826ac03..5f75b40 100644
--- a/erpnext/stock/doctype/serial_and_batch_bundle/test_serial_and_batch_bundle.py
+++ b/erpnext/stock/doctype/serial_and_batch_bundle/test_serial_and_batch_bundle.py
@@ -650,7 +650,7 @@
 
 	batches = get_batch_nos(bundle)
 
-	return list(batches.keys())[0]
+	return next(iter(batches.keys()))
 
 
 def get_serial_nos_from_bundle(bundle):
diff --git a/erpnext/stock/doctype/serial_no/serial_no.py b/erpnext/stock/doctype/serial_no/serial_no.py
index 5f4f393..4c693d8 100644
--- a/erpnext/stock/doctype/serial_no/serial_no.py
+++ b/erpnext/stock/doctype/serial_no/serial_no.py
@@ -3,7 +3,6 @@
 
 
 import json
-from typing import List, Optional, Union
 
 import frappe
 from frappe import ValidationError, _
@@ -47,9 +46,7 @@
 		item_group: DF.Link | None
 		item_name: DF.Data | None
 		location: DF.Link | None
-		maintenance_status: DF.Literal[
-			"", "Under Warranty", "Out of Warranty", "Under AMC", "Out of AMC"
-		]
+		maintenance_status: DF.Literal["", "Under Warranty", "Out of Warranty", "Under AMC", "Out of AMC"]
 		purchase_document_no: DF.Data | None
 		purchase_rate: DF.Float
 		serial_no: DF.Data
@@ -61,7 +58,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(SerialNo, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 		self.via_stock_ledger = False
 
 	def validate(self):
@@ -121,9 +118,9 @@
 			)
 
 
-def get_available_serial_nos(serial_no_series, qty) -> List[str]:
+def get_available_serial_nos(serial_no_series, qty) -> list[str]:
 	serial_nos = []
-	for i in range(cint(qty)):
+	for _i in range(cint(qty)):
 		serial_nos.append(get_new_serial_number(serial_no_series))
 
 	return serial_nos
@@ -138,13 +135,11 @@
 
 def get_items_html(serial_nos, item_code):
 	body = ", ".join(serial_nos)
-	return """<details><summary>
-		<b>{0}:</b> {1} Serial Numbers <span class="caret"></span>
+	return f"""<details><summary>
+		<b>{item_code}:</b> {len(serial_nos)} Serial Numbers <span class="caret"></span>
 	</summary>
-	<div class="small">{2}</div></details>
-	""".format(
-		item_code, len(serial_nos), body
-	)
+	<div class="small">{body}</div></details>
+	"""
 
 
 def get_serial_nos(serial_no):
@@ -177,11 +172,9 @@
 def get_delivery_note_serial_no(item_code, qty, delivery_note):
 	serial_nos = ""
 	dn_serial_nos = frappe.db.sql_list(
-		""" select name from `tabSerial No`
+		f""" select name from `tabSerial No`
 		where item_code = %(item_code)s and delivery_document_no = %(delivery_note)s
-		and sales_invoice is null limit {0}""".format(
-			cint(qty)
-		),
+		and sales_invoice is null limit {cint(qty)}""",
 		{"item_code": item_code, "delivery_note": delivery_note},
 	)
 
@@ -196,12 +189,11 @@
 	qty: int,
 	item_code: str,
 	warehouse: str,
-	posting_date: Optional[str] = None,
-	batch_nos: Optional[Union[str, List[str]]] = None,
-	for_doctype: Optional[str] = None,
+	posting_date: str | None = None,
+	batch_nos: str | list[str] | None = None,
+	for_doctype: str | None = None,
 	exclude_sr_nos=None,
-) -> List[str]:
-
+) -> list[str]:
 	filters = frappe._dict({"item_code": item_code, "warehouse": warehouse})
 
 	if exclude_sr_nos is None:
diff --git a/erpnext/stock/doctype/serial_no/test_serial_no.py b/erpnext/stock/doctype/serial_no/test_serial_no.py
index 5a5c403..79291af 100644
--- a/erpnext/stock/doctype/serial_no/test_serial_no.py
+++ b/erpnext/stock/doctype/serial_no/test_serial_no.py
@@ -6,9 +6,8 @@
 
 
 import frappe
-from frappe import _, _dict
+from frappe import _dict
 from frappe.tests.utils import FrappeTestCase
-from frappe.utils import today
 
 from erpnext.stock.doctype.delivery_note.test_delivery_note import create_delivery_note
 from erpnext.stock.doctype.item.test_item import make_item
@@ -16,10 +15,8 @@
 from erpnext.stock.doctype.serial_and_batch_bundle.test_serial_and_batch_bundle import (
 	get_batch_from_bundle,
 	get_serial_nos_from_bundle,
-	make_serial_batch_bundle,
 )
 from erpnext.stock.doctype.serial_no.serial_no import *
-from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
 from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
 from erpnext.stock.doctype.stock_entry.test_stock_entry import make_serialized_item
 from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse
@@ -53,9 +50,7 @@
 		se = make_serialized_item(target_warehouse="_Test Warehouse - _TC")
 		serial_nos = get_serial_nos_from_bundle(se.get("items")[0].serial_and_batch_bundle)
 
-		dn = create_delivery_note(
-			item_code="_Test Serialized Item With Series", qty=1, serial_no=[serial_nos[0]]
-		)
+		create_delivery_note(item_code="_Test Serialized Item With Series", qty=1, serial_no=[serial_nos[0]])
 
 		serial_no = frappe.get_doc("Serial No", serial_nos[0])
 
@@ -63,7 +58,7 @@
 		self.assertEqual(serial_no.warehouse, None)
 
 		wh = create_warehouse("_Test Warehouse", company="_Test Company 1")
-		pr = make_purchase_receipt(
+		make_purchase_receipt(
 			item_code="_Test Serialized Item With Series",
 			qty=1,
 			serial_no=[serial_nos[0]],
@@ -118,7 +113,7 @@
 		self.assertRaises(frappe.ValidationError, dn.cancel)
 
 		# deliver from second company
-		dn_2 = create_delivery_note(
+		create_delivery_note(
 			item_code="_Test Serialized Item With Series",
 			qty=1,
 			serial_no=[serial_nos[0]],
@@ -201,16 +196,14 @@
 					{"doctype": "Serial No", "item_code": item_code, "serial_no": serial_no}
 				).insert()
 
-		in1 = make_stock_entry(
+		make_stock_entry(
 			item_code=item_code, to_warehouse=warehouse, qty=1, rate=42, serial_no=[serial_nos[0]]
 		)
-		in2 = make_stock_entry(
+		make_stock_entry(
 			item_code=item_code, to_warehouse=warehouse, qty=1, rate=113, serial_no=[serial_nos[1]]
 		)
 
-		out = create_delivery_note(
-			item_code=item_code, qty=1, serial_no=[serial_nos[0]], do_not_submit=True
-		)
+		out = create_delivery_note(item_code=item_code, qty=1, serial_no=[serial_nos[0]], do_not_submit=True)
 
 		bundle = out.items[0].serial_and_batch_bundle
 		doc = frappe.get_doc("Serial and Batch Bundle", bundle)
diff --git a/erpnext/stock/doctype/shipment/test_shipment.py b/erpnext/stock/doctype/shipment/test_shipment.py
index 726dff4..4d4eadc 100644
--- a/erpnext/stock/doctype/shipment/test_shipment.py
+++ b/erpnext/stock/doctype/shipment/test_shipment.py
@@ -76,9 +76,7 @@
 	shipment.description_of_content = "unit test entry"
 	for delivery_note in delivery_notes:
 		shipment.append("shipment_delivery_note", {"delivery_note": delivery_note.name})
-	shipment.append(
-		"shipment_parcel", {"length": 5, "width": 5, "height": 5, "weight": 5, "count": 5}
-	)
+	shipment.append("shipment_parcel", {"length": 5, "width": 5, "height": 5, "weight": 5, "count": 5})
 	shipment.insert()
 	return shipment
 
@@ -96,9 +94,7 @@
 
 def get_shipment_customer_address(customer_name):
 	address_title = customer_name + " address 123"
-	customer_address = frappe.get_all(
-		"Address", fields=["name"], filters={"address_title": address_title}
-	)
+	customer_address = frappe.get_all("Address", fields=["name"], filters={"address_title": address_title})
 	if len(customer_address):
 		return customer_address[0]
 	else:
@@ -160,9 +156,7 @@
 	customer.is_primary_contact = 1
 	customer.is_billing_contact = 1
 	customer.append("email_ids", {"email_id": "randomme@email.com", "is_primary": 1})
-	customer.append(
-		"phone_nos", {"phone": "123123123", "is_primary_phone": 1, "is_primary_mobile_no": 1}
-	)
+	customer.append("phone_nos", {"phone": "123123123", "is_primary_phone": 1, "is_primary_mobile_no": 1})
 	customer.status = "Passive"
 	customer.insert()
 	return customer
diff --git a/erpnext/stock/doctype/stock_entry/stock_entry.py b/erpnext/stock/doctype/stock_entry/stock_entry.py
index d2dab8a..9bb607c 100644
--- a/erpnext/stock/doctype/stock_entry/stock_entry.py
+++ b/erpnext/stock/doctype/stock_entry/stock_entry.py
@@ -4,7 +4,6 @@
 
 import json
 from collections import defaultdict
-from typing import List
 
 import frappe
 from frappe import _
@@ -147,7 +146,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(StockEntry, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 		if self.purchase_order:
 			self.subcontract_data = frappe._dict(
 				{
@@ -174,9 +173,7 @@
 	def before_validate(self):
 		from erpnext.stock.doctype.putaway_rule.putaway_rule import apply_putaway_rule
 
-		apply_rule = self.apply_putaway_rule and (
-			self.purpose in ["Material Transfer", "Material Receipt"]
-		)
+		apply_rule = self.apply_putaway_rule and (self.purpose in ["Material Transfer", "Material Receipt"])
 
 		if self.get("items") and apply_rule:
 			apply_putaway_rule(self.doctype, self.get("items"), self.company, purpose=self.purpose)
@@ -345,7 +342,11 @@
 		if self.purpose == "Send to Warehouse":
 			for d in frappe.get_all(
 				"Stock Entry",
-				filters={"docstatus": 0, "outgoing_stock_entry": self.name, "purpose": "Receive at Warehouse"},
+				filters={
+					"docstatus": 0,
+					"outgoing_stock_entry": self.name,
+					"purpose": "Receive at Warehouse",
+				},
 			):
 				frappe.delete_doc("Stock Entry", d.name)
 
@@ -487,7 +488,7 @@
 			return
 
 		precision = frappe.get_precision("Stock Entry Detail", "qty")
-		fg_item = list(fg_qty.keys())[0]
+		fg_item = next(iter(fg_qty.keys()))
 		fg_item_qty = flt(fg_qty[fg_item], precision)
 		fg_completed_qty = flt(self.fg_completed_qty, precision)
 
@@ -670,14 +671,13 @@
 			production_item, qty = frappe.db.get_value(
 				"Work Order", self.work_order, ["production_item", "qty"]
 			)
-			args = other_ste + [production_item]
+			args = [*other_ste, production_item]
 			fg_qty_already_entered = frappe.db.sql(
 				"""select sum(transfer_qty)
 				from `tabStock Entry Detail`
-				where parent in (%s)
-					and item_code = %s
-					and ifnull(s_warehouse,'')='' """
-				% (", ".join(["%s" * len(other_ste)]), "%s"),
+				where parent in ({})
+					and item_code = {}
+					and ifnull(s_warehouse,'')='' """.format(", ".join(["%s" * len(other_ste)]), "%s"),
 				args,
 			)[0][0]
 			if fg_qty_already_entered and fg_qty_already_entered >= qty:
@@ -758,9 +758,7 @@
 		Set rate for outgoing, scrapped and finished items
 		"""
 		# Set rate for outgoing items
-		outgoing_items_cost = self.set_rate_for_outgoing_items(
-			reset_outgoing_rate, raise_error_if_no_rate
-		)
+		outgoing_items_cost = self.set_rate_for_outgoing_items(reset_outgoing_rate, raise_error_if_no_rate)
 		finished_item_qty = sum(d.transfer_qty for d in self.items if d.is_finished_item)
 
 		items = []
@@ -867,7 +865,6 @@
 
 		if settings.material_consumption:
 			if settings.get_rm_cost_from_consumption_entry and self.work_order:
-
 				# Validate only if Material Consumption Entry exists for the Work Order.
 				if frappe.db.exists(
 					"Stock Entry",
@@ -879,7 +876,9 @@
 				):
 					for item in self.items:
 						if not item.is_finished_item and not item.is_scrap_item:
-							label = frappe.get_meta(settings.doctype).get_label("get_rm_cost_from_consumption_entry")
+							label = frappe.get_meta(settings.doctype).get_label(
+								"get_rm_cost_from_consumption_entry"
+							)
 							frappe.throw(
 								_(
 									"Row {0}: As {1} is enabled, raw materials cannot be added to {2} entry. Use {3} entry to consume raw materials."
@@ -892,7 +891,8 @@
 							)
 
 					if frappe.db.exists(
-						"Stock Entry", {"docstatus": 1, "work_order": self.work_order, "purpose": "Manufacture"}
+						"Stock Entry",
+						{"docstatus": 1, "work_order": self.work_order, "purpose": "Manufacture"},
 					):
 						frappe.throw(
 							_("Only one {0} entry can be created against the Work Order {1}").format(
@@ -1060,13 +1060,17 @@
 				item_code = se_item.original_item or se_item.item_code
 				precision = cint(frappe.db.get_default("float_precision")) or 3
 				required_qty = sum(
-					[flt(d.required_qty) for d in subcontract_order.supplied_items if d.rm_item_code == item_code]
+					[
+						flt(d.required_qty)
+						for d in subcontract_order.supplied_items
+						if d.rm_item_code == item_code
+					]
 				)
 
 				total_allowed = required_qty + (required_qty * (qty_allowance / 100))
 
 				if not required_qty:
-					bom_no = frappe.db.get_value(
+					frappe.db.get_value(
 						f"{self.subcontract_data.order_doctype} Item",
 						{
 							"parent": self.get(self.subcontract_data.order_field),
@@ -1112,7 +1116,10 @@
 						& (se.docstatus == 1)
 						& (se_detail.item_code == se_item.item_code)
 						& (
-							((se.purchase_order == self.purchase_order) & (se_detail.po_detail == se_item.po_detail))
+							(
+								(se.purchase_order == self.purchase_order)
+								& (se_detail.po_detail == se_item.po_detail)
+							)
 							if self.subcontract_data.order_doctype == "Purchase Order"
 							else (
 								(se.subcontracting_order == self.subcontracting_order)
@@ -1165,7 +1172,9 @@
 					else:
 						if not se_item.allow_alternative_item:
 							frappe.throw(
-								_("Row {0}# Item {1} not found in 'Raw Materials Supplied' table in {2} {3}").format(
+								_(
+									"Row {0}# Item {1} not found in 'Raw Materials Supplied' table in {2} {3}"
+								).format(
 									se_item.idx,
 									se_item.item_code,
 									self.subcontract_data.order_doctype,
@@ -1342,12 +1351,18 @@
 		for d in self.get("items"):
 			if cstr(d.s_warehouse):
 				sle = self.get_sl_entries(
-					d, {"warehouse": cstr(d.s_warehouse), "actual_qty": -flt(d.transfer_qty), "incoming_rate": 0}
+					d,
+					{
+						"warehouse": cstr(d.s_warehouse),
+						"actual_qty": -flt(d.transfer_qty),
+						"incoming_rate": 0,
+					},
 				)
 				if cstr(d.t_warehouse):
 					sle.dependant_sle_voucher_detail_no = d.name
 				elif finished_item_row and (
-					finished_item_row.item_code != d.item_code or finished_item_row.t_warehouse != d.s_warehouse
+					finished_item_row.item_code != d.item_code
+					or finished_item_row.t_warehouse != d.s_warehouse
 				):
 					sle.dependant_sle_voucher_detail_no = finished_item_row.name
 
@@ -1419,7 +1434,7 @@
 				sl_entries.append(sle)
 
 	def get_gl_entries(self, warehouse_account):
-		gl_entries = super(StockEntry, self).get_gl_entries(warehouse_account)
+		gl_entries = super().get_gl_entries(warehouse_account)
 
 		if self.purpose in ("Repack", "Manufacture"):
 			total_basic_amount = sum(flt(t.basic_amount) for t in self.get("items") if t.is_finished_item)
@@ -1452,9 +1467,9 @@
 					flt(t.amount * multiply_based_on) / divide_based_on
 				)
 
-				item_account_wise_additional_cost[(d.item_code, d.name)][t.expense_account]["base_amount"] += (
-					flt(t.base_amount * multiply_based_on) / divide_based_on
-				)
+				item_account_wise_additional_cost[(d.item_code, d.name)][t.expense_account][
+					"base_amount"
+				] += flt(t.base_amount * multiply_based_on) / divide_based_on
 
 		if item_account_wise_additional_cost:
 			for d in self.get("items"):
@@ -1486,7 +1501,9 @@
 								"cost_center": d.cost_center,
 								"remarks": self.get("remarks") or _("Accounting Entry for Stock"),
 								"credit": -1
-								* amount["base_amount"],  # put it as negative credit instead of debit purposefully
+								* amount[
+									"base_amount"
+								],  # put it as negative credit instead of debit purposefully
 							},
 							item=d,
 						)
@@ -1607,7 +1624,10 @@
 		):
 			subcontract_items = frappe.get_all(
 				self.subcontract_data.order_supplied_items_field,
-				{"parent": self.get(self.subcontract_data.order_field), "rm_item_code": args.get("item_code")},
+				{
+					"parent": self.get(self.subcontract_data.order_field),
+					"rm_item_code": args.get("item_code"),
+				},
 				"main_item_code",
 			)
 
@@ -1655,7 +1675,6 @@
 		)
 
 		if self.bom_no:
-
 			backflush_based_on = frappe.db.get_single_value(
 				"Manufacturing Settings", "backflush_raw_materials_based_on"
 			)
@@ -1669,7 +1688,6 @@
 				"Material Transfer for Manufacture",
 				"Material Consumption for Manufacture",
 			]:
-
 				if self.work_order and self.purpose == "Material Transfer for Manufacture":
 					item_dict = self.get_pending_raw_materials(backflush_based_on)
 					if self.to_warehouse and self.pro_doc:
@@ -1679,7 +1697,10 @@
 
 				elif (
 					self.work_order
-					and (self.purpose == "Manufacture" or self.purpose == "Material Consumption for Manufacture")
+					and (
+						self.purpose == "Manufacture"
+						or self.purpose == "Material Consumption for Manufacture"
+					)
 					and not self.pro_doc.skip_transfer
 					and self.flags.backflush_based_on == "Material Transferred for Manufacture"
 				):
@@ -1687,7 +1708,10 @@
 
 				elif (
 					self.work_order
-					and (self.purpose == "Manufacture" or self.purpose == "Material Consumption for Manufacture")
+					and (
+						self.purpose == "Manufacture"
+						or self.purpose == "Material Consumption for Manufacture"
+					)
 					and self.flags.backflush_based_on == "BOM"
 					and frappe.db.get_single_value("Manufacturing Settings", "material_consumption") == 1
 				):
@@ -1700,7 +1724,10 @@
 					item_dict = self.get_bom_raw_materials(self.fg_completed_qty)
 
 					# Get Subcontract Order Supplied Items Details
-					if self.get(self.subcontract_data.order_field) and self.purpose == "Send to Subcontractor":
+					if (
+						self.get(self.subcontract_data.order_field)
+						and self.purpose == "Send to Subcontractor"
+					):
 						# Get Subcontract Order Supplied Items Details
 						parent = frappe.qb.DocType(self.subcontract_data.order_doctype)
 						child = frappe.qb.DocType(self.subcontract_data.order_supplied_items_field)
@@ -1719,9 +1746,14 @@
 						if self.pro_doc and cint(self.pro_doc.from_wip_warehouse):
 							item["from_warehouse"] = self.pro_doc.wip_warehouse
 						# Get Reserve Warehouse from Subcontract Order
-						if self.get(self.subcontract_data.order_field) and self.purpose == "Send to Subcontractor":
+						if (
+							self.get(self.subcontract_data.order_field)
+							and self.purpose == "Send to Subcontractor"
+						):
 							item["from_warehouse"] = item_wh.get(item.item_code)
-						item["to_warehouse"] = self.to_warehouse if self.purpose == "Send to Subcontractor" else ""
+						item["to_warehouse"] = (
+							self.to_warehouse if self.purpose == "Send to Subcontractor" else ""
+						)
 
 					self.add_to_stock_entry_detail(item_dict)
 
@@ -1911,9 +1943,7 @@
 		from erpnext.manufacturing.doctype.bom.bom import get_bom_items_as_dict
 
 		if (
-			frappe.db.get_single_value(
-				"Manufacturing Settings", "set_op_cost_and_scrape_from_sub_assemblies"
-			)
+			frappe.db.get_single_value("Manufacturing Settings", "set_op_cost_and_scrape_from_sub_assemblies")
 			and self.work_order
 			and frappe.get_cached_value("Work Order", self.work_order, "use_multi_level_bom")
 		):
@@ -2070,7 +2100,7 @@
 		)
 
 		precision = frappe.get_precision("Stock Entry Detail", "qty")
-		for key, row in available_materials.items():
+		for _key, row in available_materials.items():
 			remaining_qty_to_produce = flt(wo_data.trans_qty) - flt(wo_data.produced_qty)
 			if remaining_qty_to_produce <= 0 and not self.is_return:
 				continue
@@ -2244,9 +2274,7 @@
 				continue
 
 			transfer_pending = flt(d.required_qty) > flt(d.transferred_qty)
-			can_transfer = transfer_pending or (
-				backflush_based_on == "Material Transferred for Manufacture"
-			)
+			can_transfer = transfer_pending or (backflush_based_on == "Material Transferred for Manufacture")
 
 			if not can_transfer:
 				continue
@@ -2261,7 +2289,9 @@
 					)
 					item_row["job_card_item"] = job_card_item or None
 
-				if d.source_warehouse and not frappe.db.get_value("Warehouse", d.source_warehouse, "is_group"):
+				if d.source_warehouse and not frappe.db.get_value(
+					"Warehouse", d.source_warehouse, "is_group"
+				):
 					item_row["from_warehouse"] = d.source_warehouse
 
 				item_row["to_warehouse"] = wip_warehouse
@@ -2318,9 +2348,9 @@
 				if item_row.get(field):
 					se_child.set(field, item_row.get(field))
 
-			if se_child.s_warehouse == None:
+			if se_child.s_warehouse is None:
 				se_child.s_warehouse = self.from_warehouse
-			if se_child.t_warehouse == None:
+			if se_child.t_warehouse is None:
 				se_child.t_warehouse = self.to_warehouse
 
 			# in stock uom
@@ -2376,15 +2406,20 @@
 						expiry_date = frappe.db.get_value("Batch", item.batch_no, "expiry_date")
 						if expiry_date:
 							if getdate(self.posting_date) > getdate(expiry_date):
-								frappe.throw(_("Batch {0} of Item {1} has expired.").format(item.batch_no, item.item_code))
+								frappe.throw(
+									_("Batch {0} of Item {1} has expired.").format(
+										item.batch_no, item.item_code
+									)
+								)
 					else:
-						frappe.throw(_("Batch {0} of Item {1} is disabled.").format(item.batch_no, item.item_code))
+						frappe.throw(
+							_("Batch {0} of Item {1} is disabled.").format(item.batch_no, item.item_code)
+						)
 
 	def update_subcontract_order_supplied_items(self):
 		if self.get(self.subcontract_data.order_field) and (
 			self.purpose in ["Send to Subcontractor", "Material Transfer"] or self.is_return
 		):
-
 			# Get Subcontract Order Supplied Items Details
 			order_supplied_items = frappe.db.get_all(
 				self.subcontract_data.order_supplied_items_field,
@@ -2449,8 +2484,8 @@
 
 			cond = ""
 			for data, transferred_qty in stock_entries.items():
-				cond += """ WHEN (parent = %s and name = %s) THEN %s
-					""" % (
+				cond += """ WHEN (parent = {} and name = {}) THEN {}
+					""".format(
 					frappe.db.escape(data[0]),
 					frappe.db.escape(data[1]),
 					transferred_qty,
@@ -2506,7 +2541,9 @@
 			material_request = item.material_request or None
 			if self.purpose == "Material Transfer" and material_request not in material_requests:
 				if self.outgoing_stock_entry and parent_se:
-					material_request = frappe.get_value("Stock Entry Detail", item.ste_detail, "material_request")
+					material_request = frappe.get_value(
+						"Stock Entry Detail", item.ste_detail, "material_request"
+					)
 
 			if material_request and material_request not in material_requests:
 				material_requests.append(material_request)
@@ -2543,7 +2580,7 @@
 					d.serial_and_batch_bundle = id
 					d.use_serial_batch_fields = 0
 
-	def get_available_serial_nos(self) -> List[str]:
+	def get_available_serial_nos(self) -> list[str]:
 		serial_nos = []
 		data = frappe.get_all(
 			"Serial No",
@@ -2738,9 +2775,7 @@
 			)
 		)
 	):
-		operating_cost_per_unit += flt(work_order.corrective_operation_cost) / flt(
-			work_order.produced_qty
-		)
+		operating_cost_per_unit += flt(work_order.corrective_operation_cost) / flt(work_order.produced_qty)
 
 	return operating_cost_per_unit
 
@@ -2753,24 +2788,20 @@
 	if subcontract_order:
 		cond = f"and ste.purpose = 'Send to Subcontractor' and ste.{subcontract_order_field} = '{subcontract_order}'"
 	elif work_order:
-		cond = "and ste.purpose = 'Material Transfer for Manufacture' and ste.work_order = '{0}'".format(
-			work_order
-		)
+		cond = f"and ste.purpose = 'Material Transfer for Manufacture' and ste.work_order = '{work_order}'"
 
 	if not cond:
 		return {}
 
 	used_alternative_items = {}
 	data = frappe.db.sql(
-		""" select sted.original_item, sted.uom, sted.conversion_factor,
+		f""" select sted.original_item, sted.uom, sted.conversion_factor,
 			sted.item_code, sted.item_name, sted.conversion_factor,sted.stock_uom, sted.description
 		from
 			`tabStock Entry` ste, `tabStock Entry Detail` sted
 		where
 			sted.parent = ste.name and ste.docstatus = 1 and sted.original_item !=  sted.item_code
-			{0} """.format(
-			cond
-		),
+			{cond} """,
 		as_dict=1,
 	)
 
@@ -2808,9 +2839,7 @@
 	conversion_factor = get_conversion_factor(item_code, uom).get("conversion_factor")
 
 	if not conversion_factor:
-		frappe.msgprint(
-			_("UOM conversion factor required for UOM: {0} in Item: {1}").format(uom, item_code)
-		)
+		frappe.msgprint(_("UOM conversion factor required for UOM: {0} in Item: {1}").format(uom, item_code))
 		ret = {"uom": ""}
 	else:
 		ret = {
@@ -2920,9 +2949,7 @@
 		else:
 			supplied_item.supplied_qty += row.transfer_qty
 
-		supplied_item.total_supplied_qty = flt(supplied_item.supplied_qty) - flt(
-			supplied_item.returned_qty
-		)
+		supplied_item.total_supplied_qty = flt(supplied_item.supplied_qty) - flt(supplied_item.returned_qty)
 
 	return supplied_item_details
 
@@ -3034,7 +3061,11 @@
 			& (stock_entry_detail.s_warehouse.isnotnull())
 			& (
 				stock_entry.purpose.isin(
-					["Manufacture", "Material Consumption for Manufacture", "Material Transfer for Manufacture"]
+					[
+						"Manufacture",
+						"Material Consumption for Manufacture",
+						"Material Transfer for Manufacture",
+					]
 				)
 			)
 		)
@@ -3086,7 +3117,6 @@
 		doc.has_batch_no = 1
 		batchwise_serial_nos = get_batchwise_serial_nos(child.item_code, row)
 		for batch_no, qty in row.batches_to_be_consume.items():
-
 			while qty > 0:
 				qty -= 1
 				doc.append(
diff --git a/erpnext/stock/doctype/stock_entry/stock_entry_utils.py b/erpnext/stock/doctype/stock_entry/stock_entry_utils.py
index 271cbbc..e5f4e73 100644
--- a/erpnext/stock/doctype/stock_entry/stock_entry_utils.py
+++ b/erpnext/stock/doctype/stock_entry/stock_entry_utils.py
@@ -2,7 +2,7 @@
 # See license.txt
 
 
-from typing import TYPE_CHECKING, Optional, overload
+from typing import TYPE_CHECKING, overload
 
 import frappe
 from frappe.utils import cint, flt
@@ -18,15 +18,15 @@
 	*,
 	item_code: str,
 	qty: float,
-	company: Optional[str] = None,
-	from_warehouse: Optional[str] = None,
-	to_warehouse: Optional[str] = None,
-	rate: Optional[float] = None,
-	serial_no: Optional[str] = None,
-	batch_no: Optional[str] = None,
-	posting_date: Optional[str] = None,
-	posting_time: Optional[str] = None,
-	purpose: Optional[str] = None,
+	company: str | None = None,
+	from_warehouse: str | None = None,
+	to_warehouse: str | None = None,
+	rate: float | None = None,
+	serial_no: str | None = None,
+	batch_no: str | None = None,
+	posting_date: str | None = None,
+	posting_time: str | None = None,
+	purpose: str | None = None,
 	do_not_save: bool = False,
 	do_not_submit: bool = False,
 	inspection_required: bool = False,
diff --git a/erpnext/stock/doctype/stock_entry/test_stock_entry.py b/erpnext/stock/doctype/stock_entry/test_stock_entry.py
index 01a43b3..c4ead57 100644
--- a/erpnext/stock/doctype/stock_entry/test_stock_entry.py
+++ b/erpnext/stock/doctype/stock_entry/test_stock_entry.py
@@ -5,7 +5,7 @@
 import frappe
 from frappe.permissions import add_user_permission, remove_user_permission
 from frappe.tests.utils import FrappeTestCase, change_settings
-from frappe.utils import add_days, add_to_date, flt, nowdate, nowtime, today
+from frappe.utils import add_days, flt, nowdate, nowtime, today
 
 from erpnext.accounts.doctype.account.test_account import get_inventory_account
 from erpnext.controllers.accounts_controller import InvalidQtyError
@@ -20,7 +20,7 @@
 	get_serial_nos_from_bundle,
 	make_serial_batch_bundle,
 )
-from erpnext.stock.doctype.serial_no.serial_no import *  # noqa
+from erpnext.stock.doctype.serial_no.serial_no import *
 from erpnext.stock.doctype.stock_entry.stock_entry import FinishedGoodError, make_stock_in_entry
 from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
 from erpnext.stock.doctype.stock_ledger_entry.stock_ledger_entry import StockFreezeError
@@ -38,7 +38,7 @@
 	condition, values = "", []
 	for key, value in args.items():
 		condition += " and " if condition else " where "
-		condition += "`{0}`=%s".format(key)
+		condition += f"`{key}`=%s"
 		values.append(value)
 
 	return frappe.db.sql(
@@ -151,8 +151,7 @@
 		)
 
 		projected_qty = (
-			frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse}, "projected_qty")
-			or 0
+			frappe.db.get_value("Bin", {"item_code": item_code, "warehouse": warehouse}, "projected_qty") or 0
 		)
 
 		frappe.db.set_single_value("Stock Settings", "auto_indent", 1)
@@ -693,14 +692,10 @@
 		se.set_stock_entry_type()
 		se.insert()
 		se.submit()
-		self.assertTrue(
-			frappe.db.get_value("Serial No", serial_no, "warehouse"), "_Test Warehouse 1 - _TC"
-		)
+		self.assertTrue(frappe.db.get_value("Serial No", serial_no, "warehouse"), "_Test Warehouse 1 - _TC")
 
 		se.cancel()
-		self.assertTrue(
-			frappe.db.get_value("Serial No", serial_no, "warehouse"), "_Test Warehouse - _TC"
-		)
+		self.assertTrue(frappe.db.get_value("Serial No", serial_no, "warehouse"), "_Test Warehouse - _TC")
 		frappe.flags.use_serial_and_batch_fields = False
 
 	def test_serial_cancel(self):
@@ -732,9 +727,7 @@
 		else:
 			item = frappe.get_doc("Item", {"item_name": "Batched and Serialised Item"})
 
-		se = make_stock_entry(
-			item_code=item.item_code, target="_Test Warehouse - _TC", qty=1, basic_rate=100
-		)
+		se = make_stock_entry(item_code=item.item_code, target="_Test Warehouse - _TC", qty=1, basic_rate=100)
 		batch_no = get_batch_from_bundle(se.items[0].serial_and_batch_bundle)
 		serial_no = get_serial_nos_from_bundle(se.items[0].serial_and_batch_bundle)[0]
 		batch_qty = get_batch_qty(batch_no, "_Test Warehouse - _TC", item.item_code)
@@ -750,7 +743,7 @@
 		self.assertEqual(frappe.db.get_value("Serial No", serial_no, "warehouse"), None)
 
 	def test_warehouse_company_validation(self):
-		company = frappe.db.get_value("Warehouse", "_Test Warehouse 2 - _TC1", "company")
+		frappe.db.get_value("Warehouse", "_Test Warehouse 2 - _TC1", "company")
 		frappe.get_doc("User", "test2@example.com").add_roles(
 			"Sales User", "Sales Manager", "Stock User", "Stock Manager"
 		)
@@ -856,12 +849,8 @@
 		for d in stock_entry.get("items"):
 			if d.item_code != "_Test FG Item 2":
 				rm_cost += flt(d.amount)
-		fg_cost = list(filter(lambda x: x.item_code == "_Test FG Item 2", stock_entry.get("items")))[
-			0
-		].amount
-		self.assertEqual(
-			fg_cost, flt(rm_cost + bom_operation_cost + work_order.additional_operating_cost, 2)
-		)
+		fg_cost = next(filter(lambda x: x.item_code == "_Test FG Item 2", stock_entry.get("items"))).amount
+		self.assertEqual(fg_cost, flt(rm_cost + bom_operation_cost + work_order.additional_operating_cost, 2))
 
 	@change_settings("Manufacturing Settings", {"material_consumption": 1})
 	def test_work_order_manufacture_with_material_consumption(self):
@@ -904,8 +893,8 @@
 		for d in s.get("items"):
 			if d.s_warehouse:
 				rm_cost += d.amount
-		fg_cost = list(filter(lambda x: x.item_code == "_Test FG Item", s.get("items")))[0].amount
-		scrap_cost = list(filter(lambda x: x.is_scrap_item, s.get("items")))[0].amount
+		fg_cost = next(filter(lambda x: x.item_code == "_Test FG Item", s.get("items"))).amount
+		scrap_cost = next(filter(lambda x: x.is_scrap_item, s.get("items"))).amount
 		self.assertEqual(fg_cost, flt(rm_cost - scrap_cost, 2))
 
 		# When Stock Entry has only FG + Scrap
@@ -919,13 +908,11 @@
 				rm_cost += d.amount
 		self.assertEqual(rm_cost, 0)
 		expected_fg_cost = s.get_basic_rate_for_manufactured_item(1)
-		fg_cost = list(filter(lambda x: x.item_code == "_Test FG Item", s.get("items")))[0].amount
+		fg_cost = next(filter(lambda x: x.item_code == "_Test FG Item", s.get("items"))).amount
 		self.assertEqual(flt(fg_cost, 2), flt(expected_fg_cost, 2))
 
 	def test_variant_work_order(self):
-		bom_no = frappe.db.get_value(
-			"BOM", {"item": "_Test Variant Item", "is_default": 1, "docstatus": 1}
-		)
+		bom_no = frappe.db.get_value("BOM", {"item": "_Test Variant Item", "is_default": 1, "docstatus": 1})
 
 		make_item_variant()  # make variant of _Test Variant Item if absent
 
@@ -1061,9 +1048,7 @@
 		self.assertRaises(frappe.ValidationError, repack.submit)
 
 	def test_customer_provided_parts_se(self):
-		create_item(
-			"CUST-0987", is_customer_provided_item=1, customer="_Test Customer", is_purchase_item=0
-		)
+		create_item("CUST-0987", is_customer_provided_item=1, customer="_Test Customer", is_purchase_item=0)
 		se = make_stock_entry(
 			item_code="CUST-0987", purpose="Material Receipt", qty=4, to_warehouse="_Test Warehouse - _TC"
 		)
@@ -1178,9 +1163,7 @@
 		self.check_gl_entries(
 			"Stock Entry",
 			se.name,
-			sorted(
-				[["Stock Adjustment - TCP1", 100.0, 0.0], ["Miscellaneous Expenses - TCP1", 0.0, 100.0]]
-			),
+			sorted([["Stock Adjustment - TCP1", 100.0, 0.0], ["Miscellaneous Expenses - TCP1", 0.0, 100.0]]),
 		)
 
 	def test_conversion_factor_change(self):
@@ -1344,7 +1327,7 @@
 		)
 		batch_nos.append(get_batch_from_bundle(se2.items[0].serial_and_batch_bundle))
 
-		with self.assertRaises(frappe.ValidationError) as nse:
+		with self.assertRaises(frappe.ValidationError):
 			make_stock_entry(
 				item_code=item_code,
 				qty=1,
@@ -1604,15 +1587,12 @@
 		self.assertRaises(BatchExpiredError, se.save)
 
 	def test_negative_stock_reco(self):
-		from erpnext.controllers.stock_controller import BatchExpiredError
-		from erpnext.stock.doctype.batch.test_batch import make_new_batch
-
 		frappe.db.set_single_value("Stock Settings", "allow_negative_stock", 0)
 
 		item_code = "Test Negative Item - 001"
-		item_doc = create_item(item_code=item_code, is_stock_item=1, valuation_rate=10)
+		create_item(item_code=item_code, is_stock_item=1, valuation_rate=10)
 
-		se1 = make_stock_entry(
+		make_stock_entry(
 			item_code=item_code,
 			posting_date=add_days(today(), -3),
 			posting_time="00:00:00",
@@ -1621,7 +1601,7 @@
 			to_warehouse="_Test Warehouse - _TC",
 		)
 
-		se2 = make_stock_entry(
+		make_stock_entry(
 			item_code=item_code,
 			posting_date=today(),
 			posting_time="00:00:00",
diff --git a/erpnext/stock/doctype/stock_ledger_entry/stock_ledger_entry.py b/erpnext/stock/doctype/stock_ledger_entry/stock_ledger_entry.py
index b49fe22..a3166a8 100644
--- a/erpnext/stock/doctype/stock_ledger_entry/stock_ledger_entry.py
+++ b/erpnext/stock/doctype/stock_ledger_entry/stock_ledger_entry.py
@@ -232,9 +232,7 @@
 			if not self.serial_and_batch_bundle:
 				self.throw_error_message(f"Serial No / Batch No are mandatory for Item {self.item_code}")
 
-		if (
-			self.serial_and_batch_bundle and not item_detail.has_serial_no and not item_detail.has_batch_no
-		):
+		if self.serial_and_batch_bundle and not item_detail.has_serial_no and not item_detail.has_batch_no:
 			self.throw_error_message(f"Serial No and Batch No are not allowed for Item {self.item_code}")
 
 	def throw_error_message(self, message, exception=frappe.ValidationError):
@@ -262,7 +260,9 @@
 			)
 			if older_than_x_days_ago and stock_settings.stock_auth_role not in frappe.get_roles():
 				frappe.throw(
-					_("Not allowed to update stock transactions older than {0}").format(stock_frozen_upto_days),
+					_("Not allowed to update stock transactions older than {0}").format(
+						stock_frozen_upto_days
+					),
 					StockFreezeError,
 				)
 
@@ -280,7 +280,9 @@
 			expiry_date = frappe.db.get_value("Batch", self.batch_no, "expiry_date")
 			if expiry_date:
 				if getdate(self.posting_date) > getdate(expiry_date):
-					frappe.throw(_("Batch {0} of Item {1} has expired.").format(self.batch_no, self.item_code))
+					frappe.throw(
+						_("Batch {0} of Item {1} has expired.").format(self.batch_no, self.item_code)
+					)
 
 	def validate_and_set_fiscal_year(self):
 		if not self.fiscal_year:
@@ -313,7 +315,7 @@
 					(self.item_code, self.warehouse),
 				)[0][0]
 
-				cur_doc_posting_datetime = "%s %s" % (
+				cur_doc_posting_datetime = "{} {}".format(
 					self.posting_date,
 					self.get("posting_time") or "00:00:00",
 				)
@@ -322,7 +324,9 @@
 					last_transaction_time
 				):
 					msg = _("Last Stock Transaction for item {0} under warehouse {1} was on {2}.").format(
-						frappe.bold(self.item_code), frappe.bold(self.warehouse), frappe.bold(last_transaction_time)
+						frappe.bold(self.item_code),
+						frappe.bold(self.warehouse),
+						frappe.bold(last_transaction_time),
 					)
 
 					msg += "<br><br>" + _(
diff --git a/erpnext/stock/doctype/stock_ledger_entry/test_stock_ledger_entry.py b/erpnext/stock/doctype/stock_ledger_entry/test_stock_ledger_entry.py
index 40a2d5a..6c12b36 100644
--- a/erpnext/stock/doctype/stock_ledger_entry/test_stock_ledger_entry.py
+++ b/erpnext/stock/doctype/stock_ledger_entry/test_stock_ledger_entry.py
@@ -8,7 +8,6 @@
 import frappe
 from frappe.core.page.permission_manager.permission_manager import reset
 from frappe.custom.doctype.property_setter.property_setter import make_property_setter
-from frappe.query_builder.functions import CombineDatetime
 from frappe.tests.utils import FrappeTestCase, change_settings
 from frappe.utils import add_days, add_to_date, flt, today
 
@@ -20,8 +19,6 @@
 )
 from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import make_purchase_receipt
 from erpnext.stock.doctype.serial_and_batch_bundle.test_serial_and_batch_bundle import (
-	get_batch_from_bundle,
-	get_serial_nos_from_bundle,
 	make_serial_batch_bundle,
 )
 from erpnext.stock.doctype.stock_entry.stock_entry_utils import make_stock_entry
@@ -40,8 +37,7 @@
 
 		# delete SLE and BINs for all items
 		frappe.db.sql(
-			"delete from `tabStock Ledger Entry` where item_code in (%s)"
-			% (", ".join(["%s"] * len(items))),
+			"delete from `tabStock Ledger Entry` where item_code in (%s)" % (", ".join(["%s"] * len(items))),
 			items,
 		)
 		frappe.db.sql(
@@ -127,7 +123,7 @@
 		self.assertEqual(finished_item_sle.get("valuation_rate"), 540)
 
 		# Reconciliation for _Test Item for Reposting at Stores on 12-04-2020: Qty = 50, Rate = 150
-		sr = create_stock_reconciliation(
+		create_stock_reconciliation(
 			item_code="_Test Item for Reposting",
 			warehouse="Stores - _TC",
 			qty=50,
@@ -491,7 +487,7 @@
 		expected_incoming_rates = expected_abs_svd = [75.0, 125.0, 75.0, 125.0]
 
 		self.assertEqual(expected_abs_svd, svd_list, "Incorrect 'Stock Value Difference' values")
-		for dn, incoming_rate in zip(dns, expected_incoming_rates):
+		for dn, _incoming_rate in zip(dns, expected_incoming_rates, strict=False):
 			self.assertTrue(
 				dn.items[0].incoming_rate in expected_abs_svd,
 				"Incorrect 'Incoming Rate' values fetched for DN items",
@@ -567,9 +563,7 @@
 			],
 		)
 
-		reciept = make_stock_entry(
-			item_code=item_code, target=source, batch_no=batches[0], qty=5, rate=10
-		)
+		reciept = make_stock_entry(item_code=item_code, target=source, batch_no=batches[0], qty=5, rate=10)
 		self.assertSLEs(
 			reciept,
 			[
@@ -691,9 +685,7 @@
 			],
 		)
 
-		consume_today = make_stock_entry(
-			item_code=item_code, source=warehouse, batch_no=batches[0], qty=1
-		)
+		consume_today = make_stock_entry(item_code=item_code, source=warehouse, batch_no=batches[0], qty=1)
 		self.assertSLEs(
 			consume_today,
 			[
@@ -726,8 +718,8 @@
 		item, warehouses, batches = setup_item_valuation_test()
 
 		def check_sle_details_against_expected(sle_details, expected_sle_details, detail, columns):
-			for i, (sle_vals, ex_sle_vals) in enumerate(zip(sle_details, expected_sle_details)):
-				for col, sle_val, ex_sle_val in zip(columns, sle_vals, ex_sle_vals):
+			for i, (sle_vals, ex_sle_vals) in enumerate(zip(sle_details, expected_sle_details, strict=False)):
+				for col, sle_val, ex_sle_val in zip(columns, sle_vals, ex_sle_vals, strict=False):
 					if col == "stock_queue":
 						sle_val = get_stock_value_from_q(sle_val)
 						ex_sle_val = get_stock_value_from_q(ex_sle_val)
@@ -757,9 +749,7 @@
 		se_entry_list_mi = [
 			(item, warehouses[0], None, batches[1], 1, None, "2021-01-29"),
 		]
-		ses = create_stock_entry_entries_for_batchwise_item_valuation_test(
-			se_entry_list_mi, "Material Issue"
-		)
+		ses = create_stock_entry_entries_for_batchwise_item_valuation_test(se_entry_list_mi, "Material Issue")
 		sle_details = fetch_sle_details_for_doc_list(ses, columns=columns, as_dict=0)
 		expected_sle_details = [(-100.0, 50.0, -1.0, 1.0, "[]")]
 		details_list.append((sle_details, expected_sle_details, "Material Issue Entries", columns))
@@ -949,9 +939,7 @@
 
 		rates = [10 * i for i in range(1, 5)]
 
-		receipt = make_stock_entry(
-			item_code=rm.name, target=warehouse, qty=10, do_not_save=True, rate=10
-		)
+		receipt = make_stock_entry(item_code=rm.name, target=warehouse, qty=10, do_not_save=True, rate=10)
 		for rate in rates[1:]:
 			row = frappe.copy_doc(receipt.items[0], ignore_no_copy=False)
 			row.basic_rate = rate
@@ -981,9 +969,7 @@
 		repack.submit()
 
 		# same exact queue should be transferred
-		self.assertSLEs(
-			repack, [{"incoming_rate": sum(rates) * 10}], sle_filters={"item_code": packed.name}
-		)
+		self.assertSLEs(repack, [{"incoming_rate": sum(rates) * 10}], sle_filters={"item_code": packed.name})
 
 	def test_negative_fifo_valuation(self):
 		"""
@@ -993,7 +979,7 @@
 		item = make_item(properties={"allow_negative_stock": 1}).name
 		warehouse = "_Test Warehouse - _TC"
 
-		receipt = make_stock_entry(item_code=item, target=warehouse, qty=10, rate=10)
+		make_stock_entry(item_code=item, target=warehouse, qty=10, rate=10)
 		consume1 = make_stock_entry(item_code=item, source=warehouse, qty=15)
 
 		self.assertSLEs(consume1, [{"stock_value": -5 * 10, "stock_queue": [[-5, 10]]}])
@@ -1033,27 +1019,21 @@
 		self.assertEqual(50, _get_stock_credit(depdendent_consumption))
 
 		# backdated receipt - should trigger GL repost of all previous stock entries
-		bd_receipt = make_stock_entry(
-			item_code=item, to_warehouse=A, qty=5, rate=20, posting_date=_day(-1)
-		)
+		bd_receipt = make_stock_entry(item_code=item, to_warehouse=A, qty=5, rate=20, posting_date=_day(-1))
 		self.assertEqual(100, _get_stock_credit(depdendent_consumption))
 
 		# cancelling receipt should reset it back
 		bd_receipt.cancel()
 		self.assertEqual(50, _get_stock_credit(depdendent_consumption))
 
-		bd_receipt2 = make_stock_entry(
-			item_code=item, to_warehouse=A, qty=2, rate=20, posting_date=_day(-2)
-		)
+		bd_receipt2 = make_stock_entry(item_code=item, to_warehouse=A, qty=2, rate=20, posting_date=_day(-2))
 		# total as per FIFO -> 2 * 20 + 3 * 10 = 70
 		self.assertEqual(70, _get_stock_credit(depdendent_consumption))
 
 		# transfer WIP material to final destination and consume it all
 		depdendent_consumption.cancel()
 		make_stock_entry(item_code=item, from_warehouse=B, to_warehouse=C, qty=5, posting_date=_day(3))
-		final_consumption = make_stock_entry(
-			item_code=item, from_warehouse=C, qty=5, posting_date=_day(4)
-		)
+		final_consumption = make_stock_entry(item_code=item, from_warehouse=C, qty=5, posting_date=_day(4))
 		# exact amount gets consumed
 		self.assertEqual(70, _get_stock_credit(final_consumption))
 
@@ -1120,11 +1100,10 @@
 		self.assertEqual([1], ordered_qty_after_transaction())
 
 	def test_timestamp_clash(self):
-
 		item = make_item().name
 		warehouse = "_Test Warehouse - _TC"
 
-		reciept = make_stock_entry(
+		make_stock_entry(
 			item_code=item,
 			to_warehouse=warehouse,
 			qty=100,
@@ -1133,7 +1112,7 @@
 			posting_time="01:00:00",
 		)
 
-		consumption = make_stock_entry(
+		make_stock_entry(
 			item_code=item,
 			from_warehouse=warehouse,
 			qty=50,
@@ -1152,11 +1131,10 @@
 
 		try:
 			backdated_receipt.cancel()
-		except Exception as e:
+		except Exception:
 			self.fail("Double processing of qty for clashing timestamp.")
 
 	def test_previous_sle_with_clashed_timestamp(self):
-
 		item = make_item().name
 		warehouse = "_Test Warehouse - _TC"
 
@@ -1197,7 +1175,6 @@
 		self.assertEqual(sle[0].actual_qty, 5)
 
 	def test_backdated_sle_with_same_timestamp(self):
-
 		item = make_item().name
 		warehouse = "_Test Warehouse - _TC"
 
@@ -1440,12 +1417,13 @@
 
 
 def setup_item_valuation_test(
-	valuation_method="FIFO", suffix=None, use_batchwise_valuation=1, batches_list=["X", "Y"]
+	valuation_method="FIFO", suffix=None, use_batchwise_valuation=1, batches_list=None
 ):
-	from erpnext.stock.doctype.batch.batch import make_batch
 	from erpnext.stock.doctype.item.test_item import make_item
 	from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse
 
+	if batches_list is None:
+		batches_list = ["X", "Y"]
 	if not suffix:
 		suffix = get_unique_suffix()
 
@@ -1459,7 +1437,7 @@
 	for i, batch_id in enumerate(batches):
 		if not frappe.db.exists("Batch", batch_id):
 			ubw = use_batchwise_valuation
-			if isinstance(use_batchwise_valuation, (list, tuple)):
+			if isinstance(use_batchwise_valuation, list | tuple):
 				ubw = use_batchwise_valuation[i]
 			batch = frappe.get_doc(
 				frappe._dict(
@@ -1490,9 +1468,7 @@
 
 	dns = []
 	for item, warehouse, batch_no, qty, rate in dn_entry_list:
-		so = make_sales_order(
-			rate=rate, qty=qty, item=item, warehouse=warehouse, against_blanket_order=0
-		)
+		so = make_sales_order(rate=rate, qty=qty, item=item, warehouse=warehouse, against_blanket_order=0)
 
 		dn = make_delivery_note(so.name)
 
diff --git a/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.py b/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.py
index 0311481..0421f0f 100644
--- a/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.py
+++ b/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.py
@@ -1,7 +1,6 @@
 # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
 # License: GNU General Public License v3. See license.txt
 
-from typing import Optional
 
 import frappe
 from frappe import _, bold, msgprint
@@ -58,7 +57,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(StockReconciliation, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 		self.head_row = ["Item Code", "Warehouse", "Quantity", "Valuation Rate"]
 
 	def validate(self):
@@ -142,7 +141,9 @@
 						"type_of_transaction": "Outward",
 						"company": self.company,
 						"is_rejected": 0,
-						"serial_nos": get_serial_nos(row.current_serial_no) if row.current_serial_no else None,
+						"serial_nos": get_serial_nos(row.current_serial_no)
+						if row.current_serial_no
+						else None,
 						"batches": frappe._dict({row.batch_no: row.current_qty}) if row.batch_no else None,
 						"batch_no": row.batch_no,
 						"do_not_submit": True,
@@ -327,7 +328,9 @@
 			if not item.batch_no and not item.serial_no:
 				for dimension in get_inventory_dimensions():
 					if item.get(dimension.get("fieldname")):
-						inventory_dimensions_dict[dimension.get("fieldname")] = item.get(dimension.get("fieldname"))
+						inventory_dimensions_dict[dimension.get("fieldname")] = item.get(
+							dimension.get("fieldname")
+						)
 
 			item_dict = get_stock_balance_for(
 				item.item_code,
@@ -432,11 +435,17 @@
 
 			# do not allow negative valuation
 			if flt(row.valuation_rate) < 0:
-				self.validation_messages.append(_get_msg(row_num, _("Negative Valuation Rate is not allowed")))
+				self.validation_messages.append(
+					_get_msg(row_num, _("Negative Valuation Rate is not allowed"))
+				)
 
 			if row.qty and row.valuation_rate in ["", None]:
 				row.valuation_rate = get_stock_balance(
-					row.item_code, row.warehouse, self.posting_date, self.posting_time, with_valuation_rate=True
+					row.item_code,
+					row.warehouse,
+					self.posting_date,
+					self.posting_time,
+					with_valuation_rate=True,
 				)[1]
 				if not row.valuation_rate:
 					# try if there is a buying price list in default currency
@@ -508,7 +517,7 @@
 			else:
 				items_html = ""
 				for d in data:
-					items_html += "<li>{0} units of Item {1} in Warehouse {2}</li>".format(
+					items_html += "<li>{} units of Item {} in Warehouse {}</li>".format(
 						bold(d[2]), bold(d[0]), bold(d[1])
 					)
 
@@ -528,7 +537,6 @@
 
 		sl_entries = []
 		for row in self.items:
-
 			if not row.qty and not row.valuation_rate and not row.current_qty:
 				self.make_adjustment_entry(row, sl_entries)
 				continue
@@ -578,9 +586,7 @@
 				sl_entries.append(self.get_sle_for_items(row))
 
 		if sl_entries:
-			allow_negative_stock = cint(
-				frappe.db.get_single_value("Stock Settings", "allow_negative_stock")
-			)
+			allow_negative_stock = cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
 			self.make_sl_entries(sl_entries, allow_negative_stock=allow_negative_stock)
 
 	def make_adjustment_entry(self, row, sl_entries):
@@ -688,9 +694,7 @@
 				data.valuation_rate = flt(row.valuation_rate)
 				data.stock_value_difference = -1 * flt(row.amount_difference)
 
-		elif (
-			self.docstatus == 1 and has_dimensions and (not row.batch_no or not row.serial_and_batch_bundle)
-		):
+		elif self.docstatus == 1 and has_dimensions and (not row.batch_no or not row.serial_and_batch_bundle):
 			data.actual_qty = row.qty
 			data.qty_after_transaction = 0.0
 			data.incoming_rate = flt(row.valuation_rate)
@@ -711,9 +715,7 @@
 				sl_entries = self.merge_similar_item_serial_nos(sl_entries)
 
 			sl_entries.reverse()
-			allow_negative_stock = cint(
-				frappe.db.get_single_value("Stock Settings", "allow_negative_stock")
-			)
+			allow_negative_stock = cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
 			self.make_sl_entries(sl_entries, allow_negative_stock=allow_negative_stock)
 
 	def merge_similar_item_serial_nos(self, sl_entries):
@@ -750,9 +752,7 @@
 		if not self.cost_center:
 			msgprint(_("Please enter Cost Center"), raise_exception=1)
 
-		return super(StockReconciliation, self).get_gl_entries(
-			warehouse_account, self.expense_account, self.cost_center
-		)
+		return super().get_gl_entries(warehouse_account, self.expense_account, self.cost_center)
 
 	def validate_expense_account(self):
 		if not cint(erpnext.is_perpetual_inventory_enabled(self.company)):
@@ -851,7 +851,12 @@
 				val_rate = item_dict.get("rate")
 			elif row.batch_no:
 				current_qty = get_batch_qty_for_stock_reco(
-					row.item_code, row.warehouse, row.batch_no, self.posting_date, self.posting_time, self.name
+					row.item_code,
+					row.warehouse,
+					row.batch_no,
+					self.posting_date,
+					self.posting_time,
+					self.name,
 				)
 
 			precesion = row.precision("current_qty")
@@ -986,9 +991,7 @@
 		return current_qty
 
 
-def get_batch_qty_for_stock_reco(
-	item_code, warehouse, batch_no, posting_date, posting_time, voucher_no
-):
+def get_batch_qty_for_stock_reco(item_code, warehouse, batch_no, posting_date, posting_time, voucher_no):
 	ledger = frappe.qb.DocType("Stock Ledger Entry")
 
 	query = (
@@ -1018,9 +1021,7 @@
 
 
 @frappe.whitelist()
-def get_items(
-	warehouse, posting_date, posting_time, company, item_code=None, ignore_empty_stock=False
-):
+def get_items(warehouse, posting_date, posting_time, company, item_code=None, ignore_empty_stock=False):
 	ignore_empty_stock = cint(ignore_empty_stock)
 	items = [frappe._dict({"item_code": item_code, "warehouse": warehouse})]
 
@@ -1175,15 +1176,13 @@
 	warehouse: str,
 	posting_date,
 	posting_time,
-	batch_no: Optional[str] = None,
+	batch_no: str | None = None,
 	with_valuation_rate: bool = True,
 	inventory_dimensions_dict=None,
 ):
 	frappe.has_permission("Stock Reconciliation", "write", throw=True)
 
-	item_dict = frappe.get_cached_value(
-		"Item", item_code, ["has_serial_no", "has_batch_no"], as_dict=1
-	)
+	item_dict = frappe.get_cached_value("Item", item_code, ["has_serial_no", "has_batch_no"], as_dict=1)
 
 	if not item_dict:
 		# In cases of data upload to Items table
@@ -1222,9 +1221,7 @@
 		qty, rate = data
 
 	if item_dict.get("has_batch_no"):
-		qty = (
-			get_batch_qty(batch_no, warehouse, posting_date=posting_date, posting_time=posting_time) or 0
-		)
+		qty = get_batch_qty(batch_no, warehouse, posting_date=posting_date, posting_time=posting_time) or 0
 
 	return {
 		"qty": qty,
diff --git a/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py b/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
index 479a74a..0ffcdd5 100644
--- a/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
+++ b/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
@@ -7,7 +7,7 @@
 
 import frappe
 from frappe.tests.utils import FrappeTestCase, change_settings
-from frappe.utils import add_days, cstr, flt, nowdate, nowtime, random_string
+from frappe.utils import add_days, cstr, flt, nowdate, nowtime
 
 from erpnext.accounts.utils import get_stock_and_account_balance
 from erpnext.stock.doctype.item.test_item import create_item
@@ -17,7 +17,6 @@
 	get_serial_nos_from_bundle,
 	make_serial_batch_bundle,
 )
-from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
 from erpnext.stock.doctype.stock_reconciliation.stock_reconciliation import (
 	EmptyStockReconciliationItemsError,
 	get_items,
@@ -106,7 +105,8 @@
 				# no gl entries
 				self.assertTrue(
 					frappe.db.get_value(
-						"Stock Ledger Entry", {"voucher_type": "Stock Reconciliation", "voucher_no": stock_reco.name}
+						"Stock Ledger Entry",
+						{"voucher_type": "Stock Reconciliation", "voucher_no": stock_reco.name},
 					)
 				)
 
@@ -152,7 +152,6 @@
 
 	def test_stock_reco_for_serialized_item(self):
 		to_delete_records = []
-		to_delete_serial_nos = []
 
 		# Add new serial nos
 		serial_item_code = "Stock-Reco-Serial-Item-1"
@@ -344,9 +343,7 @@
 
 	def test_customer_provided_items(self):
 		item_code = "Stock-Reco-customer-Item-100"
-		create_item(
-			item_code, is_customer_provided_item=1, customer="_Test Customer", is_purchase_item=0
-		)
+		create_item(item_code, is_customer_provided_item=1, customer="_Test Customer", is_purchase_item=0)
 
 		sr = create_stock_reconciliation(item_code=item_code, qty=10, rate=420)
 
@@ -529,18 +526,18 @@
 		item_code = self.make_item().name
 		warehouse = "_Test Warehouse - _TC"
 
-		sr = create_stock_reconciliation(
+		create_stock_reconciliation(
 			item_code=item_code, warehouse=warehouse, qty=10, rate=100, posting_date=add_days(nowdate(), 10)
 		)
 
-		dn = create_delivery_note(
+		create_delivery_note(
 			item_code=item_code, warehouse=warehouse, qty=5, rate=120, posting_date=add_days(nowdate(), 12)
 		)
 		old_bin_qty = frappe.db.get_value(
 			"Bin", {"item_code": item_code, "warehouse": warehouse}, "actual_qty"
 		)
 
-		sr2 = create_stock_reconciliation(
+		create_stock_reconciliation(
 			item_code=item_code, warehouse=warehouse, qty=11, rate=100, posting_date=add_days(nowdate(), 11)
 		)
 		new_bin_qty = frappe.db.get_value(
@@ -760,8 +757,6 @@
 		self.assertEqual(flt(sle[0].actual_qty), flt(-100.0))
 
 	def test_backdated_stock_reco_entry_with_batch(self):
-		from erpnext.stock.doctype.stock_entry.test_stock_entry import make_stock_entry
-
 		item_code = self.make_item(
 			"Test New Batch Item ABCVSD",
 			{
@@ -813,7 +808,7 @@
 		)
 
 		stock_reco1.reload()
-		new_batch_no = get_batch_from_bundle(stock_reco1.items[0].serial_and_batch_bundle)
+		get_batch_from_bundle(stock_reco1.items[0].serial_and_batch_bundle)
 
 		self.assertEqual(len(sles), 2)
 
@@ -828,7 +823,7 @@
 		warehouse = "_Test Warehouse - _TC"
 
 		# Stock Value => 100 * 100 = 10000
-		se = make_stock_entry(
+		make_stock_entry(
 			item_code=item_code,
 			target=warehouse,
 			qty=100,
@@ -988,9 +983,7 @@
 				self.assertEqual(d.actual_qty, 5.0)
 				self.assertAlmostEqual(d.stock_value_difference, 500.0)
 
-		active_serial_no = frappe.get_all(
-			"Serial No", filters={"status": "Active", "item_code": item_code}
-		)
+		active_serial_no = frappe.get_all("Serial No", filters={"status": "Active", "item_code": item_code})
 		self.assertEqual(len(active_serial_no), 5)
 
 
@@ -1083,9 +1076,7 @@
 			)
 		)
 		if frappe.get_all("Stock Ledger Entry", {"company": sr.company})
-		else frappe.get_cached_value(
-			"Account", {"account_type": "Temporary", "company": sr.company}, "name"
-		)
+		else frappe.get_cached_value("Account", {"account_type": "Temporary", "company": sr.company}, "name")
 	)
 	sr.cost_center = (
 		args.cost_center
diff --git a/erpnext/stock/doctype/stock_reservation_entry/stock_reservation_entry.py b/erpnext/stock/doctype/stock_reservation_entry/stock_reservation_entry.py
index 26fe8e1..91a7375 100644
--- a/erpnext/stock/doctype/stock_reservation_entry/stock_reservation_entry.py
+++ b/erpnext/stock/doctype/stock_reservation_entry/stock_reservation_entry.py
@@ -153,7 +153,7 @@
 		if self.reservation_based_on == "Qty":
 			self.validate_with_allowed_qty(self.reserved_qty)
 
-	def auto_reserve_serial_and_batch(self, based_on: str = None) -> None:
+	def auto_reserve_serial_and_batch(self, based_on: str | None = None) -> None:
 		"""Auto pick Serial and Batch Nos to reserve when `Reservation Based On` is `Serial and Batch`."""
 
 		if (
@@ -272,9 +272,7 @@
 					if cint(frappe.db.get_value("Batch", entry.batch_no, "disabled")):
 						msg = _(
 							"Row #{0}: Stock cannot be reserved for Item {1} against a disabled Batch {2}."
-						).format(
-							entry.idx, frappe.bold(self.item_code), frappe.bold(entry.batch_no)
-						)
+						).format(entry.idx, frappe.bold(self.item_code), frappe.bold(entry.batch_no))
 						frappe.throw(msg)
 
 					available_qty_to_reserve = get_available_qty_to_reserve(
@@ -360,9 +358,7 @@
 	) -> None:
 		"""Updates total reserved qty in the Pick List."""
 
-		if (
-			self.from_voucher_type == "Pick List" and self.from_voucher_no and self.from_voucher_detail_no
-		):
+		if self.from_voucher_type == "Pick List" and self.from_voucher_no and self.from_voucher_detail_no:
 			sre = frappe.qb.DocType("Stock Reservation Entry")
 			reserved_qty = (
 				frappe.qb.from_(sre)
@@ -390,7 +386,7 @@
 		bin_doc = frappe.get_cached_doc("Bin", bin_name)
 		bin_doc.update_reserved_stock()
 
-	def update_status(self, status: str = None, update_modified: bool = True) -> None:
+	def update_status(self, status: str | None = None, update_modified: bool = True) -> None:
 		"""Updates status based on Voucher Qty, Reserved Qty and Delivered Qty."""
 
 		if not status:
@@ -448,9 +444,7 @@
 			)
 			voucher_delivered_qty = flt(delivered_qty) * flt(conversion_factor)
 
-		allowed_qty = min(
-			self.available_qty, (self.voucher_qty - voucher_delivered_qty - total_reserved_qty)
-		)
+		allowed_qty = min(self.available_qty, (self.voucher_qty - voucher_delivered_qty - total_reserved_qty))
 
 		if self.get("_action") != "submit" and self.voucher_type == "Sales Order" and allowed_qty <= 0:
 			msg = _("Item {0} is already reserved/delivered against Sales Order {1}.").format(
@@ -466,16 +460,16 @@
 		if qty_to_be_reserved > allowed_qty:
 			actual_qty = get_stock_balance(self.item_code, self.warehouse)
 			msg = """
-				Cannot reserve more than Allowed Qty {0} {1} for Item {2} against {3} {4}.<br /><br />
+				Cannot reserve more than Allowed Qty {} {} for Item {} against {} {}.<br /><br />
 				The <b>Allowed Qty</b> is calculated as follows:<br />
 				<ul>
-					<li>Actual Qty [Available Qty at Warehouse] = {5}</li>
-					<li>Reserved Stock [Ignore current SRE] = {6}</li>
-					<li>Available Qty To Reserve [Actual Qty - Reserved Stock] = {7}</li>
-					<li>Voucher Qty [Voucher Item Qty] = {8}</li>
-					<li>Delivered Qty [Qty delivered against the Voucher Item] = {9}</li>
-					<li>Total Reserved Qty [Qty reserved against the Voucher Item] = {10}</li>
-					<li>Allowed Qty [Minimum of (Available Qty To Reserve, (Voucher Qty - Delivered Qty - Total Reserved Qty))] = {11}</li>
+					<li>Actual Qty [Available Qty at Warehouse] = {}</li>
+					<li>Reserved Stock [Ignore current SRE] = {}</li>
+					<li>Available Qty To Reserve [Actual Qty - Reserved Stock] = {}</li>
+					<li>Voucher Qty [Voucher Item Qty] = {}</li>
+					<li>Delivered Qty [Qty delivered against the Voucher Item] = {}</li>
+					<li>Total Reserved Qty [Qty reserved against the Voucher Item] = {}</li>
+					<li>Allowed Qty [Minimum of (Available Qty To Reserve, (Voucher Qty - Delivered Qty - Total Reserved Qty))] = {}</li>
 				</ul>
 			""".format(
 				frappe.bold(allowed_qty),
@@ -511,14 +505,12 @@
 	allowed_voucher_types = ["Sales Order"]
 
 	if voucher.doctype not in allowed_voucher_types:
-		msg = _("Stock Reservation can only be created against {0}.").format(
-			", ".join(allowed_voucher_types)
-		)
+		msg = _("Stock Reservation can only be created against {0}.").format(", ".join(allowed_voucher_types))
 		frappe.throw(msg)
 
 
 def get_available_qty_to_reserve(
-	item_code: str, warehouse: str, batch_no: str = None, ignore_sre=None
+	item_code: str, warehouse: str, batch_no: str | None = None, ignore_sre=None
 ) -> float:
 	"""Returns `Available Qty to Reserve (Actual Qty - Reserved Qty)` for Item, Warehouse and Batch combination."""
 
@@ -611,7 +603,7 @@
 	return available_serial_nos_list
 
 
-def get_sre_reserved_qty_for_item_and_warehouse(item_code: str, warehouse: str = None) -> float:
+def get_sre_reserved_qty_for_item_and_warehouse(item_code: str, warehouse: str | None = None) -> float:
 	"""Returns current `Reserved Qty` for Item and Warehouse combination."""
 
 	sre = frappe.qb.DocType("Stock Reservation Entry")
@@ -635,7 +627,7 @@
 
 
 def get_sre_reserved_qty_for_items_and_warehouses(
-	item_code_list: list, warehouse_list: list = None
+	item_code_list: list, warehouse_list: list | None = None
 ) -> dict:
 	"""Returns a dict like {("item_code", "warehouse"): "reserved_qty", ... }."""
 
@@ -689,7 +681,7 @@
 
 
 def get_sre_reserved_warehouses_for_voucher(
-	voucher_type: str, voucher_no: str, voucher_detail_no: str = None
+	voucher_type: str, voucher_no: str, voucher_detail_no: str | None = None
 ) -> list:
 	"""Returns a list of warehouses where the stock is reserved for the provided voucher."""
 
@@ -744,7 +736,7 @@
 
 
 def get_sre_reserved_serial_nos_details(
-	item_code: str, warehouse: str, serial_nos: list = None
+	item_code: str, warehouse: str, serial_nos: list | None = None
 ) -> dict:
 	"""Returns a dict of `Serial No` reserved in Stock Reservation Entry. The dict is like {serial_no: sre_name, ...}"""
 
@@ -772,9 +764,7 @@
 	return frappe._dict(query.run())
 
 
-def get_sre_reserved_batch_nos_details(
-	item_code: str, warehouse: str, batch_nos: list = None
-) -> dict:
+def get_sre_reserved_batch_nos_details(item_code: str, warehouse: str, batch_nos: list | None = None) -> dict:
 	"""Returns a dict of `Batch Qty` reserved in Stock Reservation Entry. The dict is like {batch_no: qty, ...}"""
 
 	sre = frappe.qb.DocType("Stock Reservation Entry")
@@ -849,9 +839,7 @@
 			sb_entry.batch_no,
 			(sb_entry.qty - sb_entry.delivered_qty).as_("qty"),
 		)
-		.where(
-			(sre.docstatus == 1) & (sre.name == sre_name) & (sre.status.notin(["Delivered", "Cancelled"]))
-		)
+		.where((sre.docstatus == 1) & (sre.name == sre_name) & (sre.status.notin(["Delivered", "Cancelled"])))
 		.where(sb_entry.qty > sb_entry.delivered_qty)
 		.orderby(sb_entry.creation)
 	).run(as_dict=True)
@@ -880,7 +868,7 @@
 		return bundle.name
 
 
-def has_reserved_stock(voucher_type: str, voucher_no: str, voucher_detail_no: str = None) -> bool:
+def has_reserved_stock(voucher_type: str, voucher_no: str, voucher_detail_no: str | None = None) -> bool:
 	"""Returns True if there is any Stock Reservation Entry for the given voucher."""
 
 	if get_stock_reservation_entries_for_voucher(
@@ -893,7 +881,7 @@
 
 def create_stock_reservation_entries_for_so_items(
 	sales_order: object,
-	items_details: list[dict] = None,
+	items_details: list[dict] | None = None,
 	from_voucher_type: Literal["Pick List", "Purchase Receipt"] = None,
 	notify=True,
 ) -> None:
@@ -914,9 +902,7 @@
 
 	validate_stock_reservation_settings(sales_order)
 
-	allow_partial_reservation = frappe.db.get_single_value(
-		"Stock Settings", "allow_partial_reservation"
-	)
+	allow_partial_reservation = frappe.db.get_single_value("Stock Settings", "allow_partial_reservation")
 
 	items = []
 	if items_details:
@@ -1041,7 +1027,9 @@
 			# Skip the item if `Partial Reservation` is disabled in the Stock Settings.
 			if not allow_partial_reservation:
 				if qty_to_be_reserved == flt(item.get("qty_to_reserve")):
-					msg = _("Enable Allow Partial Reservation in the Stock Settings to reserve partial stock.")
+					msg = _(
+						"Enable Allow Partial Reservation in the Stock Settings to reserve partial stock."
+					)
 					frappe.msgprint(msg, title=_("Partial Stock Reservation"), indicator="yellow")
 
 				continue
@@ -1099,13 +1087,13 @@
 
 
 def cancel_stock_reservation_entries(
-	voucher_type: str = None,
-	voucher_no: str = None,
-	voucher_detail_no: str = None,
+	voucher_type: str | None = None,
+	voucher_no: str | None = None,
+	voucher_detail_no: str | None = None,
 	from_voucher_type: Literal["Pick List", "Purchase Receipt"] = None,
-	from_voucher_no: str = None,
-	from_voucher_detail_no: str = None,
-	sre_list: list = None,
+	from_voucher_no: str | None = None,
+	from_voucher_detail_no: str | None = None,
+	sre_list: list | None = None,
 	notify: bool = True,
 ) -> None:
 	"""Cancel Stock Reservation Entries."""
@@ -1151,8 +1139,8 @@
 def get_stock_reservation_entries_for_voucher(
 	voucher_type: str,
 	voucher_no: str,
-	voucher_detail_no: str = None,
-	fields: list[str] = None,
+	voucher_detail_no: str | None = None,
+	fields: list[str] | None = None,
 	ignore_status: bool = False,
 ) -> list[dict]:
 	"""Returns list of Stock Reservation Entries against a Voucher."""
@@ -1171,9 +1159,7 @@
 	sre = frappe.qb.DocType("Stock Reservation Entry")
 	query = (
 		frappe.qb.from_(sre)
-		.where(
-			(sre.docstatus == 1) & (sre.voucher_type == voucher_type) & (sre.voucher_no == voucher_no)
-		)
+		.where((sre.docstatus == 1) & (sre.voucher_type == voucher_type) & (sre.voucher_no == voucher_no))
 		.orderby(sre.creation)
 	)
 
diff --git a/erpnext/stock/doctype/stock_reservation_entry/test_stock_reservation_entry.py b/erpnext/stock/doctype/stock_reservation_entry/test_stock_reservation_entry.py
index dd023e2..ddbf0b2 100644
--- a/erpnext/stock/doctype/stock_reservation_entry/test_stock_reservation_entry.py
+++ b/erpnext/stock/doctype/stock_reservation_entry/test_stock_reservation_entry.py
@@ -25,9 +25,7 @@
 	def setUp(self) -> None:
 		self.warehouse = "_Test Warehouse - _TC"
 		self.sr_item = make_item(properties={"is_stock_item": 1, "valuation_rate": 100})
-		create_material_receipt(
-			items={self.sr_item.name: self.sr_item}, warehouse=self.warehouse, qty=100
-		)
+		create_material_receipt(items={self.sr_item.name: self.sr_item}, warehouse=self.warehouse, qty=100)
 
 	@change_settings("Stock Settings", {"allow_negative_stock": 0})
 	def test_validate_stock_reservation_settings(self) -> None:
diff --git a/erpnext/stock/doctype/stock_settings/stock_settings.py b/erpnext/stock/doctype/stock_settings/stock_settings.py
index d975c29..7fcda1d 100644
--- a/erpnext/stock/doctype/stock_settings/stock_settings.py
+++ b/erpnext/stock/doctype/stock_settings/stock_settings.py
@@ -112,9 +112,9 @@
 		for field in warehouse_fields:
 			if frappe.db.get_value("Warehouse", self.get(field), "is_group"):
 				frappe.throw(
-					_("Group Warehouses cannot be used in transactions. Please change the value of {0}").format(
-						frappe.bold(self.meta.get_field(field).label)
-					),
+					_(
+						"Group Warehouses cannot be used in transactions. Please change the value of {0}"
+					).format(frappe.bold(self.meta.get_field(field).label)),
 					title=_("Incorrect Warehouse"),
 				)
 
@@ -160,7 +160,6 @@
 
 		# Change in value of `Allow Negative Stock`
 		if self.has_value_changed("allow_negative_stock"):
-
 			# Disable -> Enable: Don't allow if `Stock Reservation` is enabled
 			if self.allow_negative_stock and self.enable_stock_reservation:
 				frappe.throw(
@@ -171,10 +170,8 @@
 
 		# Change in value of `Enable Stock Reservation`
 		if self.has_value_changed("enable_stock_reservation"):
-
 			# Disable -> Enable
 			if self.enable_stock_reservation:
-
 				# Don't allow if `Allow Negative Stock` is enabled
 				if self.allow_negative_stock:
 					frappe.throw(
@@ -190,7 +187,10 @@
 					precision = frappe.db.get_single_value("System Settings", "float_precision") or 3
 					bin = frappe.qb.DocType("Bin")
 					bin_with_negative_stock = (
-						frappe.qb.from_(bin).select(bin.name).where(Round(bin.actual_qty, precision) < 0).limit(1)
+						frappe.qb.from_(bin)
+						.select(bin.name)
+						.where(Round(bin.actual_qty, precision) < 0)
+						.limit(1)
 					).run()
 
 					if bin_with_negative_stock:
diff --git a/erpnext/stock/doctype/stock_settings/test_stock_settings.py b/erpnext/stock/doctype/stock_settings/test_stock_settings.py
index cda739e..4b5ae43 100644
--- a/erpnext/stock/doctype/stock_settings/test_stock_settings.py
+++ b/erpnext/stock/doctype/stock_settings/test_stock_settings.py
@@ -1,7 +1,6 @@
 # Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
 # See license.txt
 
-import unittest
 
 import frappe
 from frappe.tests.utils import FrappeTestCase
diff --git a/erpnext/stock/doctype/warehouse/test_warehouse.py b/erpnext/stock/doctype/warehouse/test_warehouse.py
index 5a7228a..02d64ca 100644
--- a/erpnext/stock/doctype/warehouse/test_warehouse.py
+++ b/erpnext/stock/doctype/warehouse/test_warehouse.py
@@ -58,7 +58,7 @@
 			warehouse_ids.append(warehouse_id)
 
 		item_names = [f"_Test Item {i} for Unlinking" for i in range(2)]
-		for item, warehouse in zip(item_names, warehouse_ids):
+		for item, warehouse in zip(item_names, warehouse_ids, strict=False):
 			create_item(item, warehouse=warehouse, company=company)
 
 		# Delete warehouses
@@ -78,7 +78,6 @@
 				)
 
 	def test_group_non_group_conversion(self):
-
 		warehouse = frappe.get_doc("Warehouse", create_warehouse("TestGroupConversion"))
 
 		convert_to_group_or_ledger(warehouse.name)
diff --git a/erpnext/stock/doctype/warehouse/warehouse.py b/erpnext/stock/doctype/warehouse/warehouse.py
index 07b354a..00ed00b 100644
--- a/erpnext/stock/doctype/warehouse/warehouse.py
+++ b/erpnext/stock/doctype/warehouse/warehouse.py
@@ -55,9 +55,7 @@
 
 	def onload(self):
 		"""load account name for General Ledger Report"""
-		if self.company and cint(
-			frappe.db.get_value("Company", self.company, "enable_perpetual_inventory")
-		):
+		if self.company and cint(frappe.db.get_value("Company", self.company, "enable_perpetual_inventory")):
 			account = self.account or get_warehouse_account(self)
 
 			if account:
diff --git a/erpnext/stock/get_item_details.py b/erpnext/stock/get_item_details.py
index d09282d..ee2f9cb 100644
--- a/erpnext/stock/get_item_details.py
+++ b/erpnext/stock/get_item_details.py
@@ -156,19 +156,14 @@
 
 
 def update_bin_details(args, out, doc):
-	if (
-		args.get("doctype") == "Material Request"
-		and args.get("material_request_type") == "Material Transfer"
-	):
+	if args.get("doctype") == "Material Request" and args.get("material_request_type") == "Material Transfer":
 		out.update(get_bin_details(args.item_code, args.get("from_warehouse")))
 
 	elif out.get("warehouse"):
 		company = args.company if (doc and doc.get("doctype") == "Purchase Order") else None
 
 		# calculate company_total_stock only for po
-		bin_details = get_bin_details(
-			args.item_code, out.warehouse, company, include_child_warehouses=True
-		)
+		bin_details = get_bin_details(args.item_code, out.warehouse, company, include_child_warehouses=True)
 
 		out.update(bin_details)
 
@@ -274,9 +269,7 @@
 	if not item:
 		item = frappe.get_doc("Item", args.get("item_code"))
 
-	if (
-		item.variant_of and not item.taxes and frappe.db.exists("Item Tax", {"parent": item.variant_of})
-	):
+	if item.variant_of and not item.taxes and frappe.db.exists("Item Tax", {"parent": item.variant_of}):
 		item.update_template_tables()
 
 	item_defaults = get_item_defaults(item.name, args.company)
@@ -321,9 +314,7 @@
 	# Set stock UOM in args, so that it can be used while fetching item price
 	args.stock_uom = item.stock_uom
 
-	if args.get("batch_no") and item.name != frappe.get_cached_value(
-		"Batch", args.get("batch_no"), "item"
-	):
+	if args.get("batch_no") and item.name != frappe.get_cached_value("Batch", args.get("batch_no"), "item"):
 		args["batch_no"] = ""
 
 	out = frappe._dict(
@@ -344,9 +335,7 @@
 			"provisional_expense_account": get_provisional_account(
 				args, item_defaults, item_group_defaults, brand_defaults
 			),
-			"cost_center": get_default_cost_center(
-				args, item_defaults, item_group_defaults, brand_defaults
-			),
+			"cost_center": get_default_cost_center(args, item_defaults, item_group_defaults, brand_defaults),
 			"has_serial_no": item.has_serial_no,
 			"has_batch_no": item.has_batch_no,
 			"batch_no": args.get("batch_no"),
@@ -372,9 +361,7 @@
 			if args.get("doctype") in ["Sales Order", "Sales Invoice"]
 			else 0,
 			"is_fixed_asset": item.is_fixed_asset,
-			"last_purchase_rate": item.last_purchase_rate
-			if args.get("doctype") in ["Purchase Order"]
-			else 0,
+			"last_purchase_rate": item.last_purchase_rate if args.get("doctype") in ["Purchase Order"] else 0,
 			"transaction_date": args.get("transaction_date"),
 			"against_blanket_order": args.get("against_blanket_order"),
 			"bom_no": item.get("default_bom"),
@@ -510,9 +497,7 @@
 
 	itemwise_barcode = {}
 	for item in items_list:
-		barcodes = frappe.db.get_all(
-			"Item Barcode", filters={"parent": item.item_code}, fields="barcode"
-		)
+		barcodes = frappe.db.get_all("Item Barcode", filters={"parent": item.item_code}, fields="barcode")
 
 		for barcode in barcodes:
 			if item.item_code not in itemwise_barcode:
@@ -532,13 +517,13 @@
 	if item_rates is None:
 		item_rates = {}
 
-	if isinstance(item_codes, (str,)):
+	if isinstance(item_codes, str):
 		item_codes = json.loads(item_codes)
 
-	if isinstance(item_rates, (str,)):
+	if isinstance(item_rates, str):
 		item_rates = json.loads(item_rates)
 
-	if isinstance(item_tax_templates, (str,)):
+	if isinstance(item_tax_templates, str):
 		item_tax_templates = json.loads(item_tax_templates)
 
 	for item_code in item_codes:
@@ -606,9 +591,7 @@
 				taxes_with_no_validity.append(tax)
 
 	if taxes_with_validity:
-		taxes = sorted(
-			taxes_with_validity, key=lambda i: i.valid_from or tax.maximum_net_rate, reverse=True
-		)
+		taxes = sorted(taxes_with_validity, key=lambda i: i.valid_from or tax.maximum_net_rate, reverse=True)
 	else:
 		taxes = taxes_with_no_validity
 
@@ -761,7 +744,7 @@
 
 	elif not cost_center and args.get("item_code") and company:
 		for method in ["get_item_defaults", "get_item_group_defaults", "get_brand_defaults"]:
-			path = "erpnext.stock.get_item_details.{0}".format(method)
+			path = f"erpnext.stock.get_item_details.{method}"
 			data = frappe.get_attr(path)(args.get("item_code"), company)
 
 			if data and (data.selling_cost_center or data.buying_cost_center):
@@ -776,11 +759,7 @@
 	if not cost_center and args.get("cost_center"):
 		cost_center = args.get("cost_center")
 
-	if (
-		company
-		and cost_center
-		and frappe.get_cached_value("Cost Center", cost_center, "company") != company
-	):
+	if company and cost_center and frappe.get_cached_value("Cost Center", cost_center, "company") != company:
 		return None
 
 	if not cost_center and company:
@@ -790,11 +769,7 @@
 
 
 def get_default_supplier(args, item, item_group, brand):
-	return (
-		item.get("default_supplier")
-		or item_group.get("default_supplier")
-		or brand.get("default_supplier")
-	)
+	return item.get("default_supplier") or item_group.get("default_supplier") or brand.get("default_supplier")
 
 
 def get_price_list_rate(args, item_doc, out=None):
@@ -829,9 +804,7 @@
 			if not price_list_rate:
 				return out
 
-		out.price_list_rate = (
-			flt(price_list_rate) * flt(args.plc_conversion_rate) / flt(args.conversion_rate)
-		)
+		out.price_list_rate = flt(price_list_rate) * flt(args.plc_conversion_rate) / flt(args.conversion_rate)
 
 		if frappe.db.get_single_value("Buying Settings", "disable_last_purchase_rate"):
 			return out
@@ -846,9 +819,7 @@
 
 def insert_item_price(args):
 	"""Insert Item Price if Price List and Price List Rate are specified and currency is the same"""
-	if frappe.db.get_value(
-		"Price List", args.price_list, "currency", cache=True
-	) == args.currency and cint(
+	if frappe.db.get_value("Price List", args.price_list, "currency", cache=True) == args.currency and cint(
 		frappe.db.get_single_value("Stock Settings", "auto_insert_price_list_rate_if_missing")
 	):
 		if frappe.has_permission("Item Price", "write"):
@@ -870,7 +841,9 @@
 				):
 					frappe.db.set_value("Item Price", item_price.name, "price_list_rate", price_list_rate)
 					frappe.msgprint(
-						_("Item Price updated for {0} in Price List {1}").format(args.item_code, args.price_list),
+						_("Item Price updated for {0} in Price List {1}").format(
+							args.item_code, args.price_list
+						),
 						alert=True,
 					)
 			else:
@@ -1011,11 +984,7 @@
 	if not args.conversion_rate and args.currency == company_currency:
 		args.conversion_rate = 1.0
 
-	if (
-		not args.ignore_conversion_rate
-		and args.conversion_rate == 1
-		and args.currency != company_currency
-	):
+	if not args.ignore_conversion_rate and args.conversion_rate == 1 and args.currency != company_currency:
 		args.conversion_rate = (
 			get_exchange_rate(args.currency, company_currency, args.transaction_date, "for_buying") or 1.0
 		)
@@ -1050,7 +1019,9 @@
 			if meta.get_field("plc_conversion_rate"):
 				args.plc_conversion_rate = flt(
 					args.plc_conversion_rate,
-					get_field_precision(meta.get_field("plc_conversion_rate"), frappe._dict({"fields": args})),
+					get_field_precision(
+						meta.get_field("plc_conversion_rate"), frappe._dict({"fields": args})
+					),
 				)
 
 
@@ -1288,9 +1259,7 @@
 	company_currency = get_company_currency(args.company)
 
 	if (not plc_conversion_rate) or (
-		price_list_currency
-		and args.price_list_currency
-		and price_list_currency != args.price_list_currency
+		price_list_currency and args.price_list_currency and price_list_currency != args.price_list_currency
 	):
 		# cksgb 19/09/2016: added args.transaction_date as posting_date argument for get_exchange_rate
 		plc_conversion_rate = (
@@ -1312,9 +1281,7 @@
 @frappe.whitelist()
 def get_default_bom(item_code=None):
 	def _get_bom(item):
-		bom = frappe.get_all(
-			"BOM", dict(item=item, is_active=True, is_default=True, docstatus=1), limit=1
-		)
+		bom = frappe.get_all("BOM", dict(item=item, is_active=True, is_default=True, docstatus=1), limit=1)
 		return bom[0].name if bom else None
 
 	if not item_code:
@@ -1354,7 +1321,7 @@
 		pi_item = frappe.qb.DocType("Purchase Invoice Item")
 		valuation_rate = (
 			frappe.qb.from_(pi_item)
-			.select((Sum(pi_item.base_net_amount) / Sum(pi_item.qty * pi_item.conversion_factor)))
+			.select(Sum(pi_item.base_net_amount) / Sum(pi_item.qty * pi_item.conversion_factor))
 			.where((pi_item.docstatus == 1) & (pi_item.item_code == item_code))
 		).run()
 
diff --git a/erpnext/stock/reorder_item.py b/erpnext/stock/reorder_item.py
index 59f8b20..a24e852 100644
--- a/erpnext/stock/reorder_item.py
+++ b/erpnext/stock/reorder_item.py
@@ -58,9 +58,7 @@
 				item_warehouse_projected_qty.get(kwargs.item_code, {}).get(kwargs.warehouse_group)
 			)
 		else:
-			projected_qty = flt(
-				item_warehouse_projected_qty.get(kwargs.item_code, {}).get(kwargs.warehouse)
-			)
+			projected_qty = flt(item_warehouse_projected_qty.get(kwargs.item_code, {}).get(kwargs.warehouse))
 
 		if (reorder_level or reorder_qty) and projected_qty <= reorder_level:
 			deficiency = reorder_level - projected_qty
@@ -188,13 +186,12 @@
 
 	for item_code, warehouse, projected_qty in frappe.db.sql(
 		"""select item_code, warehouse, projected_qty
-		from tabBin where item_code in ({0})
+		from tabBin where item_code in ({})
 			and (warehouse != '' and warehouse is not null)""".format(
 			", ".join(["%s"] * len(items_to_consider))
 		),
 		items_to_consider,
 	):
-
 		if item_code not in item_warehouse_projected_qty:
 			item_warehouse_projected_qty.setdefault(item_code, {})
 
@@ -242,7 +239,9 @@
 					{
 						"company": company,
 						"transaction_date": nowdate(),
-						"material_request_type": "Material Transfer" if request_type == "Transfer" else request_type,
+						"material_request_type": "Material Transfer"
+						if request_type == "Transfer"
+						else request_type,
 					}
 				)
 
@@ -257,7 +256,9 @@
 						if uom != item.stock_uom:
 							conversion_factor = (
 								frappe.db.get_value(
-									"UOM Conversion Detail", {"parent": item.name, "uom": uom}, "conversion_factor"
+									"UOM Conversion Detail",
+									{"parent": item.name, "uom": uom},
+									"conversion_factor",
 								)
 								or 1.0
 							)
@@ -323,9 +324,7 @@
 
 		msg = frappe.render_template("templates/emails/reorder_item.html", {"mr_list": mr_list})
 
-		frappe.sendmail(
-			recipients=email_list, subject=_("Auto Material Requests Generated"), message=msg
-		)
+		frappe.sendmail(recipients=email_list, subject=_("Auto Material Requests Generated"), message=msg)
 
 
 def get_email_list(company):
@@ -378,7 +377,7 @@
 	for exception in exceptions_list:
 		try:
 			exception = json.loads(exception)
-			error_message = """<div class='small text-muted'>{0}</div><br>""".format(
+			error_message = """<div class='small text-muted'>{}</div><br>""".format(
 				_(exception.get("message"))
 			)
 			content += error_message
diff --git a/erpnext/stock/report/batch_item_expiry_status/batch_item_expiry_status.py b/erpnext/stock/report/batch_item_expiry_status/batch_item_expiry_status.py
index 5661e8b..3820b3e 100644
--- a/erpnext/stock/report/batch_item_expiry_status/batch_item_expiry_status.py
+++ b/erpnext/stock/report/batch_item_expiry_status/batch_item_expiry_status.py
@@ -28,15 +28,15 @@
 
 
 def get_columns():
-	return (
-		[_("Item") + ":Link/Item:150"]
-		+ [_("Item Name") + "::150"]
-		+ [_("Batch") + ":Link/Batch:150"]
-		+ [_("Stock UOM") + ":Link/UOM:100"]
-		+ [_("Quantity") + ":Float:100"]
-		+ [_("Expires On") + ":Date:100"]
-		+ [_("Expiry (In Days)") + ":Int:130"]
-	)
+	return [
+		_("Item") + ":Link/Item:150",
+		_("Item Name") + "::150",
+		_("Batch") + ":Link/Batch:150",
+		_("Stock UOM") + ":Link/UOM:100",
+		_("Quantity") + ":Float:100",
+		_("Expires On") + ":Date:100",
+		_("Expiry (In Days)") + ":Int:130",
+	]
 
 
 def get_data(filters):
@@ -76,9 +76,7 @@
 		.where(
 			(batch.disabled == 0)
 			& (batch.batch_qty > 0)
-			& (
-				(Date(batch.creation) >= filters["from_date"]) & (Date(batch.creation) <= filters["to_date"])
-			)
+			& ((Date(batch.creation) >= filters["from_date"]) & (Date(batch.creation) <= filters["to_date"]))
 		)
 		.orderby(batch.creation)
 	)
diff --git a/erpnext/stock/report/batch_wise_balance_history/batch_wise_balance_history.py b/erpnext/stock/report/batch_wise_balance_history/batch_wise_balance_history.py
index 7f2608e..fe0cefd 100644
--- a/erpnext/stock/report/batch_wise_balance_history/batch_wise_balance_history.py
+++ b/erpnext/stock/report/batch_wise_balance_history/batch_wise_balance_history.py
@@ -70,18 +70,18 @@
 def get_columns(filters):
 	"""return columns based on filters"""
 
-	columns = (
-		[_("Item") + ":Link/Item:100"]
-		+ [_("Item Name") + "::150"]
-		+ [_("Description") + "::150"]
-		+ [_("Warehouse") + ":Link/Warehouse:100"]
-		+ [_("Batch") + ":Link/Batch:100"]
-		+ [_("Opening Qty") + ":Float:90"]
-		+ [_("In Qty") + ":Float:80"]
-		+ [_("Out Qty") + ":Float:80"]
-		+ [_("Balance Qty") + ":Float:90"]
-		+ [_("UOM") + "::90"]
-	)
+	columns = [
+		_("Item") + ":Link/Item:100",
+		_("Item Name") + "::150",
+		_("Description") + "::150",
+		_("Warehouse") + ":Link/Warehouse:100",
+		_("Batch") + ":Link/Batch:100",
+		_("Opening Qty") + ":Float:90",
+		_("In Qty") + ":Float:80",
+		_("Out Qty") + ":Float:80",
+		_("Balance Qty") + ":Float:90",
+		_("UOM") + "::90",
+	]
 
 	return columns
 
@@ -195,9 +195,7 @@
 
 def get_item_details(filters):
 	item_map = {}
-	for d in (frappe.qb.from_("Item").select("name", "item_name", "description", "stock_uom")).run(
-		as_dict=1
-	):
+	for d in (frappe.qb.from_("Item").select("name", "item_name", "description", "stock_uom")).run(as_dict=1):
 		item_map.setdefault(d.name, d)
 
 	return item_map
diff --git a/erpnext/stock/report/cogs_by_item_group/cogs_by_item_group.py b/erpnext/stock/report/cogs_by_item_group/cogs_by_item_group.py
index 4642a53..b3c8e93 100644
--- a/erpnext/stock/report/cogs_by_item_group/cogs_by_item_group.py
+++ b/erpnext/stock/report/cogs_by_item_group/cogs_by_item_group.py
@@ -3,7 +3,7 @@
 
 import datetime
 from collections import OrderedDict
-from typing import Dict, List, Tuple, Union
+from typing import Union
 
 import frappe
 from frappe import _
@@ -13,15 +13,15 @@
 
 Filters = frappe._dict
 Row = frappe._dict
-Data = List[Row]
-Columns = List[Dict[str, str]]
+Data = list[Row]
+Columns = list[dict[str, str]]
 DateTime = Union[datetime.date, datetime.datetime]
-FilteredEntries = List[Dict[str, Union[str, float, DateTime, None]]]
-ItemGroupsDict = Dict[Tuple[int, int], Dict[str, Union[str, int]]]
-SVDList = List[frappe._dict]
+FilteredEntries = list[dict[str, str | float | DateTime | None]]
+ItemGroupsDict = dict[tuple[int, int], dict[str, str | int]]
+SVDList = list[frappe._dict]
 
 
-def execute(filters: Filters) -> Tuple[Columns, Data]:
+def execute(filters: Filters) -> tuple[Columns, Data]:
 	update_filters_with_account(filters)
 	validate_filters(filters)
 	columns = get_columns()
@@ -158,7 +158,7 @@
 		item.item_group = ig_map[item.get("item_code")]
 
 
-def get_item_groups_map(svd_list: SVDList) -> Dict[str, str]:
+def get_item_groups_map(svd_list: SVDList) -> dict[str, str]:
 	item_codes = set(i["item_code"] for i in svd_list)
 	ig_list = frappe.get_list(
 		"Item", fields=["item_code", "item_group"], filters=[("item_code", "in", item_codes)]
@@ -168,9 +168,7 @@
 
 def get_item_groups_dict() -> ItemGroupsDict:
 	item_groups_list = frappe.get_all("Item Group", fields=("name", "is_group", "lft", "rgt"))
-	return {
-		(i["lft"], i["rgt"]): {"name": i["name"], "is_group": i["is_group"]} for i in item_groups_list
-	}
+	return {(i["lft"], i["rgt"]): {"name": i["name"], "is_group": i["is_group"]} for i in item_groups_list}
 
 
 def update_leveled_dict(leveled_dict: OrderedDict) -> None:
diff --git a/erpnext/stock/report/delayed_item_report/delayed_item_report.py b/erpnext/stock/report/delayed_item_report/delayed_item_report.py
index 546a834..0bfb4da 100644
--- a/erpnext/stock/report/delayed_item_report/delayed_item_report.py
+++ b/erpnext/stock/report/delayed_item_report/delayed_item_report.py
@@ -13,7 +13,7 @@
 	return data, columns
 
 
-class DelayedItemReport(object):
+class DelayedItemReport:
 	def __init__(self, filters=None):
 		self.filters = frappe._dict(filters or {})
 
diff --git a/erpnext/stock/report/delayed_order_report/delayed_order_report.py b/erpnext/stock/report/delayed_order_report/delayed_order_report.py
index 197218d..24be939 100644
--- a/erpnext/stock/report/delayed_order_report/delayed_order_report.py
+++ b/erpnext/stock/report/delayed_order_report/delayed_order_report.py
@@ -20,7 +20,7 @@
 		return self.get_columns(), self.get_data(consolidated=True) or []
 
 	def get_data(self, consolidated=False):
-		data = super(DelayedOrderReport, self).get_data(consolidated) or []
+		data = super().get_data(consolidated) or []
 
 		so_list = []
 		result = []
diff --git a/erpnext/stock/report/fifo_queue_vs_qty_after_transaction_comparison/fifo_queue_vs_qty_after_transaction_comparison.py b/erpnext/stock/report/fifo_queue_vs_qty_after_transaction_comparison/fifo_queue_vs_qty_after_transaction_comparison.py
index 9e14033..404a58b 100644
--- a/erpnext/stock/report/fifo_queue_vs_qty_after_transaction_comparison/fifo_queue_vs_qty_after_transaction_comparison.py
+++ b/erpnext/stock/report/fifo_queue_vs_qty_after_transaction_comparison/fifo_queue_vs_qty_after_transaction_comparison.py
@@ -40,19 +40,18 @@
 
 
 def get_stock_ledger_entries(filters):
-
 	sle_filters = {"is_cancelled": 0}
 
 	if filters.warehouse:
 		children = get_descendants_of("Warehouse", filters.warehouse)
-		sle_filters["warehouse"] = ("in", children + [filters.warehouse])
+		sle_filters["warehouse"] = ("in", [*children, filters.warehouse])
 
 	if filters.item_code:
 		sle_filters["item_code"] = filters.item_code
 	elif filters.get("item_group"):
 		item_group = filters.get("item_group")
 		children = get_descendants_of("Item Group", item_group)
-		item_group_filter = {"item_group": ("in", children + [item_group])}
+		item_group_filter = {"item_group": ("in", [*children, item_group])}
 		sle_filters["item_code"] = (
 			"in",
 			frappe.get_all("Item", filters=item_group_filter, pluck="name", order_by=None),
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 b68db35..163e7ab 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
@@ -27,7 +27,7 @@
 
 def validate_data(itewise_balance_qty):
 	res = []
-	for key, data in itewise_balance_qty.items():
+	for _key, data in itewise_balance_qty.items():
 		row = get_incorrect_data(data)
 		if row:
 			res.append(row)
diff --git a/erpnext/stock/report/incorrect_serial_no_valuation/incorrect_serial_no_valuation.py b/erpnext/stock/report/incorrect_serial_no_valuation/incorrect_serial_no_valuation.py
index 39d84a7..4d740bd 100644
--- a/erpnext/stock/report/incorrect_serial_no_valuation/incorrect_serial_no_valuation.py
+++ b/erpnext/stock/report/incorrect_serial_no_valuation/incorrect_serial_no_valuation.py
@@ -43,11 +43,9 @@
 def get_incorrect_serial_nos(serial_nos_data):
 	result = []
 
-	total_value = frappe._dict(
-		{"qty": 0, "valuation_rate": 0, "serial_no": frappe.bold(_("Balance"))}
-	)
+	total_value = frappe._dict({"qty": 0, "valuation_rate": 0, "serial_no": frappe.bold(_("Balance"))})
 
-	for serial_no, data in serial_nos_data.items():
+	for _serial_no, data in serial_nos_data.items():
 		total_dict = frappe._dict({"qty": 0, "valuation_rate": 0, "serial_no": frappe.bold(_("Total"))})
 
 		if check_incorrect_serial_data(data, total_dict):
diff --git a/erpnext/stock/report/incorrect_stock_value_report/incorrect_stock_value_report.py b/erpnext/stock/report/incorrect_stock_value_report/incorrect_stock_value_report.py
index da958a8..7be8831 100644
--- a/erpnext/stock/report/incorrect_stock_value_report/incorrect_stock_value_report.py
+++ b/erpnext/stock/report/incorrect_stock_value_report/incorrect_stock_value_report.py
@@ -16,9 +16,7 @@
 def execute(filters=None):
 	if not erpnext.is_perpetual_inventory_enabled(filters.company):
 		frappe.throw(
-			_("Perpetual inventory required for the company {0} to view this report.").format(
-				filters.company
-			)
+			_("Perpetual inventory required for the company {0} to view this report.").format(filters.company)
 		)
 
 	data = get_data(filters)
@@ -83,9 +81,7 @@
 
 	closing_date = add_days(from_date, -1)
 	for key, stock_data in voucher_wise_dict.items():
-		prev_stock_value = get_stock_value_on(
-			posting_date=closing_date, item_code=key[0], warehouses=key[1]
-		)
+		prev_stock_value = get_stock_value_on(posting_date=closing_date, item_code=key[0], warehouses=key[1])
 		for data in stock_data:
 			expected_stock_value = prev_stock_value + data.stock_value_difference
 			if abs(data.stock_value - expected_stock_value) > 0.1:
diff --git a/erpnext/stock/report/item_prices/item_prices.py b/erpnext/stock/report/item_prices/item_prices.py
index a53a9f2..5c5b84f 100644
--- a/erpnext/stock/report/item_prices/item_prices.py
+++ b/erpnext/stock/report/item_prices/item_prices.py
@@ -111,9 +111,7 @@
 	).run(as_dict=True)
 
 	for d in price_list:
-		d.update(
-			{"price": "{0} {1} - {2}".format(d.currency, round(d.price_list_rate, 2), d.price_list)}
-		)
+		d.update({"price": f"{d.currency} {round(d.price_list_rate, 2)} - {d.price_list}"})
 		d.pop("currency")
 		d.pop("price_list_rate")
 		d.pop("price_list")
diff --git a/erpnext/stock/report/itemwise_recommended_reorder_level/itemwise_recommended_reorder_level.py b/erpnext/stock/report/itemwise_recommended_reorder_level/itemwise_recommended_reorder_level.py
index c4358b8..dffe948 100644
--- a/erpnext/stock/report/itemwise_recommended_reorder_level/itemwise_recommended_reorder_level.py
+++ b/erpnext/stock/report/itemwise_recommended_reorder_level/itemwise_recommended_reorder_level.py
@@ -24,9 +24,7 @@
 
 	data = []
 	for item in items:
-		total_outgoing = flt(consumed_item_map.get(item.name, 0)) + flt(
-			delivered_item_map.get(item.name, 0)
-		)
+		total_outgoing = flt(consumed_item_map.get(item.name, 0)) + flt(delivered_item_map.get(item.name, 0))
 		avg_daily_outgoing = flt(total_outgoing / diff, float_precision)
 		reorder_level = (avg_daily_outgoing * flt(item.lead_time_days)) + flt(item.safety_stock)
 
diff --git a/erpnext/stock/report/reserved_stock/reserved_stock.py b/erpnext/stock/report/reserved_stock/reserved_stock.py
index 21ce203..7963851 100644
--- a/erpnext/stock/report/reserved_stock/reserved_stock.py
+++ b/erpnext/stock/report/reserved_stock/reserved_stock.py
@@ -73,10 +73,10 @@
 		"project",
 	]:
 		if value := filters.get(field):
-			query = query.where((sre[field] == value))
+			query = query.where(sre[field] == value)
 
 	if value := filters.get("stock_reservation_entry"):
-		query = query.where((sre.name == value))
+		query = query.where(sre.name == value)
 
 	data = query.run(as_list=True)
 
diff --git a/erpnext/stock/report/reserved_stock/test_reserved_stock.py b/erpnext/stock/report/reserved_stock/test_reserved_stock.py
index 6ef89f9..16906fb 100644
--- a/erpnext/stock/report/reserved_stock/test_reserved_stock.py
+++ b/erpnext/stock/report/reserved_stock/test_reserved_stock.py
@@ -2,7 +2,6 @@
 # See license.txt
 from random import randint
 
-import frappe
 from frappe.tests.utils import FrappeTestCase, change_settings
 from frappe.utils.data import today
 
diff --git a/erpnext/stock/report/serial_and_batch_summary/serial_and_batch_summary.py b/erpnext/stock/report/serial_and_batch_summary/serial_and_batch_summary.py
index 3ea5e82..7bd8d70 100644
--- a/erpnext/stock/report/serial_and_batch_summary/serial_and_batch_summary.py
+++ b/erpnext/stock/report/serial_and_batch_summary/serial_and_batch_summary.py
@@ -146,9 +146,7 @@
 		)
 
 	if not item_details or item_details.get("has_serial_no"):
-		columns.append(
-			{"label": _("Serial No"), "fieldname": "serial_no", "fieldtype": "Data", "width": 120}
-		)
+		columns.append({"label": _("Serial No"), "fieldname": "serial_no", "fieldtype": "Data", "width": 120})
 
 	if not item_details or item_details.get("has_batch_no"):
 		columns.extend(
@@ -184,7 +182,7 @@
 
 	query_filters = {"options": ["in", [d.parent for d in child_doctypes]]}
 	if txt:
-		query_filters["parent"] = ["like", "%{}%".format(txt)]
+		query_filters["parent"] = ["like", f"%{txt}%"]
 
 	return frappe.get_all("DocField", filters=query_filters, fields=["distinct parent"], as_list=True)
 
diff --git a/erpnext/stock/report/serial_no_ledger/serial_no_ledger.py b/erpnext/stock/report/serial_no_ledger/serial_no_ledger.py
index 3f5216b..f229f73 100644
--- a/erpnext/stock/report/serial_no_ledger/serial_no_ledger.py
+++ b/erpnext/stock/report/serial_no_ledger/serial_no_ledger.py
@@ -84,9 +84,7 @@
 		return []
 
 	data = []
-	serial_bundle_ids = [
-		d.serial_and_batch_bundle for d in stock_ledgers if d.serial_and_batch_bundle
-	]
+	serial_bundle_ids = [d.serial_and_batch_bundle for d in stock_ledgers if d.serial_and_batch_bundle]
 
 	bundle_wise_serial_nos = get_serial_nos(filters, serial_bundle_ids)
 
diff --git a/erpnext/stock/report/stock_ageing/stock_ageing.py b/erpnext/stock/report/stock_ageing/stock_ageing.py
index 02ac8c6..efa736c 100644
--- a/erpnext/stock/report/stock_ageing/stock_ageing.py
+++ b/erpnext/stock/report/stock_ageing/stock_ageing.py
@@ -2,8 +2,8 @@
 # License: GNU General Public License v3. See license.txt
 
 
+from collections.abc import Iterator
 from operator import itemgetter
-from typing import Dict, Iterator, List, Tuple, Union
 
 import frappe
 from frappe import _
@@ -14,7 +14,7 @@
 Filters = frappe._dict
 
 
-def execute(filters: Filters = None) -> Tuple:
+def execute(filters: Filters = None) -> tuple:
 	to_date = filters["to_date"]
 	columns = get_columns(filters)
 
@@ -26,14 +26,14 @@
 	return columns, data, None, chart_data
 
 
-def format_report_data(filters: Filters, item_details: Dict, to_date: str) -> List[Dict]:
+def format_report_data(filters: Filters, item_details: dict, to_date: str) -> list[dict]:
 	"Returns ordered, formatted data with ranges."
 	_func = itemgetter(1)
 	data = []
 
 	precision = cint(frappe.db.get_single_value("System Settings", "float_precision", cache=True))
 
-	for item, item_dict in item_details.items():
+	for _item, item_dict in item_details.items():
 		if not flt(item_dict.get("total_qty"), precision):
 			continue
 
@@ -74,12 +74,12 @@
 	return data
 
 
-def get_average_age(fifo_queue: List, to_date: str) -> float:
+def get_average_age(fifo_queue: list, to_date: str) -> float:
 	batch_age = age_qty = total_qty = 0.0
 	for batch in fifo_queue:
 		batch_age = date_diff(to_date, batch[1])
 
-		if isinstance(batch[0], (int, float)):
+		if isinstance(batch[0], int | float):
 			age_qty += batch_age * batch[0]
 			total_qty += batch[0]
 		else:
@@ -89,8 +89,7 @@
 	return flt(age_qty / total_qty, 2) if total_qty else 0.0
 
 
-def get_range_age(filters: Filters, fifo_queue: List, to_date: str, item_dict: Dict) -> Tuple:
-
+def get_range_age(filters: Filters, fifo_queue: list, to_date: str, item_dict: dict) -> tuple:
 	precision = cint(frappe.db.get_single_value("System Settings", "float_precision", cache=True))
 
 	range1 = range2 = range3 = above_range3 = 0.0
@@ -111,7 +110,7 @@
 	return range1, range2, range3, above_range3
 
 
-def get_columns(filters: Filters) -> List[Dict]:
+def get_columns(filters: Filters) -> list[dict]:
 	range_columns = []
 	setup_ageing_columns(filters, range_columns)
 	columns = [
@@ -169,7 +168,7 @@
 	return columns
 
 
-def get_chart_data(data: List, filters: Filters) -> Dict:
+def get_chart_data(data: list, filters: Filters) -> dict:
 	if not data:
 		return []
 
@@ -193,7 +192,7 @@
 	}
 
 
-def setup_ageing_columns(filters: Filters, range_columns: List):
+def setup_ageing_columns(filters: Filters, range_columns: list):
 	ranges = [
 		f"0 - {filters['range1']}",
 		f"{cint(filters['range1']) + 1} - {cint(filters['range2'])}",
@@ -205,23 +204,21 @@
 		add_column(range_columns, label=_("Age ({0})").format(label), fieldname=fieldname)
 
 
-def add_column(
-	range_columns: List, label: str, fieldname: str, fieldtype: str = "Float", width: int = 140
-):
+def add_column(range_columns: list, label: str, fieldname: str, fieldtype: str = "Float", width: int = 140):
 	range_columns.append(dict(label=label, fieldname=fieldname, fieldtype=fieldtype, width=width))
 
 
 class FIFOSlots:
 	"Returns FIFO computed slots of inwarded stock as per date."
 
-	def __init__(self, filters: Dict = None, sle: List = None):
+	def __init__(self, filters: dict | None = None, sle: list | None = None):
 		self.item_details = {}
 		self.transferred_item_details = {}
 		self.serial_no_batch_purchase_details = {}
 		self.filters = filters
 		self.sle = sle
 
-	def generate(self) -> Dict:
+	def generate(self) -> dict:
 		"""
 		Returns dict of the foll.g structure:
 		Key = Item A / (Item A, Warehouse A)
@@ -264,7 +261,7 @@
 
 		return self.item_details
 
-	def __init_key_stores(self, row: Dict) -> Tuple:
+	def __init_key_stores(self, row: dict) -> tuple:
 		"Initialise keys and FIFO Queue."
 
 		key = (row.name, row.warehouse)
@@ -276,9 +273,7 @@
 
 		return key, fifo_queue, transferred_item_key
 
-	def __compute_incoming_stock(
-		self, row: Dict, fifo_queue: List, transfer_key: Tuple, serial_nos: List
-	):
+	def __compute_incoming_stock(self, row: dict, fifo_queue: list, transfer_key: tuple, serial_nos: list):
 		"Update FIFO Queue on inward stock."
 
 		transfer_data = self.transferred_item_details.get(transfer_key)
@@ -304,9 +299,7 @@
 					self.serial_no_batch_purchase_details.setdefault(serial_no, row.posting_date)
 					fifo_queue.append([serial_no, row.posting_date])
 
-	def __compute_outgoing_stock(
-		self, row: Dict, fifo_queue: List, transfer_key: Tuple, serial_nos: List
-	):
+	def __compute_outgoing_stock(self, row: dict, fifo_queue: list, transfer_key: tuple, serial_nos: list):
 		"Update FIFO Queue on outward stock."
 		if serial_nos:
 			fifo_queue[:] = [serial_no for serial_no in fifo_queue if serial_no[0] not in serial_nos]
@@ -332,7 +325,7 @@
 				self.transferred_item_details[transfer_key].append([qty_to_pop, slot[1]])
 				qty_to_pop = 0
 
-	def __adjust_incoming_transfer_qty(self, transfer_data: Dict, fifo_queue: List, row: Dict):
+	def __adjust_incoming_transfer_qty(self, transfer_data: dict, fifo_queue: list, row: dict):
 		"Add previously removed stock back to FIFO Queue."
 		transfer_qty_to_pop = flt(row.actual_qty)
 
@@ -359,7 +352,7 @@
 				add_to_fifo_queue([transfer_qty_to_pop, transfer_data[0][1]])
 				transfer_qty_to_pop = 0
 
-	def __update_balances(self, row: Dict, key: Union[Tuple, str]):
+	def __update_balances(self, row: dict, key: tuple | str):
 		self.item_details[key]["qty_after_transaction"] = row.qty_after_transaction
 
 		if "total_qty" not in self.item_details[key]:
@@ -369,7 +362,7 @@
 
 		self.item_details[key]["has_serial_no"] = row.has_serial_no
 
-	def __aggregate_details_by_item(self, wh_wise_data: Dict) -> Dict:
+	def __aggregate_details_by_item(self, wh_wise_data: dict) -> dict:
 		"Aggregate Item-Wh wise data into single Item entry."
 		item_aggregated_data = {}
 		for key, row in wh_wise_data.items():
@@ -377,7 +370,12 @@
 			if not item_aggregated_data.get(item):
 				item_aggregated_data.setdefault(
 					item,
-					{"details": frappe._dict(), "fifo_queue": [], "qty_after_transaction": 0.0, "total_qty": 0.0},
+					{
+						"details": frappe._dict(),
+						"fifo_queue": [],
+						"qty_after_transaction": 0.0,
+						"total_qty": 0.0,
+					},
 				)
 			item_row = item_aggregated_data.get(item)
 			item_row["details"].update(row["details"])
@@ -388,7 +386,7 @@
 
 		return item_aggregated_data
 
-	def __get_stock_ledger_entries(self) -> Iterator[Dict]:
+	def __get_stock_ledger_entries(self) -> Iterator[dict]:
 		sle = frappe.qb.DocType("Stock Ledger Entry")
 		item = self.__get_item_query()  # used as derived table in sle query
 
diff --git a/erpnext/stock/report/stock_analytics/stock_analytics.py b/erpnext/stock/report/stock_analytics/stock_analytics.py
index ab48181..920c315 100644
--- a/erpnext/stock/report/stock_analytics/stock_analytics.py
+++ b/erpnext/stock/report/stock_analytics/stock_analytics.py
@@ -1,7 +1,6 @@
 # Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
 # For license information, please see license.txt
 import datetime
-from typing import List
 
 import frappe
 from frappe import _, scrub
@@ -48,12 +47,10 @@
 
 	ranges = get_period_date_ranges(filters)
 
-	for dummy, end_date in ranges:
+	for _dummy, end_date in ranges:
 		period = get_period(end_date, filters)
 
-		columns.append(
-			{"label": _(period), "fieldname": scrub(period), "fieldtype": "Float", "width": 120}
-		)
+		columns.append({"label": _(period), "fieldname": scrub(period), "fieldtype": "Float", "width": 120})
 
 	return columns
 
@@ -67,7 +64,7 @@
 	increment = {"Monthly": 1, "Quarterly": 3, "Half-Yearly": 6, "Yearly": 12}.get(filters.range, 1)
 
 	periodic_daterange = []
-	for dummy in range(1, 53, increment):
+	for _dummy in range(1, 53, increment):
 		if filters.range == "Weekly":
 			period_end_date = from_date + relativedelta(days=6)
 		else:
@@ -116,9 +113,7 @@
 	elif filters.range == "Monthly":
 		period = _(str(months[posting_date.month - 1])) + " " + str(posting_date.year)
 	elif filters.range == "Quarterly":
-		period = _("Quarter {0} {1}").format(
-			str(((posting_date.month - 1) // 3) + 1), str(posting_date.year)
-		)
+		period = _("Quarter {0} {1}").format(str(((posting_date.month - 1) // 3) + 1), str(posting_date.year))
 	else:
 		year = get_fiscal_year(posting_date, company=filters.company)
 		period = str(year[2])
@@ -188,15 +183,13 @@
 		periodic_data.setdefault(d.item_code, {}).setdefault(period, {}).setdefault(d.warehouse, 0.0)
 
 		periodic_data[d.item_code]["balance"][d.warehouse] += value
-		periodic_data[d.item_code][period][d.warehouse] = periodic_data[d.item_code]["balance"][
-			d.warehouse
-		]
+		periodic_data[d.item_code][period][d.warehouse] = periodic_data[d.item_code]["balance"][d.warehouse]
 
 	return periodic_data
 
 
 def fill_intermediate_periods(
-	periodic_data, item_code: str, current_period: str, all_periods: List[str]
+	periodic_data, item_code: str, current_period: str, all_periods: list[str]
 ) -> None:
 	"""There might be intermediate periods where no stock ledger entry exists, copy previous previous data.
 
@@ -235,7 +228,7 @@
 
 	today = getdate()
 
-	for dummy, item_data in item_details.items():
+	for _dummy, item_data in item_details.items():
 		row = {
 			"name": item_data.name,
 			"item_name": item_data.item_name,
@@ -273,7 +266,7 @@
 		item_filters = {"is_stock_item": 1}
 		if item_group := filters.get("item_group"):
 			children = get_descendants_of("Item Group", item_group, ignore_permissions=True)
-			item_filters["item_group"] = ("in", children + [item_group])
+			item_filters["item_group"] = ("in", [*children, item_group])
 		if brand := filters.get("brand"):
 			item_filters["brand"] = brand
 
diff --git a/erpnext/stock/report/stock_analytics/test_stock_analytics.py b/erpnext/stock/report/stock_analytics/test_stock_analytics.py
index dd8f8d8..b4f086c 100644
--- a/erpnext/stock/report/stock_analytics/test_stock_analytics.py
+++ b/erpnext/stock/report/stock_analytics/test_stock_analytics.py
@@ -3,7 +3,7 @@
 import frappe
 from frappe import _dict
 from frappe.tests.utils import FrappeTestCase
-from frappe.utils.data import add_to_date, get_datetime, getdate, nowdate
+from frappe.utils.data import add_to_date, getdate
 
 from erpnext.accounts.utils import get_fiscal_year
 from erpnext.stock.doctype.item.test_item import make_item
@@ -55,7 +55,6 @@
 		self.assertEqual(actual_buckets, expected_buckets)
 
 	def test_get_period_date_ranges(self):
-
 		filters = _dict(range="Monthly", from_date="2020-12-28", to_date="2021-02-06")
 
 		ranges = get_period_date_ranges(filters)
@@ -69,7 +68,6 @@
 		self.assertEqual(ranges, expected_ranges)
 
 	def test_get_period_date_ranges_yearly(self):
-
 		filters = _dict(range="Yearly", from_date="2021-01-28", to_date="2021-02-06")
 
 		ranges = get_period_date_ranges(filters)
diff --git a/erpnext/stock/report/stock_and_account_value_comparison/stock_and_account_value_comparison.py b/erpnext/stock/report/stock_and_account_value_comparison/stock_and_account_value_comparison.py
index 416cf48..67e340d 100644
--- a/erpnext/stock/report/stock_and_account_value_comparison/stock_and_account_value_comparison.py
+++ b/erpnext/stock/report/stock_and_account_value_comparison/stock_and_account_value_comparison.py
@@ -14,9 +14,7 @@
 def execute(filters=None):
 	if not erpnext.is_perpetual_inventory_enabled(filters.company):
 		frappe.throw(
-			_("Perpetual inventory required for the company {0} to view this report.").format(
-				filters.company
-			)
+			_("Perpetual inventory required for the company {0} to view this report.").format(filters.company)
 		)
 
 	data = get_data(filters)
@@ -34,7 +32,7 @@
 		"posting_date": ("<=", report_filters.as_on_date),
 	}
 
-	currency_precision = get_currency_precision() or 2
+	get_currency_precision() or 2
 	stock_ledger_entries = get_stock_ledger_data(report_filters, filters)
 	voucher_wise_gl_data = get_gl_data(report_filters, filters)
 
diff --git a/erpnext/stock/report/stock_balance/stock_balance.py b/erpnext/stock/report/stock_balance/stock_balance.py
index 500affa..0d31398 100644
--- a/erpnext/stock/report/stock_balance/stock_balance.py
+++ b/erpnext/stock/report/stock_balance/stock_balance.py
@@ -3,7 +3,7 @@
 
 
 from operator import itemgetter
-from typing import Any, Dict, List, Optional, TypedDict
+from typing import Any, TypedDict
 
 import frappe
 from frappe import _
@@ -20,27 +20,27 @@
 
 
 class StockBalanceFilter(TypedDict):
-	company: Optional[str]
+	company: str | None
 	from_date: str
 	to_date: str
-	item_group: Optional[str]
-	item: Optional[str]
-	warehouse: Optional[str]
-	warehouse_type: Optional[str]
-	include_uom: Optional[str]  # include extra info in converted UOM
+	item_group: str | None
+	item: str | None
+	warehouse: str | None
+	warehouse_type: str | None
+	include_uom: str | None  # include extra info in converted UOM
 	show_stock_ageing_data: bool
 	show_variant_attributes: bool
 
 
-SLEntry = Dict[str, Any]
+SLEntry = dict[str, Any]
 
 
-def execute(filters: Optional[StockBalanceFilter] = None):
+def execute(filters: StockBalanceFilter | None = None):
 	return StockBalanceReport(filters).run()
 
 
-class StockBalanceReport(object):
-	def __init__(self, filters: Optional[StockBalanceFilter]) -> None:
+class StockBalanceReport:
+	def __init__(self, filters: StockBalanceFilter | None) -> None:
 		self.filters = filters
 		self.from_date = getdate(filters.get("from_date"))
 		self.to_date = getdate(filters.get("to_date"))
@@ -48,7 +48,7 @@
 		self.start_from = None
 		self.data = []
 		self.columns = []
-		self.sle_entries: List[SLEntry] = []
+		self.sle_entries: list[SLEntry] = []
 		self.set_company_currency()
 
 	def set_company_currency(self) -> None:
@@ -106,7 +106,7 @@
 		if self.filters.get("show_variant_attributes"):
 			variant_values = self.get_variant_values_for()
 
-		for key, report_data in self.item_warehouse_map.items():
+		for _key, report_data in self.item_warehouse_map.items():
 			if variant_data := variant_values.get(report_data.item_code):
 				report_data.update(variant_data)
 
@@ -201,7 +201,6 @@
 			qty_dict.opening_val += value_diff
 
 		elif entry.posting_date >= self.from_date and entry.posting_date <= self.to_date:
-
 			if flt(qty_diff, self.float_precision) >= 0:
 				qty_dict.in_qty += qty_diff
 				qty_dict.in_val += value_diff
@@ -247,7 +246,7 @@
 
 		return tuple(group_by_key)
 
-	def get_closing_balance(self) -> List[Dict[str, Any]]:
+	def get_closing_balance(self) -> list[dict[str, Any]]:
 		if self.filters.get("ignore_closing_balance"):
 			return []
 
@@ -342,7 +341,7 @@
 	def apply_items_filters(self, query, item_table) -> str:
 		if item_group := self.filters.get("item_group"):
 			children = get_descendants_of("Item Group", item_group, ignore_permissions=True)
-			query = query.where(item_table.item_group.isin(children + [item_group]))
+			query = query.where(item_table.item_group.isin([*children, item_group]))
 
 		for field in ["item_code", "brand"]:
 			if not self.filters.get(field):
@@ -566,7 +565,9 @@
 					frappe.qb.from_(sr)
 					.select(sr.name, Coalesce("Stock Reconciliation").as_("voucher_type"))
 					.where(
-						(sr.docstatus == 1) & (sr.posting_date <= self.to_date) & (sr.purpose == "Opening Stock")
+						(sr.docstatus == 1)
+						& (sr.posting_date <= self.to_date)
+						& (sr.purpose == "Opening Stock")
 					)
 				)
 			).select("voucher_type", "name")
@@ -592,7 +593,7 @@
 
 
 def filter_items_with_no_transactions(
-	iwb_map, float_precision: float, inventory_dimensions: list = None
+	iwb_map, float_precision: float, inventory_dimensions: list | None = None
 ):
 	pop_keys = []
 	for group_by_key in iwb_map:
@@ -629,6 +630,6 @@
 	return iwb_map
 
 
-def get_variants_attributes() -> List[str]:
+def get_variants_attributes() -> list[str]:
 	"""Return all item variant attributes."""
 	return frappe.get_all("Item Attribute", pluck="name")
diff --git a/erpnext/stock/report/stock_balance/test_stock_balance.py b/erpnext/stock/report/stock_balance/test_stock_balance.py
index e963de2..8b3dbee 100644
--- a/erpnext/stock/report/stock_balance/test_stock_balance.py
+++ b/erpnext/stock/report/stock_balance/test_stock_balance.py
@@ -1,4 +1,4 @@
-from typing import Any, Dict
+from typing import Any
 
 import frappe
 from frappe import _dict
@@ -32,12 +32,11 @@
 	def tearDown(self):
 		frappe.db.rollback()
 
-	def assertPartialDictEq(self, expected: Dict[str, Any], actual: Dict[str, Any]):
+	def assertPartialDictEq(self, expected: dict[str, Any], actual: dict[str, Any]):
 		for k, v in expected.items():
 			self.assertEqual(v, actual[k], msg=f"{expected=}\n{actual=}")
 
 	def generate_stock_ledger(self, item_code: str, movements):
-
 		for movement in map(_dict, movements):
 			if "to_warehouse" not in movement:
 				movement.to_warehouse = "_Test Warehouse - _TC"
@@ -128,7 +127,6 @@
 		self.assertPartialDictEq({"opening_qty": 6, "in_qty": 0}, rows[0])
 
 	def test_uom_converted_info(self):
-
 		self.item.append("uoms", {"conversion_factor": 5, "uom": "Box"})
 		self.item.save()
 
@@ -167,8 +165,6 @@
 		variant.save()
 
 		self.generate_stock_ledger(variant.name, [_dict(qty=5, rate=10)])
-		rows = stock_balance(
-			self.filters.update({"show_variant_attributes": 1, "item_code": variant.name})
-		)
+		rows = stock_balance(self.filters.update({"show_variant_attributes": 1, "item_code": variant.name}))
 		self.assertPartialDictEq(attributes, rows[0])
 		self.assertInvariants(rows)
diff --git a/erpnext/stock/report/stock_ledger/stock_ledger.py b/erpnext/stock/report/stock_ledger/stock_ledger.py
index e98351a..97e2f55 100644
--- a/erpnext/stock/report/stock_ledger/stock_ledger.py
+++ b/erpnext/stock/report/stock_ledger/stock_ledger.py
@@ -547,11 +547,8 @@
 def get_warehouse_condition(warehouse):
 	warehouse_details = frappe.db.get_value("Warehouse", warehouse, ["lft", "rgt"], as_dict=1)
 	if warehouse_details:
-		return (
-			" exists (select name from `tabWarehouse` wh \
-			where wh.lft >= %s and wh.rgt <= %s and warehouse = wh.name)"
-			% (warehouse_details.lft, warehouse_details.rgt)
-		)
+		return f" exists (select name from `tabWarehouse` wh \
+			where wh.lft >= {warehouse_details.lft} and wh.rgt <= {warehouse_details.rgt} and warehouse = wh.name)"
 
 	return ""
 
@@ -562,22 +559,17 @@
 		if item_table:
 			ig = frappe.qb.DocType("Item Group")
 			return item_table.item_group.isin(
-				(
-					frappe.qb.from_(ig)
-					.select(ig.name)
-					.where(
-						(ig.lft >= item_group_details.lft)
-						& (ig.rgt <= item_group_details.rgt)
-						& (item_table.item_group == ig.name)
-					)
+				frappe.qb.from_(ig)
+				.select(ig.name)
+				.where(
+					(ig.lft >= item_group_details.lft)
+					& (ig.rgt <= item_group_details.rgt)
+					& (item_table.item_group == ig.name)
 				)
 			)
 		else:
-			return (
-				"item.item_group in (select ig.name from `tabItem Group` ig \
-				where ig.lft >= %s and ig.rgt <= %s and item.item_group = ig.name)"
-				% (item_group_details.lft, item_group_details.rgt)
-			)
+			return f"item.item_group in (select ig.name from `tabItem Group` ig \
+				where ig.lft >= {item_group_details.lft} and ig.rgt <= {item_group_details.rgt} and item.item_group = ig.name)"
 
 
 def check_inventory_dimension_filters_applied(filters) -> bool:
diff --git a/erpnext/stock/report/stock_ledger/test_stock_ledger_report.py b/erpnext/stock/report/stock_ledger/test_stock_ledger_report.py
index c3c85aa..12800f2 100644
--- a/erpnext/stock/report/stock_ledger/test_stock_ledger_report.py
+++ b/erpnext/stock/report/stock_ledger/test_stock_ledger_report.py
@@ -8,9 +8,6 @@
 from erpnext.maintenance.doctype.maintenance_schedule.test_maintenance_schedule import (
 	make_serial_item_with_serial,
 )
-from erpnext.stock.doctype.delivery_note.test_delivery_note import create_delivery_note
-from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
-from erpnext.stock.report.stock_ledger.stock_ledger import execute
 
 
 class TestStockLedgerReeport(FrappeTestCase):
diff --git a/erpnext/stock/report/stock_ledger_variance/stock_ledger_variance.py b/erpnext/stock/report/stock_ledger_variance/stock_ledger_variance.py
index 189a90a..0b7e551 100644
--- a/erpnext/stock/report/stock_ledger_variance/stock_ledger_variance.py
+++ b/erpnext/stock/report/stock_ledger_variance/stock_ledger_variance.py
@@ -228,7 +228,7 @@
 	return data
 
 
-def get_item_warehouse_combinations(filters: dict = None) -> dict:
+def get_item_warehouse_combinations(filters: dict | None = None) -> dict:
 	filters = frappe._dict(filters or {})
 
 	bin = frappe.qb.DocType("Bin")
@@ -284,7 +284,5 @@
 		return True
 	elif difference_in == "Valuation" and valuation_diff:
 		return True
-	elif difference_in not in ["Qty", "Value", "Valuation"] and (
-		qty_diff or value_diff or valuation_diff
-	):
+	elif difference_in not in ["Qty", "Value", "Valuation"] and (qty_diff or value_diff or valuation_diff):
 		return True
diff --git a/erpnext/stock/report/stock_projected_qty/stock_projected_qty.py b/erpnext/stock/report/stock_projected_qty/stock_projected_qty.py
index 31c756d..743656c 100644
--- a/erpnext/stock/report/stock_projected_qty/stock_projected_qty.py
+++ b/erpnext/stock/report/stock_projected_qty/stock_projected_qty.py
@@ -250,9 +250,7 @@
 		query = query.where(bin.item_code == filters.item_code)
 
 	if filters.warehouse:
-		warehouse_details = frappe.db.get_value(
-			"Warehouse", filters.warehouse, ["lft", "rgt"], as_dict=1
-		)
+		warehouse_details = frappe.db.get_value("Warehouse", filters.warehouse, ["lft", "rgt"], as_dict=1)
 
 		if warehouse_details:
 			wh = frappe.qb.DocType("Warehouse")
@@ -286,7 +284,9 @@
 			(item.is_stock_item == 1)
 			& (item.disabled == 0)
 			& (
-				(item.end_of_life > today()) | (item.end_of_life.isnull()) | (item.end_of_life == "0000-00-00")
+				(item.end_of_life > today())
+				| (item.end_of_life.isnull())
+				| (item.end_of_life == "0000-00-00")
 			)
 			& (ExistsCriterion(frappe.qb.from_(bin).select(bin.name).where(bin.item_code == item.name)))
 		)
diff --git a/erpnext/stock/report/supplier_wise_sales_analytics/supplier_wise_sales_analytics.py b/erpnext/stock/report/supplier_wise_sales_analytics/supplier_wise_sales_analytics.py
index 8c76908..e28b2d7 100644
--- a/erpnext/stock/report/supplier_wise_sales_analytics/supplier_wise_sales_analytics.py
+++ b/erpnext/stock/report/supplier_wise_sales_analytics/supplier_wise_sales_analytics.py
@@ -20,7 +20,6 @@
 		total_qty = total_amount = 0.0
 		if consumed_details.get(item_code):
 			for cd in consumed_details.get(item_code):
-
 				if cd.voucher_no not in material_transfer_vouchers:
 					if cd.voucher_type in ["Delivery Note", "Sales Invoice"]:
 						delivered_qty += abs(flt(cd.actual_qty))
@@ -54,19 +53,19 @@
 def get_columns(filters):
 	"""return columns based on filters"""
 
-	columns = (
-		[_("Item") + ":Link/Item:100"]
-		+ [_("Item Name") + "::100"]
-		+ [_("Description") + "::150"]
-		+ [_("UOM") + ":Link/UOM:90"]
-		+ [_("Consumed Qty") + ":Float:110"]
-		+ [_("Consumed Amount") + ":Currency:130"]
-		+ [_("Delivered Qty") + ":Float:110"]
-		+ [_("Delivered Amount") + ":Currency:130"]
-		+ [_("Total Qty") + ":Float:110"]
-		+ [_("Total Amount") + ":Currency:130"]
-		+ [_("Supplier(s)") + "::250"]
-	)
+	columns = [
+		_("Item") + ":Link/Item:100",
+		_("Item Name") + "::100",
+		_("Description") + "::150",
+		_("UOM") + ":Link/UOM:90",
+		_("Consumed Qty") + ":Float:110",
+		_("Consumed Amount") + ":Currency:130",
+		_("Delivered Qty") + ":Float:110",
+		_("Delivered Amount") + ":Currency:130",
+		_("Total Qty") + ":Float:110",
+		_("Total Amount") + ":Currency:130",
+		_("Supplier(s)") + "::250",
+	]
 
 	return columns
 
@@ -173,9 +172,7 @@
 def get_material_transfer_vouchers():
 	se = frappe.qb.DocType("Stock Entry")
 	query = (
-		frappe.qb.from_(se)
-		.select(se.name)
-		.where((se.purpose == "Material Transfer") & (se.docstatus == 1))
+		frappe.qb.from_(se).select(se.name).where((se.purpose == "Material Transfer") & (se.docstatus == 1))
 	)
 
 	return [r[0] for r in query.run()]
diff --git a/erpnext/stock/report/test_reports.py b/erpnext/stock/report/test_reports.py
index d118d8e..74c6afa 100644
--- a/erpnext/stock/report/test_reports.py
+++ b/erpnext/stock/report/test_reports.py
@@ -1,5 +1,4 @@
 import unittest
-from typing import List, Tuple
 
 import frappe
 
@@ -14,7 +13,7 @@
 
 batch = frappe.db.get_value("Batch", fieldname=["name"], as_dict=True, order_by="creation desc")
 
-REPORT_FILTER_TEST_CASES: List[Tuple[ReportName, ReportFilters]] = [
+REPORT_FILTER_TEST_CASES: list[tuple[ReportName, ReportFilters]] = [
 	("Stock Ledger", {"_optional": True}),
 	("Stock Ledger", {"batch_no": batch}),
 	("Stock Ledger", {"item_code": "_Test Item", "warehouse": "_Test Warehouse - _TC"}),
diff --git a/erpnext/stock/report/total_stock_summary/total_stock_summary.py b/erpnext/stock/report/total_stock_summary/total_stock_summary.py
index c3155bd..4848c21 100644
--- a/erpnext/stock/report/total_stock_summary/total_stock_summary.py
+++ b/erpnext/stock/report/total_stock_summary/total_stock_summary.py
@@ -8,7 +8,6 @@
 
 
 def execute(filters=None):
-
 	if not filters:
 		filters = {}
 	columns = get_columns(filters)
@@ -54,8 +53,8 @@
 	else:
 		query = query.select(wh.company).groupby(wh.company)
 
-	query = query.select(
-		item.item_code, item.description, Sum(bin.actual_qty).as_("actual_qty")
-	).groupby(item.item_code)
+	query = query.select(item.item_code, item.description, Sum(bin.actual_qty).as_("actual_qty")).groupby(
+		item.item_code
+	)
 
 	return query.run()
diff --git a/erpnext/stock/report/warehouse_wise_item_balance_age_and_value/warehouse_wise_item_balance_age_and_value.py b/erpnext/stock/report/warehouse_wise_item_balance_age_and_value/warehouse_wise_item_balance_age_and_value.py
index 5dbdcef..e1cce31 100644
--- a/erpnext/stock/report/warehouse_wise_item_balance_age_and_value/warehouse_wise_item_balance_age_and_value.py
+++ b/erpnext/stock/report/warehouse_wise_item_balance_age_and_value/warehouse_wise_item_balance_age_and_value.py
@@ -40,7 +40,7 @@
 	item_balance = {}
 	item_value = {}
 
-	for (company, item, warehouse) in sorted(iwb_map):
+	for company, item, warehouse in sorted(iwb_map):
 		if not item_map.get(item):
 			continue
 
@@ -71,7 +71,7 @@
 
 		row += [average_age]
 
-		bal_qty = [sum(bal_qty) for bal_qty in zip(*wh_balance)]
+		bal_qty = [sum(bal_qty) for bal_qty in zip(*wh_balance, strict=False)]
 		total_qty = sum(bal_qty)
 		if len(warehouse_list) > 1:
 			row += [total_qty]
diff --git a/erpnext/stock/report/warehouse_wise_stock_balance/warehouse_wise_stock_balance.py b/erpnext/stock/report/warehouse_wise_stock_balance/warehouse_wise_stock_balance.py
index a0e9944..39baa54 100644
--- a/erpnext/stock/report/warehouse_wise_stock_balance/warehouse_wise_stock_balance.py
+++ b/erpnext/stock/report/warehouse_wise_stock_balance/warehouse_wise_stock_balance.py
@@ -1,7 +1,7 @@
 # Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
 # For license information, please see license.txt
 
-from typing import Any, Dict, List, Optional, TypedDict
+from typing import Any, TypedDict
 
 import frappe
 from frappe import _
@@ -9,12 +9,12 @@
 
 
 class StockBalanceFilter(TypedDict):
-	company: Optional[str]
-	warehouse: Optional[str]
-	show_disabled_warehouses: Optional[int]
+	company: str | None
+	warehouse: str | None
+	show_disabled_warehouses: int | None
 
 
-SLEntry = Dict[str, Any]
+SLEntry = dict[str, Any]
 
 
 def execute(filters=None):
@@ -25,7 +25,7 @@
 	return columns, data
 
 
-def get_warehouse_wise_balance(filters: StockBalanceFilter) -> List[SLEntry]:
+def get_warehouse_wise_balance(filters: StockBalanceFilter) -> list[SLEntry]:
 	sle = frappe.qb.DocType("Stock Ledger Entry")
 
 	query = (
@@ -95,7 +95,7 @@
 		update_balance(warehouse, warehouse.stock_balance)
 
 
-def get_columns(filters: StockBalanceFilter) -> List[Dict]:
+def get_columns(filters: StockBalanceFilter) -> list[dict]:
 	columns = [
 		{
 			"label": _("Warehouse"),
diff --git a/erpnext/stock/serial_batch_bundle.py b/erpnext/stock/serial_batch_bundle.py
index 9625b20..d9f3473 100644
--- a/erpnext/stock/serial_batch_bundle.py
+++ b/erpnext/stock/serial_batch_bundle.py
@@ -1,5 +1,4 @@
 from collections import defaultdict
-from typing import List
 
 import frappe
 from frappe import _, bold
@@ -130,13 +129,14 @@
 			frappe.throw(_(error_msg))
 
 	def set_serial_and_batch_bundle(self, sn_doc):
-		self.sle.db_set(
-			{"serial_and_batch_bundle": sn_doc.name, "auto_created_serial_and_batch_bundle": 1}
-		)
+		self.sle.db_set({"serial_and_batch_bundle": sn_doc.name, "auto_created_serial_and_batch_bundle": 1})
 
 		if sn_doc.is_rejected:
 			frappe.db.set_value(
-				self.child_doctype, self.sle.voucher_detail_no, "rejected_serial_and_batch_bundle", sn_doc.name
+				self.child_doctype,
+				self.sle.voucher_detail_no,
+				"rejected_serial_and_batch_bundle",
+				sn_doc.name,
 			)
 		else:
 			values_to_update = {
@@ -157,9 +157,7 @@
 	def child_doctype(self):
 		child_doctype = self.sle.voucher_type + " Item"
 
-		if (
-			self.sle.voucher_type == "Subcontracting Receipt" and self.sle.dependant_sle_voucher_detail_no
-		):
+		if self.sle.voucher_type == "Subcontracting Receipt" and self.sle.dependant_sle_voucher_detail_no:
 			child_doctype = "Subcontracting Receipt Supplied Item"
 
 		if self.sle.voucher_type == "Stock Entry":
@@ -343,9 +341,7 @@
 	if serial_nos:
 		filters["serial_no"] = ("in", serial_nos)
 
-	entries = frappe.get_all(
-		"Serial and Batch Entry", fields=["serial_no"], filters=filters, order_by="idx"
-	)
+	entries = frappe.get_all("Serial and Batch Entry", fields=["serial_no"], filters=filters, order_by="idx")
 	if not entries:
 		return []
 
@@ -497,9 +493,7 @@
 				# else it remains the same as that of previous entry
 				self.wh_data.valuation_rate = new_stock_value / new_stock_qty
 
-		if (
-			not self.wh_data.valuation_rate and self.sle.voucher_detail_no and not self.is_rejected_entry()
-		):
+		if not self.wh_data.valuation_rate and self.sle.voucher_detail_no and not self.is_rejected_entry():
 			allow_zero_rate = self.sle_self.check_if_allow_zero_valuation_rate(
 				self.sle.voucher_type, self.sle.voucher_detail_no
 			)
@@ -507,9 +501,7 @@
 				self.wh_data.valuation_rate = self.sle_self.get_fallback_rate(self.sle)
 
 		self.wh_data.qty_after_transaction += self.sle.actual_qty
-		self.wh_data.stock_value = flt(self.wh_data.qty_after_transaction) * flt(
-			self.wh_data.valuation_rate
-		)
+		self.wh_data.stock_value = flt(self.wh_data.qty_after_transaction) * flt(self.wh_data.valuation_rate)
 
 	def is_rejected_entry(self):
 		return is_rejected(self.sle.voucher_type, self.sle.voucher_detail_no, self.sle.warehouse)
@@ -560,7 +552,7 @@
 			self.calculate_avg_rate_for_non_batchwise_valuation()
 			self.set_stock_value_difference()
 
-	def get_batch_no_ledgers(self) -> List[dict]:
+	def get_batch_no_ledgers(self) -> list[dict]:
 		if not self.batchwise_valuation_batches:
 			return []
 
@@ -620,9 +612,7 @@
 		for batch in batches:
 			self.batchwise_valuation_batches.append(batch.name)
 
-		self.non_batchwise_valuation_batches = list(
-			set(self.batches) - set(self.batchwise_valuation_batches)
-		)
+		self.non_batchwise_valuation_batches = list(set(self.batches) - set(self.batchwise_valuation_batches))
 
 	def get_batch_nos(self) -> list:
 		if self.sle.get("batch_nos"):
@@ -659,9 +649,7 @@
 		if not hasattr(self, "wh_data"):
 			return
 
-		self.wh_data.stock_value = round_off_if_near_zero(
-			self.wh_data.stock_value + self.stock_value_change
-		)
+		self.wh_data.stock_value = round_off_if_near_zero(self.wh_data.stock_value + self.stock_value_change)
 
 		self.wh_data.qty_after_transaction += self.sle.actual_qty
 		if self.wh_data.qty_after_transaction:
@@ -796,17 +784,17 @@
 
 	def set_other_details(self):
 		if not self.get("posting_date"):
-			setattr(self, "posting_date", today())
+			self.posting_date = today()
 			self.__dict__["posting_date"] = self.posting_date
 
 		if not self.get("actual_qty"):
 			qty = self.get("qty") or self.get("total_qty")
 
-			setattr(self, "actual_qty", qty)
+			self.actual_qty = qty
 			self.__dict__["actual_qty"] = self.actual_qty
 
 		if not hasattr(self, "use_serial_batch_fields"):
-			setattr(self, "use_serial_batch_fields", 0)
+			self.use_serial_batch_fields = 0
 
 	def duplicate_package(self):
 		if not self.serial_and_batch_bundle:
@@ -920,9 +908,7 @@
 			self.batches = get_available_batches(kwargs)
 
 	def set_auto_serial_batch_entries_for_inward(self):
-		if (self.get("batches") and self.has_batch_no) or (
-			self.get("serial_nos") and self.has_serial_no
-		):
+		if (self.get("batches") and self.has_batch_no) or (self.get("serial_nos") and self.has_serial_no):
 			if self.use_serial_batch_fields and self.get("serial_nos"):
 				self.make_serial_no_if_not_exists()
 
@@ -950,7 +936,7 @@
 		serial_nos_details = []
 		batch_no = None
 		if self.batches:
-			batch_no = list(self.batches.keys())[0]
+			batch_no = next(iter(self.batches.keys()))
 
 		for serial_no in serial_nos:
 			serial_nos_details.append(
@@ -1040,7 +1026,7 @@
 			msg = f"Please set Serial No Series in the item {self.item_code} or create Serial and Batch Bundle manually."
 			frappe.throw(_(msg))
 
-		for i in range(abs(cint(self.actual_qty))):
+		for _i in range(abs(cint(self.actual_qty))):
 			serial_no = make_autoname(self.serial_no_series, "Serial No")
 			sr_nos.append(serial_no)
 			serial_nos_details.append(
diff --git a/erpnext/stock/stock_balance.py b/erpnext/stock/stock_balance.py
index ba03ff2..20bd4ca 100644
--- a/erpnext/stock/stock_balance.py
+++ b/erpnext/stock/stock_balance.py
@@ -15,9 +15,7 @@
 	frappe.db.auto_commit_on_many_writes = 1
 
 	if allow_negative_stock:
-		existing_allow_negative_stock = frappe.db.get_single_value(
-			"Stock Settings", "allow_negative_stock"
-		)
+		existing_allow_negative_stock = frappe.db.get_single_value("Stock Settings", "allow_negative_stock")
 		frappe.db.set_single_value("Stock Settings", "allow_negative_stock", 1)
 
 	item_warehouses = frappe.db.sql(
@@ -37,9 +35,7 @@
 			frappe.db.rollback()
 
 	if allow_negative_stock:
-		frappe.db.set_single_value(
-			"Stock Settings", "allow_negative_stock", existing_allow_negative_stock
-		)
+		frappe.db.set_single_value("Stock Settings", "allow_negative_stock", existing_allow_negative_stock)
 	frappe.db.auto_commit_on_many_writes = 0
 
 
@@ -51,7 +47,6 @@
 	only_bin=False,
 	allow_negative_stock=False,
 ):
-
 	if not only_bin:
 		repost_actual_qty(item_code, warehouse, allow_zero_rate, allow_negative_stock)
 
diff --git a/erpnext/stock/stock_ledger.py b/erpnext/stock/stock_ledger.py
index aef1a82..edb4df6 100644
--- a/erpnext/stock/stock_ledger.py
+++ b/erpnext/stock/stock_ledger.py
@@ -4,7 +4,6 @@
 import copy
 import gzip
 import json
-from typing import Optional, Set, Tuple
 
 import frappe
 from frappe import _, scrub
@@ -272,12 +271,10 @@
 		)
 		affected_transactions.update(obj.affected_transactions)
 
-		distinct_item_warehouses[
-			(args[i].get("item_code"), args[i].get("warehouse"))
-		].reposting_status = True
+		distinct_item_warehouses[(args[i].get("item_code"), args[i].get("warehouse"))].reposting_status = True
 
 		if obj.new_items_found:
-			for item_wh, data in distinct_item_warehouses.items():
+			for _item_wh, data in distinct_item_warehouses.items():
 				if ("args_idx" not in data and not data.reposting_status) or (
 					data.sle_changed and data.reposting_status
 				):
@@ -324,9 +321,7 @@
 			frappe.throw(_(validation_msg))
 
 
-def update_args_in_repost_item_valuation(
-	doc, index, args, distinct_item_warehouses, affected_transactions
-):
+def update_args_in_repost_item_valuation(doc, index, args, distinct_item_warehouses, affected_transactions):
 	if not doc.items_to_be_repost:
 		file_name = ""
 		if doc.reposting_data_file:
@@ -478,7 +473,7 @@
 	return new_dict
 
 
-def get_affected_transactions(doc, reposting_data=None) -> Set[Tuple[str, str]]:
+def get_affected_transactions(doc, reposting_data=None) -> set[tuple[str, str]]:
 	if not reposting_data and doc and doc.reposting_data_file:
 		reposting_data = get_reposting_data(doc.reposting_data_file)
 
@@ -497,7 +492,7 @@
 		return doc.current_index
 
 
-class update_entries_after(object):
+class update_entries_after:
 	"""
 	update valution rate and qty after transaction
 	from the current time-bucket onwards
@@ -539,7 +534,7 @@
 
 		self.new_items_found = False
 		self.distinct_item_warehouses = args.get("distinct_item_warehouses", frappe._dict())
-		self.affected_transactions: Set[Tuple[str, str]] = set()
+		self.affected_transactions: set[tuple[str, str]] = set()
 		self.reserved_stock = flt(self.args.reserved_stock)
 
 		self.data = frappe._dict()
@@ -618,9 +613,7 @@
 			self.process_sle(sle)
 
 	def get_sle_against_current_voucher(self):
-		self.args["posting_datetime"] = get_combine_datetime(
-			self.args.posting_date, self.args.posting_time
-		)
+		self.args["posting_datetime"] = get_combine_datetime(self.args.posting_date, self.args.posting_time)
 
 		return frappe.db.sql(
 			"""
@@ -658,9 +651,7 @@
 
 		if not dependant_sle:
 			return entries_to_fix
-		elif (
-			dependant_sle.item_code == self.item_code and dependant_sle.warehouse == self.args.warehouse
-		):
+		elif dependant_sle.item_code == self.item_code and dependant_sle.warehouse == self.args.warehouse:
 			return entries_to_fix
 		elif dependant_sle.item_code != self.item_code:
 			self.update_distinct_item_warehouses(dependant_sle)
@@ -680,9 +671,7 @@
 			self.distinct_item_warehouses[key] = val
 			self.new_items_found = True
 		else:
-			existing_sle_posting_date = (
-				self.distinct_item_warehouses[key].get("sle", {}).get("posting_date")
-			)
+			existing_sle_posting_date = self.distinct_item_warehouses[key].get("sle", {}).get("posting_date")
 
 			dependent_voucher_detail_nos = self.get_dependent_voucher_detail_nos(key)
 
@@ -774,7 +763,9 @@
 					self.wh_data.valuation_rate
 				)
 				if self.valuation_method != "Moving Average":
-					self.wh_data.stock_queue = [[self.wh_data.qty_after_transaction, self.wh_data.valuation_rate]]
+					self.wh_data.stock_queue = [
+						[self.wh_data.qty_after_transaction, self.wh_data.valuation_rate]
+					]
 			else:
 				if self.valuation_method == "Moving Average":
 					self.get_moving_average_values(sle)
@@ -843,9 +834,7 @@
 				self.wh_data.valuation_rate = new_stock_value / new_stock_qty
 
 		if not self.wh_data.valuation_rate and sle.voucher_detail_no:
-			allow_zero_rate = self.check_if_allow_zero_valuation_rate(
-				sle.voucher_type, sle.voucher_detail_no
-			)
+			allow_zero_rate = self.check_if_allow_zero_valuation_rate(sle.voucher_type, sle.voucher_detail_no)
 			if not allow_zero_rate:
 				self.wh_data.valuation_rate = self.get_fallback_rate(sle)
 
@@ -862,9 +851,7 @@
 			if abs(sle.actual_qty) == 0.0:
 				sle.is_cancelled = 1
 
-		if sle.serial_and_batch_bundle and frappe.get_cached_value(
-			"Item", sle.item_code, "has_serial_no"
-		):
+		if sle.serial_and_batch_bundle and frappe.get_cached_value("Item", sle.item_code, "has_serial_no"):
 			self.update_serial_no_status(sle)
 
 	def update_serial_no_status(self, sle):
@@ -1265,9 +1252,7 @@
 		stock_value_difference = stock_value - prev_stock_value
 
 		self.wh_data.stock_queue = stock_queue.state
-		self.wh_data.stock_value = round_off_if_near_zero(
-			self.wh_data.stock_value + stock_value_difference
-		)
+		self.wh_data.stock_value = round_off_if_near_zero(self.wh_data.stock_value + stock_value_difference)
 
 		if not self.wh_data.stock_queue:
 			self.wh_data.stock_queue.append(
@@ -1305,9 +1290,7 @@
 				outgoing_rate = self.get_fallback_rate(sle)
 			stock_value_difference = outgoing_rate * actual_qty
 
-		self.wh_data.stock_value = round_off_if_near_zero(
-			self.wh_data.stock_value + stock_value_difference
-		)
+		self.wh_data.stock_value = round_off_if_near_zero(self.wh_data.stock_value + stock_value_difference)
 		if self.wh_data.qty_after_transaction:
 			self.wh_data.valuation_rate = self.wh_data.stock_value / self.wh_data.qty_after_transaction
 
@@ -1356,7 +1339,6 @@
 				exceptions[0]["voucher_type"],
 				exceptions[0]["voucher_no"],
 			) in frappe.local.flags.currently_saving:
-
 				msg = _("{0} units of {1} needed in {2} to complete this transaction.").format(
 					frappe.bold(abs(deficiency)),
 					frappe.get_desk_link("Item", exceptions[0]["item_code"]),
@@ -1379,13 +1361,11 @@
 					allowed_qty = abs(exceptions[0]["actual_qty"]) - abs(exceptions[0]["diff"])
 
 					if allowed_qty > 0:
-						msg = "{0} As {1} units are reserved for other sales orders, you are allowed to consume only {2} units.".format(
+						msg = "{} As {} units are reserved for other sales orders, you are allowed to consume only {} units.".format(
 							msg, frappe.bold(self.reserved_stock), frappe.bold(allowed_qty)
 						)
 					else:
-						msg = "{0} As the full stock is reserved for other sales orders, you're not allowed to consume the stock.".format(
-							msg,
-						)
+						msg = f"{msg} As the full stock is reserved for other sales orders, you're not allowed to consume the stock."
 
 				msg_list.append(msg)
 
@@ -1434,7 +1414,7 @@
 		voucher_condition = f"and voucher_no != '{voucher_no}'"
 
 	sle = frappe.db.sql(
-		"""
+		f"""
 		select *, posting_datetime as "timestamp"
 		from `tabStock Ledger Entry`
 		where item_code = %(item_code)s
@@ -1446,10 +1426,7 @@
 			)
 		order by posting_datetime desc, creation desc
 		limit 1
-		for update""".format(
-			operator=operator,
-			voucher_condition=voucher_condition,
-		),
+		for update""",
 		args,
 		as_dict=1,
 	)
@@ -1489,7 +1466,7 @@
 	extra_cond=None,
 ):
 	"""get stock ledger entries filtered by specific posting datetime conditions"""
-	conditions = " and posting_datetime {0} %(posting_datetime)s".format(operator)
+	conditions = f" and posting_datetime {operator} %(posting_datetime)s"
 	if previous_sle.get("warehouse"):
 		conditions += " and warehouse = %(warehouse)s"
 	elif previous_sle.get("warehouse_condition"):
@@ -1501,17 +1478,17 @@
 		conditions += (
 			""" and
 			(
-				serial_no = {0}
-				or serial_no like {1}
-				or serial_no like {2}
-				or serial_no like {3}
+				serial_no = {}
+				or serial_no like {}
+				or serial_no like {}
+				or serial_no like {}
 			)
 		"""
 		).format(
 			frappe.db.escape(serial_no),
-			frappe.db.escape("{}\n%".format(serial_no)),
-			frappe.db.escape("%\n{}".format(serial_no)),
-			frappe.db.escape("%\n{}\n%".format(serial_no)),
+			frappe.db.escape(f"{serial_no}\n%"),
+			frappe.db.escape(f"%\n{serial_no}"),
+			frappe.db.escape(f"%\n{serial_no}\n%"),
 		)
 
 	if not previous_sle.get("posting_date"):
@@ -1531,17 +1508,16 @@
 		"""
 		select *, posting_datetime as "timestamp"
 		from `tabStock Ledger Entry`
-		where item_code = %%(item_code)s
+		where item_code = %(item_code)s
 		and is_cancelled = 0
-		%(conditions)s
-		order by posting_datetime %(order)s, creation %(order)s
-		%(limit)s %(for_update)s"""
-		% {
-			"conditions": conditions,
-			"limit": limit or "",
-			"for_update": for_update and "for update" or "",
-			"order": order,
-		},
+		{conditions}
+		order by posting_datetime {order}, creation {order}
+		{limit} {for_update}""".format(
+			conditions=conditions,
+			limit=limit or "",
+			for_update=for_update and "for update" or "",
+			order=order,
+		),
 		previous_sle,
 		as_dict=1,
 		debug=debug,
@@ -1566,17 +1542,14 @@
 	)
 
 
-def get_batch_incoming_rate(
-	item_code, warehouse, batch_no, posting_date, posting_time, creation=None
-):
-
+def get_batch_incoming_rate(item_code, warehouse, batch_no, posting_date, posting_time, creation=None):
 	sle = frappe.qb.DocType("Stock Ledger Entry")
 
 	timestamp_condition = sle.posting_datetime < get_combine_datetime(posting_date, posting_time)
 	if creation:
-		timestamp_condition |= (
-			sle.posting_datetime == get_combine_datetime(posting_date, posting_time)
-		) & (sle.creation < creation)
+		timestamp_condition |= (sle.posting_datetime == get_combine_datetime(posting_date, posting_time)) & (
+			sle.creation < creation
+		)
 
 	batch_details = (
 		frappe.qb.from_(sle)
@@ -1606,7 +1579,6 @@
 	batch_no=None,
 	serial_and_batch_bundle=None,
 ):
-
 	from erpnext.stock.serial_batch_bundle import BatchNoValuation
 
 	if not company:
@@ -1697,7 +1669,7 @@
 		solutions += (
 			"<li>"
 			+ _("If not, you can Cancel / Submit this entry")
-			+ " {0} ".format(frappe.bold(_("after")))
+			+ " {} ".format(frappe.bold(_("after")))
 			+ _("performing either one below:")
 			+ "</li>"
 		)
@@ -1833,9 +1805,7 @@
 	neg_sle = get_future_sle_with_negative_qty(args)
 
 	if is_negative_with_precision(neg_sle):
-		message = _(
-			"{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction."
-		).format(
+		message = _("{0} units of {1} needed in {2} on {3} {4} for {5} to complete this transaction.").format(
 			abs(neg_sle[0]["qty_after_transaction"]),
 			frappe.get_desk_link("Item", args.item_code),
 			frappe.get_desk_link("Warehouse", args.warehouse),
@@ -1970,12 +1940,8 @@
 
 
 def validate_reserved_serial_nos(item_code, warehouse, serial_nos):
-	if reserved_serial_nos_details := get_sre_reserved_serial_nos_details(
-		item_code, warehouse, serial_nos
-	):
-		if common_serial_nos := list(
-			set(serial_nos).intersection(set(reserved_serial_nos_details.keys()))
-		):
+	if reserved_serial_nos_details := get_sre_reserved_serial_nos_details(item_code, warehouse, serial_nos):
+		if common_serial_nos := list(set(serial_nos).intersection(set(reserved_serial_nos_details.keys()))):
 			msg = _(
 				"Serial Nos are reserved in Stock Reservation Entries, you need to unreserve them before proceeding."
 			)
@@ -2019,7 +1985,7 @@
 				frappe.throw(msg, title=_("Reserved Stock for Batch"))
 
 
-def is_negative_stock_allowed(*, item_code: Optional[str] = None) -> bool:
+def is_negative_stock_allowed(*, item_code: str | None = None) -> bool:
 	if cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock", cache=True)):
 		return True
 	if item_code and cint(frappe.db.get_value("Item", item_code, "allow_negative_stock", cache=True)):
diff --git a/erpnext/stock/tests/test_get_item_details.py b/erpnext/stock/tests/test_get_item_details.py
index b53e29e..30f748a 100644
--- a/erpnext/stock/tests/test_get_item_details.py
+++ b/erpnext/stock/tests/test_get_item_details.py
@@ -1,5 +1,3 @@
-import json
-
 import frappe
 from frappe.test_runner import make_test_records
 from frappe.tests.utils import FrappeTestCase
@@ -16,7 +14,6 @@
 		super().setUp()
 
 	def test_get_item_detail_purchase_order(self):
-
 		args = frappe._dict(
 			{
 				"item_code": "_Test Item",
@@ -29,7 +26,6 @@
 				"name": None,
 				"supplier": "_Test Supplier",
 				"transaction_date": None,
-				"conversion_rate": 1.0,
 				"price_list": "_Test Buying Price List",
 				"is_subcontracted": 0,
 				"ignore_pricing_rule": 1,
diff --git a/erpnext/stock/tests/test_utils.py b/erpnext/stock/tests/test_utils.py
index 4e93ac9..bc646fa 100644
--- a/erpnext/stock/tests/test_utils.py
+++ b/erpnext/stock/tests/test_utils.py
@@ -28,7 +28,7 @@
 		)
 		self.assertGreaterEqual(len(sles), len(expected_sles))
 
-		for exp_sle, act_sle in zip(expected_sles, sles):
+		for exp_sle, act_sle in zip(expected_sles, sles, strict=False):
 			for k, v in exp_sle.items():
 				act_value = act_sle[k]
 				if k == "stock_queue":
@@ -51,7 +51,7 @@
 			order_by=order_by or "posting_date, creation",
 		)
 		self.assertGreaterEqual(len(actual_gles), len(expected_gles))
-		for exp_gle, act_gle in zip(expected_gles, actual_gles):
+		for exp_gle, act_gle in zip(expected_gles, actual_gles, strict=False):
 			for k, exp_value in exp_gle.items():
 				act_value = act_gle[k]
 				self.assertEqual(exp_value, act_value, msg=f"{k} doesn't match \n{exp_gle}\n{act_gle}")
diff --git a/erpnext/stock/tests/test_valuation.py b/erpnext/stock/tests/test_valuation.py
index 4d8990a..47b8f0b 100644
--- a/erpnext/stock/tests/test_valuation.py
+++ b/erpnext/stock/tests/test_valuation.py
@@ -28,9 +28,7 @@
 		self.assertAlmostEqual(sum(q for q, _ in self.queue), qty, msg=f"queue: {self.queue}", places=4)
 
 	def assertTotalValue(self, value):
-		self.assertAlmostEqual(
-			sum(q * r for q, r in self.queue), value, msg=f"queue: {self.queue}", places=2
-		)
+		self.assertAlmostEqual(sum(q * r for q, r in self.queue), value, msg=f"queue: {self.queue}", places=2)
 
 	def test_simple_addition(self):
 		self.queue.add_stock(1, 10)
@@ -210,9 +208,7 @@
 		self.assertAlmostEqual(sum(q for q, _ in self.stack), qty, msg=f"stack: {self.stack}", places=4)
 
 	def assertTotalValue(self, value):
-		self.assertAlmostEqual(
-			sum(q * r for q, r in self.stack), value, msg=f"stack: {self.stack}", places=2
-		)
+		self.assertAlmostEqual(sum(q * r for q, r in self.stack), value, msg=f"stack: {self.stack}", places=2)
 
 	def test_simple_addition(self):
 		self.stack.add_stock(1, 10)
@@ -355,7 +351,6 @@
 			self.assertEqual(stock_queue, expected_queue)
 
 	def test_lifo_values(self):
-
 		in1 = self._make_stock_entry(1, 1)
 		self.assertStockQueue(in1, [[1, 1]])
 
diff --git a/erpnext/stock/utils.py b/erpnext/stock/utils.py
index 93e2fa4..64c239a 100644
--- a/erpnext/stock/utils.py
+++ b/erpnext/stock/utils.py
@@ -3,7 +3,6 @@
 
 
 import json
-from typing import Dict, Optional
 
 import frappe
 from frappe import _
@@ -18,7 +17,7 @@
 from erpnext.stock.serial_batch_bundle import BatchNoValuation, SerialNoValuation
 from erpnext.stock.valuation import FIFOValuation, LIFOValuation
 
-BarcodeScanResult = Dict[str, Optional[str]]
+BarcodeScanResult = dict[str, str | None]
 
 
 class InvalidWarehouseCompany(frappe.ValidationError):
@@ -59,7 +58,7 @@
 
 
 def get_stock_value_on(
-	warehouses: list | str = None, posting_date: str = None, item_code: str = None
+	warehouses: list | str | None = None, posting_date: str | None = None, item_code: str | None = None
 ) -> float:
 	if not posting_date:
 		posting_date = nowdate()
@@ -150,9 +149,7 @@
 				else (0.0, 0.0, None)
 			)
 		else:
-			return (
-				(last_entry.qty_after_transaction, last_entry.valuation_rate) if last_entry else (0.0, 0.0)
-			)
+			return (last_entry.qty_after_transaction, last_entry.valuation_rate) if last_entry else (0.0, 0.0)
 	else:
 		return last_entry.qty_after_transaction if last_entry else 0.0
 
@@ -180,10 +177,8 @@
 			condition += " AND warehouse = %s"
 
 	actual_qty = frappe.db.sql(
-		"""select sum(actual_qty) from tabBin
-		where item_code=%s {0}""".format(
-			condition
-		),
+		f"""select sum(actual_qty) from tabBin
+		where item_code=%s {condition}""",
 		values,
 	)[0][0]
 
@@ -278,9 +273,7 @@
 		args.actual_qty = args.qty
 		args.serial_nos = get_serial_nos_data(args.get("serial_no"))
 
-		sn_obj = SerialNoValuation(
-			sle=args, warehouse=args.get("warehouse"), item_code=args.get("item_code")
-		)
+		sn_obj = SerialNoValuation(sle=args, warehouse=args.get("warehouse"), item_code=args.get("item_code"))
 
 		return sn_obj.get_incoming_rate()
 	elif (
@@ -288,7 +281,6 @@
 		and frappe.db.get_value("Batch", args.get("batch_no"), "use_batchwise_valuation", cache=True)
 		and not args.get("serial_and_batch_bundle")
 	):
-
 		args.actual_qty = args.qty
 		args.batch_nos = frappe._dict({args.batch_no: args})
 
@@ -329,10 +321,7 @@
 	return flt(in_rate)
 
 
-def get_batch_incoming_rate(
-	item_code, warehouse, batch_no, posting_date, posting_time, creation=None
-):
-
+def get_batch_incoming_rate(item_code, warehouse, batch_no, posting_date, posting_time, creation=None):
 	sle = frappe.qb.DocType("Stock Ledger Entry")
 
 	timestamp_condition = CombineDatetime(sle.posting_date, sle.posting_time) < CombineDatetime(
@@ -340,8 +329,7 @@
 	)
 	if creation:
 		timestamp_condition |= (
-			CombineDatetime(sle.posting_date, sle.posting_time)
-			== CombineDatetime(posting_date, posting_time)
+			CombineDatetime(sle.posting_date, sle.posting_time) == CombineDatetime(posting_date, posting_time)
 		) & (sle.creation < creation)
 
 	batch_details = (
@@ -379,9 +367,7 @@
 	"""get valuation method from item or default"""
 	val_method = frappe.db.get_value("Item", item_code, "valuation_method", cache=True)
 	if not val_method:
-		val_method = (
-			frappe.db.get_single_value("Stock Settings", "valuation_method", cache=True) or "FIFO"
-		)
+		val_method = frappe.db.get_single_value("Stock Settings", "valuation_method", cache=True) or "FIFO"
 	return val_method
 
 
@@ -456,7 +442,6 @@
 	if not include_uom or not conversion_factors:
 		return
 
-	convertible_cols = {}
 	is_dict_obj = False
 	if isinstance(result[0], dict):
 		is_dict_obj = True
@@ -471,8 +456,8 @@
 			columns.insert(
 				idx + 1,
 				{
-					"label": "{0} (per {1})".format(d.get("label"), include_uom),
-					"fieldname": "{0}_{1}".format(d.get("fieldname"), frappe.scrub(include_uom)),
+					"label": "{} (per {})".format(d.get("label"), include_uom),
+					"fieldname": "{}_{}".format(d.get("fieldname"), frappe.scrub(include_uom)),
 					"fieldtype": "Currency" if d.get("convertible") == "rate" else "Float",
 				},
 			)
@@ -495,7 +480,7 @@
 			if not is_dict_obj:
 				row.insert(key + 1, new_value)
 			else:
-				new_key = "{0}_{1}".format(key, frappe.scrub(include_uom))
+				new_key = f"{key}_{frappe.scrub(include_uom)}"
 				update_dict_values.append([row, new_key, new_value])
 
 	for data in update_dict_values:
@@ -518,9 +503,9 @@
 				{"converted_col": columns[next_col]["fieldname"], "for_type": col.get("convertible")}
 			)
 			if col.get("convertible") == "rate":
-				columns[next_col]["label"] += " (per {})".format(include_uom)
+				columns[next_col]["label"] += f" (per {include_uom})"
 			else:
-				columns[next_col]["label"] += " ({})".format(include_uom)
+				columns[next_col]["label"] += f" ({include_uom})"
 
 	for row_idx, row in enumerate(result):
 		for convertible_col, data in convertible_column_map.items():
@@ -594,7 +579,7 @@
 	def set_cache(data: BarcodeScanResult):
 		frappe.cache().set_value(f"erpnext:barcode_scan:{search_value}", data, expires_in_sec=120)
 
-	def get_cache() -> Optional[BarcodeScanResult]:
+	def get_cache() -> BarcodeScanResult | None:
 		if data := frappe.cache().get_value(f"erpnext:barcode_scan:{search_value}"):
 			return data
 
@@ -647,7 +632,7 @@
 	return {}
 
 
-def _update_item_info(scan_result: Dict[str, Optional[str]]) -> Dict[str, Optional[str]]:
+def _update_item_info(scan_result: dict[str, str | None]) -> dict[str, str | None]:
 	if item_code := scan_result.get("item_code"):
 		if item_info := frappe.get_cached_value(
 			"Item",
diff --git a/erpnext/stock/valuation.py b/erpnext/stock/valuation.py
index 35f4f12..b1df982 100644
--- a/erpnext/stock/valuation.py
+++ b/erpnext/stock/valuation.py
@@ -1,9 +1,10 @@
 from abc import ABC, abstractmethod, abstractproperty
-from typing import Callable, List, NewType, Optional, Tuple
+from collections.abc import Callable
+from typing import NewType
 
 from frappe.utils import flt
 
-StockBin = NewType("StockBin", List[float])  # [[qty, rate], ...]
+StockBin = NewType("StockBin", list[float])  # [[qty, rate], ...]
 
 # Indexes of values inside FIFO bin 2-tuple
 QTY = 0
@@ -17,15 +18,15 @@
 
 	@abstractmethod
 	def remove_stock(
-		self, qty: float, outgoing_rate: float = 0.0, rate_generator: Callable[[], float] = None
-	) -> List[StockBin]:
+		self, qty: float, outgoing_rate: float = 0.0, rate_generator: Callable[[], float] | None = None
+	) -> list[StockBin]:
 		pass
 
 	@abstractproperty
-	def state(self) -> List[StockBin]:
+	def state(self) -> list[StockBin]:
 		pass
 
-	def get_total_stock_and_value(self) -> Tuple[float, float]:
+	def get_total_stock_and_value(self) -> tuple[float, float]:
 		total_qty = 0.0
 		total_value = 0.0
 
@@ -62,11 +63,11 @@
 	# ref: https://docs.python.org/3/reference/datamodel.html#slots
 	__slots__ = ["queue"]
 
-	def __init__(self, state: Optional[List[StockBin]]):
-		self.queue: List[StockBin] = state if state is not None else []
+	def __init__(self, state: list[StockBin] | None):
+		self.queue: list[StockBin] = state if state is not None else []
 
 	@property
-	def state(self) -> List[StockBin]:
+	def state(self) -> list[StockBin]:
 		"""Get current state of queue."""
 		return self.queue
 
@@ -95,8 +96,8 @@
 					self.queue[-1][QTY] = qty
 
 	def remove_stock(
-		self, qty: float, outgoing_rate: float = 0.0, rate_generator: Callable[[], float] = None
-	) -> List[StockBin]:
+		self, qty: float, outgoing_rate: float = 0.0, rate_generator: Callable[[], float] | None = None
+	) -> list[StockBin]:
 		"""Remove stock from the queue and return popped bins.
 
 		args:
@@ -166,11 +167,11 @@
 	# ref: https://docs.python.org/3/reference/datamodel.html#slots
 	__slots__ = ["stack"]
 
-	def __init__(self, state: Optional[List[StockBin]]):
-		self.stack: List[StockBin] = state if state is not None else []
+	def __init__(self, state: list[StockBin] | None):
+		self.stack: list[StockBin] = state if state is not None else []
 
 	@property
-	def state(self) -> List[StockBin]:
+	def state(self) -> list[StockBin]:
 		"""Get current state of stack."""
 		return self.stack
 
@@ -201,8 +202,8 @@
 					self.stack[-1][QTY] = qty
 
 	def remove_stock(
-		self, qty: float, outgoing_rate: float = 0.0, rate_generator: Callable[[], float] = None
-	) -> List[StockBin]:
+		self, qty: float, outgoing_rate: float = 0.0, rate_generator: Callable[[], float] | None = None
+	) -> list[StockBin]:
 		"""Remove stock from the stack and return popped bins.
 
 		args:
diff --git a/erpnext/subcontracting/doctype/subcontracting_bom/subcontracting_bom.py b/erpnext/subcontracting/doctype/subcontracting_bom/subcontracting_bom.py
index 6a889b1..a7a9b42 100644
--- a/erpnext/subcontracting/doctype/subcontracting_bom/subcontracting_bom.py
+++ b/erpnext/subcontracting/doctype/subcontracting_bom/subcontracting_bom.py
@@ -45,9 +45,7 @@
 		if disabled:
 			frappe.throw(_("Finished Good {0} is disabled.").format(frappe.bold(self.finished_good)))
 		if not is_stock_item:
-			frappe.throw(
-				_("Finished Good {0} must be a stock item.").format(frappe.bold(self.finished_good))
-			)
+			frappe.throw(_("Finished Good {0} must be a stock item.").format(frappe.bold(self.finished_good)))
 		if not default_bom:
 			frappe.throw(
 				_("Finished Good {0} does not have a default BOM.").format(frappe.bold(self.finished_good))
diff --git a/erpnext/subcontracting/doctype/subcontracting_order/subcontracting_order.py b/erpnext/subcontracting/doctype/subcontracting_order/subcontracting_order.py
index 321ae51..4d3441a 100644
--- a/erpnext/subcontracting/doctype/subcontracting_order/subcontracting_order.py
+++ b/erpnext/subcontracting/doctype/subcontracting_order/subcontracting_order.py
@@ -83,7 +83,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(SubcontractingOrder, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 
 		self.status_updater = [
 			{
@@ -100,10 +100,10 @@
 		]
 
 	def before_validate(self):
-		super(SubcontractingOrder, self).before_validate()
+		super().before_validate()
 
 	def validate(self):
-		super(SubcontractingOrder, self).validate()
+		super().validate()
 		self.validate_purchase_order_for_subcontracting()
 		self.validate_items()
 		self.validate_service_items()
@@ -198,9 +198,7 @@
 			):
 				item_wh_list.append([item.item_code, item.warehouse])
 		for item_code, warehouse in item_wh_list:
-			update_bin_qty(
-				item_code, warehouse, {"ordered_qty": self.get_ordered_qty(item_code, warehouse)}
-			)
+			update_bin_qty(item_code, warehouse, {"ordered_qty": self.get_ordered_qty(item_code, warehouse)})
 
 	@staticmethod
 	def get_ordered_qty(item_code, warehouse):
@@ -239,7 +237,9 @@
 				item = frappe.get_doc("Item", si.fg_item)
 				bom = (
 					frappe.db.get_value(
-						"Subcontracting BOM", {"finished_good": item.item_code, "is_active": 1}, "finished_good_bom"
+						"Subcontracting BOM",
+						{"finished_good": item.item_code, "is_active": 1},
+						"finished_good_bom",
 					)
 					or item.default_bom
 				)
diff --git a/erpnext/subcontracting/doctype/subcontracting_order/test_subcontracting_order.py b/erpnext/subcontracting/doctype/subcontracting_order/test_subcontracting_order.py
index 6c0ee45..0ae0799 100644
--- a/erpnext/subcontracting/doctype/subcontracting_order/test_subcontracting_order.py
+++ b/erpnext/subcontracting/doctype/subcontracting_order/test_subcontracting_order.py
@@ -211,7 +211,7 @@
 			item["qty"] -= 1
 			itemwise_transfer_qty[item["item_code"]] += item["qty"]
 
-		ste = make_stock_transfer_entry(
+		make_stock_transfer_entry(
 			sco_no=sco.name,
 			rm_items=rm_items,
 			itemwise_details=copy.deepcopy(itemwise_details),
@@ -713,7 +713,7 @@
 		warehouses.add(item.warehouse)
 
 	if len(warehouses) == 1:
-		sco.set_warehouse = list(warehouses)[0]
+		sco.set_warehouse = next(iter(warehouses))
 
 	if not args.do_not_save:
 		sco.insert()
diff --git a/erpnext/subcontracting/doctype/subcontracting_receipt/subcontracting_receipt.py b/erpnext/subcontracting/doctype/subcontracting_receipt/subcontracting_receipt.py
index 4e2b9c2..49b7b0f 100644
--- a/erpnext/subcontracting/doctype/subcontracting_receipt/subcontracting_receipt.py
+++ b/erpnext/subcontracting/doctype/subcontracting_receipt/subcontracting_receipt.py
@@ -85,7 +85,7 @@
 	# end: auto-generated types
 
 	def __init__(self, *args, **kwargs):
-		super(SubcontractingReceipt, self).__init__(*args, **kwargs)
+		super().__init__(*args, **kwargs)
 		self.status_updater = [
 			{
 				"target_dt": "Subcontracting Order Item",
@@ -104,13 +104,11 @@
 	def onload(self):
 		self.set_onload(
 			"backflush_based_on",
-			frappe.db.get_single_value(
-				"Buying Settings", "backflush_raw_materials_of_subcontract_based_on"
-			),
+			frappe.db.get_single_value("Buying Settings", "backflush_raw_materials_of_subcontract_based_on"),
 		)
 
 	def before_validate(self):
-		super(SubcontractingReceipt, self).before_validate()
+		super().before_validate()
 		self.validate_items_qty()
 		self.set_items_bom()
 		self.set_items_cost_center()
@@ -126,7 +124,7 @@
 		if getdate(self.posting_date) > getdate(nowdate()):
 			frappe.throw(_("Posting Date cannot be future date"))
 
-		super(SubcontractingReceipt, self).validate()
+		super().validate()
 
 		if self.is_new() and self.get("_action") == "save" and not frappe.flags.in_test:
 			self.get_scrap_items()
@@ -190,7 +188,9 @@
 		for item in self.items:
 			if not (item.qty or item.rejected_qty):
 				frappe.throw(
-					_("Row {0}: Accepted Qty and Rejected Qty can't be zero at the same time.").format(item.idx)
+					_("Row {0}: Accepted Qty and Rejected Qty can't be zero at the same time.").format(
+						item.idx
+					)
 				)
 
 	def set_items_bom(self):
@@ -306,7 +306,9 @@
 				.select(
 					sco_supplied_item.rm_item_code,
 					sco_supplied_item.reference_name,
-					(sco_supplied_item.total_supplied_qty - sco_supplied_item.consumed_qty).as_("available_qty"),
+					(sco_supplied_item.total_supplied_qty - sco_supplied_item.consumed_qty).as_(
+						"available_qty"
+					),
 				)
 				.where(
 					(sco_supplied_item.parent == item.subcontracting_order)
@@ -319,7 +321,9 @@
 				supplied_items_details[item.name] = {}
 
 				for supplied_item in supplied_items:
-					supplied_items_details[item.name][supplied_item.rm_item_code] = supplied_item.available_qty
+					supplied_items_details[item.name][
+						supplied_item.rm_item_code
+					] = supplied_item.available_qty
 		else:
 			for item in self.get("supplied_items"):
 				item.available_qty_for_consumption = supplied_items_details.get(item.reference_name, {}).get(
@@ -515,10 +519,12 @@
 
 					warehouse_account_name = warehouse_account[item.warehouse]["account"]
 					warehouse_account_currency = warehouse_account[item.warehouse]["account_currency"]
-					supplier_warehouse_account = warehouse_account.get(self.supplier_warehouse, {}).get("account")
-					supplier_warehouse_account_currency = warehouse_account.get(self.supplier_warehouse, {}).get(
-						"account_currency"
+					supplier_warehouse_account = warehouse_account.get(self.supplier_warehouse, {}).get(
+						"account"
 					)
+					supplier_warehouse_account_currency = warehouse_account.get(
+						self.supplier_warehouse, {}
+					).get("account_currency")
 					remarks = self.get("remarks") or _("Accounting Entry for Stock")
 
 					# FG Warehouse Account (Debit)
@@ -662,7 +668,9 @@
 			if item.purchase_order and item.purchase_order_item:
 				if item.purchase_order not in po_items_details:
 					po_doc = frappe.get_doc("Purchase Order", item.purchase_order)
-					po_items_details[item.purchase_order] = {po_item.name: po_item for po_item in po_doc.items}
+					po_items_details[item.purchase_order] = {
+						po_item.name: po_item for po_item in po_doc.items
+					}
 
 				if po_item := po_items_details[item.purchase_order].get(item.purchase_order_item):
 					conversion_factor = flt(po_item.qty) / flt(po_item.fg_item_qty)
diff --git a/erpnext/subcontracting/doctype/subcontracting_receipt/test_subcontracting_receipt.py b/erpnext/subcontracting/doctype/subcontracting_receipt/test_subcontracting_receipt.py
index 4f4a1bd..564096f 100644
--- a/erpnext/subcontracting/doctype/subcontracting_receipt/test_subcontracting_receipt.py
+++ b/erpnext/subcontracting/doctype/subcontracting_receipt/test_subcontracting_receipt.py
@@ -6,7 +6,7 @@
 
 import frappe
 from frappe.tests.utils import FrappeTestCase, change_settings
-from frappe.utils import add_days, cint, cstr, flt, nowtime, today
+from frappe.utils import add_days, cint, flt, nowtime, today
 
 import erpnext
 from erpnext.accounts.doctype.account.test_account import get_inventory_account
@@ -48,9 +48,7 @@
 
 	def test_subcontracting(self):
 		set_backflush_based_on("BOM")
-		make_stock_entry(
-			item_code="_Test Item", qty=100, target="_Test Warehouse 1 - _TC", basic_rate=100
-		)
+		make_stock_entry(item_code="_Test Item", qty=100, target="_Test Warehouse 1 - _TC", basic_rate=100)
 		make_stock_entry(
 			item_code="_Test Item Home Desktop 100",
 			qty=100,
@@ -82,9 +80,7 @@
 		self.assertEqual(scr.get("items")[0].rm_supp_cost, flt(rm_supp_cost))
 
 	def test_available_qty_for_consumption(self):
-		make_stock_entry(
-			item_code="_Test Item", qty=100, target="_Test Warehouse 1 - _TC", basic_rate=100
-		)
+		make_stock_entry(item_code="_Test Item", qty=100, target="_Test Warehouse 1 - _TC", basic_rate=100)
 		make_stock_entry(
 			item_code="_Test Item Home Desktop 100",
 			qty=100,
@@ -185,9 +181,6 @@
 		from erpnext.subcontracting.doctype.subcontracting_order.subcontracting_order import (
 			make_subcontracting_receipt,
 		)
-		from erpnext.subcontracting.doctype.subcontracting_order.test_subcontracting_order import (
-			make_subcontracted_item,
-		)
 
 		set_backflush_based_on("Material Transferred for Subcontract")
 		item_code = "_Test Subcontracted FG Item 1"
@@ -211,12 +204,8 @@
 		make_stock_entry(
 			target="_Test Warehouse - _TC", item_code="Test Extra Item 1", qty=10, basic_rate=100
 		)
-		make_stock_entry(
-			target="_Test Warehouse - _TC", item_code="_Test FG Item", qty=1, basic_rate=100
-		)
-		make_stock_entry(
-			target="_Test Warehouse - _TC", item_code="Test Extra Item 2", qty=1, basic_rate=100
-		)
+		make_stock_entry(target="_Test Warehouse - _TC", item_code="_Test FG Item", qty=1, basic_rate=100)
+		make_stock_entry(target="_Test Warehouse - _TC", item_code="Test Extra Item 2", qty=1, basic_rate=100)
 
 		rm_items = [
 			{
@@ -397,9 +386,7 @@
 		set_backflush_based_on("Material Transferred for Subcontract")
 
 		# Create Material Receipt for RM's
-		make_stock_entry(
-			item_code="_Test Item", qty=100, target="_Test Warehouse 1 - _TC", basic_rate=100
-		)
+		make_stock_entry(item_code="_Test Item", qty=100, target="_Test Warehouse 1 - _TC", basic_rate=100)
 		make_stock_entry(
 			item_code="_Test Item Home Desktop 100",
 			qty=100,
@@ -614,7 +601,6 @@
 
 		bom = make_bom(item=fg_item, raw_materials=[rm_item1, rm_item2, rm_item3])
 
-		rm_batch_no = None
 		for row in bom.items:
 			make_stock_entry(
 				item_code=row.item_code,
@@ -642,9 +628,7 @@
 		]
 		sco = get_subcontracting_order(service_items=service_items)
 
-		frappe.db.set_single_value(
-			"Stock Settings", "auto_create_serial_and_batch_bundle_for_outward", 1
-		)
+		frappe.db.set_single_value("Stock Settings", "auto_create_serial_and_batch_bundle_for_outward", 1)
 		scr = make_subcontracting_receipt(sco.name)
 		scr.save()
 		scr.submit()
@@ -663,9 +647,7 @@
 
 		self.assertEqual(scr.items[0].rm_cost_per_qty, 900)
 		self.assertEqual(scr.items[0].service_cost_per_qty, 100)
-		frappe.db.set_single_value(
-			"Stock Settings", "auto_create_serial_and_batch_bundle_for_outward", 0
-		)
+		frappe.db.set_single_value("Stock Settings", "auto_create_serial_and_batch_bundle_for_outward", 0)
 
 	def test_subcontracting_receipt_valuation_for_fg_with_auto_created_serial_batch_bundle(self):
 		frappe.db.set_single_value("Stock Settings", "use_serial_batch_fields", 0)
@@ -711,7 +693,6 @@
 
 		bom = make_bom(item=fg_item, raw_materials=[rm_item1, rm_item2, rm_item3])
 
-		rm_batch_no = None
 		for row in bom.items:
 			make_stock_entry(
 				item_code=row.item_code,
@@ -732,9 +713,7 @@
 		]
 		sco = get_subcontracting_order(service_items=service_items)
 
-		frappe.db.set_single_value(
-			"Stock Settings", "auto_create_serial_and_batch_bundle_for_outward", 1
-		)
+		frappe.db.set_single_value("Stock Settings", "auto_create_serial_and_batch_bundle_for_outward", 1)
 		scr = make_subcontracting_receipt(sco.name)
 		scr.save()
 		scr.submit()
@@ -762,9 +741,7 @@
 
 		self.assertEqual(flt(valuation_rate), flt(1000))
 
-		frappe.db.set_single_value(
-			"Stock Settings", "auto_create_serial_and_batch_bundle_for_outward", 0
-		)
+		frappe.db.set_single_value("Stock Settings", "auto_create_serial_and_batch_bundle_for_outward", 0)
 		frappe.db.set_single_value("Stock Settings", "use_serial_batch_fields", 1)
 
 	def test_subcontracting_receipt_raw_material_rate(self):
@@ -1225,9 +1202,7 @@
 def make_return_subcontracting_receipt(**args):
 	args = frappe._dict(args)
 	return_doc = make_return_doc("Subcontracting Receipt", args.scr_name)
-	return_doc.supplier_warehouse = (
-		args.supplier_warehouse or args.warehouse or "_Test Warehouse 1 - _TC"
-	)
+	return_doc.supplier_warehouse = args.supplier_warehouse or args.warehouse or "_Test Warehouse 1 - _TC"
 
 	if args.qty:
 		for item in return_doc.items:
diff --git a/erpnext/support/doctype/issue/issue.py b/erpnext/support/doctype/issue/issue.py
index e4c4d60..c8b85db 100644
--- a/erpnext/support/doctype/issue/issue.py
+++ b/erpnext/support/doctype/issue/issue.py
@@ -163,7 +163,7 @@
 				"comment_type": "Info",
 				"reference_doctype": "Issue",
 				"reference_name": replicated_issue.name,
-				"content": " - Split the Issue from <a href='/app/Form/Issue/{0}'>{1}</a>".format(
+				"content": " - Split the Issue from <a href='/app/Form/Issue/{}'>{}</a>".format(
 					self.name, frappe.bold(self.name)
 				),
 			}
@@ -217,7 +217,6 @@
 
 @frappe.whitelist()
 def set_multiple_status(names, status):
-
 	for name in json.loads(names):
 		frappe.db.set_value("Issue", name, "status", status)
 
@@ -229,9 +228,7 @@
 
 def auto_close_tickets():
 	"""Auto-close replied support tickets after 7 days"""
-	auto_close_after_days = (
-		frappe.db.get_single_value("Support Settings", "close_issue_after_days") or 7
-	)
+	auto_close_after_days = frappe.db.get_single_value("Support Settings", "close_issue_after_days") or 7
 
 	table = frappe.qb.DocType("Issue")
 	issues = (
@@ -299,9 +296,7 @@
 	if communication.get("reference_doctype") == "Issue":
 		issue = get_parent_doc(communication)
 		if is_first_response(issue) and issue.service_level_agreement:
-			first_response_time = calculate_first_response_time(
-				issue, get_datetime(issue.first_responded_on)
-			)
+			first_response_time = calculate_first_response_time(issue, get_datetime(issue.first_responded_on))
 			issue.db_set("first_response_time", first_response_time)
 
 
diff --git a/erpnext/support/doctype/issue/test_issue.py b/erpnext/support/doctype/issue/test_issue.py
index b30b699..acad115 100644
--- a/erpnext/support/doctype/issue/test_issue.py
+++ b/erpnext/support/doctype/issue/test_issue.py
@@ -29,23 +29,21 @@
 		creation = get_datetime("2019-03-04 12:00")
 
 		# make issue with customer specific SLA
-		customer = create_customer("_Test Customer", "__Test SLA Customer Group", "__Test SLA Territory")
+		create_customer("_Test Customer", "__Test SLA Customer Group", "__Test SLA Territory")
 		issue = make_issue(creation, "_Test Customer", 1)
 
 		self.assertEqual(issue.response_by, get_datetime("2019-03-04 14:00"))
 		self.assertEqual(issue.resolution_by, get_datetime("2019-03-04 15:00"))
 
 		# make issue with customer_group specific SLA
-		customer = create_customer("__Test Customer", "_Test SLA Customer Group", "__Test SLA Territory")
+		create_customer("__Test Customer", "_Test SLA Customer Group", "__Test SLA Territory")
 		issue = make_issue(creation, "__Test Customer", 2)
 
 		self.assertEqual(issue.response_by, get_datetime("2019-03-04 14:00"))
 		self.assertEqual(issue.resolution_by, get_datetime("2019-03-04 15:00"))
 
 		# make issue with territory specific SLA
-		customer = create_customer(
-			"___Test Customer", "__Test SLA Customer Group", "_Test SLA Territory"
-		)
+		create_customer("___Test Customer", "__Test SLA Customer Group", "_Test SLA Territory")
 		issue = make_issue(creation, "___Test Customer", 3)
 
 		self.assertEqual(issue.response_by, get_datetime("2019-03-04 14:00"))
@@ -147,16 +145,15 @@
 		self.assertEqual(issue.agreement_status, "Fulfilled")
 
 	def test_issue_open_after_closed(self):
-
 		# Created on -> 1 pm, Response Time -> 4 hrs, Resolution Time -> 6 hrs
 		frappe.flags.current_time = get_datetime("2021-11-01 13:00")
 		issue = make_issue(
 			frappe.flags.current_time, index=1, issue_type="Critical"
 		)  # Applies 24hr working time SLA
 		create_communication(issue.name, "test@example.com", "Received", frappe.flags.current_time)
-		self.assertEquals(issue.agreement_status, "First Response Due")
-		self.assertEquals(issue.response_by, get_datetime("2021-11-01 17:00"))
-		self.assertEquals(issue.resolution_by, get_datetime("2021-11-01 19:00"))
+		self.assertEqual(issue.agreement_status, "First Response Due")
+		self.assertEqual(issue.response_by, get_datetime("2021-11-01 17:00"))
+		self.assertEqual(issue.resolution_by, get_datetime("2021-11-01 19:00"))
 
 		# Replied on → 2 pm
 		frappe.flags.current_time = get_datetime("2021-11-01 14:00")
@@ -164,19 +161,19 @@
 		issue.reload()
 		issue.status = "Replied"
 		issue.save()
-		self.assertEquals(issue.agreement_status, "Resolution Due")
-		self.assertEquals(issue.on_hold_since, frappe.flags.current_time)
-		self.assertEquals(issue.first_responded_on, frappe.flags.current_time)
+		self.assertEqual(issue.agreement_status, "Resolution Due")
+		self.assertEqual(issue.on_hold_since, frappe.flags.current_time)
+		self.assertEqual(issue.first_responded_on, frappe.flags.current_time)
 
 		# Customer Replied → 3 pm
 		frappe.flags.current_time = get_datetime("2021-11-01 15:00")
 		create_communication(issue.name, "test@example.com", "Received", frappe.flags.current_time)
 		issue.reload()
-		self.assertEquals(issue.status, "Open")
+		self.assertEqual(issue.status, "Open")
 		# Hold Time + 1 Hrs
-		self.assertEquals(issue.total_hold_time, 3600)
+		self.assertEqual(issue.total_hold_time, 3600)
 		# Resolution By should increase by one hrs
-		self.assertEquals(issue.resolution_by, get_datetime("2021-11-01 20:00"))
+		self.assertEqual(issue.resolution_by, get_datetime("2021-11-01 20:00"))
 
 		# Replied on → 4 pm, Open → 1 hr, Resolution Due → 8 pm
 		frappe.flags.current_time = get_datetime("2021-11-01 16:00")
@@ -184,37 +181,37 @@
 		issue.reload()
 		issue.status = "Replied"
 		issue.save()
-		self.assertEquals(issue.agreement_status, "Resolution Due")
+		self.assertEqual(issue.agreement_status, "Resolution Due")
 
 		# Customer Closed → 10 pm
 		frappe.flags.current_time = get_datetime("2021-11-01 22:00")
 		issue.status = "Closed"
 		issue.save()
 		# Hold Time + 6 Hrs
-		self.assertEquals(issue.total_hold_time, 3600 + 21600)
+		self.assertEqual(issue.total_hold_time, 3600 + 21600)
 		# Resolution By should increase by 6 hrs
-		self.assertEquals(issue.resolution_by, get_datetime("2021-11-02 02:00"))
-		self.assertEquals(issue.agreement_status, "Fulfilled")
-		self.assertEquals(issue.resolution_date, frappe.flags.current_time)
+		self.assertEqual(issue.resolution_by, get_datetime("2021-11-02 02:00"))
+		self.assertEqual(issue.agreement_status, "Fulfilled")
+		self.assertEqual(issue.resolution_date, frappe.flags.current_time)
 
 		# Customer Open → 3 am i.e after resolution by is crossed
 		frappe.flags.current_time = get_datetime("2021-11-02 03:00")
 		create_communication(issue.name, "test@example.com", "Received", frappe.flags.current_time)
 		issue.reload()
 		# Since issue was Resolved, Resolution By should be increased by 5 hrs (3am - 10pm)
-		self.assertEquals(issue.total_hold_time, 3600 + 21600 + 18000)
+		self.assertEqual(issue.total_hold_time, 3600 + 21600 + 18000)
 		# Resolution By should increase by 5 hrs
-		self.assertEquals(issue.resolution_by, get_datetime("2021-11-02 07:00"))
-		self.assertEquals(issue.agreement_status, "Resolution Due")
+		self.assertEqual(issue.resolution_by, get_datetime("2021-11-02 07:00"))
+		self.assertEqual(issue.agreement_status, "Resolution Due")
 		self.assertFalse(issue.resolution_date)
 
 		# We Closed → 4 am, SLA should be Fulfilled
 		frappe.flags.current_time = get_datetime("2021-11-02 04:00")
 		issue.status = "Closed"
 		issue.save()
-		self.assertEquals(issue.resolution_by, get_datetime("2021-11-02 07:00"))
-		self.assertEquals(issue.agreement_status, "Fulfilled")
-		self.assertEquals(issue.resolution_date, frappe.flags.current_time)
+		self.assertEqual(issue.resolution_by, get_datetime("2021-11-02 07:00"))
+		self.assertEqual(issue.agreement_status, "Fulfilled")
+		self.assertEqual(issue.resolution_date, frappe.flags.current_time)
 
 	def test_recording_of_assignment_on_first_reponse_failure(self):
 		from frappe.desk.form.assign_to import add as add_assignment
@@ -255,8 +252,8 @@
 		create_communication(issue.name, "test@admin.com", "Sent", frappe.flags.current_time)
 
 		issue.reload()
-		self.assertEquals(issue.first_responded_on, frappe.flags.current_time)
-		self.assertEquals(issue.agreement_status, "Resolution Due")
+		self.assertEqual(issue.first_responded_on, frappe.flags.current_time)
+		self.assertEqual(issue.agreement_status, "Resolution Due")
 
 
 class TestFirstResponseTime(TestSetUp):
@@ -547,7 +544,7 @@
 	issue = frappe.get_doc(
 		{
 			"doctype": "Issue",
-			"subject": "Service Level Agreement Issue {0}".format(index),
+			"subject": f"Service Level Agreement Issue {index}",
 			"customer": customer,
 			"raised_by": "test@example.com",
 			"description": "Service Level Agreement Issue",
@@ -564,7 +561,6 @@
 
 
 def create_customer(name, customer_group, territory):
-
 	create_customer_group(customer_group)
 	create_territory(territory)
 
@@ -580,7 +576,6 @@
 
 
 def create_customer_group(customer_group):
-
 	if not frappe.db.exists("Customer Group", {"customer_group_name": customer_group}):
 		frappe.get_doc({"doctype": "Customer Group", "customer_group_name": customer_group}).insert(
 			ignore_permissions=True
@@ -588,7 +583,6 @@
 
 
 def create_territory(territory):
-
 	if not frappe.db.exists("Territory", {"territory_name": territory}):
 		frappe.get_doc(
 			{
diff --git a/erpnext/support/doctype/service_level_agreement/service_level_agreement.py b/erpnext/support/doctype/service_level_agreement/service_level_agreement.py
index f6b3a13..0fa2d61 100644
--- a/erpnext/support/doctype/service_level_agreement/service_level_agreement.py
+++ b/erpnext/support/doctype/service_level_agreement/service_level_agreement.py
@@ -79,22 +79,26 @@
 			# Check if response and resolution time is set for every priority
 			if not priority.response_time:
 				frappe.throw(
-					_("Set Response Time for Priority {0} in row {1}.").format(priority.priority, priority.idx)
+					_("Set Response Time for Priority {0} in row {1}.").format(
+						priority.priority, priority.idx
+					)
 				)
 
 			if self.apply_sla_for_resolution:
 				if not priority.resolution_time:
 					frappe.throw(
-						_("Set Response Time for Priority {0} in row {1}.").format(priority.priority, priority.idx)
+						_("Set Response Time for Priority {0} in row {1}.").format(
+							priority.priority, priority.idx
+						)
 					)
 
 				response = priority.response_time
 				resolution = priority.resolution_time
 				if response > resolution:
 					frappe.throw(
-						_("Response Time for {0} priority in row {1} can't be greater than Resolution Time.").format(
-							priority.priority, priority.idx
-						)
+						_(
+							"Response Time for {0} priority in row {1} can't be greater than Resolution Time."
+						).format(priority.priority, priority.idx)
 					)
 
 			priorities.append(priority.priority)
@@ -358,7 +362,7 @@
 					"Service Level Agreement",
 					"entity",
 					"in",
-					[customer] + get_customer_group(customer) + get_customer_territory(customer),
+					[customer, *get_customer_group(customer), *get_customer_territory(customer)],
 				],
 				["Service Level Agreement", "entity_type", "is", "not set"],
 			]
@@ -366,9 +370,7 @@
 	else:
 		or_filters.append(["Service Level Agreement", "entity_type", "is", "not set"])
 
-	default_sla_filter = filters + [
-		["Service Level Agreement", "default_service_level_agreement", "=", 1]
-	]
+	default_sla_filter = [*filters, ["Service Level Agreement", "default_service_level_agreement", "=", 1]]
 	default_sla = frappe.get_all(
 		"Service Level Agreement",
 		filters=default_sla_filter,
@@ -409,7 +411,7 @@
 	customer_group = frappe.db.get_value("Customer", customer, "customer_group") if customer else None
 	if customer_group:
 		ancestors = get_ancestors_of("Customer Group", customer_group)
-		customer_groups = [customer_group] + ancestors
+		customer_groups = [customer_group, *ancestors]
 
 	return customer_groups
 
@@ -419,7 +421,7 @@
 	customer_territory = frappe.db.get_value("Customer", customer, "territory") if customer else None
 	if customer_territory:
 		ancestors = get_ancestors_of("Territory", customer_territory)
-		customer_territories = [customer_territory] + ancestors
+		customer_territories = [customer_territory, *ancestors]
 
 	return customer_territories
 
@@ -443,7 +445,7 @@
 				"Service Level Agreement",
 				"entity",
 				"in",
-				[""] + [customer] + get_customer_group(customer) + get_customer_territory(customer),
+				["", customer, *get_customer_group(customer), *get_customer_territory(customer)],
 			]
 		)
 
@@ -455,8 +457,7 @@
 			)
 		],
 		"service_level_agreements": [
-			d.name
-			for d in frappe.get_all("Service Level Agreement", filters=filters, or_filters=or_filters)
+			d.name for d in frappe.get_all("Service Level Agreement", filters=filters, or_filters=or_filters)
 		],
 	}
 
@@ -517,7 +518,6 @@
 
 
 def process_sla(doc, sla):
-
 	if not doc.creation:
 		doc.creation = now_datetime(doc.get("owner"))
 		if doc.meta.has_field("service_level_agreement_creation"):
@@ -747,16 +747,13 @@
 		and frappe.db.exists("Issue", self.name)
 		and frappe.db.get_single_value("Support Settings", "track_service_level_agreement")
 	):
-
 		if self.priority != frappe.db.get_value("Issue", self.name, "priority"):
 			self.set_response_and_resolution_time(
 				priority=self.priority, service_level_agreement=self.service_level_agreement
 			)
 			frappe.msgprint(_("Priority has been changed to {0}.").format(self.priority))
 
-		if self.service_level_agreement != frappe.db.get_value(
-			"Issue", self.name, "service_level_agreement"
-		):
+		if self.service_level_agreement != frappe.db.get_value("Issue", self.name, "service_level_agreement"):
 			self.set_response_and_resolution_time(
 				priority=self.priority, service_level_agreement=self.service_level_agreement
 			)
@@ -768,9 +765,7 @@
 def get_response_and_resolution_duration(doc):
 	sla = frappe.get_doc("Service Level Agreement", doc.service_level_agreement)
 	priority = sla.get_service_level_agreement_priority(doc.priority)
-	priority.update(
-		{"support_and_resolution": sla.support_and_resolution, "holiday_list": sla.holiday_list}
-	)
+	priority.update({"support_and_resolution": sla.support_and_resolution, "holiday_list": sla.holiday_list})
 	return priority
 
 
@@ -787,7 +782,7 @@
 			"reference_doctype": doc.doctype,
 			"reference_name": doc.name,
 			"comment_email": user,
-			"content": " resetted Service Level Agreement - {0}".format(_(reason)),
+			"content": f" resetted Service Level Agreement - {_(reason)}",
 		}
 	).insert(ignore_permissions=True)
 
@@ -895,7 +890,7 @@
 	if assigned_users:
 		from frappe.utils import get_fullname
 
-		assigned_users = ", ".join((get_fullname(user) for user in assigned_users))
+		assigned_users = ", ".join(get_fullname(user) for user in assigned_users)
 		message = _("First Response SLA Failed by {}").format(assigned_users)
 		doc.add_comment(comment_type="Assigned", text=message)
 
diff --git a/erpnext/support/doctype/service_level_agreement/test_service_level_agreement.py b/erpnext/support/doctype/service_level_agreement/test_service_level_agreement.py
index 1f8f4a2..47ea251 100644
--- a/erpnext/support/doctype/service_level_agreement/test_service_level_agreement.py
+++ b/erpnext/support/doctype/service_level_agreement/test_service_level_agreement.py
@@ -51,9 +51,7 @@
 			resolution_time=21600,
 		)
 
-		get_default_service_level_agreement = get_service_level_agreement(
-			default_service_level_agreement=1
-		)
+		get_default_service_level_agreement = get_service_level_agreement(default_service_level_agreement=1)
 
 		self.assertEqual(
 			create_default_service_level_agreement.name, get_default_service_level_agreement.name
@@ -198,9 +196,7 @@
 		)
 
 		# check default SLA for custom dt
-		default_sla = get_service_level_agreement(
-			default_service_level_agreement=1, doctype=doctype.name
-		)
+		default_sla = get_service_level_agreement(default_service_level_agreement=1, doctype=doctype.name)
 		self.assertEqual(sla.name, default_sla.name)
 
 		# check SLA docfields created
@@ -390,14 +386,17 @@
 	resolution_time=0,
 	doctype="Issue",
 	condition="",
-	sla_fulfilled_on=[],
-	pause_sla_on=[],
+	sla_fulfilled_on=None,
+	pause_sla_on=None,
 	apply_sla_for_resolution=1,
 	service_level=None,
 	start_time="10:00:00",
 	end_time="18:00:00",
 ):
-
+	if pause_sla_on is None:
+		pause_sla_on = []
+	if sla_fulfilled_on is None:
+		sla_fulfilled_on = []
 	make_holiday_list()
 	make_priorities()
 
@@ -484,9 +483,7 @@
 	if sla:
 		frappe.delete_doc("Service Level Agreement", sla, force=1)
 
-	return frappe.get_doc(service_level_agreement).insert(
-		ignore_permissions=True, ignore_if_duplicate=True
-	)
+	return frappe.get_doc(service_level_agreement).insert(ignore_permissions=True, ignore_if_duplicate=True)
 
 
 def create_customer():
@@ -615,7 +612,12 @@
 				"fields": [
 					{"label": "Date", "fieldname": "date", "fieldtype": "Date"},
 					{"label": "Description", "fieldname": "desc", "fieldtype": "Long Text"},
-					{"label": "Email ID", "fieldname": "email_id", "fieldtype": "Link", "options": "Customer"},
+					{
+						"label": "Email ID",
+						"fieldname": "email_id",
+						"fieldtype": "Link",
+						"options": "Customer",
+					},
 					{
 						"label": "Status",
 						"fieldname": "status",
@@ -637,8 +639,8 @@
 	return frappe.get_doc(
 		{
 			"doctype": "Lead",
-			"email_id": "test_lead1@example{0}.com".format(index),
-			"lead_name": "_Test Lead {0}".format(index),
+			"email_id": f"test_lead1@example{index}.com",
+			"lead_name": f"_Test Lead {index}",
 			"status": "Open",
 			"creation": creation,
 			"service_level_agreement_creation": creation,
diff --git a/erpnext/support/doctype/warranty_claim/warranty_claim.py b/erpnext/support/doctype/warranty_claim/warranty_claim.py
index 658be57..644f47e 100644
--- a/erpnext/support/doctype/warranty_claim/warranty_claim.py
+++ b/erpnext/support/doctype/warranty_claim/warranty_claim.py
@@ -45,9 +45,7 @@
 		service_address: DF.SmallText | None
 		status: DF.Literal["", "Open", "Closed", "Work In Progress", "Cancelled"]
 		territory: DF.Link | None
-		warranty_amc_status: DF.Literal[
-			"", "Under Warranty", "Out of Warranty", "Under AMC", "Out of AMC"
-		]
+		warranty_amc_status: DF.Literal["", "Under Warranty", "Out of Warranty", "Under AMC", "Out of AMC"]
 		warranty_expiry_date: DF.Date | None
 	# end: auto-generated types
 
diff --git a/erpnext/support/report/issue_analytics/issue_analytics.py b/erpnext/support/report/issue_analytics/issue_analytics.py
index 00ba25a..7f02372 100644
--- a/erpnext/support/report/issue_analytics/issue_analytics.py
+++ b/erpnext/support/report/issue_analytics/issue_analytics.py
@@ -15,7 +15,7 @@
 	return IssueAnalytics(filters).run()
 
 
-class IssueAnalytics(object):
+class IssueAnalytics:
 	def __init__(self, filters=None):
 		"""Issue Analytics Report"""
 		self.filters = frappe._dict(filters or {})
@@ -44,7 +44,13 @@
 
 		elif self.filters.based_on == "Assigned To":
 			self.columns.append(
-				{"label": _("User"), "fieldname": "user", "fieldtype": "Link", "options": "User", "width": 200}
+				{
+					"label": _("User"),
+					"fieldname": "user",
+					"fieldtype": "Link",
+					"options": "User",
+					"width": 200,
+				}
 			)
 
 		elif self.filters.based_on == "Issue Type":
@@ -75,9 +81,7 @@
 				{"label": _(period), "fieldname": scrub(period), "fieldtype": "Int", "width": 120}
 			)
 
-		self.columns.append(
-			{"label": _("Total"), "fieldname": "total", "fieldtype": "Int", "width": 120}
-		)
+		self.columns.append({"label": _("Total"), "fieldname": "total", "fieldtype": "Int", "width": 120})
 
 	def get_data(self):
 		self.get_issues()
@@ -109,9 +113,7 @@
 
 		from_date, to_date = getdate(self.filters.from_date), getdate(self.filters.to_date)
 
-		increment = {"Monthly": 1, "Quarterly": 3, "Half-Yearly": 6, "Yearly": 12}.get(
-			self.filters.range, 1
-		)
+		increment = {"Monthly": 1, "Quarterly": 3, "Half-Yearly": 6, "Yearly": 12}.get(self.filters.range, 1)
 
 		if self.filters.range in ["Monthly", "Quarterly"]:
 			from_date = from_date.replace(day=1)
@@ -121,7 +123,7 @@
 			from_date = from_date + relativedelta(from_date, weekday=MO(-1))
 
 		self.periodic_daterange = []
-		for dummy in range(1, 53):
+		for _dummy in range(1, 53):
 			if self.filters.range == "Weekly":
 				period_end_date = add_days(from_date, 6)
 			else:
diff --git a/erpnext/support/report/issue_summary/issue_summary.py b/erpnext/support/report/issue_summary/issue_summary.py
index c80ce88..d976c28 100644
--- a/erpnext/support/report/issue_summary/issue_summary.py
+++ b/erpnext/support/report/issue_summary/issue_summary.py
@@ -13,7 +13,7 @@
 	return IssueSummary(filters).run()
 
 
-class IssueSummary(object):
+class IssueSummary:
 	def __init__(self, filters=None):
 		self.filters = frappe._dict(filters or {})
 
@@ -41,7 +41,13 @@
 
 		elif self.filters.based_on == "Assigned To":
 			self.columns.append(
-				{"label": _("User"), "fieldname": "user", "fieldtype": "Link", "options": "User", "width": 200}
+				{
+					"label": _("User"),
+					"fieldname": "user",
+					"fieldtype": "Link",
+					"options": "User",
+					"width": 200,
+				}
 			)
 
 		elif self.filters.based_on == "Issue Type":
@@ -84,9 +90,7 @@
 		}
 
 		for label, fieldname in self.sla_status_map.items():
-			self.columns.append(
-				{"label": _(label), "fieldname": fieldname, "fieldtype": "Int", "width": 100}
-			)
+			self.columns.append({"label": _(label), "fieldname": fieldname, "fieldtype": "Int", "width": 100})
 
 		self.metrics = [
 			"Avg First Response Time",
@@ -185,8 +189,12 @@
 				if d._assign:
 					for entry in json.loads(d._assign):
 						self.issue_summary_data.setdefault(entry, frappe._dict()).setdefault(status, 0.0)
-						self.issue_summary_data.setdefault(entry, frappe._dict()).setdefault(agreement_status, 0.0)
-						self.issue_summary_data.setdefault(entry, frappe._dict()).setdefault("total_issues", 0.0)
+						self.issue_summary_data.setdefault(entry, frappe._dict()).setdefault(
+							agreement_status, 0.0
+						)
+						self.issue_summary_data.setdefault(entry, frappe._dict()).setdefault(
+							"total_issues", 0.0
+						)
 						self.issue_summary_data[entry][status] += 1
 						self.issue_summary_data[entry][agreement_status] += 1
 						self.issue_summary_data[entry]["total_issues"] += 1
@@ -229,14 +237,20 @@
 					if d._assign:
 						for entry in json.loads(d._assign):
 							for metric in metrics_list:
-								self.issue_summary_data.setdefault(entry, frappe._dict()).setdefault(metric, 0.0)
+								self.issue_summary_data.setdefault(entry, frappe._dict()).setdefault(
+									metric, 0.0
+								)
 
-							self.issue_summary_data[entry]["avg_response_time"] += d.get("avg_response_time") or 0.0
+							self.issue_summary_data[entry]["avg_response_time"] += (
+								d.get("avg_response_time") or 0.0
+							)
 							self.issue_summary_data[entry]["avg_first_response_time"] += (
 								d.get("first_response_time") or 0.0
 							)
 							self.issue_summary_data[entry]["avg_hold_time"] += d.get("total_hold_time") or 0.0
-							self.issue_summary_data[entry]["avg_resolution_time"] += d.get("resolution_time") or 0.0
+							self.issue_summary_data[entry]["avg_resolution_time"] += (
+								d.get("resolution_time") or 0.0
+							)
 							self.issue_summary_data[entry]["avg_user_resolution_time"] += (
 								d.get("user_resolution_time") or 0.0
 							)
@@ -251,9 +265,9 @@
 
 			else:
 				data = frappe.db.sql(
-					"""
+					f"""
 					SELECT
-						{0}, AVG(first_response_time) as avg_frt,
+						{field}, AVG(first_response_time) as avg_frt,
 						AVG(avg_response_time) as avg_resp_time,
 						AVG(total_hold_time) as avg_hold_time,
 						AVG(resolution_time) as avg_resolution_time,
@@ -261,10 +275,8 @@
 					FROM `tabIssue`
 					WHERE
 						name IN %(issues)s
-					GROUP BY {0}
-				""".format(
-						field
-					),
+					GROUP BY {field}
+				""",
 					{"issues": issues},
 					as_dict=1,
 				)
diff --git a/erpnext/support/report/support_hour_distribution/support_hour_distribution.py b/erpnext/support/report/support_hour_distribution/support_hour_distribution.py
index 5496721..2a97831 100644
--- a/erpnext/support/report/support_hour_distribution/support_hour_distribution.py
+++ b/erpnext/support/report/support_hour_distribution/support_hour_distribution.py
@@ -37,8 +37,8 @@
 		hours_count = {"date": start_date}
 		for key, value in time_slots.items():
 			start_time, end_time = value.split("-")
-			start_time = get_datetime("{0} {1}".format(start_date.strftime("%Y-%m-%d"), start_time))
-			end_time = get_datetime("{0} {1}".format(start_date.strftime("%Y-%m-%d"), end_time))
+			start_time = get_datetime("{} {}".format(start_date.strftime("%Y-%m-%d"), start_time))
+			end_time = get_datetime("{} {}".format(start_date.strftime("%Y-%m-%d"), end_time))
 			hours_count[key] = get_hours_count(start_time, end_time)
 			time_slot_wise_total_count[key] = time_slot_wise_total_count.get(key, 0) + hours_count[key]
 
diff --git a/erpnext/telephony/doctype/call_log/call_log.py b/erpnext/telephony/doctype/call_log/call_log.py
index 259f55b..7afa06f 100644
--- a/erpnext/telephony/doctype/call_log/call_log.py
+++ b/erpnext/telephony/doctype/call_log/call_log.py
@@ -68,9 +68,7 @@
 	def on_update(self):
 		def _is_call_missed(doc_before_save, doc_after_save):
 			# FIXME: This works for Exotel but not for all telepony providers
-			return (
-				doc_before_save.to != doc_after_save.to and doc_after_save.status not in END_CALL_STATUSES
-			)
+			return doc_before_save.to != doc_after_save.to and doc_after_save.status not in END_CALL_STATUSES
 
 		def _is_call_ended(doc_before_save, doc_after_save):
 			return doc_before_save.status not in END_CALL_STATUSES and self.status in END_CALL_STATUSES
@@ -83,11 +81,11 @@
 			self.update_received_by()
 
 		if _is_call_missed(doc_before_save, self):
-			frappe.publish_realtime("call_{id}_missed".format(id=self.id), self)
+			frappe.publish_realtime(f"call_{self.id}_missed", self)
 			self.trigger_call_popup()
 
 		if _is_call_ended(doc_before_save, self):
-			frappe.publish_realtime("call_{id}_ended".format(id=self.id), self)
+			frappe.publish_realtime(f"call_{self.id}_ended", self)
 
 	def is_incoming_call(self):
 		return self.type == "Incoming"
diff --git a/erpnext/telephony/doctype/incoming_call_handling_schedule/incoming_call_handling_schedule.py b/erpnext/telephony/doctype/incoming_call_handling_schedule/incoming_call_handling_schedule.py
index ddc86c4..33d65bd 100644
--- a/erpnext/telephony/doctype/incoming_call_handling_schedule/incoming_call_handling_schedule.py
+++ b/erpnext/telephony/doctype/incoming_call_handling_schedule/incoming_call_handling_schedule.py
@@ -16,9 +16,7 @@
 		from frappe.types import DF
 
 		agent_group: DF.Link
-		day_of_week: DF.Literal[
-			"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
-		]
+		day_of_week: DF.Literal["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
 		from_time: DF.Time
 		parent: DF.Data
 		parentfield: DF.Data
diff --git a/erpnext/telephony/doctype/incoming_call_settings/incoming_call_settings.py b/erpnext/telephony/doctype/incoming_call_settings/incoming_call_settings.py
index f80c2d2..a036533 100644
--- a/erpnext/telephony/doctype/incoming_call_settings/incoming_call_settings.py
+++ b/erpnext/telephony/doctype/incoming_call_settings/incoming_call_settings.py
@@ -3,7 +3,6 @@
 
 
 from datetime import datetime
-from typing import Tuple
 
 import frappe
 from frappe import _
@@ -73,7 +72,7 @@
 					frappe.throw(_("Please fix overlapping time slots for {0}.").format(day))
 
 	@staticmethod
-	def check_timeslots_overlap(ts1: Tuple[int, int], ts2: Tuple[int, int]) -> bool:
+	def check_timeslots_overlap(ts1: tuple[int, int], ts2: tuple[int, int]) -> bool:
 		if (ts1[0] < ts2[0] and ts1[1] <= ts2[0]) or (ts1[0] >= ts2[1] and ts1[1] > ts2[1]):
 			return False
 		return True
diff --git a/erpnext/templates/pages/order.py b/erpnext/templates/pages/order.py
index 41b1384..d8e6334 100644
--- a/erpnext/templates/pages/order.py
+++ b/erpnext/templates/pages/order.py
@@ -36,9 +36,7 @@
 	context.available_loyalty_points = 0.0
 	if context.doc.get("customer"):
 		# check for the loyalty program of the customer
-		customer_loyalty_program = frappe.db.get_value(
-			"Customer", context.doc.customer, "loyalty_program"
-		)
+		customer_loyalty_program = frappe.db.get_value("Customer", context.doc.customer, "loyalty_program")
 
 		if customer_loyalty_program:
 			from erpnext.accounts.doctype.loyalty_program.loyalty_program import (
@@ -67,9 +65,12 @@
 
 def get_payment_details(doc):
 	show_pay_button, amount = (
-		"payments" in frappe.get_installed_apps()
-		and frappe.db.get_single_value("Buying Settings", "show_pay_button")
-	), 0
+		(
+			"payments" in frappe.get_installed_apps()
+			and frappe.db.get_single_value("Buying Settings", "show_pay_button")
+		),
+		0,
+	)
 	if not show_pay_button:
 		return show_pay_button, amount
 	amount = get_amount(doc)
diff --git a/erpnext/templates/pages/projects.py b/erpnext/templates/pages/projects.py
index 4b3089b..e3e26fc 100644
--- a/erpnext/templates/pages/projects.py
+++ b/erpnext/templates/pages/projects.py
@@ -12,9 +12,7 @@
 		["user", "view_attachments"],
 		as_dict=True,
 	)
-	if frappe.session.user != "Administrator" and (
-		not project_user or frappe.session.user == "Guest"
-	):
+	if frappe.session.user != "Administrator" and (not project_user or frappe.session.user == "Guest"):
 		raise frappe.PermissionError
 
 	context.no_cache = 1
@@ -38,7 +36,7 @@
 def get_tasks(project, start=0, search=None, item_status=None):
 	filters = {"project": project}
 	if search:
-		filters["subject"] = ("like", "%{0}%".format(search))
+		filters["subject"] = ("like", f"%{search}%")
 	tasks = frappe.get_all(
 		"Task",
 		filters=filters,
@@ -83,7 +81,7 @@
 def get_timesheets(project, start=0, search=None):
 	filters = {"project": project}
 	if search:
-		filters["activity_type"] = ("like", "%{0}%".format(search))
+		filters["activity_type"] = ("like", f"%{search}%")
 
 	timesheets = frappe.get_all(
 		"Timesheet Detail",
diff --git a/erpnext/templates/pages/rfq.py b/erpnext/templates/pages/rfq.py
index 4b83642..8431486 100644
--- a/erpnext/templates/pages/rfq.py
+++ b/erpnext/templates/pages/rfq.py
@@ -23,9 +23,7 @@
 
 def get_supplier():
 	doctype = frappe.form_dict.doctype
-	parties_doctype = (
-		"Request for Quotation Supplier" if doctype == "Request for Quotation" else doctype
-	)
+	parties_doctype = "Request for Quotation Supplier" if doctype == "Request for Quotation" else doctype
 	customers, suppliers = get_customers_suppliers(parties_doctype, frappe.session.user)
 
 	return suppliers[0] if suppliers else ""
@@ -44,7 +42,7 @@
 
 def unauthorized_user(supplier):
 	status = check_supplier_has_docname_access(supplier) or False
-	if status == False:
+	if status is False:
 		frappe.throw(_("Not Permitted"), frappe.PermissionError)
 
 
@@ -53,9 +51,7 @@
 	context.doc.currency = supplier_doc.default_currency or frappe.get_cached_value(
 		"Company", context.doc.company, "default_currency"
 	)
-	context.doc.currency_symbol = frappe.db.get_value(
-		"Currency", context.doc.currency, "symbol", cache=True
-	)
+	context.doc.currency_symbol = frappe.db.get_value("Currency", context.doc.currency, "symbol", cache=True)
 	context.doc.number_format = frappe.db.get_value(
 		"Currency", context.doc.currency, "number_format", cache=True
 	)
diff --git a/erpnext/templates/pages/search_help.py b/erpnext/templates/pages/search_help.py
index d158167..18a0a67 100644
--- a/erpnext/templates/pages/search_help.py
+++ b/erpnext/templates/pages/search_help.py
@@ -47,9 +47,7 @@
 
 
 def get_response(api, text):
-	response = requests.get(
-		api.base_url + "/" + api.query_route, data={api.search_term_param_name: text}
-	)
+	response = requests.get(api.base_url + "/" + api.query_route, data={api.search_term_param_name: text})
 
 	response.raise_for_status()
 	return response.json()
diff --git a/erpnext/tests/test_init.py b/erpnext/tests/test_init.py
index 18ce93a..2b4ea9f 100644
--- a/erpnext/tests/test_init.py
+++ b/erpnext/tests/test_init.py
@@ -9,36 +9,35 @@
 
 class TestInit(unittest.TestCase):
 	def test_encode_company_abbr(self):
-
 		abbr = "NFECT"
 
 		names = [
 			"Warehouse Name",
 			"ERPNext Foundation India",
-			"Gold - Member - {a}".format(a=abbr),
-			" - {a}".format(a=abbr),
+			f"Gold - Member - {abbr}",
+			f" - {abbr}",
 			"ERPNext - Foundation - India",
-			"ERPNext Foundation India - {a}".format(a=abbr),
-			"No-Space-{a}".format(a=abbr),
+			f"ERPNext Foundation India - {abbr}",
+			f"No-Space-{abbr}",
 			"- Warehouse",
 		]
 
 		expected_names = [
-			"Warehouse Name - {a}".format(a=abbr),
-			"ERPNext Foundation India - {a}".format(a=abbr),
-			"Gold - Member - {a}".format(a=abbr),
-			" - {a}".format(a=abbr),
-			"ERPNext - Foundation - India - {a}".format(a=abbr),
-			"ERPNext Foundation India - {a}".format(a=abbr),
-			"No-Space-{a} - {a}".format(a=abbr),
-			"- Warehouse - {a}".format(a=abbr),
+			f"Warehouse Name - {abbr}",
+			f"ERPNext Foundation India - {abbr}",
+			f"Gold - Member - {abbr}",
+			f" - {abbr}",
+			f"ERPNext - Foundation - India - {abbr}",
+			f"ERPNext Foundation India - {abbr}",
+			f"No-Space-{abbr} - {abbr}",
+			f"- Warehouse - {abbr}",
 		]
 
 		for i in range(len(names)):
 			enc_name = encode_company_abbr(names[i], abbr=abbr)
 			self.assertTrue(
 				enc_name == expected_names[i],
-				"{enc} is not same as {exp}".format(enc=enc_name, exp=expected_names[i]),
+				f"{enc_name} is not same as {expected_names[i]}",
 			)
 
 	def test_translation_files(self):
diff --git a/erpnext/tests/utils.py b/erpnext/tests/utils.py
index b553a7c..7ed8451 100644
--- a/erpnext/tests/utils.py
+++ b/erpnext/tests/utils.py
@@ -1,12 +1,12 @@
 # Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors
 # License: GNU General Public License v3. See license.txt
 
-from typing import Any, Dict, NewType, Optional
+from typing import Any, NewType
 
 import frappe
 from frappe.core.doctype.report.report import get_report_module_dotted_path
 
-ReportFilters = Dict[str, Any]
+ReportFilters = dict[str, Any]
 ReportName = NewType("ReportName", str)
 
 
@@ -57,8 +57,8 @@
 	report_name: ReportName,
 	module: str,
 	filters: ReportFilters,
-	default_filters: Optional[ReportFilters] = None,
-	optional_filters: Optional[ReportFilters] = None,
+	default_filters: ReportFilters | None = None,
+	optional_filters: ReportFilters | None = None,
 ):
 	"""Util for testing execution of a report with specified filters.
 
@@ -77,9 +77,7 @@
 		default_filters = {}
 
 	test_filters = []
-	report_execute_fn = frappe.get_attr(
-		get_report_module_dotted_path(module, report_name) + ".execute"
-	)
+	report_execute_fn = frappe.get_attr(get_report_module_dotted_path(module, report_name) + ".execute")
 	report_filters = frappe._dict(default_filters).copy().update(filters)
 
 	test_filters.append(report_filters)
diff --git a/erpnext/utilities/activation.py b/erpnext/utilities/activation.py
index 581b53d..1a70c6b 100644
--- a/erpnext/utilities/activation.py
+++ b/erpnext/utilities/activation.py
@@ -54,9 +54,7 @@
 	sales_data.append({"Communication": communication_number})
 
 	# recent login
-	if frappe.db.sql(
-		"select name from tabUser where last_login > date_sub(now(), interval 2 day) limit 1"
-	):
+	if frappe.db.sql("select name from tabUser where last_login > date_sub(now(), interval 2 day) limit 1"):
 		activation_level += 1
 
 	level = {"activation_level": activation_level, "sales_data": sales_data}
diff --git a/erpnext/utilities/bulk_transaction.py b/erpnext/utilities/bulk_transaction.py
index 343a881..bff83f9 100644
--- a/erpnext/utilities/bulk_transaction.py
+++ b/erpnext/utilities/bulk_transaction.py
@@ -18,9 +18,7 @@
 
 	length_of_data = len(deserialized_data)
 
-	frappe.msgprint(
-		_("Started a background job to create {1} {0}").format(to_doctype, length_of_data)
-	)
+	frappe.msgprint(_("Started a background job to create {1} {0}").format(to_doctype, length_of_data))
 	frappe.enqueue(
 		job,
 		deserialized_data=deserialized_data,
@@ -61,7 +59,7 @@
 			try:
 				frappe.db.savepoint("before_creation_state")
 				task(log.transaction_name, log.from_doctype, log.to_doctype)
-			except Exception as e:
+			except Exception:
 				frappe.db.rollback(save_point="before_creation_state")
 				update_log(log.name, "Failed", 1, str(frappe.get_traceback(with_context=True)))
 			else:
@@ -87,7 +85,7 @@
 			doc_name = d.get("name")
 			frappe.db.savepoint("before_creation_state")
 			task(doc_name, from_doctype, to_doctype)
-		except Exception as e:
+		except Exception:
 			frappe.db.rollback(save_point="before_creation_state")
 			fail_count += 1
 			create_log(
@@ -99,9 +97,7 @@
 				log_date=str(date.today()),
 			)
 		else:
-			create_log(
-				doc_name, None, from_doctype, to_doctype, status="Success", log_date=str(date.today())
-			)
+			create_log(doc_name, None, from_doctype, to_doctype, status="Success", log_date=str(date.today()))
 
 	show_job_status(fail_count, len(deserialized_data), to_doctype)
 
diff --git a/erpnext/utilities/doctype/video/video.py b/erpnext/utilities/doctype/video/video.py
index 875c4e7..bee00a8 100644
--- a/erpnext/utilities/doctype/video/video.py
+++ b/erpnext/utilities/doctype/video/video.py
@@ -112,9 +112,7 @@
 	if not isinstance(url, str):
 		frappe.throw(_("URL can only be a string"), title=_("Invalid URL"))
 
-	pattern = re.compile(
-		r'[a-z\:\//\.]+(youtube|youtu)\.(com|be)/(watch\?v=|embed/|.+\?v=)?([^"&?\s]{11})?'
-	)
+	pattern = re.compile(r'[a-z\:\//\.]+(youtube|youtu)\.(com|be)/(watch\?v=|embed/|.+\?v=)?([^"&?\s]{11})?')
 	id = pattern.match(url)
 	return id.groups()[-1]
 
diff --git a/erpnext/utilities/naming.py b/erpnext/utilities/naming.py
index 52bbade..84079ef 100644
--- a/erpnext/utilities/naming.py
+++ b/erpnext/utilities/naming.py
@@ -6,9 +6,7 @@
 	pass
 
 
-def set_by_naming_series(
-	doctype, fieldname, naming_series, hide_name_field=True, make_mandatory=1
-):
+def set_by_naming_series(doctype, fieldname, naming_series, hide_name_field=True, make_mandatory=1):
 	"""Change a doctype's naming to user naming series"""
 	from frappe.custom.doctype.property_setter.property_setter import make_property_setter
 
@@ -24,9 +22,7 @@
 		try:
 			frappe.db.sql(
 				"""update `tab{doctype}` set naming_series={s} where
-				ifnull(naming_series, '')=''""".format(
-					doctype=doctype, s="%s"
-				),
+				ifnull(naming_series, '')=''""".format(doctype=doctype, s="%s"),
 				get_default_naming_series(doctype),
 			)
 		except NamingSeriesNotSetError:
@@ -34,27 +30,19 @@
 
 		if hide_name_field:
 			make_property_setter(doctype, fieldname, "reqd", 0, "Check", validate_fields_for_doctype=False)
-			make_property_setter(
-				doctype, fieldname, "hidden", 1, "Check", validate_fields_for_doctype=False
-			)
+			make_property_setter(doctype, fieldname, "hidden", 1, "Check", validate_fields_for_doctype=False)
 	else:
-		make_property_setter(
-			doctype, "naming_series", "reqd", 0, "Check", validate_fields_for_doctype=False
-		)
+		make_property_setter(doctype, "naming_series", "reqd", 0, "Check", validate_fields_for_doctype=False)
 		make_property_setter(
 			doctype, "naming_series", "hidden", 1, "Check", validate_fields_for_doctype=False
 		)
 
 		if hide_name_field:
-			make_property_setter(
-				doctype, fieldname, "hidden", 0, "Check", validate_fields_for_doctype=False
-			)
+			make_property_setter(doctype, fieldname, "hidden", 0, "Check", validate_fields_for_doctype=False)
 			make_property_setter(doctype, fieldname, "reqd", 1, "Check", validate_fields_for_doctype=False)
 
 			# set values for mandatory
 			frappe.db.sql(
-				"""update `tab{doctype}` set `{fieldname}`=`name` where
-				ifnull({fieldname}, '')=''""".format(
-					doctype=doctype, fieldname=fieldname
-				)
+				f"""update `tab{doctype}` set `{fieldname}`=`name` where
+				ifnull({fieldname}, '')=''"""
 			)
diff --git a/erpnext/utilities/product.py b/erpnext/utilities/product.py
index 7897c15..029af44 100644
--- a/erpnext/utilities/product.py
+++ b/erpnext/utilities/product.py
@@ -61,7 +61,9 @@
 				if pricing_rule.pricing_rule_for == "Rate":
 					rate_discount = flt(mrp) - flt(pricing_rule.price_list_rate)
 					if rate_discount > 0:
-						price_obj.formatted_discount_rate = fmt_money(rate_discount, currency=price_obj["currency"])
+						price_obj.formatted_discount_rate = fmt_money(
+							rate_discount, currency=price_obj["currency"]
+						)
 					price_obj.price_list_rate = pricing_rule.price_list_rate or 0
 
 			if price_obj:
@@ -131,7 +133,7 @@
 		else:
 			variant_of_query = ""
 
-		query = """
+		query = f"""
 			SELECT
 				t1.parent
 			FROM
@@ -154,9 +156,7 @@
 				t1.parent
 			ORDER BY
 				NULL
-		""".format(
-			attribute_query=attribute_query, variant_of_query=variant_of_query
-		)
+		"""
 
 		item_codes = set([r[0] for r in frappe.db.sql(query, query_values)])
 		items.append(item_codes)
diff --git a/erpnext/utilities/transaction_base.py b/erpnext/utilities/transaction_base.py
index b083614..d89095e 100644
--- a/erpnext/utilities/transaction_base.py
+++ b/erpnext/utilities/transaction_base.py
@@ -58,9 +58,7 @@
 
 	def compare_values(self, ref_doc, fields, doc=None):
 		for reference_doctype, ref_dn_list in ref_doc.items():
-			prev_doc_detail_map = self.get_prev_doc_reference_details(
-				ref_dn_list, reference_doctype, fields
-			)
+			prev_doc_detail_map = self.get_prev_doc_reference_details(ref_dn_list, reference_doctype, fields)
 			for reference_name in ref_dn_list:
 				prevdoc_values = prev_doc_detail_map.get(reference_name)
 				if not prevdoc_values: