Merge pull request #32238 from rohitwaghchaure/fix-pricing-rules-issues

fix: suggestion threshold label and rule was not working for other item with min and max amount
diff --git a/.mergify.yml b/.mergify.yml
index d7f82e6..c5f3d83 100644
--- a/.mergify.yml
+++ b/.mergify.yml
@@ -9,6 +9,7 @@
           - author!=nabinhait
           - author!=ankush
           - author!=deepeshgarg007
+          - author!=frappe-pr-bot
           - author!=mergify[bot]
 
         - or:
diff --git a/README.md b/README.md
index cea3472..0708266 100644
--- a/README.md
+++ b/README.md
@@ -82,6 +82,8 @@
 
 The ERPNext code is licensed as GNU General Public License (v3) and the Documentation is licensed as Creative Commons (CC-BY-SA-3.0) and the copyright is owned by Frappe Technologies Pvt Ltd (Frappe) and Contributors.
 
+By contributing to ERPNext, you agree that your contributions will be licensed under its GNU General Public License (v3).
+
 ## Logo and Trademark Policy
 
 Please read our [Logo and Trademark Policy](TRADEMARK_POLICY.md).
diff --git a/erpnext/accounts/doctype/account/account.py b/erpnext/accounts/doctype/account/account.py
index 2610c86..9dff116 100644
--- a/erpnext/accounts/doctype/account/account.py
+++ b/erpnext/accounts/doctype/account/account.py
@@ -37,7 +37,7 @@
 	def autoname(self):
 		from erpnext.accounts.utils import get_autoname_with_number
 
-		self.name = get_autoname_with_number(self.account_number, self.account_name, None, self.company)
+		self.name = get_autoname_with_number(self.account_number, self.account_name, self.company)
 
 	def validate(self):
 		from erpnext.accounts.utils import validate_field_number
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 3f5c064..d8880f7 100644
--- a/erpnext/accounts/doctype/bank_statement_import/bank_statement_import.py
+++ b/erpnext/accounts/doctype/bank_statement_import/bank_statement_import.py
@@ -53,15 +53,13 @@
 		if "Bank Account" not in json.dumps(preview["columns"]):
 			frappe.throw(_("Please add the Bank Account column"))
 
-		from frappe.core.page.background_jobs.background_jobs import get_info
+		from frappe.utils.background_jobs import is_job_queued
 		from frappe.utils.scheduler import is_scheduler_inactive
 
 		if is_scheduler_inactive() and not frappe.flags.in_test:
 			frappe.throw(_("Scheduler is inactive. Cannot import data."), title=_("Scheduler Inactive"))
 
-		enqueued_jobs = [d.get("job_name") for d in get_info()]
-
-		if self.name not in enqueued_jobs:
+		if not is_job_queued(self.name):
 			enqueue(
 				start_import,
 				queue="default",
diff --git a/erpnext/accounts/doctype/cost_center/cost_center.py b/erpnext/accounts/doctype/cost_center/cost_center.py
index 31055c3..e8b34bb 100644
--- a/erpnext/accounts/doctype/cost_center/cost_center.py
+++ b/erpnext/accounts/doctype/cost_center/cost_center.py
@@ -16,7 +16,7 @@
 		from erpnext.accounts.utils import get_autoname_with_number
 
 		self.name = get_autoname_with_number(
-			self.cost_center_number, self.cost_center_name, None, self.company
+			self.cost_center_number, self.cost_center_name, self.company
 		)
 
 	def validate(self):
diff --git a/erpnext/accounts/doctype/ledger_merge/ledger_merge.py b/erpnext/accounts/doctype/ledger_merge/ledger_merge.py
index 18e5a1a..7cd6d04 100644
--- a/erpnext/accounts/doctype/ledger_merge/ledger_merge.py
+++ b/erpnext/accounts/doctype/ledger_merge/ledger_merge.py
@@ -4,22 +4,20 @@
 import frappe
 from frappe import _
 from frappe.model.document import Document
+from frappe.utils.background_jobs import is_job_queued
 
 from erpnext.accounts.doctype.account.account import merge_account
 
 
 class LedgerMerge(Document):
 	def start_merge(self):
-		from frappe.core.page.background_jobs.background_jobs import get_info
 		from frappe.utils.background_jobs import enqueue
 		from frappe.utils.scheduler import is_scheduler_inactive
 
 		if is_scheduler_inactive() and not frappe.flags.in_test:
 			frappe.throw(_("Scheduler is inactive. Cannot merge accounts."), title=_("Scheduler Inactive"))
 
-		enqueued_jobs = [d.get("job_name") for d in get_info()]
-
-		if self.name not in enqueued_jobs:
+		if not is_job_queued(self.name):
 			enqueue(
 				start_merge,
 				queue="default",
diff --git a/erpnext/accounts/doctype/opening_invoice_creation_tool/opening_invoice_creation_tool.py b/erpnext/accounts/doctype/opening_invoice_creation_tool/opening_invoice_creation_tool.py
index 9937742..f7df1ff 100644
--- a/erpnext/accounts/doctype/opening_invoice_creation_tool/opening_invoice_creation_tool.py
+++ b/erpnext/accounts/doctype/opening_invoice_creation_tool/opening_invoice_creation_tool.py
@@ -6,7 +6,7 @@
 from frappe import _, scrub
 from frappe.model.document import Document
 from frappe.utils import flt, nowdate
-from frappe.utils.background_jobs import enqueue
+from frappe.utils.background_jobs import enqueue, is_job_queued
 
 from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import (
 	get_accounting_dimensions,
@@ -207,14 +207,12 @@
 		if len(invoices) < 50:
 			return start_import(invoices)
 		else:
-			from frappe.core.page.background_jobs.background_jobs import get_info
 			from frappe.utils.scheduler import is_scheduler_inactive
 
 			if is_scheduler_inactive() and not frappe.flags.in_test:
 				frappe.throw(_("Scheduler is inactive. Cannot import data."), title=_("Scheduler Inactive"))
 
-			enqueued_jobs = [d.get("job_name") for d in get_info()]
-			if self.name not in enqueued_jobs:
+			if not is_job_queued(self.name):
 				enqueue(
 					start_import,
 					queue="default",
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 81a234a..a0a1c8c 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
@@ -6,11 +6,10 @@
 
 import frappe
 from frappe import _
-from frappe.core.page.background_jobs.background_jobs import get_info
 from frappe.model.document import Document
 from frappe.model.mapper import map_child_doc, map_doc
 from frappe.utils import cint, flt, get_time, getdate, nowdate, nowtime
-from frappe.utils.background_jobs import enqueue
+from frappe.utils.background_jobs import enqueue, is_job_queued
 from frappe.utils.scheduler import is_scheduler_inactive
 
 
@@ -467,7 +466,7 @@
 	closing_entry = kwargs.get("closing_entry") or {}
 
 	job_name = closing_entry.get("name")
-	if not job_already_enqueued(job_name):
+	if not is_job_queued(job_name):
 		enqueue(
 			job,
 			**kwargs,
@@ -491,12 +490,6 @@
 		frappe.throw(_("Scheduler is inactive. Cannot enqueue job."), title=_("Scheduler Inactive"))
 
 
-def job_already_enqueued(job_name):
-	enqueued_jobs = [d.get("job_name") for d in get_info()]
-	if job_name in enqueued_jobs:
-		return True
-
-
 def safe_load_json(message):
 	try:
 		json_message = json.loads(message).get("message")
diff --git a/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.html b/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.html
index 82705a9..0da44a4 100644
--- a/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.html
+++ b/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.html
@@ -25,7 +25,7 @@
 	</div>
 	<br>
 
-	<table class="table table-bordered">
+	<table class="table table-bordered" style="font-size: 10px">
 		<thead>
 			<tr>
 				<th style="width: 12%">{{ _("Date") }}</th>
diff --git a/erpnext/accounts/doctype/promotional_scheme/promotional_scheme.py b/erpnext/accounts/doctype/promotional_scheme/promotional_scheme.py
index fac9be7..4d28d10 100644
--- a/erpnext/accounts/doctype/promotional_scheme/promotional_scheme.py
+++ b/erpnext/accounts/doctype/promotional_scheme/promotional_scheme.py
@@ -34,8 +34,8 @@
 other_fields = [
 	"min_qty",
 	"max_qty",
-	"min_amt",
-	"max_amt",
+	"min_amount",
+	"max_amount",
 	"priority",
 	"warehouse",
 	"threshold_percentage",
@@ -246,7 +246,11 @@
 def set_args(args, pr, doc, child_doc, discount_fields, child_doc_fields):
 	pr.update(args)
 	for field in other_fields + discount_fields:
-		pr.set(field, child_doc_fields.get(field))
+		target_field = field
+		if target_field in ["min_amount", "max_amount"]:
+			target_field = "min_amt" if field == "min_amount" else "max_amt"
+
+		pr.set(target_field, child_doc_fields.get(field))
 
 	pr.promotional_scheme_id = child_doc_fields.name
 	pr.promotional_scheme = doc.name
diff --git a/erpnext/accounts/doctype/promotional_scheme/test_promotional_scheme.py b/erpnext/accounts/doctype/promotional_scheme/test_promotional_scheme.py
index b3b9d7b..9e576fb 100644
--- a/erpnext/accounts/doctype/promotional_scheme/test_promotional_scheme.py
+++ b/erpnext/accounts/doctype/promotional_scheme/test_promotional_scheme.py
@@ -90,6 +90,23 @@
 		price_rules = frappe.get_all("Pricing Rule", filters={"promotional_scheme": ps.name})
 		self.assertEqual(price_rules, [])
 
+	def test_min_max_amount_configuration(self):
+		ps = make_promotional_scheme()
+		ps.price_discount_slabs[0].min_amount = 10
+		ps.price_discount_slabs[0].max_amount = 1000
+		ps.save()
+
+		price_rules_data = frappe.db.get_value(
+			"Pricing Rule", {"promotional_scheme": ps.name}, ["min_amt", "max_amt"], as_dict=1
+		)
+
+		self.assertEqual(price_rules_data.min_amt, 10)
+		self.assertEqual(price_rules_data.max_amt, 1000)
+
+		frappe.delete_doc("Promotional Scheme", ps.name)
+		price_rules = frappe.get_all("Pricing Rule", filters={"promotional_scheme": ps.name})
+		self.assertEqual(price_rules, [])
+
 
 def make_promotional_scheme(**args):
 	args = frappe._dict(args)
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
index 1f5879d..e51938b 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
@@ -7,17 +7,7 @@
 from frappe.contacts.doctype.address.address import get_address_display
 from frappe.model.mapper import get_mapped_doc
 from frappe.model.utils import get_fetch_values
-from frappe.utils import (
-	add_days,
-	add_months,
-	cint,
-	cstr,
-	flt,
-	formatdate,
-	get_link_to_form,
-	getdate,
-	nowdate,
-)
+from frappe.utils import add_days, cint, cstr, flt, formatdate, get_link_to_form, getdate, nowdate
 
 import erpnext
 from erpnext.accounts.deferred_revenue import validate_service_stop_date
@@ -35,7 +25,6 @@
 	get_disposal_account_and_cost_center,
 	get_gl_entries_on_asset_disposal,
 	get_gl_entries_on_asset_regain,
-	make_depreciation_entry,
 )
 from erpnext.controllers.accounts_controller import validate_account_head
 from erpnext.controllers.selling_controller import SellingController
@@ -186,7 +175,7 @@
 					if self.update_stock:
 						frappe.throw(_("'Update Stock' cannot be checked for fixed asset sale"))
 
-					elif asset.status in ("Scrapped", "Cancelled") or (
+					elif asset.status in ("Scrapped", "Cancelled", "Capitalized", "Decapitalized") or (
 						asset.status == "Sold" and not self.is_return
 					):
 						frappe.throw(
@@ -1097,7 +1086,7 @@
 						asset.db_set("disposal_date", None)
 
 						if asset.calculate_depreciation:
-							self.reverse_depreciation_entry_made_after_sale(asset)
+							self.reverse_depreciation_entry_made_after_disposal(asset)
 							self.reset_depreciation_schedule(asset)
 
 					else:
@@ -1162,101 +1151,6 @@
 		self.check_finance_books(item, asset)
 		return asset
 
-	def check_finance_books(self, item, asset):
-		if (
-			len(asset.finance_books) > 1 and not item.finance_book and asset.finance_books[0].finance_book
-		):
-			frappe.throw(
-				_("Select finance book for the item {0} at row {1}").format(item.item_code, item.idx)
-			)
-
-	def depreciate_asset(self, asset):
-		asset.flags.ignore_validate_update_after_submit = True
-		asset.prepare_depreciation_data(date_of_sale=self.posting_date)
-		asset.save()
-
-		make_depreciation_entry(asset.name, self.posting_date)
-
-	def reset_depreciation_schedule(self, asset):
-		asset.flags.ignore_validate_update_after_submit = True
-
-		# recreate original depreciation schedule of the asset
-		asset.prepare_depreciation_data(date_of_return=self.posting_date)
-
-		self.modify_depreciation_schedule_for_asset_repairs(asset)
-		asset.save()
-
-	def modify_depreciation_schedule_for_asset_repairs(self, asset):
-		asset_repairs = frappe.get_all(
-			"Asset Repair", filters={"asset": asset.name}, fields=["name", "increase_in_asset_life"]
-		)
-
-		for repair in asset_repairs:
-			if repair.increase_in_asset_life:
-				asset_repair = frappe.get_doc("Asset Repair", repair.name)
-				asset_repair.modify_depreciation_schedule()
-				asset.prepare_depreciation_data()
-
-	def reverse_depreciation_entry_made_after_sale(self, asset):
-		from erpnext.accounts.doctype.journal_entry.journal_entry import make_reverse_journal_entry
-
-		posting_date_of_original_invoice = self.get_posting_date_of_sales_invoice()
-
-		row = -1
-		finance_book = asset.get("schedules")[0].get("finance_book")
-		for schedule in asset.get("schedules"):
-			if schedule.finance_book != finance_book:
-				row = 0
-				finance_book = schedule.finance_book
-			else:
-				row += 1
-
-			if schedule.schedule_date == posting_date_of_original_invoice:
-				if not self.sale_was_made_on_original_schedule_date(
-					asset, schedule, row, posting_date_of_original_invoice
-				) or self.sale_happens_in_the_future(posting_date_of_original_invoice):
-
-					reverse_journal_entry = make_reverse_journal_entry(schedule.journal_entry)
-					reverse_journal_entry.posting_date = nowdate()
-					frappe.flags.is_reverse_depr_entry = True
-					reverse_journal_entry.submit()
-
-					frappe.flags.is_reverse_depr_entry = False
-					asset.flags.ignore_validate_update_after_submit = True
-					schedule.journal_entry = None
-					depreciation_amount = self.get_depreciation_amount_in_je(reverse_journal_entry)
-					asset.finance_books[0].value_after_depreciation += depreciation_amount
-					asset.save()
-
-	def get_posting_date_of_sales_invoice(self):
-		return frappe.db.get_value("Sales Invoice", self.return_against, "posting_date")
-
-	# if the invoice had been posted on the date the depreciation was initially supposed to happen, the depreciation shouldn't be undone
-	def sale_was_made_on_original_schedule_date(
-		self, asset, schedule, row, posting_date_of_original_invoice
-	):
-		for finance_book in asset.get("finance_books"):
-			if schedule.finance_book == finance_book.finance_book:
-				orginal_schedule_date = add_months(
-					finance_book.depreciation_start_date, row * cint(finance_book.frequency_of_depreciation)
-				)
-
-				if orginal_schedule_date == posting_date_of_original_invoice:
-					return True
-		return False
-
-	def sale_happens_in_the_future(self, posting_date_of_original_invoice):
-		if posting_date_of_original_invoice > getdate():
-			return True
-
-		return False
-
-	def get_depreciation_amount_in_je(self, journal_entry):
-		if journal_entry.accounts[0].debit_in_account_currency:
-			return journal_entry.accounts[0].debit_in_account_currency
-		else:
-			return journal_entry.accounts[0].credit_in_account_currency
-
 	@property
 	def enable_discount_accounting(self):
 		if not hasattr(self, "_enable_discount_accounting"):
@@ -2535,7 +2429,6 @@
 				target.closing_text = letter_text.get("closing_text")
 				target.language = letter_text.get("language")
 			amounts = calculate_interest_and_amount(
-				target.posting_date,
 				target.outstanding_amount,
 				target.rate_of_interest,
 				target.dunning_fee,
diff --git a/erpnext/accounts/general_ledger.py b/erpnext/accounts/general_ledger.py
index 16072f3..f4a50a5 100644
--- a/erpnext/accounts/general_ledger.py
+++ b/erpnext/accounts/general_ledger.py
@@ -489,7 +489,6 @@
 		).run(as_dict=1)
 
 	if gl_entries:
-		create_payment_ledger_entry(gl_entries, cancel=1)
 		create_payment_ledger_entry(
 			gl_entries, cancel=1, adv_adj=adv_adj, update_outstanding=update_outstanding
 		)
diff --git a/erpnext/accounts/report/accounts_receivable/accounts_receivable.py b/erpnext/accounts/report/accounts_receivable/accounts_receivable.py
index 3f504b1..8557c03 100755
--- a/erpnext/accounts/report/accounts_receivable/accounts_receivable.py
+++ b/erpnext/accounts/report/accounts_receivable/accounts_receivable.py
@@ -784,7 +784,7 @@
 	def add_customer_filters(
 		self,
 	):
-		self.customter = qb.DocType("Customer")
+		self.customer = qb.DocType("Customer")
 
 		if self.filters.get("customer_group"):
 			self.get_hierarchical_filters("Customer Group", "customer_group")
@@ -838,7 +838,7 @@
 		customer = self.customer
 		groups = qb.from_(doc).select(doc.name).where((doc.lft >= lft) & (doc.rgt <= rgt))
 		customers = qb.from_(customer).select(customer.name).where(customer[key].isin(groups))
-		self.qb_selection_filter.append(ple.isin(ple.party.isin(customers)))
+		self.qb_selection_filter.append(ple.party.isin(customers))
 
 	def add_accounting_dimensions_filters(self):
 		accounting_dimensions = get_accounting_dimensions(as_list=False)
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 9d2deea..449ebdc 100644
--- a/erpnext/accounts/report/bank_clearance_summary/bank_clearance_summary.py
+++ b/erpnext/accounts/report/bank_clearance_summary/bank_clearance_summary.py
@@ -22,8 +22,7 @@
 		{
 			"label": _("Payment Document Type"),
 			"fieldname": "payment_document_type",
-			"fieldtype": "Link",
-			"options": "Doctype",
+			"fieldtype": "Data",
 			"width": 130,
 		},
 		{
@@ -33,15 +32,15 @@
 			"options": "payment_document_type",
 			"width": 140,
 		},
-		{"label": _("Posting Date"), "fieldname": "posting_date", "fieldtype": "Date", "width": 100},
+		{"label": _("Posting Date"), "fieldname": "posting_date", "fieldtype": "Date", "width": 120},
 		{"label": _("Cheque/Reference No"), "fieldname": "cheque_no", "width": 120},
-		{"label": _("Clearance Date"), "fieldname": "clearance_date", "fieldtype": "Date", "width": 100},
+		{"label": _("Clearance Date"), "fieldname": "clearance_date", "fieldtype": "Date", "width": 120},
 		{
 			"label": _("Against Account"),
 			"fieldname": "against",
 			"fieldtype": "Link",
 			"options": "Account",
-			"width": 170,
+			"width": 200,
 		},
 		{"label": _("Amount"), "fieldname": "amount", "fieldtype": "Currency", "width": 120},
 	]
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 ac70666..c987231 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
@@ -97,6 +97,7 @@
 			row.update({"rate": d.base_net_rate, "amount": d.base_net_amount})
 
 		total_tax = 0
+		total_other_charges = 0
 		for tax in tax_columns:
 			item_tax = itemised_tax.get(d.name, {}).get(tax, {})
 			row.update(
@@ -105,10 +106,18 @@
 					frappe.scrub(tax + " Amount"): item_tax.get("tax_amount", 0),
 				}
 			)
-			total_tax += flt(item_tax.get("tax_amount"))
+			if item_tax.get("is_other_charges"):
+				total_other_charges += flt(item_tax.get("tax_amount"))
+			else:
+				total_tax += flt(item_tax.get("tax_amount"))
 
 		row.update(
-			{"total_tax": total_tax, "total": d.base_net_amount + total_tax, "currency": company_currency}
+			{
+				"total_tax": total_tax,
+				"total_other_charges": total_other_charges,
+				"total": d.base_net_amount + total_tax,
+				"currency": company_currency,
+			}
 		)
 
 		if filters.get("group_by"):
@@ -477,7 +486,7 @@
 	tax_details = frappe.db.sql(
 		"""
 		select
-			name, parent, description, item_wise_tax_detail,
+			name, parent, description, item_wise_tax_detail, account_head,
 			charge_type, {add_deduct_tax}, base_tax_amount_after_discount_amount
 		from `tab%s`
 		where
@@ -493,11 +502,22 @@
 		tuple([doctype] + list(invoice_item_row)),
 	)
 
+	account_doctype = frappe.qb.DocType("Account")
+
+	query = (
+		frappe.qb.from_(account_doctype)
+		.select(account_doctype.name)
+		.where((account_doctype.account_type == "Tax"))
+	)
+
+	tax_accounts = query.run()
+
 	for (
 		name,
 		parent,
 		description,
 		item_wise_tax_detail,
+		account_head,
 		charge_type,
 		add_deduct_tax,
 		tax_amount,
@@ -540,7 +560,11 @@
 							)
 
 							itemised_tax.setdefault(d.name, {})[description] = frappe._dict(
-								{"tax_rate": tax_rate, "tax_amount": tax_value}
+								{
+									"tax_rate": tax_rate,
+									"tax_amount": tax_value,
+									"is_other_charges": 0 if tuple([account_head]) in tax_accounts else 1,
+								}
 							)
 
 			except ValueError:
@@ -584,6 +608,13 @@
 			"width": 100,
 		},
 		{
+			"label": _("Total Other Charges"),
+			"fieldname": "total_other_charges",
+			"fieldtype": "Currency",
+			"options": "currency",
+			"width": 100,
+		},
+		{
 			"label": _("Total"),
 			"fieldname": "total",
 			"fieldtype": "Currency",
diff --git a/erpnext/accounts/utils.py b/erpnext/accounts/utils.py
index f61e8ac..c5eb7d8 100644
--- a/erpnext/accounts/utils.py
+++ b/erpnext/accounts/utils.py
@@ -1037,7 +1037,7 @@
 
 	frappe.db.set_value("Cost Center", docname, "cost_center_name", cost_center_name.strip())
 
-	new_name = get_autoname_with_number(cost_center_number, cost_center_name, docname, company)
+	new_name = get_autoname_with_number(cost_center_number, cost_center_name, company)
 	if docname != new_name:
 		frappe.rename_doc("Cost Center", docname, new_name, force=1, merge=merge)
 		return new_name
@@ -1060,16 +1060,14 @@
 			)
 
 
-def get_autoname_with_number(number_value, doc_title, name, company):
+def get_autoname_with_number(number_value, doc_title, company):
 	"""append title with prefix as number and suffix as company's abbreviation separated by '-'"""
-	if name:
-		name_split = name.split("-")
-		parts = [doc_title.strip(), name_split[len(name_split) - 1].strip()]
-	else:
-		abbr = frappe.get_cached_value("Company", company, ["abbr"], as_dict=True)
-		parts = [doc_title.strip(), abbr.abbr]
+	company_abbr = frappe.get_cached_value("Company", company, "abbr")
+	parts = [doc_title.strip(), company_abbr]
+
 	if cstr(number_value).strip():
 		parts.insert(0, cstr(number_value).strip())
+
 	return " - ".join(parts)
 
 
diff --git a/erpnext/assets/doctype/asset/asset.py b/erpnext/assets/doctype/asset/asset.py
index a22d70d..8ac7ed6 100644
--- a/erpnext/assets/doctype/asset/asset.py
+++ b/erpnext/assets/doctype/asset/asset.py
@@ -79,12 +79,12 @@
 				_("Purchase Invoice cannot be made against an existing asset {0}").format(self.name)
 			)
 
-	def prepare_depreciation_data(self, date_of_sale=None, date_of_return=None):
+	def prepare_depreciation_data(self, date_of_disposal=None, date_of_return=None):
 		if self.calculate_depreciation:
 			self.value_after_depreciation = 0
 			self.set_depreciation_rate()
-			self.make_depreciation_schedule(date_of_sale)
-			self.set_accumulated_depreciation(date_of_sale, date_of_return)
+			self.make_depreciation_schedule(date_of_disposal)
+			self.set_accumulated_depreciation(date_of_disposal, date_of_return)
 		else:
 			self.finance_books = []
 			self.value_after_depreciation = flt(self.gross_purchase_amount) - flt(
@@ -223,7 +223,7 @@
 				self.get_depreciation_rate(d, on_validate=True), d.precision("rate_of_depreciation")
 			)
 
-	def make_depreciation_schedule(self, date_of_sale):
+	def make_depreciation_schedule(self, date_of_disposal):
 		if "Manual" not in [d.depreciation_method for d in self.finance_books] and not self.get(
 			"schedules"
 		):
@@ -235,9 +235,9 @@
 		start = self.clear_depreciation_schedule()
 
 		for finance_book in self.get("finance_books"):
-			self._make_depreciation_schedule(finance_book, start, date_of_sale)
+			self._make_depreciation_schedule(finance_book, start, date_of_disposal)
 
-	def _make_depreciation_schedule(self, finance_book, start, date_of_sale):
+	def _make_depreciation_schedule(self, finance_book, start, date_of_disposal):
 		self.validate_asset_finance_books(finance_book)
 
 		value_after_depreciation = self._get_value_after_depreciation(finance_book)
@@ -274,15 +274,15 @@
 				monthly_schedule_date = add_months(schedule_date, -finance_book.frequency_of_depreciation + 1)
 
 			# if asset is being sold
-			if date_of_sale:
+			if date_of_disposal:
 				from_date = self.get_from_date(finance_book.finance_book)
 				depreciation_amount, days, months = self.get_pro_rata_amt(
-					finance_book, depreciation_amount, from_date, date_of_sale
+					finance_book, depreciation_amount, from_date, date_of_disposal
 				)
 
 				if depreciation_amount > 0:
 					self._add_depreciation_row(
-						date_of_sale,
+						date_of_disposal,
 						depreciation_amount,
 						finance_book.depreciation_method,
 						finance_book.finance_book,
diff --git a/erpnext/assets/doctype/asset/asset_list.js b/erpnext/assets/doctype/asset/asset_list.js
index 4302cb2..3d00eb7 100644
--- a/erpnext/assets/doctype/asset/asset_list.js
+++ b/erpnext/assets/doctype/asset/asset_list.js
@@ -10,6 +10,9 @@
 		} else if (doc.status === "Sold") {
 			return [__("Sold"), "green", "status,=,Sold"];
 
+		} else if (["Capitalized", "Decapitalized"].includes(doc.status)) {
+			return [__(doc.status), "grey", "status,=," + doc.status];
+
 		} else if (doc.status === "Scrapped") {
 			return [__("Scrapped"), "grey", "status,=,Scrapped"];
 
diff --git a/erpnext/assets/doctype/asset/depreciation.py b/erpnext/assets/doctype/asset/depreciation.py
index 3f7e945..7438638 100644
--- a/erpnext/assets/doctype/asset/depreciation.py
+++ b/erpnext/assets/doctype/asset/depreciation.py
@@ -11,7 +11,7 @@
 )
 
 
-def post_depreciation_entries(date=None):
+def post_depreciation_entries(date=None, commit=True):
 	# Return if automatic booking of asset depreciation is disabled
 	if not cint(
 		frappe.db.get_value("Accounts Settings", None, "book_asset_depreciation_entry_automatically")
@@ -22,7 +22,8 @@
 		date = today()
 	for asset in get_depreciable_assets(date):
 		make_depreciation_entry(asset, date)
-		frappe.db.commit()
+		if commit:
+			frappe.db.commit()
 
 
 def get_depreciable_assets(date):
@@ -190,7 +191,7 @@
 
 	if asset.docstatus != 1:
 		frappe.throw(_("Asset {0} must be submitted").format(asset.name))
-	elif asset.status in ("Cancelled", "Sold", "Scrapped"):
+	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)
 		)
@@ -358,3 +359,30 @@
 		frappe.throw(_("Please set 'Asset Depreciation Cost Center' in Company {0}").format(company))
 
 	return disposal_account, depreciation_cost_center
+
+
+@frappe.whitelist()
+def get_value_after_depreciation_on_disposal_date(asset, disposal_date, finance_book=None):
+	asset_doc = frappe.get_doc("Asset", asset)
+
+	if asset_doc.calculate_depreciation:
+		asset_doc.prepare_depreciation_data(getdate(disposal_date))
+
+		finance_book_id = 1
+		if finance_book:
+			for fb in asset_doc.finance_books:
+				if fb.finance_book == finance_book:
+					finance_book_id = fb.idx
+					break
+
+		asset_schedules = [
+			sch for sch in asset_doc.schedules if cint(sch.finance_book_id) == finance_book_id
+		]
+		accumulated_depr_amount = asset_schedules[-1].accumulated_depreciation_amount
+
+		return flt(
+			flt(asset_doc.gross_purchase_amount) - accumulated_depr_amount,
+			asset_doc.precision("gross_purchase_amount"),
+		)
+	else:
+		return flt(asset_doc.value_after_depreciation)
diff --git a/erpnext/assets/doctype/asset/test_asset.py b/erpnext/assets/doctype/asset/test_asset.py
index 132840e..e7af9bd 100644
--- a/erpnext/assets/doctype/asset/test_asset.py
+++ b/erpnext/assets/doctype/asset/test_asset.py
@@ -1425,6 +1425,16 @@
 			"depreciation_expense_account": "_Test Depreciations - _TC",
 		},
 	)
+	asset_category.append(
+		"accounts",
+		{
+			"company_name": "_Test Company with perpetual inventory",
+			"fixed_asset_account": "_Test Fixed Asset - TCP1",
+			"accumulated_depreciation_account": "_Test Accumulated Depreciations - TCP1",
+			"depreciation_expense_account": "_Test Depreciations - TCP1",
+		},
+	)
+
 	asset_category.insert()
 
 
diff --git a/erpnext/assets/doctype/asset_capitalization/__init__.py b/erpnext/assets/doctype/asset_capitalization/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/assets/doctype/asset_capitalization/__init__.py
diff --git a/erpnext/assets/doctype/asset_capitalization/asset_capitalization.js b/erpnext/assets/doctype/asset_capitalization/asset_capitalization.js
new file mode 100644
index 0000000..9c7f70b
--- /dev/null
+++ b/erpnext/assets/doctype/asset_capitalization/asset_capitalization.js
@@ -0,0 +1,417 @@
+// Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
+// For license information, please see license.txt
+
+frappe.provide("erpnext.assets");
+
+
+erpnext.assets.AssetCapitalization = class AssetCapitalization extends erpnext.stock.StockController {
+	setup() {
+		this.setup_posting_date_time_check();
+	}
+
+	onload() {
+		this.setup_queries();
+	}
+
+	refresh() {
+		erpnext.hide_company();
+		this.show_general_ledger();
+		if ((this.frm.doc.stock_items && this.frm.doc.stock_items.length) || !this.frm.doc.target_is_fixed_asset) {
+			this.show_stock_ledger();
+		}
+	}
+
+	setup_queries() {
+		var me = this;
+
+		me.setup_warehouse_query();
+
+		me.frm.set_query("target_item_code", function() {
+			if (me.frm.doc.entry_type == "Capitalization") {
+				return erpnext.queries.item({"is_stock_item": 0, "is_fixed_asset": 1});
+			} else {
+				return erpnext.queries.item({"is_stock_item": 1, "is_fixed_asset": 0});
+			}
+		});
+
+		me.frm.set_query("target_asset", function() {
+			var filters = {};
+
+			if (me.frm.doc.target_item_code) {
+				filters['item_code'] = me.frm.doc.target_item_code;
+			}
+
+			filters['status'] = ["not in", ["Draft", "Scrapped", "Sold", "Capitalized", "Decapitalized"]];
+			filters['docstatus'] = 1;
+
+			return {
+				filters: filters
+			};
+		});
+
+		me.frm.set_query("asset", "asset_items", function() {
+			var filters = {
+				'status': ["not in", ["Draft", "Scrapped", "Sold", "Capitalized", "Decapitalized"]],
+				'docstatus': 1
+			};
+
+			if (me.frm.doc.target_asset) {
+				filters['name'] = ['!=', me.frm.doc.target_asset];
+			}
+
+			return {
+				filters: filters
+			};
+		});
+
+		me.frm.set_query("item_code", "stock_items", function() {
+			return erpnext.queries.item({"is_stock_item": 1});
+		});
+
+		me.frm.set_query("item_code", "service_items", function() {
+			return erpnext.queries.item({"is_stock_item": 0, "is_fixed_asset": 0});
+		});
+
+		me.frm.set_query('batch_no', 'stock_items', function(doc, cdt, cdn) {
+			var item = locals[cdt][cdn];
+			if (!item.item_code) {
+				frappe.throw(__("Please enter Item Code to get Batch Number"));
+			} else {
+				var filters = {
+					'item_code': item.item_code,
+					'posting_date': me.frm.doc.posting_date || frappe.datetime.nowdate(),
+					'warehouse': item.warehouse
+				};
+
+				return {
+					query: "erpnext.controllers.queries.get_batch_no",
+					filters: filters
+				};
+			}
+		});
+
+		me.frm.set_query('expense_account', 'service_items', function() {
+			return {
+				filters: {
+					"account_type": ['in', ["Tax", "Expense Account", "Income Account", "Expenses Included In Valuation", "Expenses Included In Asset Valuation"]],
+					"is_group": 0,
+					"company": me.frm.doc.company
+				}
+			};
+		});
+	}
+
+	target_item_code() {
+		return this.get_target_item_details();
+	}
+
+	target_asset() {
+		return this.get_target_asset_details();
+	}
+
+	item_code(doc, cdt, cdn) {
+		var row = frappe.get_doc(cdt, cdn);
+		if (cdt === "Asset Capitalization Stock Item") {
+			this.get_consumed_stock_item_details(row);
+		} else if (cdt == "Asset Capitalization Service Item") {
+			this.get_service_item_details(row);
+		}
+	}
+
+	warehouse(doc, cdt, cdn) {
+		var row = frappe.get_doc(cdt, cdn);
+		if (cdt === "Asset Capitalization Stock Item") {
+			this.get_warehouse_details(row);
+		}
+	}
+
+	asset(doc, cdt, cdn) {
+		var row = frappe.get_doc(cdt, cdn);
+		if (cdt === "Asset Capitalization Asset Item") {
+			this.get_consumed_asset_details(row);
+		}
+	}
+
+	posting_date() {
+		if (this.frm.doc.posting_date) {
+			frappe.run_serially([
+				() => this.get_all_item_warehouse_details(),
+				() => this.get_all_asset_values()
+			]);
+		}
+	}
+
+	posting_time() {
+		if (this.frm.doc.posting_time) {
+			this.get_all_item_warehouse_details();
+		}
+	}
+
+	finance_book(doc, cdt, cdn) {
+		if (cdt === "Asset Capitalization Asset Item") {
+			var row = frappe.get_doc(cdt, cdn);
+			this.get_consumed_asset_details(row);
+		} else {
+			this.get_all_asset_values();
+		}
+	}
+
+	stock_qty() {
+		this.calculate_totals();
+	}
+
+	qty() {
+		this.calculate_totals();
+	}
+
+	target_qty() {
+		this.calculate_totals();
+	}
+
+	rate() {
+		this.calculate_totals();
+	}
+
+	company() {
+		var me = this;
+
+		if (me.frm.doc.company) {
+			frappe.model.set_value(me.frm.doc.doctype, me.frm.doc.name, "cost_center", null);
+			$.each(me.frm.doc.stock_items || [], function (i, d) {
+				frappe.model.set_value(d.doctype, d.name, "cost_center", null);
+			});
+			$.each(me.frm.doc.asset_items || [], function (i, d) {
+				frappe.model.set_value(d.doctype, d.name, "cost_center", null);
+			});
+			$.each(me.frm.doc.service_items || [], function (i, d) {
+				frappe.model.set_value(d.doctype, d.name, "cost_center", null);
+			});
+		}
+
+		erpnext.accounts.dimensions.update_dimension(me.frm, me.frm.doctype);
+	}
+
+	stock_items_add(doc, cdt, cdn) {
+		erpnext.accounts.dimensions.copy_dimension_from_first_row(this.frm, cdt, cdn, 'stock_items');
+	}
+
+	asset_items_add(doc, cdt, cdn) {
+		erpnext.accounts.dimensions.copy_dimension_from_first_row(this.frm, cdt, cdn, 'asset_items');
+	}
+
+	serivce_items_add(doc, cdt, cdn) {
+		erpnext.accounts.dimensions.copy_dimension_from_first_row(this.frm, cdt, cdn, 'service_items');
+	}
+
+	get_target_item_details() {
+		var me = this;
+
+		if (me.frm.doc.target_item_code) {
+			return me.frm.call({
+				method: "erpnext.assets.doctype.asset_capitalization.asset_capitalization.get_target_item_details",
+				child: me.frm.doc,
+				args: {
+					item_code: me.frm.doc.target_item_code,
+					company: me.frm.doc.company,
+				},
+				callback: function (r) {
+					if (!r.exc) {
+						me.frm.refresh_fields();
+					}
+				}
+			});
+		}
+	}
+
+	get_target_asset_details() {
+		var me = this;
+
+		if (me.frm.doc.target_asset) {
+			return me.frm.call({
+				method: "erpnext.assets.doctype.asset_capitalization.asset_capitalization.get_target_asset_details",
+				child: me.frm.doc,
+				args: {
+					asset: me.frm.doc.target_asset,
+					company: me.frm.doc.company,
+				},
+				callback: function (r) {
+					if (!r.exc) {
+						me.frm.refresh_fields();
+					}
+				}
+			});
+		}
+	}
+
+	get_consumed_stock_item_details(row) {
+		var me = this;
+
+		if (row && row.item_code) {
+			return me.frm.call({
+				method: "erpnext.assets.doctype.asset_capitalization.asset_capitalization.get_consumed_stock_item_details",
+				child: row,
+				args: {
+					args: {
+						item_code: row.item_code,
+						warehouse: row.warehouse,
+						stock_qty: flt(row.stock_qty),
+						doctype: me.frm.doc.doctype,
+						name: me.frm.doc.name,
+						company: me.frm.doc.company,
+						posting_date: me.frm.doc.posting_date,
+						posting_time: me.frm.doc.posting_time,
+					}
+				},
+				callback: function (r) {
+					if (!r.exc) {
+						me.calculate_totals();
+					}
+				}
+			});
+		}
+	}
+
+	get_consumed_asset_details(row) {
+		var me = this;
+
+		if (row && row.asset) {
+			return me.frm.call({
+				method: "erpnext.assets.doctype.asset_capitalization.asset_capitalization.get_consumed_asset_details",
+				child: row,
+				args: {
+					args: {
+						asset: row.asset,
+						doctype: me.frm.doc.doctype,
+						name: me.frm.doc.name,
+						company: me.frm.doc.company,
+						finance_book: row.finance_book || me.frm.doc.finance_book,
+						posting_date: me.frm.doc.posting_date,
+						posting_time: me.frm.doc.posting_time,
+					}
+				},
+				callback: function (r) {
+					if (!r.exc) {
+						me.calculate_totals();
+					}
+				}
+			});
+		}
+	}
+
+	get_service_item_details(row) {
+		var me = this;
+
+		if (row && row.item_code) {
+			return me.frm.call({
+				method: "erpnext.assets.doctype.asset_capitalization.asset_capitalization.get_service_item_details",
+				child: row,
+				args: {
+					args: {
+						item_code: row.item_code,
+						qty: flt(row.qty),
+						expense_account: row.expense_account,
+						company: me.frm.doc.company,
+					}
+				},
+				callback: function (r) {
+					if (!r.exc) {
+						me.calculate_totals();
+					}
+				}
+			});
+		}
+	}
+
+	get_warehouse_details(item) {
+		var me = this;
+		if (item.item_code && item.warehouse) {
+			me.frm.call({
+				method: "erpnext.assets.doctype.asset_capitalization.asset_capitalization.get_warehouse_details",
+				child: item,
+				args: {
+					args: {
+						'item_code': item.item_code,
+						'warehouse': cstr(item.warehouse),
+						'qty': flt(item.stock_qty),
+						'serial_no': item.serial_no,
+						'posting_date': me.frm.doc.posting_date,
+						'posting_time': me.frm.doc.posting_time,
+						'company': me.frm.doc.company,
+						'voucher_type': me.frm.doc.doctype,
+						'voucher_no': me.frm.doc.name,
+						'allow_zero_valuation': 1
+					}
+				},
+				callback: function(r) {
+					if (!r.exc) {
+						me.calculate_totals();
+					}
+				}
+			});
+		}
+	}
+
+	get_all_item_warehouse_details() {
+		var me = this;
+		return me.frm.call({
+			method: "set_warehouse_details",
+			doc: me.frm.doc,
+			callback: function(r) {
+				if (!r.exc) {
+					me.calculate_totals();
+				}
+			}
+		});
+	}
+
+	get_all_asset_values() {
+		var me = this;
+		return me.frm.call({
+			method: "set_asset_values",
+			doc: me.frm.doc,
+			callback: function(r) {
+				if (!r.exc) {
+					me.calculate_totals();
+				}
+			}
+		});
+	}
+
+	calculate_totals() {
+		var me = this;
+
+		me.frm.doc.stock_items_total = 0;
+		me.frm.doc.asset_items_total = 0;
+		me.frm.doc.service_items_total = 0;
+
+		$.each(me.frm.doc.stock_items || [], function (i, d) {
+			d.amount = flt(flt(d.stock_qty) * flt(d.valuation_rate), precision('amount', d));
+			me.frm.doc.stock_items_total += d.amount;
+		});
+
+		$.each(me.frm.doc.asset_items || [], function (i, d) {
+			d.asset_value = flt(flt(d.asset_value), precision('asset_value', d));
+			me.frm.doc.asset_items_total += d.asset_value;
+		});
+
+		$.each(me.frm.doc.service_items || [], function (i, d) {
+			d.amount = flt(flt(d.qty) * flt(d.rate), precision('amount', d));
+			me.frm.doc.service_items_total += d.amount;
+		});
+
+		me.frm.doc.stock_items_total = flt(me.frm.doc.stock_items_total, precision('stock_items_total'));
+		me.frm.doc.asset_items_total = flt(me.frm.doc.asset_items_total, precision('asset_items_total'));
+		me.frm.doc.service_items_total = flt(me.frm.doc.service_items_total, precision('service_items_total'));
+
+		me.frm.doc.total_value = me.frm.doc.stock_items_total + me.frm.doc.asset_items_total + me.frm.doc.service_items_total;
+		me.frm.doc.total_value = flt(me.frm.doc.total_value, precision('total_value'));
+
+		me.frm.doc.target_qty = flt(me.frm.doc.target_qty, precision('target_qty'));
+		me.frm.doc.target_incoming_rate = me.frm.doc.target_qty ? me.frm.doc.total_value / flt(me.frm.doc.target_qty)
+			: me.frm.doc.total_value;
+
+		me.frm.refresh_fields();
+	}
+};
+
+cur_frm.cscript = new erpnext.assets.AssetCapitalization({frm: cur_frm});
diff --git a/erpnext/assets/doctype/asset_capitalization/asset_capitalization.json b/erpnext/assets/doctype/asset_capitalization/asset_capitalization.json
new file mode 100644
index 0000000..d1be575
--- /dev/null
+++ b/erpnext/assets/doctype/asset_capitalization/asset_capitalization.json
@@ -0,0 +1,381 @@
+{
+ "actions": [],
+ "autoname": "naming_series:",
+ "creation": "2021-09-04 13:38:04.217187",
+ "doctype": "DocType",
+ "document_type": "Document",
+ "editable_grid": 1,
+ "engine": "InnoDB",
+ "field_order": [
+  "title",
+  "naming_series",
+  "entry_type",
+  "target_item_code",
+  "target_item_name",
+  "target_is_fixed_asset",
+  "target_has_batch_no",
+  "target_has_serial_no",
+  "column_break_9",
+  "target_asset",
+  "target_asset_name",
+  "target_warehouse",
+  "target_qty",
+  "target_stock_uom",
+  "target_batch_no",
+  "target_serial_no",
+  "column_break_5",
+  "company",
+  "finance_book",
+  "posting_date",
+  "posting_time",
+  "set_posting_time",
+  "amended_from",
+  "section_break_16",
+  "stock_items",
+  "stock_items_total",
+  "section_break_26",
+  "asset_items",
+  "asset_items_total",
+  "service_expenses_section",
+  "service_items",
+  "service_items_total",
+  "totals_section",
+  "total_value",
+  "column_break_36",
+  "target_incoming_rate",
+  "accounting_dimensions_section",
+  "cost_center",
+  "dimension_col_break",
+  "target_fixed_asset_account"
+ ],
+ "fields": [
+  {
+   "fieldname": "title",
+   "fieldtype": "Data",
+   "hidden": 1,
+   "label": "Title"
+  },
+  {
+   "fieldname": "target_item_code",
+   "fieldtype": "Link",
+   "in_standard_filter": 1,
+   "label": "Target Item Code",
+   "options": "Item",
+   "reqd": 1
+  },
+  {
+   "depends_on": "eval:doc.target_item_code && doc.target_item_name != doc.target_item_code",
+   "fetch_from": "target_item_code.item_name",
+   "fieldname": "target_item_name",
+   "fieldtype": "Data",
+   "label": "Target Item Name",
+   "read_only": 1
+  },
+  {
+   "default": "0",
+   "fetch_from": "target_item_code.is_fixed_asset",
+   "fieldname": "target_is_fixed_asset",
+   "fieldtype": "Check",
+   "hidden": 1,
+   "label": "Target Is Fixed Asset",
+   "read_only": 1
+  },
+  {
+   "fieldname": "column_break_5",
+   "fieldtype": "Column Break"
+  },
+  {
+   "depends_on": "eval:doc.entry_type=='Capitalization'",
+   "fieldname": "target_asset",
+   "fieldtype": "Link",
+   "in_standard_filter": 1,
+   "label": "Target Asset",
+   "mandatory_depends_on": "eval:doc.entry_type=='Capitalization'",
+   "no_copy": 1,
+   "options": "Asset"
+  },
+  {
+   "depends_on": "eval:doc.entry_type=='Capitalization'",
+   "fetch_from": "target_asset.asset_name",
+   "fieldname": "target_asset_name",
+   "fieldtype": "Data",
+   "label": "Asset Name",
+   "no_copy": 1,
+   "read_only": 1
+  },
+  {
+   "fieldname": "column_break_9",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fetch_from": "asset.company",
+   "fieldname": "company",
+   "fieldtype": "Link",
+   "label": "Company",
+   "options": "Company",
+   "reqd": 1
+  },
+  {
+   "default": "Today",
+   "fieldname": "posting_date",
+   "fieldtype": "Date",
+   "in_list_view": 1,
+   "in_standard_filter": 1,
+   "label": "Posting Date",
+   "no_copy": 1,
+   "reqd": 1,
+   "search_index": 1
+  },
+  {
+   "default": "Now",
+   "fieldname": "posting_time",
+   "fieldtype": "Time",
+   "label": "Posting Time",
+   "no_copy": 1,
+   "reqd": 1
+  },
+  {
+   "default": "0",
+   "depends_on": "eval:doc.docstatus==0",
+   "fieldname": "set_posting_time",
+   "fieldtype": "Check",
+   "label": "Edit Posting Date and Time"
+  },
+  {
+   "fieldname": "naming_series",
+   "fieldtype": "Select",
+   "label": "Series",
+   "options": "ACC-ASC-.YYYY.-",
+   "reqd": 1
+  },
+  {
+   "fieldname": "amended_from",
+   "fieldtype": "Link",
+   "label": "Amended From",
+   "no_copy": 1,
+   "options": "Asset Capitalization",
+   "print_hide": 1,
+   "read_only": 1
+  },
+  {
+   "depends_on": "eval:doc.docstatus == 0 || (doc.stock_items && doc.stock_items.length)",
+   "fieldname": "section_break_16",
+   "fieldtype": "Section Break",
+   "label": "Consumed Stock Items"
+  },
+  {
+   "fieldname": "stock_items",
+   "fieldtype": "Table",
+   "label": "Stock Items",
+   "options": "Asset Capitalization Stock Item"
+  },
+  {
+   "depends_on": "eval:doc.entry_type=='Decapitalization'",
+   "fieldname": "target_warehouse",
+   "fieldtype": "Link",
+   "label": "Target Warehouse",
+   "mandatory_depends_on": "eval:doc.entry_type=='Decapitalization'",
+   "options": "Warehouse"
+  },
+  {
+   "depends_on": "target_has_batch_no",
+   "fieldname": "target_batch_no",
+   "fieldtype": "Link",
+   "label": "Target Batch No",
+   "options": "Batch"
+  },
+  {
+   "default": "1",
+   "fieldname": "target_qty",
+   "fieldtype": "Float",
+   "label": "Target Qty",
+   "read_only_depends_on": "target_is_fixed_asset"
+  },
+  {
+   "fetch_from": "target_item_code.stock_uom",
+   "fieldname": "target_stock_uom",
+   "fieldtype": "Link",
+   "label": "Stock UOM",
+   "options": "UOM",
+   "read_only": 1
+  },
+  {
+   "default": "0",
+   "fetch_from": "target_item_code.has_batch_no",
+   "fieldname": "target_has_batch_no",
+   "fieldtype": "Check",
+   "hidden": 1,
+   "label": "Target Has Batch No",
+   "read_only": 1
+  },
+  {
+   "default": "0",
+   "fetch_from": "target_item_code.has_serial_no",
+   "fieldname": "target_has_serial_no",
+   "fieldtype": "Check",
+   "hidden": 1,
+   "label": "Target Has Serial No",
+   "read_only": 1
+  },
+  {
+   "depends_on": "target_has_serial_no",
+   "fieldname": "target_serial_no",
+   "fieldtype": "Small Text",
+   "label": "Target Serial No"
+  },
+  {
+   "depends_on": "eval:doc.docstatus == 0 || (doc.asset_items && doc.asset_items.length)",
+   "fieldname": "section_break_26",
+   "fieldtype": "Section Break",
+   "label": "Consumed Asset Items"
+  },
+  {
+   "fieldname": "asset_items",
+   "fieldtype": "Table",
+   "label": "Assets",
+   "options": "Asset Capitalization Asset Item"
+  },
+  {
+   "default": "Capitalization",
+   "fieldname": "entry_type",
+   "fieldtype": "Select",
+   "in_list_view": 1,
+   "in_standard_filter": 1,
+   "label": "Entry Type",
+   "options": "Capitalization\nDecapitalization",
+   "reqd": 1
+  },
+  {
+   "fieldname": "stock_items_total",
+   "fieldtype": "Currency",
+   "label": "Consumed Stock Total Value",
+   "options": "Company:company:default_currency",
+   "read_only": 1
+  },
+  {
+   "fieldname": "asset_items_total",
+   "fieldtype": "Currency",
+   "label": "Consumed Asset Total Value",
+   "options": "Company:company:default_currency",
+   "read_only": 1
+  },
+  {
+   "fieldname": "finance_book",
+   "fieldtype": "Link",
+   "label": "Finance Book",
+   "options": "Finance Book"
+  },
+  {
+   "depends_on": "eval:doc.docstatus == 0 || (doc.service_items && doc.service_items.length)",
+   "fieldname": "service_expenses_section",
+   "fieldtype": "Section Break",
+   "label": "Service Expenses"
+  },
+  {
+   "fieldname": "service_items",
+   "fieldtype": "Table",
+   "label": "Services",
+   "options": "Asset Capitalization Service Item"
+  },
+  {
+   "fieldname": "service_items_total",
+   "fieldtype": "Currency",
+   "label": "Service Expense Total Amount",
+   "options": "Company:company:default_currency",
+   "read_only": 1
+  },
+  {
+   "fieldname": "totals_section",
+   "fieldtype": "Section Break",
+   "label": "Totals"
+  },
+  {
+   "fieldname": "total_value",
+   "fieldtype": "Currency",
+   "label": "Total Value",
+   "options": "Company:company:default_currency",
+   "read_only": 1
+  },
+  {
+   "fieldname": "column_break_36",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "target_incoming_rate",
+   "fieldtype": "Currency",
+   "label": "Target Incoming Rate",
+   "options": "Company:company:default_currency",
+   "read_only": 1
+  },
+  {
+   "collapsible": 1,
+   "fieldname": "accounting_dimensions_section",
+   "fieldtype": "Section Break",
+   "label": "Accounting Dimensions"
+  },
+  {
+   "fieldname": "cost_center",
+   "fieldtype": "Link",
+   "label": "Cost Center",
+   "options": "Cost Center"
+  },
+  {
+   "fieldname": "dimension_col_break",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "target_fixed_asset_account",
+   "fieldtype": "Link",
+   "label": "Target Fixed Asset Account",
+   "options": "Account",
+   "read_only": 1
+  }
+ ],
+ "index_web_pages_for_search": 1,
+ "is_submittable": 1,
+ "links": [],
+ "modified": "2022-09-12 15:09:40.771332",
+ "modified_by": "Administrator",
+ "module": "Assets",
+ "name": "Asset Capitalization",
+ "naming_rule": "By \"Naming Series\" field",
+ "owner": "Administrator",
+ "permissions": [
+  {
+   "amend": 1,
+   "cancel": 1,
+   "create": 1,
+   "delete": 1,
+   "email": 1,
+   "export": 1,
+   "print": 1,
+   "read": 1,
+   "report": 1,
+   "role": "Manufacturing Manager",
+   "share": 1,
+   "submit": 1,
+   "write": 1
+  },
+  {
+   "amend": 1,
+   "cancel": 1,
+   "create": 1,
+   "delete": 1,
+   "email": 1,
+   "export": 1,
+   "print": 1,
+   "read": 1,
+   "report": 1,
+   "role": "Quality Manager",
+   "share": 1,
+   "submit": 1,
+   "write": 1
+  }
+ ],
+ "sort_field": "modified",
+ "sort_order": "DESC",
+ "states": [],
+ "title_field": "title",
+ "track_changes": 1,
+ "track_seen": 1
+}
\ No newline at end of file
diff --git a/erpnext/assets/doctype/asset_capitalization/asset_capitalization.py b/erpnext/assets/doctype/asset_capitalization/asset_capitalization.py
new file mode 100644
index 0000000..2e6f0ad
--- /dev/null
+++ b/erpnext/assets/doctype/asset_capitalization/asset_capitalization.py
@@ -0,0 +1,749 @@
+# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
+# For license information, please see license.txt
+
+import json
+
+import frappe
+
+# import erpnext
+from frappe import _
+from frappe.utils import cint, flt
+from six import string_types
+
+import erpnext
+from erpnext.assets.doctype.asset.depreciation import (
+	get_gl_entries_on_asset_disposal,
+	get_value_after_depreciation_on_disposal_date,
+)
+from erpnext.assets.doctype.asset_category.asset_category import get_asset_category_account
+from erpnext.assets.doctype.asset_value_adjustment.asset_value_adjustment import (
+	get_current_asset_value,
+)
+from erpnext.controllers.stock_controller import StockController
+from erpnext.setup.doctype.brand.brand import get_brand_defaults
+from erpnext.setup.doctype.item_group.item_group import get_item_group_defaults
+from erpnext.stock import get_warehouse_account_map
+from erpnext.stock.doctype.item.item import get_item_defaults
+from erpnext.stock.get_item_details import (
+	get_default_cost_center,
+	get_default_expense_account,
+	get_item_warehouse,
+)
+from erpnext.stock.stock_ledger import get_previous_sle
+from erpnext.stock.utils import get_incoming_rate
+
+force_fields = [
+	"target_item_name",
+	"target_asset_name",
+	"item_name",
+	"asset_name",
+	"target_is_fixed_asset",
+	"target_has_serial_no",
+	"target_has_batch_no",
+	"target_stock_uom",
+	"stock_uom",
+	"target_fixed_asset_account",
+	"fixed_asset_account",
+	"valuation_rate",
+]
+
+
+class AssetCapitalization(StockController):
+	def validate(self):
+		self.validate_posting_time()
+		self.set_missing_values(for_validate=True)
+		self.validate_target_item()
+		self.validate_target_asset()
+		self.validate_consumed_stock_item()
+		self.validate_consumed_asset_item()
+		self.validate_service_item()
+		self.set_warehouse_details()
+		self.set_asset_values()
+		self.calculate_totals()
+		self.set_title()
+
+	def before_submit(self):
+		self.validate_source_mandatory()
+
+	def on_submit(self):
+		self.update_stock_ledger()
+		self.make_gl_entries()
+		self.update_target_asset()
+
+	def on_cancel(self):
+		self.ignore_linked_doctypes = ("GL Entry", "Stock Ledger Entry", "Repost Item Valuation")
+		self.update_stock_ledger()
+		self.make_gl_entries()
+		self.update_target_asset()
+
+	def set_title(self):
+		self.title = self.target_asset_name or self.target_item_name or self.target_item_code
+
+	def set_missing_values(self, for_validate=False):
+		target_item_details = get_target_item_details(self.target_item_code, self.company)
+		for k, v in target_item_details.items():
+			if self.meta.has_field(k) and (not self.get(k) or k in force_fields):
+				self.set(k, v)
+
+		# Remove asset if item not a fixed asset
+		if not self.target_is_fixed_asset:
+			self.target_asset = None
+
+		target_asset_details = get_target_asset_details(self.target_asset, self.company)
+		for k, v in target_asset_details.items():
+			if self.meta.has_field(k) and (not self.get(k) or k in force_fields):
+				self.set(k, v)
+
+		for d in self.stock_items:
+			args = self.as_dict()
+			args.update(d.as_dict())
+			args.doctype = self.doctype
+			args.name = self.name
+			consumed_stock_item_details = get_consumed_stock_item_details(args)
+			for k, v in consumed_stock_item_details.items():
+				if d.meta.has_field(k) and (not d.get(k) or k in force_fields):
+					d.set(k, v)
+
+		for d in self.asset_items:
+			args = self.as_dict()
+			args.update(d.as_dict())
+			args.doctype = self.doctype
+			args.name = self.name
+			args.finance_book = d.get("finance_book") or self.get("finance_book")
+			consumed_asset_details = get_consumed_asset_details(args)
+			for k, v in consumed_asset_details.items():
+				if d.meta.has_field(k) and (not d.get(k) or k in force_fields):
+					d.set(k, v)
+
+		for d in self.service_items:
+			args = self.as_dict()
+			args.update(d.as_dict())
+			args.doctype = self.doctype
+			args.name = self.name
+			service_item_details = get_service_item_details(args)
+			for k, v in service_item_details.items():
+				if d.meta.has_field(k) and (not d.get(k) or k in force_fields):
+					d.set(k, v)
+
+	def validate_target_item(self):
+		target_item = frappe.get_cached_doc("Item", self.target_item_code)
+
+		if not target_item.is_fixed_asset and not target_item.is_stock_item:
+			frappe.throw(
+				_("Target Item {0} is neither a Fixed Asset nor a Stock Item").format(target_item.name)
+			)
+
+		if self.entry_type == "Capitalization" and not target_item.is_fixed_asset:
+			frappe.throw(_("Target Item {0} must be a Fixed Asset item").format(target_item.name))
+		elif self.entry_type == "Decapitalization" and not target_item.is_stock_item:
+			frappe.throw(_("Target Item {0} must be a Stock Item").format(target_item.name))
+
+		if target_item.is_fixed_asset:
+			self.target_qty = 1
+		if flt(self.target_qty) <= 0:
+			frappe.throw(_("Target Qty must be a positive number"))
+
+		if not target_item.is_stock_item:
+			self.target_warehouse = None
+		if not target_item.is_fixed_asset:
+			self.target_asset = None
+			self.target_fixed_asset_account = None
+		if not target_item.has_batch_no:
+			self.target_batch_no = None
+		if not target_item.has_serial_no:
+			self.target_serial_no = ""
+
+		if target_item.is_stock_item and not self.target_warehouse:
+			frappe.throw(_("Target Warehouse is mandatory for Decapitalization"))
+
+		self.validate_item(target_item)
+
+	def validate_target_asset(self):
+		if self.target_asset:
+			target_asset = self.get_asset_for_validation(self.target_asset)
+
+			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)
+				)
+
+			self.validate_asset(target_asset)
+
+	def validate_consumed_stock_item(self):
+		for d in self.stock_items:
+			if d.item_code:
+				item = frappe.get_cached_doc("Item", d.item_code)
+
+				if not item.is_stock_item:
+					frappe.throw(_("Row #{0}: Item {1} is not a stock item").format(d.idx, d.item_code))
+
+				if flt(d.stock_qty) <= 0:
+					frappe.throw(_("Row #{0}: Qty must be a positive number").format(d.idx))
+
+				self.validate_item(item)
+
+	def validate_consumed_asset_item(self):
+		for d in self.asset_items:
+			if d.asset:
+				if d.asset == self.target_asset:
+					frappe.throw(
+						_("Row #{0}: Consumed Asset {1} cannot be the same as the Target Asset").format(
+							d.idx, d.asset
+						)
+					)
+
+				asset = self.get_asset_for_validation(d.asset)
+				self.validate_asset(asset)
+
+	def validate_service_item(self):
+		for d in self.service_items:
+			if d.item_code:
+				item = frappe.get_cached_doc("Item", d.item_code)
+
+				if item.is_stock_item or item.is_fixed_asset:
+					frappe.throw(_("Row #{0}: Item {1} is not a service item").format(d.idx, d.item_code))
+
+				if flt(d.qty) <= 0:
+					frappe.throw(_("Row #{0}: Qty must be a positive number").format(d.idx))
+
+				if flt(d.rate) <= 0:
+					frappe.throw(_("Row #{0}: Amount must be a positive number").format(d.idx))
+
+				self.validate_item(item)
+
+			if not d.cost_center:
+				d.cost_center = frappe.get_cached_value("Company", self.company, "cost_center")
+
+	def validate_source_mandatory(self):
+		if not self.target_is_fixed_asset and not self.get("asset_items"):
+			frappe.throw(_("Consumed Asset Items is mandatory for Decapitalization"))
+
+		if not self.get("stock_items") and not self.get("asset_items"):
+			frappe.throw(_("Consumed Stock Items or Consumed Asset Items is mandatory for Capitalization"))
+
+	def validate_item(self, item):
+		from erpnext.stock.doctype.item.item import validate_end_of_life
+
+		validate_end_of_life(item.name, item.end_of_life, item.disabled)
+
+	def get_asset_for_validation(self, asset):
+		return frappe.db.get_value(
+			"Asset", asset, ["name", "item_code", "company", "status", "docstatus"], as_dict=1
+		)
+
+	def validate_asset(self, asset):
+		if asset.status in ("Draft", "Scrapped", "Sold", "Capitalized", "Decapitalized"):
+			frappe.throw(_("Asset {0} is {1}").format(asset.name, asset.status))
+
+		if asset.docstatus == 0:
+			frappe.throw(_("Asset {0} is Draft").format(asset.name))
+		if asset.docstatus == 2:
+			frappe.throw(_("Asset {0} is cancelled").format(asset.name))
+
+		if asset.company != self.company:
+			frappe.throw(_("Asset {0} does not belong to company {1}").format(asset.name, self.company))
+
+	@frappe.whitelist()
+	def set_warehouse_details(self):
+		for d in self.get("stock_items"):
+			if d.item_code and d.warehouse:
+				args = self.get_args_for_incoming_rate(d)
+				warehouse_details = get_warehouse_details(args)
+				d.update(warehouse_details)
+
+	@frappe.whitelist()
+	def set_asset_values(self):
+		for d in self.get("asset_items"):
+			if d.asset:
+				finance_book = d.get("finance_book") or self.get("finance_book")
+				d.current_asset_value = flt(get_current_asset_value(d.asset, finance_book=finance_book))
+				d.asset_value = get_value_after_depreciation_on_disposal_date(
+					d.asset, self.posting_date, finance_book=finance_book
+				)
+
+	def get_args_for_incoming_rate(self, item):
+		return frappe._dict(
+			{
+				"item_code": item.item_code,
+				"warehouse": item.warehouse,
+				"posting_date": self.posting_date,
+				"posting_time": self.posting_time,
+				"qty": -1 * flt(item.stock_qty),
+				"serial_no": item.serial_no,
+				"batch_no": item.batch_no,
+				"voucher_type": self.doctype,
+				"voucher_no": self.name,
+				"company": self.company,
+				"allow_zero_valuation": cint(item.get("allow_zero_valuation_rate")),
+			}
+		)
+
+	def calculate_totals(self):
+		self.stock_items_total = 0
+		self.asset_items_total = 0
+		self.service_items_total = 0
+
+		for d in self.stock_items:
+			d.amount = flt(flt(d.stock_qty) * flt(d.valuation_rate), d.precision("amount"))
+			self.stock_items_total += d.amount
+
+		for d in self.asset_items:
+			d.asset_value = flt(flt(d.asset_value), d.precision("asset_value"))
+			self.asset_items_total += d.asset_value
+
+		for d in self.service_items:
+			d.amount = flt(flt(d.qty) * flt(d.rate), d.precision("amount"))
+			self.service_items_total += d.amount
+
+		self.stock_items_total = flt(self.stock_items_total, self.precision("stock_items_total"))
+		self.asset_items_total = flt(self.asset_items_total, self.precision("asset_items_total"))
+		self.service_items_total = flt(self.service_items_total, self.precision("service_items_total"))
+
+		self.total_value = self.stock_items_total + self.asset_items_total + self.service_items_total
+		self.total_value = flt(self.total_value, self.precision("total_value"))
+
+		self.target_qty = flt(self.target_qty, self.precision("target_qty"))
+		self.target_incoming_rate = self.total_value / self.target_qty
+
+	def update_stock_ledger(self):
+		sl_entries = []
+
+		for d in self.stock_items:
+			sle = self.get_sl_entries(
+				d,
+				{
+					"actual_qty": -flt(d.stock_qty),
+				},
+			)
+			sl_entries.append(sle)
+
+		if self.entry_type == "Decapitalization" and not self.target_is_fixed_asset:
+			sle = self.get_sl_entries(
+				self,
+				{
+					"item_code": self.target_item_code,
+					"warehouse": self.target_warehouse,
+					"batch_no": self.target_batch_no,
+					"serial_no": self.target_serial_no,
+					"actual_qty": flt(self.target_qty),
+					"incoming_rate": flt(self.target_incoming_rate),
+				},
+			)
+			sl_entries.append(sle)
+
+		# reverse sl entries if cancel
+		if self.docstatus == 2:
+			sl_entries.reverse()
+
+		if sl_entries:
+			self.make_sl_entries(sl_entries)
+
+	def make_gl_entries(self, gl_entries=None, from_repost=False):
+		from erpnext.accounts.general_ledger import make_gl_entries, make_reverse_gl_entries
+
+		if self.docstatus == 1:
+			if not gl_entries:
+				gl_entries = self.get_gl_entries()
+
+			if gl_entries:
+				make_gl_entries(gl_entries, from_repost=from_repost)
+		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
+	):
+		# Stock GL Entries
+		gl_entries = []
+
+		self.warehouse_account = warehouse_account
+		if not self.warehouse_account:
+			self.warehouse_account = get_warehouse_account_map(self.company)
+
+		precision = self.get_debit_field_precision()
+		self.sle_map = self.get_stock_ledger_details()
+
+		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_target_item(gl_entries, target_against, precision)
+		return gl_entries
+
+	def get_target_account(self):
+		if self.target_is_fixed_asset:
+			return self.target_fixed_asset_account
+		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
+	):
+		# Consumed Stock Items
+		for item_row in self.stock_items:
+			sle_list = self.sle_map.get(item_row.name)
+			if sle_list:
+				for sle in sle_list:
+					stock_value_difference = flt(sle.stock_value_difference, precision)
+
+					if erpnext.is_perpetual_inventory_enabled(self.company):
+						account = self.warehouse_account[sle.warehouse]["account"]
+					else:
+						account = self.get_company_default("default_expense_account")
+
+					target_against.add(account)
+					gl_entries.append(
+						self.get_gl_dict(
+							{
+								"account": account,
+								"against": target_account,
+								"cost_center": item_row.cost_center,
+								"project": item_row.get("project") or self.get("project"),
+								"remarks": self.get("remarks") or "Accounting Entry for Stock",
+								"credit": -1 * stock_value_difference,
+							},
+							self.warehouse_account[sle.warehouse]["account_currency"],
+							item=item_row,
+						)
+					)
+
+	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 = self.get_asset(item)
+
+			if asset.calculate_depreciation:
+				self.depreciate_asset(asset)
+				asset.reload()
+
+			fixed_asset_gl_entries = get_gl_entries_on_asset_disposal(
+				asset, item.asset_value, item.get("finance_book") or self.get("finance_book")
+			)
+
+			asset.db_set("disposal_date", self.posting_date)
+
+			self.set_consumed_asset_status(asset)
+
+			for gle in fixed_asset_gl_entries:
+				gle["against"] = target_account
+				gl_entries.append(self.get_gl_dict(gle, item=item))
+				target_against.add(gle["account"])
+
+	def get_gl_entries_for_consumed_service_items(
+		self, gl_entries, target_account, target_against, precision
+	):
+		# Service Expenses
+		for item_row in self.service_items:
+			expense_amount = flt(item_row.amount, precision)
+			target_against.add(item_row.expense_account)
+
+			gl_entries.append(
+				self.get_gl_dict(
+					{
+						"account": item_row.expense_account,
+						"against": target_account,
+						"cost_center": item_row.cost_center,
+						"project": item_row.get("project") or self.get("project"),
+						"remarks": self.get("remarks") or "Accounting Entry for Stock",
+						"credit": expense_amount,
+					},
+					item=item_row,
+				)
+			)
+
+	def get_gl_entries_for_target_item(self, gl_entries, target_against, precision):
+		if self.target_is_fixed_asset:
+			# Capitalization
+			gl_entries.append(
+				self.get_gl_dict(
+					{
+						"account": self.target_fixed_asset_account,
+						"against": ", ".join(target_against),
+						"remarks": self.get("remarks") or _("Accounting Entry for Asset"),
+						"debit": flt(self.total_value, precision),
+						"cost_center": self.get("cost_center"),
+					},
+					item=self,
+				)
+			)
+		else:
+			# Target Stock Item
+			sle_list = self.sle_map.get(self.name)
+			for sle in sle_list:
+				stock_value_difference = flt(sle.stock_value_difference, precision)
+				account = self.warehouse_account[sle.warehouse]["account"]
+
+				gl_entries.append(
+					self.get_gl_dict(
+						{
+							"account": account,
+							"against": ", ".join(target_against),
+							"cost_center": self.cost_center,
+							"project": self.get("project"),
+							"remarks": self.get("remarks") or "Accounting Entry for Stock",
+							"debit": stock_value_difference,
+						},
+						self.warehouse_account[sle.warehouse]["account_currency"],
+						item=self,
+					)
+				)
+
+	def update_target_asset(self):
+		total_target_asset_value = flt(self.total_value, self.precision("total_value"))
+		if self.docstatus == 1 and self.entry_type == "Capitalization":
+			asset_doc = frappe.get_doc("Asset", self.target_asset)
+			asset_doc.purchase_date = self.posting_date
+			asset_doc.gross_purchase_amount = total_target_asset_value
+			asset_doc.purchase_receipt_amount = total_target_asset_value
+			asset_doc.prepare_depreciation_data()
+			asset_doc.flags.ignore_validate_update_after_submit = True
+			asset_doc.save()
+		elif self.docstatus == 2:
+			for item in self.asset_items:
+				asset = self.get_asset(item)
+				asset.db_set("disposal_date", None)
+				self.set_consumed_asset_status(asset)
+
+				if asset.calculate_depreciation:
+					self.reverse_depreciation_entry_made_after_disposal(asset)
+					self.reset_depreciation_schedule(asset)
+
+	def get_asset(self, item):
+		asset = frappe.get_doc("Asset", item.asset)
+		self.check_finance_books(item, asset)
+		return asset
+
+	def set_consumed_asset_status(self, asset):
+		if self.docstatus == 1:
+			asset.set_status("Capitalized" if self.target_is_fixed_asset else "Decapitalized")
+		else:
+			asset.set_status()
+
+
+@frappe.whitelist()
+def get_target_item_details(item_code=None, company=None):
+	out = frappe._dict()
+
+	# Get Item Details
+	item = frappe._dict()
+	if item_code:
+		item = frappe.get_cached_doc("Item", item_code)
+
+	# Set Item Details
+	out.target_item_name = item.item_name
+	out.target_stock_uom = item.stock_uom
+	out.target_is_fixed_asset = cint(item.is_fixed_asset)
+	out.target_has_batch_no = cint(item.has_batch_no)
+	out.target_has_serial_no = cint(item.has_serial_no)
+
+	if out.target_is_fixed_asset:
+		out.target_qty = 1
+		out.target_warehouse = None
+	else:
+		out.target_asset = None
+
+	if not out.target_has_batch_no:
+		out.target_batch_no = None
+	if not out.target_has_serial_no:
+		out.target_serial_no = ""
+
+	# Cost Center
+	item_defaults = get_item_defaults(item.name, company)
+	item_group_defaults = get_item_group_defaults(item.name, company)
+	brand_defaults = get_brand_defaults(item.name, company)
+	out.cost_center = get_default_cost_center(
+		frappe._dict({"item_code": item.name, "company": company}),
+		item_defaults,
+		item_group_defaults,
+		brand_defaults,
+	)
+
+	return out
+
+
+@frappe.whitelist()
+def get_target_asset_details(asset=None, company=None):
+	out = frappe._dict()
+
+	# Get Asset Details
+	asset_details = frappe._dict()
+	if asset:
+		asset_details = frappe.db.get_value("Asset", asset, ["asset_name", "item_code"], as_dict=1)
+		if not asset_details:
+			frappe.throw(_("Asset {0} does not exist").format(asset))
+
+		# Re-set item code from Asset
+		out.target_item_code = asset_details.item_code
+
+	# Set Asset Details
+	out.asset_name = asset_details.asset_name
+
+	if asset_details.item_code:
+		out.target_fixed_asset_account = get_asset_category_account(
+			"fixed_asset_account", item=asset_details.item_code, company=company
+		)
+	else:
+		out.target_fixed_asset_account = None
+
+	return out
+
+
+@frappe.whitelist()
+def get_consumed_stock_item_details(args):
+	if isinstance(args, string_types):
+		args = json.loads(args)
+
+	args = frappe._dict(args)
+	out = frappe._dict()
+
+	item = frappe._dict()
+	if args.item_code:
+		item = frappe.get_cached_doc("Item", args.item_code)
+
+	out.item_name = item.item_name
+	out.batch_no = None
+	out.serial_no = ""
+
+	out.stock_qty = flt(args.stock_qty) or 1
+	out.stock_uom = item.stock_uom
+
+	out.warehouse = get_item_warehouse(item, args, overwrite_warehouse=True) if item else None
+
+	# Cost Center
+	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
+	)
+
+	if args.item_code and out.warehouse:
+		incoming_rate_args = frappe._dict(
+			{
+				"item_code": args.item_code,
+				"warehouse": out.warehouse,
+				"posting_date": args.posting_date,
+				"posting_time": args.posting_time,
+				"qty": -1 * flt(out.stock_qty),
+				"voucher_type": args.doctype,
+				"voucher_no": args.name,
+				"company": args.company,
+				"serial_no": args.serial_no,
+				"batch_no": args.batch_no,
+			}
+		)
+		out.update(get_warehouse_details(incoming_rate_args))
+	else:
+		out.valuation_rate = 0
+		out.actual_qty = 0
+
+	return out
+
+
+@frappe.whitelist()
+def get_warehouse_details(args):
+	if isinstance(args, string_types):
+		args = json.loads(args)
+
+	args = frappe._dict(args)
+
+	out = {}
+	if args.warehouse and args.item_code:
+		out = {
+			"actual_qty": get_previous_sle(args).get("qty_after_transaction") or 0,
+			"valuation_rate": get_incoming_rate(args, raise_error_if_no_rate=False),
+		}
+	return out
+
+
+@frappe.whitelist()
+def get_consumed_asset_details(args):
+	if isinstance(args, string_types):
+		args = json.loads(args)
+
+	args = frappe._dict(args)
+	out = frappe._dict()
+
+	asset_details = frappe._dict()
+	if args.asset:
+		asset_details = frappe.db.get_value(
+			"Asset", args.asset, ["asset_name", "item_code", "item_name"], as_dict=1
+		)
+		if not asset_details:
+			frappe.throw(_("Asset {0} does not exist").format(args.asset))
+
+	out.item_code = asset_details.item_code
+	out.asset_name = asset_details.asset_name
+	out.item_name = asset_details.item_name
+
+	if args.asset:
+		out.current_asset_value = flt(
+			get_current_asset_value(args.asset, finance_book=args.finance_book)
+		)
+		out.asset_value = get_value_after_depreciation_on_disposal_date(
+			args.asset, args.posting_date, finance_book=args.finance_book
+		)
+	else:
+		out.current_asset_value = 0
+		out.asset_value = 0
+
+	# Account
+	if asset_details.item_code:
+		out.fixed_asset_account = get_asset_category_account(
+			"fixed_asset_account", item=asset_details.item_code, company=args.company
+		)
+	else:
+		out.fixed_asset_account = None
+
+	# Cost Center
+	if asset_details.item_code:
+		item = frappe.get_cached_doc("Item", asset_details.item_code)
+		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
+		)
+
+	return out
+
+
+@frappe.whitelist()
+def get_service_item_details(args):
+	if isinstance(args, string_types):
+		args = json.loads(args)
+
+	args = frappe._dict(args)
+	out = frappe._dict()
+
+	item = frappe._dict()
+	if args.item_code:
+		item = frappe.get_cached_doc("Item", args.item_code)
+
+	out.item_name = item.item_name
+	out.qty = flt(args.qty) or 1
+	out.uom = item.purchase_uom or item.stock_uom
+
+	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.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
+	)
+
+	return out
diff --git a/erpnext/assets/doctype/asset_capitalization/test_asset_capitalization.py b/erpnext/assets/doctype/asset_capitalization/test_asset_capitalization.py
new file mode 100644
index 0000000..86861f0
--- /dev/null
+++ b/erpnext/assets/doctype/asset_capitalization/test_asset_capitalization.py
@@ -0,0 +1,494 @@
+# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors
+# See license.txt
+
+import unittest
+
+import frappe
+from frappe.utils import cint, flt, getdate, now_datetime
+
+from erpnext.assets.doctype.asset.depreciation import post_depreciation_entries
+from erpnext.assets.doctype.asset.test_asset import (
+	create_asset,
+	create_asset_data,
+	set_depreciation_settings_in_company,
+)
+from erpnext.stock.doctype.item.test_item import create_item
+
+
+class TestAssetCapitalization(unittest.TestCase):
+	def setUp(self):
+		set_depreciation_settings_in_company()
+		create_asset_data()
+		create_asset_capitalization_data()
+		frappe.db.sql("delete from `tabTax Rule`")
+
+	def test_capitalization_with_perpetual_inventory(self):
+		company = "_Test Company with perpetual inventory"
+		set_depreciation_settings_in_company(company=company)
+
+		# Variables
+		consumed_asset_value = 100000
+
+		stock_rate = 1000
+		stock_qty = 2
+		stock_amount = 2000
+
+		service_rate = 500
+		service_qty = 2
+		service_amount = 1000
+
+		total_amount = 103000
+
+		# Create assets
+		target_asset = create_asset(
+			asset_name="Asset Capitalization Target Asset",
+			submit=1,
+			warehouse="Stores - TCP1",
+			company=company,
+		)
+		consumed_asset = create_asset(
+			asset_name="Asset Capitalization Consumable Asset",
+			asset_value=consumed_asset_value,
+			submit=1,
+			warehouse="Stores - TCP1",
+			company=company,
+		)
+
+		# Create and submit Asset Captitalization
+		asset_capitalization = create_asset_capitalization(
+			entry_type="Capitalization",
+			target_asset=target_asset.name,
+			stock_qty=stock_qty,
+			stock_rate=stock_rate,
+			consumed_asset=consumed_asset.name,
+			service_qty=service_qty,
+			service_rate=service_rate,
+			service_expense_account="Expenses Included In Asset Valuation - TCP1",
+			company=company,
+			submit=1,
+		)
+
+		# Test Asset Capitalization values
+		self.assertEqual(asset_capitalization.entry_type, "Capitalization")
+		self.assertEqual(asset_capitalization.target_qty, 1)
+
+		self.assertEqual(asset_capitalization.stock_items[0].valuation_rate, stock_rate)
+		self.assertEqual(asset_capitalization.stock_items[0].amount, stock_amount)
+		self.assertEqual(asset_capitalization.stock_items_total, stock_amount)
+
+		self.assertEqual(asset_capitalization.asset_items[0].asset_value, consumed_asset_value)
+		self.assertEqual(asset_capitalization.asset_items_total, consumed_asset_value)
+
+		self.assertEqual(asset_capitalization.service_items[0].amount, service_amount)
+		self.assertEqual(asset_capitalization.service_items_total, service_amount)
+
+		self.assertEqual(asset_capitalization.total_value, total_amount)
+		self.assertEqual(asset_capitalization.target_incoming_rate, total_amount)
+
+		# Test Target Asset values
+		target_asset.reload()
+		self.assertEqual(target_asset.gross_purchase_amount, total_amount)
+		self.assertEqual(target_asset.purchase_receipt_amount, total_amount)
+
+		# Test Consumed Asset values
+		self.assertEqual(consumed_asset.db_get("status"), "Capitalized")
+
+		# Test General Ledger Entries
+		expected_gle = {
+			"_Test Fixed Asset - TCP1": 3000,
+			"Expenses Included In Asset Valuation - TCP1": -1000,
+			"_Test Warehouse - TCP1": -2000,
+		}
+		actual_gle = get_actual_gle_dict(asset_capitalization.name)
+
+		self.assertEqual(actual_gle, expected_gle)
+
+		# Test Stock Ledger Entries
+		expected_sle = {
+			("Capitalization Source Stock Item", "_Test Warehouse - TCP1"): {
+				"actual_qty": -stock_qty,
+				"stock_value_difference": -stock_amount,
+			}
+		}
+		actual_sle = get_actual_sle_dict(asset_capitalization.name)
+		self.assertEqual(actual_sle, expected_sle)
+
+		# Cancel Asset Capitalization and make test entries and status are reversed
+		asset_capitalization.cancel()
+		self.assertEqual(consumed_asset.db_get("status"), "Submitted")
+		self.assertFalse(get_actual_gle_dict(asset_capitalization.name))
+		self.assertFalse(get_actual_sle_dict(asset_capitalization.name))
+
+	def test_capitalization_with_periodical_inventory(self):
+		company = "_Test Company"
+		# Variables
+		consumed_asset_value = 100000
+
+		stock_rate = 1000
+		stock_qty = 2
+		stock_amount = 2000
+
+		service_rate = 500
+		service_qty = 2
+		service_amount = 1000
+
+		total_amount = 103000
+
+		# Create assets
+		target_asset = create_asset(
+			asset_name="Asset Capitalization Target Asset",
+			submit=1,
+			warehouse="Stores - _TC",
+			company=company,
+		)
+		consumed_asset = create_asset(
+			asset_name="Asset Capitalization Consumable Asset",
+			asset_value=consumed_asset_value,
+			submit=1,
+			warehouse="Stores - _TC",
+			company=company,
+		)
+
+		# Create and submit Asset Captitalization
+		asset_capitalization = create_asset_capitalization(
+			entry_type="Capitalization",
+			target_asset=target_asset.name,
+			stock_qty=stock_qty,
+			stock_rate=stock_rate,
+			consumed_asset=consumed_asset.name,
+			service_qty=service_qty,
+			service_rate=service_rate,
+			service_expense_account="Expenses Included In Asset Valuation - _TC",
+			company=company,
+			submit=1,
+		)
+
+		# Test Asset Capitalization values
+		self.assertEqual(asset_capitalization.entry_type, "Capitalization")
+		self.assertEqual(asset_capitalization.target_qty, 1)
+
+		self.assertEqual(asset_capitalization.stock_items[0].valuation_rate, stock_rate)
+		self.assertEqual(asset_capitalization.stock_items[0].amount, stock_amount)
+		self.assertEqual(asset_capitalization.stock_items_total, stock_amount)
+
+		self.assertEqual(asset_capitalization.asset_items[0].asset_value, consumed_asset_value)
+		self.assertEqual(asset_capitalization.asset_items_total, consumed_asset_value)
+
+		self.assertEqual(asset_capitalization.service_items[0].amount, service_amount)
+		self.assertEqual(asset_capitalization.service_items_total, service_amount)
+
+		self.assertEqual(asset_capitalization.total_value, total_amount)
+		self.assertEqual(asset_capitalization.target_incoming_rate, total_amount)
+
+		# Test Target Asset values
+		target_asset.reload()
+		self.assertEqual(target_asset.gross_purchase_amount, total_amount)
+		self.assertEqual(target_asset.purchase_receipt_amount, total_amount)
+
+		# Test Consumed Asset values
+		self.assertEqual(consumed_asset.db_get("status"), "Capitalized")
+
+		# Test General Ledger Entries
+		default_expense_account = frappe.db.get_value("Company", company, "default_expense_account")
+		expected_gle = {
+			"_Test Fixed Asset - _TC": 3000,
+			"Expenses Included In Asset Valuation - _TC": -1000,
+			default_expense_account: -2000,
+		}
+		actual_gle = get_actual_gle_dict(asset_capitalization.name)
+
+		self.assertEqual(actual_gle, expected_gle)
+
+		# Test Stock Ledger Entries
+		expected_sle = {
+			("Capitalization Source Stock Item", "_Test Warehouse - _TC"): {
+				"actual_qty": -stock_qty,
+				"stock_value_difference": -stock_amount,
+			}
+		}
+		actual_sle = get_actual_sle_dict(asset_capitalization.name)
+		self.assertEqual(actual_sle, expected_sle)
+
+		# Cancel Asset Capitalization and make test entries and status are reversed
+		asset_capitalization.cancel()
+		self.assertEqual(consumed_asset.db_get("status"), "Submitted")
+		self.assertFalse(get_actual_gle_dict(asset_capitalization.name))
+		self.assertFalse(get_actual_sle_dict(asset_capitalization.name))
+
+	def test_decapitalization_with_depreciation(self):
+		# Variables
+		purchase_date = "2020-01-01"
+		depreciation_start_date = "2020-12-31"
+		capitalization_date = "2021-06-30"
+
+		total_number_of_depreciations = 3
+		expected_value_after_useful_life = 10_000
+		consumed_asset_purchase_value = 100_000
+		consumed_asset_current_value = 70_000
+		consumed_asset_value_before_disposal = 55_000
+
+		target_qty = 10
+		target_incoming_rate = 5500
+
+		depreciation_before_disposal_amount = 15_000
+		accumulated_depreciation = 45_000
+
+		# to accomodate for depreciation on disposal calculation minor difference
+		consumed_asset_value_before_disposal = 55_123.29
+		target_incoming_rate = 5512.329
+		depreciation_before_disposal_amount = 14_876.71
+		accumulated_depreciation = 44_876.71
+
+		# Create assets
+		consumed_asset = create_depreciation_asset(
+			asset_name="Asset Capitalization Consumable Asset",
+			asset_value=consumed_asset_purchase_value,
+			purchase_date=purchase_date,
+			depreciation_start_date=depreciation_start_date,
+			depreciation_method="Straight Line",
+			total_number_of_depreciations=total_number_of_depreciations,
+			frequency_of_depreciation=12,
+			expected_value_after_useful_life=expected_value_after_useful_life,
+			company="_Test Company with perpetual inventory",
+			submit=1,
+		)
+
+		# Create and submit Asset Captitalization
+		asset_capitalization = create_asset_capitalization(
+			entry_type="Decapitalization",
+			posting_date=capitalization_date,  # half a year
+			target_item_code="Capitalization Target Stock Item",
+			target_qty=target_qty,
+			consumed_asset=consumed_asset.name,
+			company="_Test Company with perpetual inventory",
+			submit=1,
+		)
+
+		# Test Asset Capitalization values
+		self.assertEqual(asset_capitalization.entry_type, "Decapitalization")
+
+		self.assertEqual(
+			asset_capitalization.asset_items[0].current_asset_value, consumed_asset_current_value
+		)
+		self.assertEqual(
+			asset_capitalization.asset_items[0].asset_value, consumed_asset_value_before_disposal
+		)
+		self.assertEqual(asset_capitalization.asset_items_total, consumed_asset_value_before_disposal)
+
+		self.assertEqual(asset_capitalization.total_value, consumed_asset_value_before_disposal)
+		self.assertEqual(asset_capitalization.target_incoming_rate, target_incoming_rate)
+
+		# Test Consumed Asset values
+		consumed_asset.reload()
+		self.assertEqual(consumed_asset.status, "Decapitalized")
+
+		consumed_depreciation_schedule = [
+			d for d in consumed_asset.schedules if getdate(d.schedule_date) == getdate(capitalization_date)
+		]
+		self.assertTrue(
+			consumed_depreciation_schedule and consumed_depreciation_schedule[0].journal_entry
+		)
+		self.assertEqual(
+			consumed_depreciation_schedule[0].depreciation_amount, depreciation_before_disposal_amount
+		)
+
+		# Test General Ledger Entries
+		expected_gle = {
+			"_Test Warehouse - TCP1": consumed_asset_value_before_disposal,
+			"_Test Accumulated Depreciations - TCP1": accumulated_depreciation,
+			"_Test Fixed Asset - TCP1": -consumed_asset_purchase_value,
+		}
+		actual_gle = get_actual_gle_dict(asset_capitalization.name)
+		self.assertEqual(actual_gle, expected_gle)
+
+		# Cancel Asset Capitalization and make test entries and status are reversed
+		asset_capitalization.reload()
+		asset_capitalization.cancel()
+		self.assertEqual(consumed_asset.db_get("status"), "Partially Depreciated")
+		self.assertFalse(get_actual_gle_dict(asset_capitalization.name))
+		self.assertFalse(get_actual_sle_dict(asset_capitalization.name))
+
+
+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
+	)
+
+
+def create_asset_capitalization(**args):
+	from erpnext.stock.doctype.warehouse.test_warehouse import create_warehouse
+
+	args = frappe._dict(args)
+
+	now = now_datetime()
+	target_asset = frappe.get_doc("Asset", args.target_asset) if args.target_asset else frappe._dict()
+	target_item_code = target_asset.item_code or args.target_item_code
+	company = target_asset.company or args.company or "_Test Company"
+	warehouse = args.warehouse or create_warehouse("_Test Warehouse", company=company)
+	target_warehouse = args.target_warehouse or warehouse
+	source_warehouse = args.source_warehouse or warehouse
+
+	asset_capitalization = frappe.new_doc("Asset Capitalization")
+	asset_capitalization.update(
+		{
+			"entry_type": args.entry_type or "Capitalization",
+			"company": company,
+			"posting_date": args.posting_date or now.strftime("%Y-%m-%d"),
+			"posting_time": args.posting_time or now.strftime("%H:%M:%S.%f"),
+			"target_item_code": target_item_code,
+			"target_asset": target_asset.name,
+			"target_warehouse": target_warehouse,
+			"target_qty": flt(args.target_qty) or 1,
+			"target_batch_no": args.target_batch_no,
+			"target_serial_no": args.target_serial_no,
+			"finance_book": args.finance_book,
+		}
+	)
+
+	if args.posting_date or args.posting_time:
+		asset_capitalization.set_posting_time = 1
+
+	if flt(args.stock_rate):
+		asset_capitalization.append(
+			"stock_items",
+			{
+				"item_code": args.stock_item or "Capitalization Source Stock Item",
+				"warehouse": source_warehouse,
+				"stock_qty": flt(args.stock_qty) or 1,
+				"batch_no": args.stock_batch_no,
+				"serial_no": args.stock_serial_no,
+			},
+		)
+
+	if args.consumed_asset:
+		asset_capitalization.append(
+			"asset_items",
+			{
+				"asset": args.consumed_asset,
+			},
+		)
+
+	if flt(args.service_rate):
+		asset_capitalization.append(
+			"service_items",
+			{
+				"item_code": args.service_item or "Capitalization Source Service Item",
+				"expense_account": args.service_expense_account,
+				"qty": flt(args.service_qty) or 1,
+				"rate": flt(args.service_rate),
+			},
+		)
+
+	if args.submit:
+		create_stock_reconciliation(asset_capitalization, stock_rate=args.stock_rate)
+
+	asset_capitalization.insert()
+
+	if args.submit:
+		asset_capitalization.submit()
+
+	return asset_capitalization
+
+
+def create_stock_reconciliation(asset_capitalization, stock_rate=0):
+	from erpnext.stock.doctype.stock_reconciliation.test_stock_reconciliation import (
+		EmptyStockReconciliationItemsError,
+		create_stock_reconciliation,
+	)
+
+	if not asset_capitalization.get("stock_items"):
+		return
+
+	try:
+		create_stock_reconciliation(
+			item_code=asset_capitalization.stock_items[0].item_code,
+			warehouse=asset_capitalization.stock_items[0].warehouse,
+			qty=flt(asset_capitalization.stock_items[0].stock_qty),
+			rate=flt(stock_rate),
+			company=asset_capitalization.company,
+		)
+	except EmptyStockReconciliationItemsError:
+		pass
+
+
+def create_depreciation_asset(**args):
+	args = frappe._dict(args)
+
+	asset = frappe.new_doc("Asset")
+	asset.is_existing_asset = 1
+	asset.calculate_depreciation = 1
+	asset.asset_owner = "Company"
+
+	asset.company = args.company or "_Test Company"
+	asset.item_code = args.item_code or "Macbook Pro"
+	asset.asset_name = args.asset_name or asset.item_code
+	asset.location = args.location or "Test Location"
+
+	asset.purchase_date = args.purchase_date or "2020-01-01"
+	asset.available_for_use_date = args.available_for_use_date or asset.purchase_date
+
+	asset.gross_purchase_amount = args.asset_value or 100000
+	asset.purchase_receipt_amount = asset.gross_purchase_amount
+
+	finance_book = asset.append("finance_books")
+	finance_book.depreciation_start_date = args.depreciation_start_date or "2020-12-31"
+	finance_book.depreciation_method = args.depreciation_method or "Straight Line"
+	finance_book.total_number_of_depreciations = cint(args.total_number_of_depreciations) or 3
+	finance_book.frequency_of_depreciation = cint(args.frequency_of_depreciation) or 12
+	finance_book.expected_value_after_useful_life = flt(args.expected_value_after_useful_life)
+
+	if args.submit:
+		asset.submit()
+
+		frappe.db.set_value("Company", "_Test Company", "series_for_depreciation_entry", "DEPR-")
+		post_depreciation_entries(date=finance_book.depreciation_start_date)
+		asset.load_from_db()
+
+	return asset
+
+
+def get_actual_gle_dict(name):
+	return dict(
+		frappe.db.sql(
+			"""
+		select account, sum(debit-credit) as diff
+		from `tabGL Entry`
+		where voucher_type = 'Asset Capitalization' and voucher_no = %s
+		group by account
+		having diff != 0
+	""",
+			name,
+		)
+	)
+
+
+def get_actual_sle_dict(name):
+	sles = frappe.db.sql(
+		"""
+		select
+			item_code, warehouse,
+			sum(actual_qty) as actual_qty,
+			sum(stock_value_difference) as stock_value_difference
+		from `tabStock Ledger Entry`
+		where voucher_type = 'Asset Capitalization' and voucher_no = %s
+		group by item_code, warehouse
+		having actual_qty != 0
+	""",
+		name,
+		as_dict=1,
+	)
+
+	sle_dict = {}
+	for d in sles:
+		sle_dict[(d.item_code, d.warehouse)] = {
+			"actual_qty": d.actual_qty,
+			"stock_value_difference": d.stock_value_difference,
+		}
+
+	return sle_dict
diff --git a/erpnext/assets/doctype/asset_capitalization_asset_item/__init__.py b/erpnext/assets/doctype/asset_capitalization_asset_item/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/assets/doctype/asset_capitalization_asset_item/__init__.py
diff --git a/erpnext/assets/doctype/asset_capitalization_asset_item/asset_capitalization_asset_item.json b/erpnext/assets/doctype/asset_capitalization_asset_item/asset_capitalization_asset_item.json
new file mode 100644
index 0000000..ebaaffb
--- /dev/null
+++ b/erpnext/assets/doctype/asset_capitalization_asset_item/asset_capitalization_asset_item.json
@@ -0,0 +1,128 @@
+{
+ "actions": [],
+ "creation": "2021-09-05 15:52:10.124538",
+ "doctype": "DocType",
+ "editable_grid": 1,
+ "engine": "InnoDB",
+ "field_order": [
+  "asset",
+  "asset_name",
+  "finance_book",
+  "column_break_3",
+  "item_code",
+  "item_name",
+  "section_break_6",
+  "current_asset_value",
+  "asset_value",
+  "column_break_9",
+  "accounting_dimensions_section",
+  "cost_center",
+  "dimension_col_break",
+  "fixed_asset_account"
+ ],
+ "fields": [
+  {
+   "fieldname": "asset",
+   "fieldtype": "Link",
+   "in_list_view": 1,
+   "label": "Asset",
+   "options": "Asset",
+   "reqd": 1
+  },
+  {
+   "fetch_from": "asset.asset_name",
+   "fieldname": "asset_name",
+   "fieldtype": "Data",
+   "in_list_view": 1,
+   "label": "Asset Name",
+   "read_only": 1
+  },
+  {
+   "fieldname": "column_break_3",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fetch_from": "asset.item_code",
+   "fieldname": "item_code",
+   "fieldtype": "Link",
+   "in_list_view": 1,
+   "label": "Item Code",
+   "options": "Item",
+   "read_only": 1,
+   "reqd": 1
+  },
+  {
+   "fieldname": "item_name",
+   "fieldtype": "Data",
+   "label": "Item Name",
+   "read_only": 1
+  },
+  {
+   "fieldname": "section_break_6",
+   "fieldtype": "Section Break",
+   "label": "Value"
+  },
+  {
+   "default": "0",
+   "fieldname": "asset_value",
+   "fieldtype": "Currency",
+   "in_list_view": 1,
+   "label": "Asset Value",
+   "options": "Company:company:default_currency",
+   "read_only": 1
+  },
+  {
+   "fieldname": "column_break_9",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "fixed_asset_account",
+   "fieldtype": "Link",
+   "label": "Fixed Asset Account",
+   "options": "Account",
+   "read_only": 1
+  },
+  {
+   "fieldname": "cost_center",
+   "fieldtype": "Link",
+   "label": "Cost Center",
+   "options": "Cost Center"
+  },
+  {
+   "collapsible": 1,
+   "fieldname": "accounting_dimensions_section",
+   "fieldtype": "Section Break",
+   "label": "Accounting Dimensions"
+  },
+  {
+   "fieldname": "dimension_col_break",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "finance_book",
+   "fieldtype": "Link",
+   "label": "Finance Book",
+   "options": "Finance Book"
+  },
+  {
+   "fieldname": "current_asset_value",
+   "fieldtype": "Currency",
+   "in_list_view": 1,
+   "label": "Current Asset Value",
+   "options": "Company:company:default_currency",
+   "read_only": 1
+  }
+ ],
+ "index_web_pages_for_search": 1,
+ "istable": 1,
+ "links": [],
+ "modified": "2021-09-12 14:30:02.915132",
+ "modified_by": "Administrator",
+ "module": "Assets",
+ "name": "Asset Capitalization Asset Item",
+ "owner": "Administrator",
+ "permissions": [],
+ "sort_field": "modified",
+ "sort_order": "DESC",
+ "track_changes": 1
+}
\ No newline at end of file
diff --git a/erpnext/assets/doctype/asset_capitalization_asset_item/asset_capitalization_asset_item.py b/erpnext/assets/doctype/asset_capitalization_asset_item/asset_capitalization_asset_item.py
new file mode 100644
index 0000000..ba356d6
--- /dev/null
+++ b/erpnext/assets/doctype/asset_capitalization_asset_item/asset_capitalization_asset_item.py
@@ -0,0 +1,9 @@
+# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
+# For license information, please see license.txt
+
+# import frappe
+from frappe.model.document import Document
+
+
+class AssetCapitalizationAssetItem(Document):
+	pass
diff --git a/erpnext/assets/doctype/asset_capitalization_service_item/__init__.py b/erpnext/assets/doctype/asset_capitalization_service_item/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/assets/doctype/asset_capitalization_service_item/__init__.py
diff --git a/erpnext/assets/doctype/asset_capitalization_service_item/asset_capitalization_service_item.json b/erpnext/assets/doctype/asset_capitalization_service_item/asset_capitalization_service_item.json
new file mode 100644
index 0000000..0ae1c14
--- /dev/null
+++ b/erpnext/assets/doctype/asset_capitalization_service_item/asset_capitalization_service_item.json
@@ -0,0 +1,122 @@
+{
+ "actions": [],
+ "creation": "2021-09-06 13:32:08.642060",
+ "doctype": "DocType",
+ "editable_grid": 1,
+ "engine": "InnoDB",
+ "field_order": [
+  "item_code",
+  "item_name",
+  "column_break_3",
+  "expense_account",
+  "section_break_6",
+  "qty",
+  "uom",
+  "column_break_9",
+  "rate",
+  "amount",
+  "accounting_dimensions_section",
+  "cost_center",
+  "dimension_col_break"
+ ],
+ "fields": [
+  {
+   "bold": 1,
+   "fieldname": "item_code",
+   "fieldtype": "Link",
+   "in_list_view": 1,
+   "label": "Item Code",
+   "options": "Item"
+  },
+  {
+   "fetch_from": "item_code.item_name",
+   "fieldname": "item_name",
+   "fieldtype": "Data",
+   "label": "Item Name",
+   "read_only": 1
+  },
+  {
+   "fieldname": "column_break_3",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "expense_account",
+   "fieldtype": "Link",
+   "in_list_view": 1,
+   "label": "Expense Account",
+   "options": "Account",
+   "reqd": 1
+  },
+  {
+   "fieldname": "section_break_6",
+   "fieldtype": "Section Break",
+   "label": "Qty and Rate"
+  },
+  {
+   "columns": 1,
+   "default": "1",
+   "fieldname": "qty",
+   "fieldtype": "Float",
+   "in_list_view": 1,
+   "label": "Qty",
+   "non_negative": 1
+  },
+  {
+   "columns": 1,
+   "fetch_from": "stock_item_code.stock_uom",
+   "fieldname": "uom",
+   "fieldtype": "Link",
+   "in_list_view": 1,
+   "label": "UOM",
+   "options": "UOM"
+  },
+  {
+   "fieldname": "column_break_9",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "rate",
+   "fieldtype": "Currency",
+   "in_list_view": 1,
+   "label": "Rate",
+   "options": "Company:company:default_currency"
+  },
+  {
+   "default": "0",
+   "fieldname": "amount",
+   "fieldtype": "Currency",
+   "in_list_view": 1,
+   "label": "Amount",
+   "options": "Company:company:default_currency",
+   "read_only": 1
+  },
+  {
+   "collapsible": 1,
+   "fieldname": "accounting_dimensions_section",
+   "fieldtype": "Section Break",
+   "label": "Accounting Dimensions"
+  },
+  {
+   "fieldname": "cost_center",
+   "fieldtype": "Link",
+   "label": "Cost Center",
+   "options": "Cost Center"
+  },
+  {
+   "fieldname": "dimension_col_break",
+   "fieldtype": "Column Break"
+  }
+ ],
+ "index_web_pages_for_search": 1,
+ "istable": 1,
+ "links": [],
+ "modified": "2021-09-08 15:52:08.598100",
+ "modified_by": "Administrator",
+ "module": "Assets",
+ "name": "Asset Capitalization Service Item",
+ "owner": "Administrator",
+ "permissions": [],
+ "sort_field": "modified",
+ "sort_order": "DESC",
+ "track_changes": 1
+}
\ No newline at end of file
diff --git a/erpnext/assets/doctype/asset_capitalization_service_item/asset_capitalization_service_item.py b/erpnext/assets/doctype/asset_capitalization_service_item/asset_capitalization_service_item.py
new file mode 100644
index 0000000..28d018e
--- /dev/null
+++ b/erpnext/assets/doctype/asset_capitalization_service_item/asset_capitalization_service_item.py
@@ -0,0 +1,9 @@
+# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
+# For license information, please see license.txt
+
+# import frappe
+from frappe.model.document import Document
+
+
+class AssetCapitalizationServiceItem(Document):
+	pass
diff --git a/erpnext/assets/doctype/asset_capitalization_stock_item/__init__.py b/erpnext/assets/doctype/asset_capitalization_stock_item/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/assets/doctype/asset_capitalization_stock_item/__init__.py
diff --git a/erpnext/assets/doctype/asset_capitalization_stock_item/asset_capitalization_stock_item.json b/erpnext/assets/doctype/asset_capitalization_stock_item/asset_capitalization_stock_item.json
new file mode 100644
index 0000000..14eb0f6
--- /dev/null
+++ b/erpnext/assets/doctype/asset_capitalization_stock_item/asset_capitalization_stock_item.json
@@ -0,0 +1,156 @@
+{
+ "actions": [],
+ "creation": "2021-09-05 15:23:23.492310",
+ "doctype": "DocType",
+ "editable_grid": 1,
+ "engine": "InnoDB",
+ "field_order": [
+  "item_code",
+  "item_name",
+  "column_break_3",
+  "warehouse",
+  "section_break_6",
+  "stock_qty",
+  "stock_uom",
+  "actual_qty",
+  "column_break_9",
+  "valuation_rate",
+  "amount",
+  "batch_and_serial_no_section",
+  "batch_no",
+  "column_break_13",
+  "serial_no",
+  "accounting_dimensions_section",
+  "cost_center",
+  "dimension_col_break"
+ ],
+ "fields": [
+  {
+   "fieldname": "column_break_3",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "warehouse",
+   "fieldtype": "Link",
+   "in_list_view": 1,
+   "label": "Warehouse",
+   "options": "Warehouse",
+   "reqd": 1
+  },
+  {
+   "fieldname": "batch_no",
+   "fieldtype": "Link",
+   "label": "Batch No",
+   "options": "Batch"
+  },
+  {
+   "fieldname": "section_break_6",
+   "fieldtype": "Section Break",
+   "label": "Qty and Rate"
+  },
+  {
+   "columns": 1,
+   "fieldname": "stock_qty",
+   "fieldtype": "Float",
+   "in_list_view": 1,
+   "label": "Qty",
+   "non_negative": 1
+  },
+  {
+   "columns": 1,
+   "fetch_from": "stock_item_code.stock_uom",
+   "fieldname": "stock_uom",
+   "fieldtype": "Link",
+   "in_list_view": 1,
+   "label": "Stock UOM",
+   "options": "UOM",
+   "read_only": 1,
+   "reqd": 1
+  },
+  {
+   "fieldname": "column_break_9",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "valuation_rate",
+   "fieldtype": "Currency",
+   "in_list_view": 1,
+   "label": "Valuation Rate",
+   "options": "Company:company:default_currency",
+   "read_only": 1
+  },
+  {
+   "default": "0",
+   "fieldname": "amount",
+   "fieldtype": "Currency",
+   "in_list_view": 1,
+   "label": "Amount",
+   "options": "Company:company:default_currency",
+   "read_only": 1
+  },
+  {
+   "fieldname": "batch_and_serial_no_section",
+   "fieldtype": "Section Break",
+   "label": "Batch and Serial No"
+  },
+  {
+   "fieldname": "column_break_13",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "serial_no",
+   "fieldtype": "Small Text",
+   "label": "Serial No"
+  },
+  {
+   "fieldname": "item_code",
+   "fieldtype": "Link",
+   "in_list_view": 1,
+   "label": "Item Code",
+   "options": "Item",
+   "reqd": 1
+  },
+  {
+   "fetch_from": "item_code.item_name",
+   "fieldname": "item_name",
+   "fieldtype": "Data",
+   "label": "Item Name",
+   "read_only": 1
+  },
+  {
+   "fieldname": "actual_qty",
+   "fieldtype": "Float",
+   "label": "Actual Qty in Warehouse",
+   "no_copy": 1,
+   "read_only": 1
+  },
+  {
+   "collapsible": 1,
+   "fieldname": "accounting_dimensions_section",
+   "fieldtype": "Section Break",
+   "label": "Accounting Dimensions"
+  },
+  {
+   "fieldname": "cost_center",
+   "fieldtype": "Link",
+   "label": "Cost Center",
+   "options": "Cost Center"
+  },
+  {
+   "fieldname": "dimension_col_break",
+   "fieldtype": "Column Break"
+  }
+ ],
+ "index_web_pages_for_search": 1,
+ "istable": 1,
+ "links": [],
+ "modified": "2021-09-08 15:56:20.230548",
+ "modified_by": "Administrator",
+ "module": "Assets",
+ "name": "Asset Capitalization Stock Item",
+ "owner": "Administrator",
+ "permissions": [],
+ "sort_field": "modified",
+ "sort_order": "DESC",
+ "track_changes": 1
+}
\ No newline at end of file
diff --git a/erpnext/assets/doctype/asset_capitalization_stock_item/asset_capitalization_stock_item.py b/erpnext/assets/doctype/asset_capitalization_stock_item/asset_capitalization_stock_item.py
new file mode 100644
index 0000000..5d6f98d
--- /dev/null
+++ b/erpnext/assets/doctype/asset_capitalization_stock_item/asset_capitalization_stock_item.py
@@ -0,0 +1,9 @@
+# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
+# For license information, please see license.txt
+
+# import frappe
+from frappe.model.document import Document
+
+
+class AssetCapitalizationStockItem(Document):
+	pass
diff --git a/erpnext/assets/workspace/assets/assets.json b/erpnext/assets/workspace/assets/assets.json
index 26a6609..c07155e 100644
--- a/erpnext/assets/workspace/assets/assets.json
+++ b/erpnext/assets/workspace/assets/assets.json
@@ -131,6 +131,17 @@
    "type": "Link"
   },
   {
+   "dependencies": "Asset",
+   "hidden": 0,
+   "is_query_report": 0,
+   "label": "Asset Capitalization",
+   "link_count": 0,
+   "link_to": "Asset Capitalization",
+   "link_type": "DocType",
+   "onboard": 0,
+   "type": "Link"
+  },
+  {
    "hidden": 0,
    "is_query_report": 0,
    "label": "Reports",
@@ -172,7 +183,7 @@
    "type": "Link"
   }
  ],
- "modified": "2022-01-13 17:25:41.730628",
+ "modified": "2022-01-13 18:25:41.730628",
  "modified_by": "Administrator",
  "module": "Assets",
  "name": "Assets",
@@ -205,4 +216,4 @@
   }
  ],
  "title": "Assets"
-}
\ No newline at end of file
+}
diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index e83ed2e..8686cb5 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -38,6 +38,7 @@
 	validate_party_frozen_disabled,
 )
 from erpnext.accounts.utils import get_account_currency, get_fiscal_years, validate_fiscal_year
+from erpnext.assets.doctype.asset.depreciation import make_depreciation_entry
 from erpnext.buying.utils import update_last_purchase_rate
 from erpnext.controllers.print_settings import (
 	set_print_templates_for_item_table,
@@ -205,6 +206,10 @@
 	def on_trash(self):
 		# delete sl and gl entries on deletion of transaction
 		if frappe.db.get_single_value("Accounts Settings", "delete_linked_ledger_entries"):
+			ple = frappe.qb.DocType("Payment Ledger Entry")
+			frappe.qb.from_(ple).delete().where(
+				(ple.voucher_type == self.doctype) & (ple.voucher_no == self.name)
+			).run()
 			frappe.db.sql(
 				"delete from `tabGL Entry` where voucher_type=%s and voucher_no=%s", (self.doctype, self.name)
 			)
@@ -1875,6 +1880,99 @@
 		):
 			throw(_("Conversion rate cannot be 0 or 1"))
 
+	def check_finance_books(self, item, asset):
+		if (
+			len(asset.finance_books) > 1
+			and not item.get("finance_book")
+			and not self.get("finance_book")
+			and asset.finance_books[0].finance_book
+		):
+			frappe.throw(
+				_("Select finance book for the item {0} at row {1}").format(item.item_code, item.idx)
+			)
+
+	def depreciate_asset(self, asset):
+		asset.flags.ignore_validate_update_after_submit = True
+		asset.prepare_depreciation_data(date_of_disposal=self.posting_date)
+		asset.save()
+
+		make_depreciation_entry(asset.name, self.posting_date)
+
+	def reset_depreciation_schedule(self, asset):
+		asset.flags.ignore_validate_update_after_submit = True
+
+		# recreate original depreciation schedule of the asset
+		asset.prepare_depreciation_data(date_of_return=self.posting_date)
+
+		self.modify_depreciation_schedule_for_asset_repairs(asset)
+		asset.save()
+
+	def modify_depreciation_schedule_for_asset_repairs(self, asset):
+		asset_repairs = frappe.get_all(
+			"Asset Repair", filters={"asset": asset.name}, fields=["name", "increase_in_asset_life"]
+		)
+
+		for repair in asset_repairs:
+			if repair.increase_in_asset_life:
+				asset_repair = frappe.get_doc("Asset Repair", repair.name)
+				asset_repair.modify_depreciation_schedule()
+				asset.prepare_depreciation_data()
+
+	def reverse_depreciation_entry_made_after_disposal(self, asset):
+		from erpnext.accounts.doctype.journal_entry.journal_entry import make_reverse_journal_entry
+
+		posting_date_of_original_disposal = self.get_posting_date_of_disposal_entry()
+
+		row = -1
+		finance_book = asset.get("schedules")[0].get("finance_book")
+		for schedule in asset.get("schedules"):
+			if schedule.finance_book != finance_book:
+				row = 0
+				finance_book = schedule.finance_book
+			else:
+				row += 1
+
+			if schedule.schedule_date == posting_date_of_original_disposal:
+				if not self.disposal_was_made_on_original_schedule_date(
+					asset, schedule, row, posting_date_of_original_disposal
+				) or self.disposal_happens_in_the_future(posting_date_of_original_disposal):
+
+					reverse_journal_entry = make_reverse_journal_entry(schedule.journal_entry)
+					reverse_journal_entry.posting_date = nowdate()
+					frappe.flags.is_reverse_depr_entry = True
+					reverse_journal_entry.submit()
+
+					frappe.flags.is_reverse_depr_entry = False
+					asset.flags.ignore_validate_update_after_submit = True
+					schedule.journal_entry = None
+					asset.save()
+
+	def get_posting_date_of_disposal_entry(self):
+		if self.doctype == "Sales Invoice" and self.return_against:
+			return frappe.db.get_value("Sales Invoice", self.return_against, "posting_date")
+		else:
+			return self.posting_date
+
+	# if the invoice had been posted on the date the depreciation was initially supposed to happen, the depreciation shouldn't be undone
+	def disposal_was_made_on_original_schedule_date(
+		self, asset, schedule, row, posting_date_of_disposal
+	):
+		for finance_book in asset.get("finance_books"):
+			if schedule.finance_book == finance_book.finance_book:
+				orginal_schedule_date = add_months(
+					finance_book.depreciation_start_date, row * cint(finance_book.frequency_of_depreciation)
+				)
+
+				if orginal_schedule_date == posting_date_of_disposal:
+					return True
+		return False
+
+	def disposal_happens_in_the_future(self, posting_date_of_disposal):
+		if posting_date_of_disposal > getdate():
+			return True
+
+		return False
+
 
 @frappe.whitelist()
 def get_tax_rate(account_head):
diff --git a/erpnext/controllers/buying_controller.py b/erpnext/controllers/buying_controller.py
index 7ab8f81..5659ad0 100644
--- a/erpnext/controllers/buying_controller.py
+++ b/erpnext/controllers/buying_controller.py
@@ -6,6 +6,7 @@
 from frappe import ValidationError, _, msgprint
 from frappe.contacts.doctype.address.address import get_address_display
 from frappe.utils import cint, cstr, flt, getdate
+from frappe.utils.data import nowtime
 
 from erpnext.accounts.doctype.budget.budget import validate_expense_against_budget
 from erpnext.accounts.party import get_party_details
@@ -289,12 +290,16 @@
 				# Get outgoing rate based on original item cost based on valuation method
 
 				if not d.get(frappe.scrub(ref_doctype)):
+					posting_time = self.get("posting_time")
+					if not posting_time and self.doctype == "Purchase Order":
+						posting_time = nowtime()
+
 					outgoing_rate = get_incoming_rate(
 						{
 							"item_code": d.item_code,
 							"warehouse": d.get("from_warehouse"),
 							"posting_date": self.get("posting_date") or self.get("transation_date"),
-							"posting_time": self.get("posting_time"),
+							"posting_time": posting_time,
 							"qty": -1 * flt(d.get("stock_qty")),
 							"serial_no": d.get("serial_no"),
 							"batch_no": d.get("batch_no"),
@@ -309,7 +314,11 @@
 					rate = flt(outgoing_rate * (d.conversion_factor or 1), d.precision("rate"))
 				else:
 					field = "incoming_rate" if self.get("is_internal_supplier") else "rate"
-					rate = frappe.db.get_value(ref_doctype, d.get(frappe.scrub(ref_doctype)), field)
+					rate = flt(
+						frappe.db.get_value(ref_doctype, d.get(frappe.scrub(ref_doctype)), field)
+						* (d.conversion_factor or 1),
+						d.precision("rate"),
+					)
 
 				if self.is_internal_transfer():
 					if rate != d.rate:
diff --git a/erpnext/controllers/employee_boarding_controller.py b/erpnext/controllers/employee_boarding_controller.py
deleted file mode 100644
index c06fb59..0000000
--- a/erpnext/controllers/employee_boarding_controller.py
+++ /dev/null
@@ -1,193 +0,0 @@
-# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors
-# License: GNU General Public License v3. See license.txt
-
-import frappe
-from frappe import _
-from frappe.desk.form import assign_to
-from frappe.model.document import Document
-from frappe.utils import add_days, flt, unique
-
-from erpnext.setup.doctype.employee.employee import get_holiday_list_for_employee
-from erpnext.setup.doctype.holiday_list.holiday_list import is_holiday
-
-
-class EmployeeBoardingController(Document):
-	"""
-	Create the project and the task for the boarding process
-	Assign to the concerned person and roles as per the onboarding/separation template
-	"""
-
-	def validate(self):
-		# remove the task if linked before submitting the form
-		if self.amended_from:
-			for activity in self.activities:
-				activity.task = ""
-
-	def on_submit(self):
-		# create the project for the given employee onboarding
-		project_name = _(self.doctype) + " : "
-		if self.doctype == "Employee Onboarding":
-			project_name += self.job_applicant
-		else:
-			project_name += self.employee
-
-		project = frappe.get_doc(
-			{
-				"doctype": "Project",
-				"project_name": project_name,
-				"expected_start_date": self.date_of_joining
-				if self.doctype == "Employee Onboarding"
-				else self.resignation_letter_date,
-				"department": self.department,
-				"company": self.company,
-			}
-		).insert(ignore_permissions=True, ignore_mandatory=True)
-
-		self.db_set("project", project.name)
-		self.db_set("boarding_status", "Pending")
-		self.reload()
-		self.create_task_and_notify_user()
-
-	def create_task_and_notify_user(self):
-		# create the task for the given project and assign to the concerned person
-		holiday_list = self.get_holiday_list()
-
-		for activity in self.activities:
-			if activity.task:
-				continue
-
-			dates = self.get_task_dates(activity, holiday_list)
-
-			task = frappe.get_doc(
-				{
-					"doctype": "Task",
-					"project": self.project,
-					"subject": activity.activity_name + " : " + self.employee_name,
-					"description": activity.description,
-					"department": self.department,
-					"company": self.company,
-					"task_weight": activity.task_weight,
-					"exp_start_date": dates[0],
-					"exp_end_date": dates[1],
-				}
-			).insert(ignore_permissions=True)
-			activity.db_set("task", task.name)
-
-			users = [activity.user] if activity.user else []
-			if activity.role:
-				user_list = frappe.db.sql_list(
-					"""
-					SELECT
-						DISTINCT(has_role.parent)
-					FROM
-						`tabHas Role` has_role
-							LEFT JOIN `tabUser` user
-								ON has_role.parent = user.name
-					WHERE
-						has_role.parenttype = 'User'
-							AND user.enabled = 1
-							AND has_role.role = %s
-				""",
-					activity.role,
-				)
-				users = unique(users + user_list)
-
-				if "Administrator" in users:
-					users.remove("Administrator")
-
-			# assign the task the users
-			if users:
-				self.assign_task_to_users(task, users)
-
-	def get_holiday_list(self):
-		if self.doctype == "Employee Separation":
-			return get_holiday_list_for_employee(self.employee)
-		else:
-			if self.employee:
-				return get_holiday_list_for_employee(self.employee)
-			else:
-				if not self.holiday_list:
-					frappe.throw(_("Please set the Holiday List."), frappe.MandatoryError)
-				else:
-					return self.holiday_list
-
-	def get_task_dates(self, activity, holiday_list):
-		start_date = end_date = None
-
-		if activity.begin_on is not None:
-			start_date = add_days(self.boarding_begins_on, activity.begin_on)
-			start_date = self.update_if_holiday(start_date, holiday_list)
-
-			if activity.duration is not None:
-				end_date = add_days(self.boarding_begins_on, activity.begin_on + activity.duration)
-				end_date = self.update_if_holiday(end_date, holiday_list)
-
-		return [start_date, end_date]
-
-	def update_if_holiday(self, date, holiday_list):
-		while is_holiday(holiday_list, date):
-			date = add_days(date, 1)
-		return date
-
-	def assign_task_to_users(self, task, users):
-		for user in users:
-			args = {
-				"assign_to": [user],
-				"doctype": task.doctype,
-				"name": task.name,
-				"description": task.description or task.subject,
-				"notify": self.notify_users_by_email,
-			}
-			assign_to.add(args)
-
-	def on_cancel(self):
-		# delete task project
-		project = self.project
-		for task in frappe.get_all("Task", filters={"project": project}):
-			frappe.delete_doc("Task", task.name, force=1)
-		frappe.delete_doc("Project", project, force=1)
-		self.db_set("project", "")
-		for activity in self.activities:
-			activity.db_set("task", "")
-
-		frappe.msgprint(
-			_("Linked Project {} and Tasks deleted.").format(project), alert=True, indicator="blue"
-		)
-
-
-@frappe.whitelist()
-def get_onboarding_details(parent, parenttype):
-	return frappe.get_all(
-		"Employee Boarding Activity",
-		fields=[
-			"activity_name",
-			"role",
-			"user",
-			"required_for_employee_creation",
-			"description",
-			"task_weight",
-			"begin_on",
-			"duration",
-		],
-		filters={"parent": parent, "parenttype": parenttype},
-		order_by="idx",
-	)
-
-
-def update_employee_boarding_status(project):
-	employee_onboarding = frappe.db.exists("Employee Onboarding", {"project": project.name})
-	employee_separation = frappe.db.exists("Employee Separation", {"project": project.name})
-
-	if not (employee_onboarding or employee_separation):
-		return
-
-	status = "Pending"
-	if flt(project.percent_complete) > 0.0 and flt(project.percent_complete) < 100.0:
-		status = "In Process"
-	elif flt(project.percent_complete) == 100.0:
-		status = "Completed"
-
-	if employee_onboarding:
-		frappe.db.set_value("Employee Onboarding", employee_onboarding, "boarding_status", status)
-	elif employee_separation:
-		frappe.db.set_value("Employee Separation", employee_separation, "boarding_status", status)
diff --git a/erpnext/controllers/subcontracting_controller.py b/erpnext/controllers/subcontracting_controller.py
index 2150477..bbd950e 100644
--- a/erpnext/controllers/subcontracting_controller.py
+++ b/erpnext/controllers/subcontracting_controller.py
@@ -877,6 +877,7 @@
 		{
 			order_doctype: {
 				"doctype": "Stock Entry",
+				"field_no_map": ["purchase_order", "subcontracting_order"],
 			},
 		},
 		ignore_child_tables=True,
diff --git a/erpnext/e_commerce/doctype/website_item/website_item.json b/erpnext/e_commerce/doctype/website_item/website_item.json
index a416aac..c5775ee 100644
--- a/erpnext/e_commerce/doctype/website_item/website_item.json
+++ b/erpnext/e_commerce/doctype/website_item/website_item.json
@@ -345,7 +345,8 @@
  "image_field": "website_image",
  "index_web_pages_for_search": 1,
  "links": [],
- "modified": "2022-06-28 17:10:30.613251",
+ "make_attachments_public": 1,
+ "modified": "2022-09-13 04:05:11.614087",
  "modified_by": "Administrator",
  "module": "E-commerce",
  "name": "Website Item",
diff --git a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
index 018832c..e9fa2ad 100644
--- a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
+++ b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
@@ -519,6 +519,8 @@
 	if not posting_date:
 		posting_date = getdate()
 
+	precision = cint(frappe.db.get_default("currency_precision")) or 2
+
 	unpaid_accrued_entries = frappe.db.sql(
 		"""
 			SELECT name, posting_date, interest_amount - paid_interest_amount as interest_amount,
@@ -539,6 +541,13 @@
 		as_dict=1,
 	)
 
+	# Skip entries with zero interest amount & payable principal amount
+	unpaid_accrued_entries = [
+		d
+		for d in unpaid_accrued_entries
+		if flt(d.interest_amount, precision) > 0 or flt(d.payable_principal_amount, precision) > 0
+	]
+
 	return unpaid_accrued_entries
 
 
diff --git a/erpnext/manufacturing/doctype/production_plan/production_plan.py b/erpnext/manufacturing/doctype/production_plan/production_plan.py
index 66d458b..f1d40c2 100644
--- a/erpnext/manufacturing/doctype/production_plan/production_plan.py
+++ b/erpnext/manufacturing/doctype/production_plan/production_plan.py
@@ -8,6 +8,7 @@
 import frappe
 from frappe import _, msgprint
 from frappe.model.document import Document
+from frappe.query_builder.functions import IfNull, Sum
 from frappe.utils import (
 	add_days,
 	ceil,
@@ -20,6 +21,7 @@
 	nowdate,
 )
 from frappe.utils.csvutils import build_csv_response
+from pypika.terms import ExistsCriterion
 
 from erpnext.manufacturing.doctype.bom.bom import get_children as get_bom_children
 from erpnext.manufacturing.doctype.bom.bom import validate_bom_no
@@ -100,39 +102,46 @@
 	@frappe.whitelist()
 	def get_pending_material_requests(self):
 		"""Pull Material Requests that are pending based on criteria selected"""
-		mr_filter = item_filter = ""
+
+		bom = frappe.qb.DocType("BOM")
+		mr = frappe.qb.DocType("Material Request")
+		mr_item = frappe.qb.DocType("Material Request Item")
+
+		pending_mr_query = (
+			frappe.qb.from_(mr)
+			.from_(mr_item)
+			.select(mr.name, mr.transaction_date)
+			.distinct()
+			.where(
+				(mr_item.parent == mr.name)
+				& (mr.material_request_type == "Manufacture")
+				& (mr.docstatus == 1)
+				& (mr.status != "Stopped")
+				& (mr.company == self.company)
+				& (mr_item.qty > IfNull(mr_item.ordered_qty, 0))
+				& (
+					ExistsCriterion(
+						frappe.qb.from_(bom)
+						.select(bom.name)
+						.where((bom.item == mr_item.item_code) & (bom.is_active == 1))
+					)
+				)
+			)
+		)
+
 		if self.from_date:
-			mr_filter += " and mr.transaction_date >= %(from_date)s"
+			pending_mr_query = pending_mr_query.where(mr.transaction_date >= self.from_date)
+
 		if self.to_date:
-			mr_filter += " and mr.transaction_date <= %(to_date)s"
+			pending_mr_query = pending_mr_query.where(mr.transaction_date <= self.to_date)
+
 		if self.warehouse:
-			mr_filter += " and mr_item.warehouse = %(warehouse)s"
+			pending_mr_query = pending_mr_query.where(mr_item.warehouse == self.warehouse)
 
 		if self.item_code:
-			item_filter += " and mr_item.item_code = %(item)s"
+			pending_mr_query = pending_mr_query.where(mr_item.item_code == self.item_code)
 
-		pending_mr = frappe.db.sql(
-			"""
-			select distinct mr.name, mr.transaction_date
-			from `tabMaterial Request` mr, `tabMaterial Request Item` mr_item
-			where mr_item.parent = mr.name
-				and mr.material_request_type = "Manufacture"
-				and mr.docstatus = 1 and mr.status != "Stopped" and mr.company = %(company)s
-				and mr_item.qty > ifnull(mr_item.ordered_qty,0) {0} {1}
-				and (exists (select name from `tabBOM` bom where bom.item=mr_item.item_code
-					and bom.is_active = 1))
-			""".format(
-				mr_filter, item_filter
-			),
-			{
-				"from_date": self.from_date,
-				"to_date": self.to_date,
-				"warehouse": self.warehouse,
-				"item": self.item_code,
-				"company": self.company,
-			},
-			as_dict=1,
-		)
+		pending_mr = pending_mr_query.run(as_dict=True)
 
 		self.add_mr_in_table(pending_mr)
 
@@ -160,16 +169,17 @@
 		so_mr_list = [d.get(field) for d in self.get(table) if d.get(field)]
 		return so_mr_list
 
-	def get_bom_item(self):
+	def get_bom_item_condition(self):
 		"""Check if Item or if its Template has a BOM."""
-		bom_item = None
+		bom_item_condition = None
 		has_bom = frappe.db.exists({"doctype": "BOM", "item": self.item_code, "docstatus": 1})
+
 		if not has_bom:
+			bom = frappe.qb.DocType("BOM")
 			template_item = frappe.db.get_value("Item", self.item_code, ["variant_of"])
-			bom_item = (
-				"bom.item = {0}".format(frappe.db.escape(template_item)) if template_item else bom_item
-			)
-		return bom_item
+			bom_item_condition = bom.item == template_item or None
+
+		return bom_item_condition
 
 	def get_so_items(self):
 		# Check for empty table or empty rows
@@ -178,46 +188,75 @@
 
 		so_list = self.get_so_mr_list("sales_order", "sales_orders")
 
-		item_condition = ""
-		bom_item = "bom.item = so_item.item_code"
-		if self.item_code and frappe.db.exists("Item", self.item_code):
-			bom_item = self.get_bom_item() or bom_item
-			item_condition = " and so_item.item_code = {0}".format(frappe.db.escape(self.item_code))
+		bom = frappe.qb.DocType("BOM")
+		so_item = frappe.qb.DocType("Sales Order Item")
 
-		items = frappe.db.sql(
-			"""
-			select
-				distinct parent, item_code, warehouse,
-				(qty - work_order_qty) * conversion_factor as pending_qty,
-				description, name
-			from
-				`tabSales Order Item` so_item
-			where
-				parent in (%s) and docstatus = 1 and qty > work_order_qty
-				and exists (select name from `tabBOM` bom where %s
-				and bom.is_active = 1) %s"""
-			% (", ".join(["%s"] * len(so_list)), bom_item, item_condition),
-			tuple(so_list),
-			as_dict=1,
+		items_subquery = frappe.qb.from_(bom).select(bom.name).where(bom.is_active == 1)
+		items_query = (
+			frappe.qb.from_(so_item)
+			.select(
+				so_item.parent,
+				so_item.item_code,
+				so_item.warehouse,
+				(
+					(so_item.qty - so_item.work_order_qty - so_item.delivered_qty) * so_item.conversion_factor
+				).as_("pending_qty"),
+				so_item.description,
+				so_item.name,
+			)
+			.distinct()
+			.where(
+				(so_item.parent.isin(so_list))
+				& (so_item.docstatus == 1)
+				& (so_item.qty > so_item.work_order_qty)
+			)
+		)
+
+		if self.item_code and frappe.db.exists("Item", self.item_code):
+			items_query = items_query.where(so_item.item_code == self.item_code)
+			items_subquery = items_subquery.where(
+				self.get_bom_item_condition() or bom.item == so_item.item_code
+			)
+
+		items_query = items_query.where(ExistsCriterion(items_subquery))
+
+		items = items_query.run(as_dict=True)
+
+		pi = frappe.qb.DocType("Packed Item")
+
+		packed_items_query = (
+			frappe.qb.from_(so_item)
+			.from_(pi)
+			.select(
+				pi.parent,
+				pi.item_code,
+				pi.warehouse.as_("warehouse"),
+				(((so_item.qty - so_item.work_order_qty) * pi.qty) / so_item.qty).as_("pending_qty"),
+				pi.parent_item,
+				pi.description,
+				so_item.name,
+			)
+			.distinct()
+			.where(
+				(so_item.parent == pi.parent)
+				& (so_item.docstatus == 1)
+				& (pi.parent_item == so_item.item_code)
+				& (so_item.parent.isin(so_list))
+				& (so_item.qty > so_item.work_order_qty)
+				& (
+					ExistsCriterion(
+						frappe.qb.from_(bom)
+						.select(bom.name)
+						.where((bom.item == pi.item_code) & (bom.is_active == 1))
+					)
+				)
+			)
 		)
 
 		if self.item_code:
-			item_condition = " and so_item.item_code = {0}".format(frappe.db.escape(self.item_code))
+			packed_items_query = packed_items_query.where(so_item.item_code == self.item_code)
 
-		packed_items = frappe.db.sql(
-			"""select distinct pi.parent, pi.item_code, pi.warehouse as warehouse,
-			(((so_item.qty - so_item.work_order_qty) * pi.qty) / so_item.qty)
-				as pending_qty, pi.parent_item, pi.description, so_item.name
-			from `tabSales Order Item` so_item, `tabPacked Item` pi
-			where so_item.parent = pi.parent and so_item.docstatus = 1
-			and pi.parent_item = so_item.item_code
-			and so_item.parent in (%s) and so_item.qty > so_item.work_order_qty
-			and exists (select name from `tabBOM` bom where bom.item=pi.item_code
-					and bom.is_active = 1) %s"""
-			% (", ".join(["%s"] * len(so_list)), item_condition),
-			tuple(so_list),
-			as_dict=1,
-		)
+		packed_items = packed_items_query.run(as_dict=True)
 
 		self.add_items(items + packed_items)
 		self.calculate_total_planned_qty()
@@ -233,22 +272,39 @@
 
 		mr_list = self.get_so_mr_list("material_request", "material_requests")
 
-		item_condition = ""
-		if self.item_code:
-			item_condition = " and mr_item.item_code ={0}".format(frappe.db.escape(self.item_code))
+		bom = frappe.qb.DocType("BOM")
+		mr_item = frappe.qb.DocType("Material Request Item")
 
-		items = frappe.db.sql(
-			"""select distinct parent, name, item_code, warehouse, description,
-			(qty - ordered_qty) * conversion_factor as pending_qty
-			from `tabMaterial Request Item` mr_item
-			where parent in (%s) and docstatus = 1 and qty > ordered_qty
-			and exists (select name from `tabBOM` bom where bom.item=mr_item.item_code
-				and bom.is_active = 1) %s"""
-			% (", ".join(["%s"] * len(mr_list)), item_condition),
-			tuple(mr_list),
-			as_dict=1,
+		items_query = (
+			frappe.qb.from_(mr_item)
+			.select(
+				mr_item.parent,
+				mr_item.name,
+				mr_item.item_code,
+				mr_item.warehouse,
+				mr_item.description,
+				((mr_item.qty - mr_item.ordered_qty) * mr_item.conversion_factor).as_("pending_qty"),
+			)
+			.distinct()
+			.where(
+				(mr_item.parent.isin(mr_list))
+				& (mr_item.docstatus == 1)
+				& (mr_item.qty > mr_item.ordered_qty)
+				& (
+					ExistsCriterion(
+						frappe.qb.from_(bom)
+						.select(bom.name)
+						.where((bom.item == mr_item.item_code) & (bom.is_active == 1))
+					)
+				)
+			)
 		)
 
+		if self.item_code:
+			items_query = items_query.where(mr_item.item_code == self.item_code)
+
+		items = items_query.run(as_dict=True)
+
 		self.add_items(items)
 		self.calculate_total_planned_qty()
 
@@ -819,29 +875,45 @@
 
 
 def get_exploded_items(item_details, company, bom_no, include_non_stock_items, planned_qty=1):
-	for d in frappe.db.sql(
-		"""select bei.item_code, item.default_bom as bom,
-			ifnull(sum(bei.stock_qty/ifnull(bom.quantity, 1)), 0)*%s as qty, item.item_name,
-			bei.description, bei.stock_uom, item.min_order_qty, bei.source_warehouse,
-			item.default_material_request_type, item.min_order_qty, item_default.default_warehouse,
-			item.purchase_uom, item_uom.conversion_factor, item.safety_stock
-		from
-			`tabBOM Explosion Item` bei
-			JOIN `tabBOM` bom ON bom.name = bei.parent
-			JOIN `tabItem` item ON item.name = bei.item_code
-			LEFT JOIN `tabItem Default` item_default
-				ON item_default.parent = item.name and item_default.company=%s
-			LEFT JOIN `tabUOM Conversion Detail` item_uom
-				ON item.name = item_uom.parent and item_uom.uom = item.purchase_uom
-		where
-			bei.docstatus < 2
-			and bom.name=%s and item.is_stock_item in (1, {0})
-		group by bei.item_code, bei.stock_uom""".format(
-			0 if include_non_stock_items else 1
-		),
-		(planned_qty, company, bom_no),
-		as_dict=1,
-	):
+	bei = frappe.qb.DocType("BOM Explosion Item")
+	bom = frappe.qb.DocType("BOM")
+	item = frappe.qb.DocType("Item")
+	item_default = frappe.qb.DocType("Item Default")
+	item_uom = frappe.qb.DocType("UOM Conversion Detail")
+
+	data = (
+		frappe.qb.from_(bei)
+		.join(bom)
+		.on(bom.name == bei.parent)
+		.join(item)
+		.on(item.name == bei.item_code)
+		.left_join(item_default)
+		.on((item_default.parent == item.name) & (item_default.company == company))
+		.left_join(item_uom)
+		.on((item.name == item_uom.parent) & (item_uom.uom == item.purchase_uom))
+		.select(
+			(IfNull(Sum(bei.stock_qty / IfNull(bom.quantity, 1)), 0) * planned_qty).as_("qty"),
+			item.item_name,
+			bei.description,
+			bei.stock_uom,
+			item.min_order_qty,
+			bei.source_warehouse,
+			item.default_material_request_type,
+			item.min_order_qty,
+			item_default.default_warehouse,
+			item.purchase_uom,
+			item_uom.conversion_factor,
+			item.safety_stock,
+		)
+		.where(
+			(bei.docstatus < 2)
+			& (bom.name == bom_no)
+			& (item.is_stock_item.isin([0, 1]) if include_non_stock_items else item.is_stock_item == 1)
+		)
+		.groupby(bei.item_code, bei.stock_uom)
+	).run(as_dict=True)
+
+	for d in data:
 		if not d.conversion_factor and d.purchase_uom:
 			d.conversion_factor = get_uom_conversion_factor(d.item_code, d.purchase_uom)
 		item_details.setdefault(d.get("item_code"), d)
@@ -866,33 +938,47 @@
 	parent_qty,
 	planned_qty=1,
 ):
-	items = frappe.db.sql(
-		"""
-		SELECT
-			bom_item.item_code, default_material_request_type, item.item_name,
-			ifnull(%(parent_qty)s * sum(bom_item.stock_qty/ifnull(bom.quantity, 1)) * %(planned_qty)s, 0) as qty,
-			item.is_sub_contracted_item as is_sub_contracted, bom_item.source_warehouse,
-			item.default_bom as default_bom, bom_item.description as description,
-			bom_item.stock_uom as stock_uom, item.min_order_qty as min_order_qty, item.safety_stock as safety_stock,
-			item_default.default_warehouse, item.purchase_uom, item_uom.conversion_factor
-		FROM
-			`tabBOM Item` bom_item
-			JOIN `tabBOM` bom ON bom.name = bom_item.parent
-			JOIN `tabItem` item ON bom_item.item_code = item.name
-			LEFT JOIN `tabItem Default` item_default
-				ON item.name = item_default.parent and item_default.company = %(company)s
-			LEFT JOIN `tabUOM Conversion Detail` item_uom
-				ON item.name = item_uom.parent and item_uom.uom = item.purchase_uom
-		where
-			bom.name = %(bom)s
-			and bom_item.docstatus < 2
-			and item.is_stock_item in (1, {0})
-		group by bom_item.item_code""".format(
-			0 if include_non_stock_items else 1
-		),
-		{"bom": bom_no, "parent_qty": parent_qty, "planned_qty": planned_qty, "company": company},
-		as_dict=1,
-	)
+	bom_item = frappe.qb.DocType("BOM Item")
+	bom = frappe.qb.DocType("BOM")
+	item = frappe.qb.DocType("Item")
+	item_default = frappe.qb.DocType("Item Default")
+	item_uom = frappe.qb.DocType("UOM Conversion Detail")
+
+	items = (
+		frappe.qb.from_(bom_item)
+		.join(bom)
+		.on(bom.name == bom_item.parent)
+		.join(item)
+		.on(bom_item.item_code == item.name)
+		.left_join(item_default)
+		.on((item.name == item_default.parent) & (item_default.company == company))
+		.left_join(item_uom)
+		.on((item.name == item_uom.parent) & (item_uom.uom == item.purchase_uom))
+		.select(
+			bom_item.item_code,
+			item.default_material_request_type,
+			item.item_name,
+			IfNull(parent_qty * Sum(bom_item.stock_qty / IfNull(bom.quantity, 1)) * planned_qty, 0).as_(
+				"qty"
+			),
+			item.is_sub_contracted_item.as_("is_sub_contracted"),
+			bom_item.source_warehouse,
+			item.default_bom.as_("default_bom"),
+			bom_item.description.as_("description"),
+			bom_item.stock_uom.as_("stock_uom"),
+			item.min_order_qty.as_("min_order_qty"),
+			item.safety_stock.as_("safety_stock"),
+			item_default.default_warehouse,
+			item.purchase_uom,
+			item_uom.conversion_factor,
+		)
+		.where(
+			(bom.name == bom_no)
+			& (bom_item.docstatus < 2)
+			& (item.is_stock_item.isin([0, 1]) if include_non_stock_items else item.is_stock_item == 1)
+		)
+		.groupby(bom_item.item_code)
+	).run(as_dict=True)
 
 	for d in items:
 		if not data.get("include_exploded_items") or not d.default_bom:
@@ -980,48 +1066,69 @@
 
 
 def get_sales_orders(self):
-	so_filter = item_filter = ""
-	bom_item = "bom.item = so_item.item_code"
+	bom = frappe.qb.DocType("BOM")
+	pi = frappe.qb.DocType("Packed Item")
+	so = frappe.qb.DocType("Sales Order")
+	so_item = frappe.qb.DocType("Sales Order Item")
+
+	open_so_subquery1 = frappe.qb.from_(bom).select(bom.name).where(bom.is_active == 1)
+
+	open_so_subquery2 = (
+		frappe.qb.from_(pi)
+		.select(pi.name)
+		.where(
+			(pi.parent == so.name)
+			& (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))
+				)
+			)
+		)
+	)
+
+	open_so_query = (
+		frappe.qb.from_(so)
+		.from_(so_item)
+		.select(so.name, so.transaction_date, so.customer, so.base_grand_total)
+		.distinct()
+		.where(
+			(so_item.parent == so.name)
+			& (so.docstatus == 1)
+			& (so.status.notin(["Stopped", "Closed"]))
+			& (so.company == self.company)
+			& (so_item.qty > so_item.work_order_qty)
+		)
+	)
 
 	date_field_mapper = {
-		"from_date": (">=", "so.transaction_date"),
-		"to_date": ("<=", "so.transaction_date"),
-		"from_delivery_date": (">=", "so_item.delivery_date"),
-		"to_delivery_date": ("<=", "so_item.delivery_date"),
+		"from_date": self.from_date >= so.transaction_date,
+		"to_date": self.to_date <= so.transaction_date,
+		"from_delivery_date": self.from_delivery_date >= so_item.delivery_date,
+		"to_delivery_date": self.to_delivery_date <= so_item.delivery_date,
 	}
 
 	for field, value in date_field_mapper.items():
 		if self.get(field):
-			so_filter += f" and {value[1]} {value[0]} %({field})s"
+			open_so_query = open_so_query.where(value)
 
-	for field in ["customer", "project", "sales_order_status"]:
+	for field in ("customer", "project", "sales_order_status"):
 		if self.get(field):
 			so_field = "status" if field == "sales_order_status" else field
-			so_filter += f" and so.{so_field} = %({field})s"
+			open_so_query = open_so_query.where(so[so_field] == self.get(field))
 
 	if self.item_code and frappe.db.exists("Item", self.item_code):
-		bom_item = self.get_bom_item() or bom_item
-		item_filter += " and so_item.item_code = %(item_code)s"
+		open_so_query = open_so_query.where(so_item.item_code == self.item_code)
+		open_so_subquery1 = open_so_subquery1.where(
+			self.get_bom_item_condition() or bom.item == so_item.item_code
+		)
 
-	open_so = frappe.db.sql(
-		f"""
-		select distinct so.name, so.transaction_date, so.customer, so.base_grand_total
-		from `tabSales Order` so, `tabSales Order Item` so_item
-		where so_item.parent = so.name
-			and so.docstatus = 1 and so.status not in ('Stopped', 'Closed')
-			and so.company = %(company)s
-			and so_item.qty > so_item.work_order_qty {so_filter} {item_filter}
-			and (exists (select name from `tabBOM` bom where {bom_item}
-					and bom.is_active = 1)
-				or exists (select name from `tabPacked Item` pi
-					where pi.parent = so.name and pi.parent_item = so_item.item_code
-						and exists (select name from `tabBOM` bom where bom.item=pi.item_code
-							and bom.is_active = 1)))
-		""",
-		self.as_dict(),
-		as_dict=1,
+	open_so_query = open_so_query.where(
+		(ExistsCriterion(open_so_subquery1) | ExistsCriterion(open_so_subquery2))
 	)
 
+	open_so = open_so_query.run(as_dict=True)
+
 	return open_so
 
 
@@ -1030,37 +1137,34 @@
 	if isinstance(row, str):
 		row = frappe._dict(json.loads(row))
 
-	company = frappe.db.escape(company)
-	conditions, warehouse = "", ""
+	bin = frappe.qb.DocType("Bin")
+	wh = frappe.qb.DocType("Warehouse")
 
-	conditions = " and warehouse in (select name from `tabWarehouse` where company = {0})".format(
-		company
-	)
+	subquery = frappe.qb.from_(wh).select(wh.name).where(wh.company == company)
+
 	if not all_warehouse:
 		warehouse = for_warehouse or row.get("source_warehouse") or row.get("default_warehouse")
 
 	if warehouse:
 		lft, rgt = frappe.db.get_value("Warehouse", warehouse, ["lft", "rgt"])
-		conditions = """ and warehouse in (select name from `tabWarehouse`
-			where lft >= {0} and rgt <= {1} and name=`tabBin`.warehouse and company = {2})
-		""".format(
-			lft, rgt, company
-		)
+		subquery = subquery.where((wh.lft >= lft) & (wh.rgt <= rgt) & (wh.name == bin.warehouse))
 
-	return frappe.db.sql(
-		""" select ifnull(sum(projected_qty),0) as projected_qty,
-		ifnull(sum(actual_qty),0) as actual_qty, ifnull(sum(ordered_qty),0) as ordered_qty,
-		ifnull(sum(reserved_qty_for_production),0) as reserved_qty_for_production, warehouse,
-		ifnull(sum(planned_qty),0) as planned_qty
-		from `tabBin` where item_code = %(item_code)s {conditions}
-		group by item_code, warehouse
-	""".format(
-			conditions=conditions
-		),
-		{"item_code": row["item_code"]},
-		as_dict=1,
+	query = (
+		frappe.qb.from_(bin)
+		.select(
+			bin.warehouse,
+			IfNull(Sum(bin.projected_qty), 0).as_("projected_qty"),
+			IfNull(Sum(bin.actual_qty), 0).as_("actual_qty"),
+			IfNull(Sum(bin.ordered_qty), 0).as_("ordered_qty"),
+			IfNull(Sum(bin.reserved_qty_for_production), 0).as_("reserved_qty_for_production"),
+			IfNull(Sum(bin.planned_qty), 0).as_("planned_qty"),
+		)
+		.where((bin.item_code == row["item_code"]) & (bin.warehouse.isin(subquery)))
+		.groupby(bin.item_code, bin.warehouse)
 	)
 
+	return query.run(as_dict=True)
+
 
 @frappe.whitelist()
 def get_so_details(sales_order):
diff --git a/erpnext/manufacturing/doctype/production_plan/test_production_plan.py b/erpnext/manufacturing/doctype/production_plan/test_production_plan.py
index 1d2d1bd..60e6398 100644
--- a/erpnext/manufacturing/doctype/production_plan/test_production_plan.py
+++ b/erpnext/manufacturing/doctype/production_plan/test_production_plan.py
@@ -12,6 +12,7 @@
 )
 from erpnext.manufacturing.doctype.work_order.work_order import OverProductionError
 from erpnext.manufacturing.doctype.work_order.work_order import make_stock_entry as make_se_from_wo
+from erpnext.selling.doctype.sales_order.sales_order import make_delivery_note
 from erpnext.selling.doctype.sales_order.test_sales_order import make_sales_order
 from erpnext.stock.doctype.item.test_item import create_item, make_item
 from erpnext.stock.doctype.stock_entry.test_stock_entry import make_stock_entry
@@ -610,15 +611,21 @@
 		"""
 		from erpnext.manufacturing.doctype.work_order.test_work_order import make_wo_order_test_record
 
+		make_stock_entry(item_code="_Test Item", target="Work In Progress - _TC", qty=2, basic_rate=100)
 		make_stock_entry(
-			item_code="Raw Material Item 1", target="Work In Progress - _TC", qty=2, basic_rate=100
-		)
-		make_stock_entry(
-			item_code="Raw Material Item 2", target="Work In Progress - _TC", qty=2, basic_rate=100
+			item_code="_Test Item Home Desktop 100", target="Work In Progress - _TC", qty=4, basic_rate=100
 		)
 
-		item = "Test Production Item 1"
-		so = make_sales_order(item_code=item, qty=1)
+		item = "_Test FG Item"
+
+		make_stock_entry(item_code=item, target="_Test Warehouse - _TC", qty=1)
+
+		so = make_sales_order(item_code=item, qty=2)
+
+		dn = make_delivery_note(so.name)
+		dn.items[0].qty = 1
+		dn.save()
+		dn.submit()
 
 		pln = create_production_plan(
 			company=so.company, get_items_from="Sales Order", sales_order=so, skip_getting_mr_items=True
diff --git a/erpnext/manufacturing/report/bom_stock_calculated/bom_stock_calculated.js b/erpnext/manufacturing/report/bom_stock_calculated/bom_stock_calculated.js
index 0d5bfcb..a0fd91e 100644
--- a/erpnext/manufacturing/report/bom_stock_calculated/bom_stock_calculated.js
+++ b/erpnext/manufacturing/report/bom_stock_calculated/bom_stock_calculated.js
@@ -11,17 +11,24 @@
 			"options": "BOM",
 			"reqd": 1
 		},
-        	{
-	            "fieldname": "qty_to_make",
-        	    "label": __("Quantity to Make"),
-        	    "fieldtype": "Int",
-        	    "default": "1"
-	       },
-
-		 {
+		{
+			"fieldname": "warehouse",
+			"label": __("Warehouse"),
+			"fieldtype": "Link",
+			"options": "Warehouse",
+		},
+		{
+			"fieldname": "qty_to_make",
+			"label": __("Quantity to Make"),
+			"fieldtype": "Float",
+			"default": "1.0",
+			"reqd": 1
+		},
+		{
 			"fieldname": "show_exploded_view",
 			"label": __("Show exploded view"),
-			"fieldtype": "Check"
+			"fieldtype": "Check",
+			"default": false,
 		}
 	]
 }
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 933be3e..ec4b25c 100644
--- a/erpnext/manufacturing/report/bom_stock_calculated/bom_stock_calculated.py
+++ b/erpnext/manufacturing/report/bom_stock_calculated/bom_stock_calculated.py
@@ -4,29 +4,31 @@
 
 import frappe
 from frappe import _
+from frappe.query_builder.functions import IfNull, Sum
 from frappe.utils.data import comma_and
+from pypika.terms import ExistsCriterion
 
 
 def execute(filters=None):
-	# if not filters: filters = {}
 	columns = get_columns()
-	summ_data = []
+	data = []
 
-	data = get_bom_stock(filters)
+	bom_data = get_bom_data(filters)
 	qty_to_make = filters.get("qty_to_make")
-
 	manufacture_details = get_manufacturer_records()
-	for row in data:
-		reqd_qty = qty_to_make * row.actual_qty
-		last_pur_price = frappe.db.get_value("Item", row.item_code, "last_purchase_rate")
 
-		summ_data.append(get_report_data(last_pur_price, reqd_qty, row, manufacture_details))
-	return columns, summ_data
+	for row in bom_data:
+		required_qty = qty_to_make * row.qty_per_unit
+		last_purchase_rate = frappe.db.get_value("Item", row.item_code, "last_purchase_rate")
+
+		data.append(get_report_data(last_purchase_rate, required_qty, row, manufacture_details))
+
+	return columns, data
 
 
-def get_report_data(last_pur_price, reqd_qty, row, manufacture_details):
-	to_build = row.to_build if row.to_build > 0 else 0
-	diff_qty = to_build - reqd_qty
+def get_report_data(last_purchase_rate, required_qty, row, manufacture_details):
+	qty_per_unit = row.qty_per_unit if row.qty_per_unit > 0 else 0
+	difference_qty = row.actual_qty - required_qty
 	return [
 		row.item_code,
 		row.description,
@@ -34,85 +36,126 @@
 		comma_and(
 			manufacture_details.get(row.item_code, {}).get("manufacturer_part", []), add_quotes=False
 		),
+		qty_per_unit,
 		row.actual_qty,
-		str(to_build),
-		reqd_qty,
-		diff_qty,
-		last_pur_price,
+		required_qty,
+		difference_qty,
+		last_purchase_rate,
 	]
 
 
 def get_columns():
-	"""return columns"""
-	columns = [
-		_("Item") + ":Link/Item:100",
-		_("Description") + "::150",
-		_("Manufacturer") + "::250",
-		_("Manufacturer Part Number") + "::250",
-		_("Qty") + ":Float:50",
-		_("Stock Qty") + ":Float:100",
-		_("Reqd Qty") + ":Float:100",
-		_("Diff Qty") + ":Float:100",
-		_("Last Purchase Price") + ":Float:100",
+	return [
+		{
+			"fieldname": "item",
+			"label": _("Item"),
+			"fieldtype": "Link",
+			"options": "Item",
+			"width": 120,
+		},
+		{
+			"fieldname": "description",
+			"label": _("Description"),
+			"fieldtype": "Data",
+			"width": 150,
+		},
+		{
+			"fieldname": "manufacturer",
+			"label": _("Manufacturer"),
+			"fieldtype": "Data",
+			"width": 120,
+		},
+		{
+			"fieldname": "manufacturer_part_number",
+			"label": _("Manufacturer Part Number"),
+			"fieldtype": "Data",
+			"width": 150,
+		},
+		{
+			"fieldname": "qty_per_unit",
+			"label": _("Qty Per Unit"),
+			"fieldtype": "Float",
+			"width": 110,
+		},
+		{
+			"fieldname": "available_qty",
+			"label": _("Available Qty"),
+			"fieldtype": "Float",
+			"width": 120,
+		},
+		{
+			"fieldname": "required_qty",
+			"label": _("Required Qty"),
+			"fieldtype": "Float",
+			"width": 120,
+		},
+		{
+			"fieldname": "difference_qty",
+			"label": _("Difference Qty"),
+			"fieldtype": "Float",
+			"width": 130,
+		},
+		{
+			"fieldname": "last_purchase_rate",
+			"label": _("Last Purchase Rate"),
+			"fieldtype": "Float",
+			"width": 160,
+		},
 	]
-	return columns
 
 
-def get_bom_stock(filters):
-	conditions = ""
-	bom = filters.get("bom")
-
-	table = "`tabBOM Item`"
-	qty_field = "qty"
-
+def get_bom_data(filters):
 	if filters.get("show_exploded_view"):
-		table = "`tabBOM Explosion Item`"
-		qty_field = "stock_qty"
+		bom_item_table = "BOM Explosion Item"
+	else:
+		bom_item_table = "BOM Item"
+
+	bom_item = frappe.qb.DocType(bom_item_table)
+	bin = frappe.qb.DocType("Bin")
+
+	query = (
+		frappe.qb.from_(bom_item)
+		.left_join(bin)
+		.on(bom_item.item_code == bin.item_code)
+		.select(
+			bom_item.item_code,
+			bom_item.description,
+			bom_item.qty_consumed_per_unit.as_("qty_per_unit"),
+			IfNull(Sum(bin.actual_qty), 0).as_("actual_qty"),
+		)
+		.where((bom_item.parent == filters.get("bom")) & (bom_item.parenttype == "BOM"))
+		.groupby(bom_item.item_code)
+	)
 
 	if filters.get("warehouse"):
 		warehouse_details = frappe.db.get_value(
 			"Warehouse", filters.get("warehouse"), ["lft", "rgt"], as_dict=1
 		)
+
 		if warehouse_details:
-			conditions += (
-				" and exists (select name from `tabWarehouse` wh \
-				where wh.lft >= %s and wh.rgt <= %s and ledger.warehouse = wh.name)"
-				% (warehouse_details.lft, warehouse_details.rgt)
+			wh = frappe.qb.DocType("Warehouse")
+			query = query.where(
+				ExistsCriterion(
+					frappe.qb.from_(wh)
+					.select(wh.name)
+					.where(
+						(wh.lft >= warehouse_details.lft)
+						& (wh.rgt <= warehouse_details.rgt)
+						& (bin.warehouse == wh.name)
+					)
+				)
 			)
 		else:
-			conditions += " and ledger.warehouse = %s" % frappe.db.escape(filters.get("warehouse"))
+			query = query.where(bin.warehouse == frappe.db.escape(filters.get("warehouse")))
 
-	else:
-		conditions += ""
-
-	return frappe.db.sql(
-		"""
-			SELECT
-				bom_item.item_code,
-				bom_item.description,
-				bom_item.{qty_field},
-				ifnull(sum(ledger.actual_qty), 0) as actual_qty,
-				ifnull(sum(FLOOR(ledger.actual_qty / bom_item.{qty_field})), 0) as to_build
-			FROM
-				{table} AS bom_item
-				LEFT JOIN `tabBin` AS ledger
-				ON bom_item.item_code = ledger.item_code
-				{conditions}
-
-			WHERE
-				bom_item.parent = '{bom}' and bom_item.parenttype='BOM'
-
-			GROUP BY bom_item.item_code""".format(
-			qty_field=qty_field, table=table, conditions=conditions, bom=bom
-		),
-		as_dict=1,
-	)
+	return query.run(as_dict=True)
 
 
 def get_manufacturer_records():
 	details = frappe.get_all(
 		"Item Manufacturer", fields=["manufacturer", "manufacturer_part_no", "item_code"]
 	)
+
 	manufacture_details = frappe._dict()
 	for detail in details:
 		dic = manufacture_details.setdefault(detail.get("item_code"), {})
diff --git a/erpnext/manufacturing/report/bom_stock_calculated/test_bom_stock_calculated.py b/erpnext/manufacturing/report/bom_stock_calculated/test_bom_stock_calculated.py
new file mode 100644
index 0000000..8ad980f
--- /dev/null
+++ b/erpnext/manufacturing/report/bom_stock_calculated/test_bom_stock_calculated.py
@@ -0,0 +1,115 @@
+# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
+# For license information, please see license.txt
+
+from frappe.tests.utils import FrappeTestCase
+
+from erpnext.manufacturing.doctype.production_plan.test_production_plan import make_bom
+from erpnext.manufacturing.report.bom_stock_calculated.bom_stock_calculated import (
+	execute as bom_stock_calculated_report,
+)
+from erpnext.stock.doctype.item.test_item import make_item
+
+
+class TestBOMStockCalculated(FrappeTestCase):
+	def setUp(self):
+		self.fg_item, self.rm_items = create_items()
+		self.boms = create_boms(self.fg_item, self.rm_items)
+
+	def test_bom_stock_calculated(self):
+		qty_to_make = 10
+
+		# Case 1: When Item(s) Qty and Stock Qty are equal.
+		data = bom_stock_calculated_report(
+			filters={
+				"qty_to_make": qty_to_make,
+				"bom": self.boms[0].name,
+			}
+		)[1]
+		expected_data = get_expected_data(self.boms[0], qty_to_make)
+		self.assertSetEqual(set(tuple(x) for x in data), set(tuple(x) for x in expected_data))
+
+		# Case 2: When Item(s) Qty and Stock Qty are different and BOM Qty is 1.
+		data = bom_stock_calculated_report(
+			filters={
+				"qty_to_make": qty_to_make,
+				"bom": self.boms[1].name,
+			}
+		)[1]
+		expected_data = get_expected_data(self.boms[1], qty_to_make)
+		self.assertSetEqual(set(tuple(x) for x in data), set(tuple(x) for x in expected_data))
+
+		# Case 3: When Item(s) Qty and Stock Qty are different and BOM Qty is greater than 1.
+		data = bom_stock_calculated_report(
+			filters={
+				"qty_to_make": qty_to_make,
+				"bom": self.boms[2].name,
+			}
+		)[1]
+		expected_data = get_expected_data(self.boms[2], qty_to_make)
+		self.assertSetEqual(set(tuple(x) for x in data), set(tuple(x) for x in expected_data))
+
+
+def create_items():
+	fg_item = make_item(properties={"is_stock_item": 1}).name
+	rm_item1 = make_item(
+		properties={
+			"is_stock_item": 1,
+			"standard_rate": 100,
+			"opening_stock": 100,
+			"last_purchase_rate": 100,
+		}
+	).name
+	rm_item2 = make_item(
+		properties={
+			"is_stock_item": 1,
+			"standard_rate": 200,
+			"opening_stock": 200,
+			"last_purchase_rate": 200,
+		}
+	).name
+
+	return fg_item, [rm_item1, rm_item2]
+
+
+def create_boms(fg_item, rm_items):
+	def update_bom_items(bom, uom, conversion_factor):
+		for item in bom.items:
+			item.uom = uom
+			item.conversion_factor = conversion_factor
+
+		return bom
+
+	bom1 = make_bom(item=fg_item, quantity=1, raw_materials=rm_items, rm_qty=10)
+
+	bom2 = make_bom(item=fg_item, quantity=1, raw_materials=rm_items, rm_qty=10, do_not_submit=True)
+	bom2 = update_bom_items(bom2, "Box", 10)
+	bom2.save()
+	bom2.submit()
+
+	bom3 = make_bom(item=fg_item, quantity=2, raw_materials=rm_items, rm_qty=10, do_not_submit=True)
+	bom3 = update_bom_items(bom3, "Box", 10)
+	bom3.save()
+	bom3.submit()
+
+	return [bom1, bom2, bom3]
+
+
+def get_expected_data(bom, qty_to_make):
+	expected_data = []
+
+	for idx in range(len(bom.items)):
+		expected_data.append(
+			[
+				bom.items[idx].item_code,
+				bom.items[idx].item_code,
+				"",
+				"",
+				float(bom.items[idx].stock_qty / bom.quantity),
+				float(100 * (idx + 1)),
+				float(qty_to_make * (bom.items[idx].stock_qty / bom.quantity)),
+				float((100 * (idx + 1)) - (qty_to_make * (bom.items[idx].stock_qty / bom.quantity))),
+				float(100 * (idx + 1)),
+			]
+		)
+
+	return expected_data
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 b10e643..ce8f4f3 100644
--- a/erpnext/manufacturing/report/process_loss_report/process_loss_report.py
+++ b/erpnext/manufacturing/report/process_loss_report/process_loss_report.py
@@ -5,6 +5,7 @@
 
 import frappe
 from frappe import _
+from frappe.query_builder.functions import Sum
 
 Filters = frappe._dict
 Row = frappe._dict
@@ -14,15 +15,50 @@
 
 
 def execute(filters: Filters) -> Tuple[Columns, Data]:
+	filters = frappe._dict(filters or {})
 	columns = get_columns()
 	data = get_data(filters)
 	return columns, data
 
 
 def get_data(filters: Filters) -> Data:
-	query_args = get_query_args(filters)
-	data = run_query(query_args)
+	wo = frappe.qb.DocType("Work Order")
+	se = frappe.qb.DocType("Stock Entry")
+
+	query = (
+		frappe.qb.from_(wo)
+		.inner_join(se)
+		.on(wo.name == se.work_order)
+		.select(
+			wo.name,
+			wo.status,
+			wo.production_item,
+			wo.qty,
+			wo.produced_qty,
+			wo.process_loss_qty,
+			(wo.produced_qty - wo.process_loss_qty).as_("actual_produced_qty"),
+			Sum(se.total_incoming_value).as_("total_fg_value"),
+			Sum(se.total_outgoing_value).as_("total_rm_value"),
+		)
+		.where(
+			(wo.process_loss_qty > 0)
+			& (wo.company == filters.company)
+			& (se.docstatus == 1)
+			& (se.posting_date.between(filters.from_date, filters.to_date))
+		)
+		.groupby(se.work_order)
+	)
+
+	if "item" in filters:
+		query.where(wo.production_item == filters.item)
+
+	if "work_order" in filters:
+		query.where(wo.name == filters.work_order)
+
+	data = query.run(as_dict=True)
+
 	update_data_with_total_pl_value(data)
+
 	return data
 
 
@@ -67,54 +103,7 @@
 	]
 
 
-def get_query_args(filters: Filters) -> QueryArgs:
-	query_args = {}
-	query_args.update(filters)
-	query_args.update(get_filter_conditions(filters))
-	return query_args
-
-
-def run_query(query_args: QueryArgs) -> Data:
-	return frappe.db.sql(
-		"""
-		SELECT
-			wo.name, wo.status, wo.production_item, wo.qty,
-			wo.produced_qty, wo.process_loss_qty,
-			(wo.produced_qty - wo.process_loss_qty) as actual_produced_qty,
-			sum(se.total_incoming_value) as total_fg_value,
-			sum(se.total_outgoing_value) as total_rm_value
-		FROM
-			`tabWork Order` wo INNER JOIN `tabStock Entry` se
-			ON wo.name=se.work_order
-		WHERE
-			process_loss_qty > 0
-			AND wo.company = %(company)s
-			AND se.docstatus = 1
-			AND se.posting_date BETWEEN %(from_date)s AND %(to_date)s
-			{item_filter}
-			{work_order_filter}
-		GROUP BY
-			se.work_order
-	""".format(
-			**query_args
-		),
-		query_args,
-		as_dict=1,
-	)
-
-
 def update_data_with_total_pl_value(data: Data) -> None:
 	for row in data:
 		value_per_unit_fg = row["total_fg_value"] / row["actual_produced_qty"]
 		row["total_pl_value"] = row["process_loss_qty"] * value_per_unit_fg
-
-
-def get_filter_conditions(filters: Filters) -> QueryArgs:
-	filter_conditions = dict(item_filter="", work_order_filter="")
-	if "item" in filters:
-		production_item = filters.get("item")
-		filter_conditions.update({"item_filter": f"AND wo.production_item='{production_item}'"})
-	if "work_order" in filters:
-		work_order_name = filters.get("work_order")
-		filter_conditions.update({"work_order_filter": f"AND wo.name='{work_order_name}'"})
-	return filter_conditions
diff --git a/erpnext/manufacturing/report/work_order_stock_report/work_order_stock_report.py b/erpnext/manufacturing/report/work_order_stock_report/work_order_stock_report.py
index 063ebba..998b0e4 100644
--- a/erpnext/manufacturing/report/work_order_stock_report/work_order_stock_report.py
+++ b/erpnext/manufacturing/report/work_order_stock_report/work_order_stock_report.py
@@ -4,6 +4,7 @@
 
 import frappe
 from frappe import _
+from frappe.query_builder.functions import IfNull
 from frappe.utils import cint
 
 
@@ -17,70 +18,70 @@
 def get_item_list(wo_list, filters):
 	out = []
 
-	# Add a row for each item/qty
-	for wo_details in wo_list:
-		desc = frappe.db.get_value("BOM", wo_details.bom_no, "description")
+	if wo_list:
+		bin = frappe.qb.DocType("Bin")
+		bom = frappe.qb.DocType("BOM")
+		bom_item = frappe.qb.DocType("BOM Item")
 
-		for wo_item_details in frappe.db.get_values(
-			"Work Order Item", {"parent": wo_details.name}, ["item_code", "source_warehouse"], as_dict=1
-		):
+		# Add a row for each item/qty
+		for wo_details in wo_list:
+			desc = frappe.db.get_value("BOM", wo_details.bom_no, "description")
 
-			item_list = frappe.db.sql(
-				"""SELECT
-					bom_item.item_code as item_code,
-					ifnull(ledger.actual_qty*bom.quantity/bom_item.stock_qty,0) as build_qty
-				FROM
-					`tabBOM` as bom, `tabBOM Item` AS bom_item
-					LEFT JOIN `tabBin` AS ledger
-						ON bom_item.item_code = ledger.item_code
-						AND ledger.warehouse = ifnull(%(warehouse)s,%(filterhouse)s)
-				WHERE
-					bom.name = bom_item.parent
-					and bom_item.item_code = %(item_code)s
-					and bom.name = %(bom)s
-				GROUP BY
-					bom_item.item_code""",
-				{
-					"bom": wo_details.bom_no,
-					"warehouse": wo_item_details.source_warehouse,
-					"filterhouse": filters.warehouse,
-					"item_code": wo_item_details.item_code,
-				},
-				as_dict=1,
-			)
+			for wo_item_details in frappe.db.get_values(
+				"Work Order Item", {"parent": wo_details.name}, ["item_code", "source_warehouse"], as_dict=1
+			):
+				item_list = (
+					frappe.qb.from_(bom)
+					.from_(bom_item)
+					.left_join(bin)
+					.on(
+						(bom_item.item_code == bin.item_code)
+						& (bin.warehouse == IfNull(wo_item_details.source_warehouse, filters.warehouse))
+					)
+					.select(
+						bom_item.item_code.as_("item_code"),
+						IfNull(bin.actual_qty * bom.quantity / bom_item.stock_qty, 0).as_("build_qty"),
+					)
+					.where(
+						(bom.name == bom_item.parent)
+						& (bom_item.item_code == wo_item_details.item_code)
+						& (bom.name == wo_details.bom_no)
+					)
+					.groupby(bom_item.item_code)
+				).run(as_dict=1)
 
-			stock_qty = 0
-			count = 0
-			buildable_qty = wo_details.qty
-			for item in item_list:
-				count = count + 1
-				if item.build_qty >= (wo_details.qty - wo_details.produced_qty):
-					stock_qty = stock_qty + 1
-				elif buildable_qty >= item.build_qty:
-					buildable_qty = item.build_qty
+				stock_qty = 0
+				count = 0
+				buildable_qty = wo_details.qty
+				for item in item_list:
+					count = count + 1
+					if item.build_qty >= (wo_details.qty - wo_details.produced_qty):
+						stock_qty = stock_qty + 1
+					elif buildable_qty >= item.build_qty:
+						buildable_qty = item.build_qty
 
-			if count == stock_qty:
-				build = "Y"
-			else:
-				build = "N"
+				if count == stock_qty:
+					build = "Y"
+				else:
+					build = "N"
 
-			row = frappe._dict(
-				{
-					"work_order": wo_details.name,
-					"status": wo_details.status,
-					"req_items": cint(count),
-					"instock": stock_qty,
-					"description": desc,
-					"source_warehouse": wo_item_details.source_warehouse,
-					"item_code": wo_item_details.item_code,
-					"bom_no": wo_details.bom_no,
-					"qty": wo_details.qty,
-					"buildable_qty": buildable_qty,
-					"ready_to_build": build,
-				}
-			)
+				row = frappe._dict(
+					{
+						"work_order": wo_details.name,
+						"status": wo_details.status,
+						"req_items": cint(count),
+						"instock": stock_qty,
+						"description": desc,
+						"source_warehouse": wo_item_details.source_warehouse,
+						"item_code": wo_item_details.item_code,
+						"bom_no": wo_details.bom_no,
+						"qty": wo_details.qty,
+						"buildable_qty": buildable_qty,
+						"ready_to_build": build,
+					}
+				)
 
-			out.append(row)
+				out.append(row)
 
 	return out
 
diff --git a/erpnext/patches.txt b/erpnext/patches.txt
index d780213..2a0ca8c 100644
--- a/erpnext/patches.txt
+++ b/erpnext/patches.txt
@@ -307,6 +307,7 @@
 erpnext.patches.v14_0.copy_is_subcontracted_value_to_is_old_subcontracting_flow
 erpnext.patches.v14_0.migrate_gl_to_payment_ledger
 erpnext.patches.v14_0.crm_ux_cleanup
+erpnext.patches.v14_0.migrate_existing_lead_notes_as_per_the_new_format
 erpnext.patches.v14_0.remove_india_localisation # 14-07-2022
 erpnext.patches.v13_0.fix_number_and_frequency_for_monthly_depreciation
 erpnext.patches.v14_0.remove_hr_and_payroll_modules # 20-07-2022
diff --git a/erpnext/patches/v14_0/migrate_existing_lead_notes_as_per_the_new_format.py b/erpnext/patches/v14_0/migrate_existing_lead_notes_as_per_the_new_format.py
new file mode 100644
index 0000000..ec72527
--- /dev/null
+++ b/erpnext/patches/v14_0/migrate_existing_lead_notes_as_per_the_new_format.py
@@ -0,0 +1,23 @@
+import frappe
+from frappe.utils import cstr, strip_html
+
+
+def execute():
+	for doctype in ("Lead", "Prospect", "Opportunity"):
+		if not frappe.db.has_column(doctype, "notes"):
+			continue
+
+		dt = frappe.qb.DocType(doctype)
+		records = (
+			frappe.qb.from_(dt)
+			.select(dt.name, dt.notes, dt.modified_by, dt.modified)
+			.where(dt.notes.isnotnull() & dt.notes != "")
+		).run(as_dict=True)
+
+		for d in records:
+			if strip_html(cstr(d.notes)).strip():
+				doc = frappe.get_doc(doctype, d.name)
+				doc.append("notes", {"note": d.notes, "added_by": d.modified_by, "added_on": d.modified})
+				doc.update_child_table("notes")
+
+		frappe.db.sql_ddl(f"alter table `tab{doctype}` drop column `notes`")
diff --git a/erpnext/projects/doctype/project/project.py b/erpnext/projects/doctype/project/project.py
index a2be936..d80133c 100644
--- a/erpnext/projects/doctype/project/project.py
+++ b/erpnext/projects/doctype/project/project.py
@@ -10,7 +10,6 @@
 from frappe.utils import add_days, flt, get_datetime, get_time, get_url, nowtime, today
 
 from erpnext import get_default_company
-from erpnext.controllers.employee_boarding_controller import update_employee_boarding_status
 from erpnext.controllers.queries import get_filters_cond
 from erpnext.setup.doctype.holiday_list.holiday_list import is_holiday
 
@@ -43,7 +42,6 @@
 		self.send_welcome_email()
 		self.update_costing()
 		self.update_percent_complete()
-		update_employee_boarding_status(self)
 
 	def copy_from_template(self):
 		"""
@@ -145,7 +143,6 @@
 	def update_project(self):
 		"""Called externally by Task"""
 		self.update_percent_complete()
-		update_employee_boarding_status(self)
 		self.update_costing()
 		self.db_update()
 
diff --git a/erpnext/setup/doctype/company/company.py b/erpnext/setup/doctype/company/company.py
index dc69888..490504a 100644
--- a/erpnext/setup/doctype/company/company.py
+++ b/erpnext/setup/doctype/company/company.py
@@ -389,6 +389,7 @@
 			"capital_work_in_progress_account": "Capital Work in Progress",
 			"asset_received_but_not_billed": "Asset Received But Not Billed",
 			"expenses_included_in_asset_valuation": "Expenses Included In Asset Valuation",
+			"default_expense_account": "Cost of Goods Sold",
 		}
 
 		if self.enable_perpetual_inventory:
@@ -398,7 +399,6 @@
 					"default_inventory_account": "Stock",
 					"stock_adjustment_account": "Stock Adjustment",
 					"expenses_included_in_valuation": "Expenses Included In Valuation",
-					"default_expense_account": "Cost of Goods Sold",
 				}
 			)
 
diff --git a/erpnext/setup/doctype/employee/employee.json b/erpnext/setup/doctype/employee/employee.json
index 39e0acd..99693d9 100644
--- a/erpnext/setup/doctype/employee/employee.json
+++ b/erpnext/setup/doctype/employee/employee.json
@@ -396,7 +396,7 @@
    "collapsible": 1,
    "fieldname": "salary_information",
    "fieldtype": "Tab Break",
-   "label": "Salary Details",
+   "label": "Salary",
    "oldfieldtype": "Section Break",
    "width": "50%"
   },
@@ -428,7 +428,7 @@
    "collapsible": 1,
    "fieldname": "contact_details",
    "fieldtype": "Tab Break",
-   "label": "Contact"
+   "label": "Address & Contacts"
   },
   {
    "fieldname": "cell_number",
@@ -507,7 +507,7 @@
    "collapsible": 1,
    "fieldname": "personal_details",
    "fieldtype": "Tab Break",
-   "label": "Personal Details"
+   "label": "Personal"
   },
   {
    "fieldname": "passport_number",
@@ -701,7 +701,7 @@
    "collapsible": 1,
    "fieldname": "attendance_and_leave_details",
    "fieldtype": "Tab Break",
-   "label": "Attendance and Leave Details"
+   "label": "Attendance & Leaves"
   },
   {
    "fieldname": "column_break_44",
@@ -726,7 +726,7 @@
   {
    "fieldname": "basic_details_tab",
    "fieldtype": "Tab Break",
-   "label": "Basic Details"
+   "label": "Overview"
   },
   {
    "fieldname": "company_details_section",
@@ -810,7 +810,7 @@
  "idx": 24,
  "image_field": "image",
  "links": [],
- "modified": "2022-08-23 13:47:46.944993",
+ "modified": "2022-09-13 10:27:14.579197",
  "modified_by": "Administrator",
  "module": "Setup",
  "name": "Employee",
diff --git a/erpnext/stock/doctype/item/item.json b/erpnext/stock/doctype/item/item.json
index 76cb31d..d1d228d 100644
--- a/erpnext/stock/doctype/item/item.json
+++ b/erpnext/stock/doctype/item/item.json
@@ -795,7 +795,7 @@
   },
   {
    "fieldname": "customer_code",
-   "fieldtype": "Data",
+   "fieldtype": "Small Text",
    "hidden": 1,
    "label": "Customer Code",
    "no_copy": 1,
@@ -910,7 +910,8 @@
  "image_field": "image",
  "index_web_pages_for_search": 1,
  "links": [],
- "modified": "2022-06-15 09:02:06.177691",
+ "make_attachments_public": 1,
+ "modified": "2022-09-13 04:08:17.431731",
  "modified_by": "Administrator",
  "module": "Stock",
  "name": "Item",
diff --git a/erpnext/stock/doctype/item/item.py b/erpnext/stock/doctype/item/item.py
index 87fa72d..143fe40 100644
--- a/erpnext/stock/doctype/item/item.py
+++ b/erpnext/stock/doctype/item/item.py
@@ -945,7 +945,12 @@
 			if doctype == "Product Bundle":
 				filters = {"new_item_code": self.name}
 
-			if doctype in (
+				if linked_doc := frappe.db.get_value(
+					doctype, filters, ["new_item_code as docname"], as_dict=True
+				):
+					return linked_doc.update({"doctype": doctype})
+
+			elif doctype in (
 				"Purchase Invoice Item",
 				"Sales Invoice Item",
 			):
diff --git a/erpnext/stock/doctype/item/test_item.py b/erpnext/stock/doctype/item/test_item.py
index 3366c73..1cee553 100644
--- a/erpnext/stock/doctype/item/test_item.py
+++ b/erpnext/stock/doctype/item/test_item.py
@@ -778,6 +778,44 @@
 			item.has_batch_no = 1
 			item.save()
 
+	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):
+			item.append("customer_items", {"ref_code": frappe.generate_hash("", 120)})
+		item.save()
+		self.assertTrue(len(item.customer_code) > 140)
+
+	def test_update_is_stock_item(self):
+		# Step - 1: Create an Item with Maintain Stock enabled
+		item = make_item(properties={"is_stock_item": 1})
+
+		# Step - 2: Disable Maintain Stock
+		item.is_stock_item = 0
+		item.save()
+		item.reload()
+		self.assertEqual(item.is_stock_item, 0)
+
+		# Step - 3: Create Product Bundle
+		pb = frappe.new_doc("Product Bundle")
+		pb.new_item_code = item.name
+		pb.flags.ignore_mandatory = True
+		pb.save()
+
+		# Step - 4: Try to enable Maintain Stock, should throw a validation error
+		item.is_stock_item = 1
+		self.assertRaises(frappe.ValidationError, item.save)
+		item.reload()
+
+		# Step - 5: Delete Product Bundle
+		pb.delete()
+
+		# Step - 6: Again try to enable Maintain Stock
+		item.is_stock_item = 1
+		item.save()
+		item.reload()
+		self.assertEqual(item.is_stock_item, 1)
+
 
 def set_item_variant_settings(fields):
 	doc = frappe.get_doc("Item Variant Settings")
diff --git a/erpnext/stock/doctype/pick_list/pick_list.py b/erpnext/stock/doctype/pick_list/pick_list.py
index d31d695..adddb41 100644
--- a/erpnext/stock/doctype/pick_list/pick_list.py
+++ b/erpnext/stock/doctype/pick_list/pick_list.py
@@ -183,7 +183,7 @@
 				frappe.throw("Row #{0}: Item Code is Mandatory".format(item.idx))
 			item_code = item.item_code
 			reference = item.sales_order_item or item.material_request_item
-			key = (item_code, item.uom, reference)
+			key = (item_code, item.uom, item.warehouse, reference)
 
 			item.idx = None
 			item.name = None
diff --git a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
index 51d914d..f85c478 100644
--- a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
+++ b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
@@ -362,6 +362,12 @@
 						if credit_currency == self.company_currency
 						else flt(d.net_amount, d.precision("net_amount"))
 					)
+
+					outgoing_amount = d.base_net_amount
+					if self.is_internal_supplier and d.valuation_rate:
+						outgoing_amount = d.valuation_rate * d.stock_qty
+						credit_amount = outgoing_amount
+
 					if credit_amount:
 						account = warehouse_account[d.from_warehouse]["account"] if d.from_warehouse else stock_rbnb
 
@@ -369,7 +375,7 @@
 							gl_entries=gl_entries,
 							account=account,
 							cost_center=d.cost_center,
-							debit=-1 * flt(d.base_net_amount, d.precision("base_net_amount")),
+							debit=-1 * flt(outgoing_amount, d.precision("base_net_amount")),
 							credit=0.0,
 							remarks=remarks,
 							against_account=warehouse_account_name,
@@ -456,7 +462,7 @@
 
 					# divisional loss adjustment
 					valuation_amount_as_per_doc = (
-						flt(d.base_net_amount, d.precision("base_net_amount"))
+						flt(outgoing_amount, d.precision("base_net_amount"))
 						+ flt(d.landed_cost_voucher_amount)
 						+ flt(d.rm_supp_cost)
 						+ flt(d.item_tax_amount)
diff --git a/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py b/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py
index d0d115d..b77c3a5 100644
--- a/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py
+++ b/erpnext/stock/doctype/purchase_receipt/test_purchase_receipt.py
@@ -5,6 +5,7 @@
 import frappe
 from frappe.tests.utils import FrappeTestCase, change_settings
 from frappe.utils import add_days, cint, cstr, flt, today
+from pypika import functions as fn
 
 import erpnext
 from erpnext.accounts.doctype.account.test_account import get_inventory_account
@@ -1156,6 +1157,125 @@
 			if gle.account == account:
 				self.assertEqual(gle.credit, 50)
 
+	def test_backdated_transaction_for_internal_transfer(self):
+		from erpnext.stock.doctype.delivery_note.delivery_note import make_inter_company_purchase_receipt
+		from erpnext.stock.doctype.delivery_note.test_delivery_note import create_delivery_note
+
+		prepare_data_for_internal_transfer()
+		customer = "_Test Internal Customer 2"
+		company = "_Test Company with perpetual inventory"
+
+		from_warehouse = create_warehouse("_Test Internal From Warehouse New", company=company)
+		to_warehouse = create_warehouse("_Test Internal To Warehouse New", company=company)
+		item_doc = create_item("Test Internal Transfer Item")
+
+		target_warehouse = create_warehouse("_Test Internal GIT Warehouse New", company=company)
+
+		make_purchase_receipt(
+			item_code=item_doc.name,
+			company=company,
+			posting_date=add_days(today(), -1),
+			warehouse=from_warehouse,
+			qty=1,
+			rate=100,
+		)
+
+		dn1 = create_delivery_note(
+			item_code=item_doc.name,
+			company=company,
+			customer=customer,
+			cost_center="Main - TCP1",
+			expense_account="Cost of Goods Sold - TCP1",
+			qty=1,
+			rate=500,
+			warehouse=from_warehouse,
+			target_warehouse=target_warehouse,
+		)
+
+		self.assertEqual(dn1.items[0].rate, 100)
+
+		pr1 = make_inter_company_purchase_receipt(dn1.name)
+		pr1.items[0].warehouse = to_warehouse
+		self.assertEqual(pr1.items[0].rate, 100)
+		pr1.submit()
+
+		# Backdated purchase receipt entry, the valuation rate should be updated for DN1 and PR1
+		make_purchase_receipt(
+			item_code=item_doc.name,
+			company=company,
+			posting_date=add_days(today(), -2),
+			warehouse=from_warehouse,
+			qty=1,
+			rate=200,
+		)
+
+		dn_value = frappe.db.get_value(
+			"Stock Ledger Entry",
+			{"voucher_type": "Delivery Note", "voucher_no": dn1.name, "warehouse": target_warehouse},
+			"stock_value_difference",
+		)
+
+		self.assertEqual(abs(dn_value), 200.00)
+
+		pr_value = frappe.db.get_value(
+			"Stock Ledger Entry",
+			{"voucher_type": "Purchase Receipt", "voucher_no": pr1.name, "warehouse": to_warehouse},
+			"stock_value_difference",
+		)
+
+		self.assertEqual(abs(pr_value), 200.00)
+		pr1.load_from_db()
+
+		self.assertEqual(pr1.items[0].valuation_rate, 200)
+		self.assertEqual(pr1.items[0].rate, 100)
+
+		Gl = frappe.qb.DocType("GL Entry")
+
+		query = (
+			frappe.qb.from_(Gl)
+			.select(
+				(fn.Sum(Gl.debit) - fn.Sum(Gl.credit)).as_("value"),
+			)
+			.where((Gl.voucher_type == pr1.doctype) & (Gl.voucher_no == pr1.name))
+		).run(as_dict=True)
+
+		self.assertEqual(query[0].value, 0)
+
+
+def prepare_data_for_internal_transfer():
+	from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_internal_supplier
+	from erpnext.selling.doctype.customer.test_customer import create_internal_customer
+
+	company = "_Test Company with perpetual inventory"
+
+	create_internal_customer(
+		"_Test Internal Customer 2",
+		company,
+		company,
+	)
+
+	create_internal_supplier(
+		"_Test Internal Supplier 2",
+		company,
+		company,
+	)
+
+	if not frappe.db.get_value("Company", company, "unrealized_profit_loss_account"):
+		account = "Unrealized Profit and Loss - TCP1"
+		if not frappe.db.exists("Account", account):
+			frappe.get_doc(
+				{
+					"doctype": "Account",
+					"account_name": "Unrealized Profit and Loss",
+					"parent_account": "Direct Income - TCP1",
+					"company": company,
+					"is_group": 0,
+					"account_type": "Income Account",
+				}
+			).insert()
+
+		frappe.db.set_value("Company", company, "unrealized_profit_loss_account", account)
+
 
 def get_sl_entries(voucher_type, voucher_no):
 	return frappe.db.sql(
diff --git a/erpnext/stock/doctype/stock_entry/stock_entry.js b/erpnext/stock/doctype/stock_entry/stock_entry.js
index 1bbe570..a952a93 100644
--- a/erpnext/stock/doctype/stock_entry/stock_entry.js
+++ b/erpnext/stock/doctype/stock_entry/stock_entry.js
@@ -815,7 +815,8 @@
 			return {
 				"filters": {
 					"docstatus": 1,
-					"company": me.frm.doc.company
+					"company": me.frm.doc.company,
+					"status": ["not in", ["Completed", "Closed"]]
 				}
 			};
 		});
diff --git a/erpnext/stock/doctype/stock_entry/stock_entry.py b/erpnext/stock/doctype/stock_entry/stock_entry.py
index d709522..76bba8a 100644
--- a/erpnext/stock/doctype/stock_entry/stock_entry.py
+++ b/erpnext/stock/doctype/stock_entry/stock_entry.py
@@ -117,6 +117,7 @@
 		self.validate_work_order()
 		self.validate_bom()
 		self.validate_purchase_order()
+		self.validate_subcontracting_order()
 
 		if self.purpose in ("Manufacture", "Repack"):
 			self.mark_finished_and_scrap_items()
@@ -875,25 +876,24 @@
 						)
 					)
 
-				parent = frappe.qb.DocType("Stock Entry")
-				child = frappe.qb.DocType("Stock Entry Detail")
-
-				conditions = (
-					(parent.docstatus == 1)
-					& (child.item_code == se_item.item_code)
-					& (
-						(parent.purchase_order == self.purchase_order)
-						if self.subcontract_data.order_doctype == "Purchase Order"
-						else (parent.subcontracting_order == self.subcontracting_order)
-					)
-				)
+				se = frappe.qb.DocType("Stock Entry")
+				se_detail = frappe.qb.DocType("Stock Entry Detail")
 
 				total_supplied = (
-					frappe.qb.from_(parent)
-					.inner_join(child)
-					.on(parent.name == child.parent)
-					.select(Sum(child.transfer_qty))
-					.where(conditions)
+					frappe.qb.from_(se)
+					.inner_join(se_detail)
+					.on(se.name == se_detail.parent)
+					.select(Sum(se_detail.transfer_qty))
+					.where(
+						(se.purpose == "Send to Subcontractor")
+						& (se.docstatus == 1)
+						& (se_detail.item_code == se_item.item_code)
+						& (
+							(se.purchase_order == self.purchase_order)
+							if self.subcontract_data.order_doctype == "Purchase Order"
+							else (se.subcontracting_order == self.subcontracting_order)
+						)
+					)
 				).run()[0][0]
 
 				if flt(total_supplied, precision) > flt(total_allowed, precision):
@@ -960,6 +960,20 @@
 					)
 				)
 
+	def validate_subcontracting_order(self):
+		if self.get("subcontracting_order") and self.purpose in [
+			"Send to Subcontractor",
+			"Material Transfer",
+		]:
+			sco_status = frappe.db.get_value("Subcontracting Order", self.subcontracting_order, "status")
+
+			if sco_status == "Closed":
+				frappe.throw(
+					_("Cannot create Stock Entry against a closed Subcontracting Order {0}.").format(
+						self.subcontracting_order
+					)
+				)
+
 	def mark_finished_and_scrap_items(self):
 		if any([d.item_code for d in self.items if (d.is_finished_item and d.t_warehouse)]):
 			return
diff --git a/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py b/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
index 191c03f..7b984d3 100644
--- a/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
+++ b/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
@@ -727,12 +727,21 @@
 	sr.set_posting_time = 1
 	sr.company = args.company or "_Test Company"
 	sr.expense_account = args.expense_account or (
-		"Stock Adjustment - _TC" if frappe.get_all("Stock Ledger Entry") else "Temporary Opening - _TC"
+		(
+			frappe.get_cached_value("Company", sr.company, "stock_adjustment_account")
+			or frappe.get_cached_value(
+				"Account", {"account_type": "Stock Adjustment", "company": sr.company}, "name"
+			)
+		)
+		if frappe.get_all("Stock Ledger Entry", {"company": sr.company})
+		else frappe.get_cached_value(
+			"Account", {"account_type": "Temporary", "company": sr.company}, "name"
+		)
 	)
 	sr.cost_center = (
 		args.cost_center
 		or frappe.get_cached_value("Company", sr.company, "cost_center")
-		or "_Test Cost Center - _TC"
+		or frappe.get_cached_value("Cost Center", filters={"is_group": 0, "company": sr.company})
 	)
 
 	sr.append(
diff --git a/erpnext/stock/stock_ledger.py b/erpnext/stock/stock_ledger.py
index 3524a47..5030964 100644
--- a/erpnext/stock/stock_ledger.py
+++ b/erpnext/stock/stock_ledger.py
@@ -649,21 +649,25 @@
 
 			elif (
 				sle.voucher_type in ["Purchase Receipt", "Purchase Invoice"]
-				and sle.actual_qty > 0
+				and sle.voucher_detail_no
 				and frappe.get_cached_value(sle.voucher_type, sle.voucher_no, "is_internal_supplier")
 			):
-				sle_details = frappe.db.get_value(
-					"Stock Ledger Entry",
-					{
-						"voucher_type": sle.voucher_type,
-						"voucher_no": sle.voucher_no,
-						"dependant_sle_voucher_detail_no": sle.voucher_detail_no,
-					},
-					["stock_value_difference", "actual_qty"],
-					as_dict=1,
+				field = (
+					"delivery_note_item" if sle.voucher_type == "Purchase Receipt" else "sales_invoice_item"
+				)
+				doctype = (
+					"Delivery Note Item" if sle.voucher_type == "Purchase Receipt" else "Sales Invoice Item"
+				)
+				refernce_name = frappe.get_cached_value(
+					sle.voucher_type + " Item", sle.voucher_detail_no, field
 				)
 
-				rate = abs(sle_details.stock_value_difference / sle.actual_qty)
+				if refernce_name:
+					rate = frappe.get_cached_value(
+						doctype,
+						refernce_name,
+						"incoming_rate",
+					)
 			else:
 				if sle.voucher_type in ("Purchase Receipt", "Purchase Invoice"):
 					rate_field = "valuation_rate"
@@ -745,7 +749,12 @@
 	def update_rate_on_purchase_receipt(self, sle, outgoing_rate):
 		if frappe.db.exists(sle.voucher_type + " Item", sle.voucher_detail_no):
 			frappe.db.set_value(
-				sle.voucher_type + " Item", sle.voucher_detail_no, "base_net_rate", outgoing_rate
+				sle.voucher_type + " Item",
+				sle.voucher_detail_no,
+				{
+					"base_net_rate": outgoing_rate,
+					"valuation_rate": outgoing_rate,
+				},
 			)
 		else:
 			frappe.db.set_value(
diff --git a/erpnext/subcontracting/doctype/subcontracting_order/subcontracting_order.js b/erpnext/subcontracting/doctype/subcontracting_order/subcontracting_order.js
index 065ef39..40963f8 100644
--- a/erpnext/subcontracting/doctype/subcontracting_order/subcontracting_order.js
+++ b/erpnext/subcontracting/doctype/subcontracting_order/subcontracting_order.js
@@ -107,7 +107,7 @@
 	get_materials_from_supplier: function (frm) {
 		let sco_rm_details = [];
 
-		if (frm.doc.supplied_items && frm.doc.per_received > 0) {
+		if (frm.doc.status != "Closed" && frm.doc.supplied_items && frm.doc.per_received > 0) {
 			frm.doc.supplied_items.forEach(d => {
 				if (d.total_supplied_qty > 0 && d.total_supplied_qty != d.consumed_qty) {
 					sco_rm_details.push(d.name);
diff --git a/erpnext/subcontracting/doctype/subcontracting_order/test_subcontracting_order.py b/erpnext/subcontracting/doctype/subcontracting_order/test_subcontracting_order.py
index 9385568..d054ce0 100644
--- a/erpnext/subcontracting/doctype/subcontracting_order/test_subcontracting_order.py
+++ b/erpnext/subcontracting/doctype/subcontracting_order/test_subcontracting_order.py
@@ -502,6 +502,35 @@
 
 		set_backflush_based_on("BOM")
 
+	def test_get_materials_from_supplier(self):
+		# Create SCO
+		sco = get_subcontracting_order()
+
+		# Transfer RM
+		rm_items = get_rm_items(sco.supplied_items)
+		itemwise_details = make_stock_in_entry(rm_items=rm_items)
+		make_stock_transfer_entry(
+			sco_no=sco.name,
+			rm_items=rm_items,
+			itemwise_details=copy.deepcopy(itemwise_details),
+		)
+
+		# Create SCR (Partial)
+		scr = make_subcontracting_receipt(sco.name)
+		scr.items[0].qty -= 5
+		scr.save()
+		scr.submit()
+
+		# Get RM from Supplier
+		ste = get_materials_from_supplier(sco.name, [d.name for d in sco.supplied_items])
+		ste.save()
+		ste.submit()
+
+		sco.load_from_db()
+
+		self.assertEqual(sco.status, "Closed")
+		self.assertEqual(sco.supplied_items[0].returned_qty, 5)
+
 
 def create_subcontracting_order(**args):
 	args = frappe._dict(args)
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 e49f212..7f4e9ef 100644
--- a/erpnext/support/doctype/service_level_agreement/service_level_agreement.py
+++ b/erpnext/support/doctype/service_level_agreement/service_level_agreement.py
@@ -776,6 +776,9 @@
 	if not parent.meta.has_field("service_level_agreement"):
 		return
 
+	if not parent.get("service_level_agreement"):
+		return
+
 	if (
 		doc.sent_or_received == "Received"  # a reply is received
 		and parent.get("status") == "Open"  # issue status is set as open from communication.py
diff --git a/license.txt b/license.txt
index a238a97..f288702 100644
--- a/license.txt
+++ b/license.txt
@@ -1,205 +1,200 @@
-### GNU GENERAL PUBLIC LICENSE
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
 
-Version 3, 29 June 2007
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
 
-Copyright (C) 2007 Free Software Foundation, Inc.
-<http://fsf.org/>
+                            Preamble
 
-Everyone is permitted to copy and distribute verbatim copies of this
-license document, but changing it is not allowed.
-
-### Preamble
-
-The GNU General Public License is a free, copyleft license for
+  The GNU General Public License is a free, copyleft license for
 software and other kinds of works.
 
-The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
-the GNU General Public License is intended to guarantee your freedom
-to share and change all versions of a program--to make sure it remains
-free software for all its users. We, the Free Software Foundation, use
-the GNU General Public License for most of our software; it applies
-also to any other work released this way by its authors. You can apply
-it to your programs, too.
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
 
-When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
 have the freedom to distribute copies of free software (and charge for
 them if you wish), that you receive source code or can get it if you
 want it, that you can change the software or use pieces of it in new
 free programs, and that you know you can do these things.
 
-To protect your rights, we need to prevent others from denying you
-these rights or asking you to surrender the rights. Therefore, you
-have certain responsibilities if you distribute copies of the
-software, or if you modify it: responsibilities to respect the freedom
-of others.
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
 
-For example, if you distribute copies of such a program, whether
+  For example, if you distribute copies of such a program, whether
 gratis or for a fee, you must pass on to the recipients the same
-freedoms that you received. You must make sure that they, too, receive
-or can get the source code. And you must show them these terms so they
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
 know their rights.
 
-Developers that use the GNU GPL protect your rights with two steps:
+  Developers that use the GNU GPL protect your rights with two steps:
 (1) assert copyright on the software, and (2) offer you this License
 giving you legal permission to copy, distribute and/or modify it.
 
-For the developers' and authors' protection, the GPL clearly explains
-that there is no warranty for this free software. For both users' and
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
 authors' sake, the GPL requires that modified versions be marked as
 changed, so that their problems will not be attributed erroneously to
 authors of previous versions.
 
-Some devices are designed to deny users access to install or run
-modified versions of the software inside them, although the
-manufacturer can do so. This is fundamentally incompatible with the
-aim of protecting users' freedom to change the software. The
-systematic pattern of such abuse occurs in the area of products for
-individuals to use, which is precisely where it is most unacceptable.
-Therefore, we have designed this version of the GPL to prohibit the
-practice for those products. If such problems arise substantially in
-other domains, we stand ready to extend this provision to those
-domains in future versions of the GPL, as needed to protect the
-freedom of users.
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
 
-Finally, every program is threatened constantly by software patents.
+  Finally, every program is threatened constantly by software patents.
 States should not allow patents to restrict development and use of
-software on general-purpose computers, but in those that do, we wish
-to avoid the special danger that patents applied to a free program
-could make it effectively proprietary. To prevent this, the GPL
-assures that patents cannot be used to render the program non-free.
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
 
-The precise terms and conditions for copying, distribution and
+  The precise terms and conditions for copying, distribution and
 modification follow.
 
-### TERMS AND CONDITIONS
+                       TERMS AND CONDITIONS
 
-#### 0. Definitions.
+  0. Definitions.
 
-"This License" refers to version 3 of the GNU General Public License.
+  "This License" refers to version 3 of the GNU General Public License.
 
-"Copyright" also means copyright-like laws that apply to other kinds
-of works, such as semiconductor masks.
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
 
-"The Program" refers to any copyrightable work licensed under this
-License. Each licensee is addressed as "you". "Licensees" and
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
 "recipients" may be individuals or organizations.
 
-To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of
-an exact copy. The resulting work is called a "modified version" of
-the earlier work or a work "based on" the earlier work.
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
 
-A "covered work" means either the unmodified Program or a work based
+  A "covered work" means either the unmodified Program or a work based
 on the Program.
 
-To "propagate" a work means to do anything with it that, without
+  To "propagate" a work means to do anything with it that, without
 permission, would make you directly or secondarily liable for
 infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy. Propagation includes copying,
+computer or modifying a private copy.  Propagation includes copying,
 distribution (with or without modification), making available to the
 public, and in some countries other activities as well.
 
-To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies. Mere interaction with a user
-through a computer network, with no transfer of a copy, is not
-conveying.
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
 
-An interactive user interface displays "Appropriate Legal Notices" to
-the extent that it includes a convenient and prominently visible
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
 feature that (1) displays an appropriate copyright notice, and (2)
 tells the user that there is no warranty for the work (except to the
 extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License. If
+work under this License, and how to view a copy of this License.  If
 the interface presents a list of user commands or options, such as a
 menu, a prominent item in the list meets this criterion.
 
-#### 1. Source Code.
+  1. Source Code.
 
-The "source code" for a work means the preferred form of the work for
-making modifications to it. "Object code" means any non-source form of
-a work.
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
 
-A "Standard Interface" means an interface that either is an official
+  A "Standard Interface" means an interface that either is an official
 standard defined by a recognized standards body, or, in the case of
 interfaces specified for a particular programming language, one that
 is widely used among developers working in that language.
 
-The "System Libraries" of an executable work include anything, other
+  The "System Libraries" of an executable work include anything, other
 than the work as a whole, that (a) is included in the normal form of
 packaging a Major Component, but which is not part of that Major
 Component, and (b) serves only to enable use of the work with that
 Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form. A
+implementation is available to the public in source code form.  A
 "Major Component", in this context, means a major essential component
 (kernel, window system, and so on) of the specific operating system
 (if any) on which the executable work runs, or a compiler used to
 produce the work, or an object code interpreter used to run it.
 
-The "Corresponding Source" for a work in object code form means all
+  The "Corresponding Source" for a work in object code form means all
 the source code needed to generate, install, and (for an executable
 work) run the object code and to modify the work, including scripts to
-control those activities. However, it does not include the work's
+control those activities.  However, it does not include the work's
 System Libraries, or general-purpose tools or generally available free
 programs which are used unmodified in performing those activities but
-which are not part of the work. For example, Corresponding Source
+which are not part of the work.  For example, Corresponding Source
 includes interface definition files associated with source files for
 the work, and the source code for shared libraries and dynamically
 linked subprograms that the work is specifically designed to require,
 such as by intimate data communication or control flow between those
 subprograms and other parts of the work.
 
-The Corresponding Source need not include anything that users can
-regenerate automatically from other parts of the Corresponding Source.
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
 
-The Corresponding Source for a work in source code form is that same
-work.
+  The Corresponding Source for a work in source code form is that
+same work.
 
-#### 2. Basic Permissions.
+  2. Basic Permissions.
 
-All rights granted under this License are granted for the term of
+  All rights granted under this License are granted for the term of
 copyright on the Program, and are irrevocable provided the stated
-conditions are met. This License explicitly affirms your unlimited
-permission to run the unmodified Program. The output from running a
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
 covered work is covered by this License only if the output, given its
-content, constitutes a covered work. This License acknowledges your
+content, constitutes a covered work.  This License acknowledges your
 rights of fair use or other equivalent, as provided by copyright law.
 
-You may make, run and propagate covered works that you do not convey,
-without conditions so long as your license otherwise remains in force.
-You may convey covered works to others for the sole purpose of having
-them make modifications exclusively for you, or provide you with
-facilities for running those works, provided that you comply with the
-terms of this License in conveying all material for which you do not
-control copyright. Those thus making or running the covered works for
-you must do so exclusively on your behalf, under your direction and
-control, on terms that prohibit them from making any copies of your
-copyrighted material outside their relationship with you.
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
 
-Conveying under any other circumstances is permitted solely under the
-conditions stated below. Sublicensing is not allowed; section 10 makes
-it unnecessary.
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
 
-#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
 
-No covered work shall be deemed part of an effective technological
+  No covered work shall be deemed part of an effective technological
 measure under any applicable law fulfilling obligations under article
 11 of the WIPO copyright treaty adopted on 20 December 1996, or
 similar laws prohibiting or restricting circumvention of such
 measures.
 
-When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such
-circumvention is effected by exercising rights under this License with
-respect to the covered work, and you disclaim any intention to limit
-operation or modification of the work as a means of enforcing, against
-the work's users, your or third parties' legal rights to forbid
-circumvention of technological measures.
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
 
-#### 4. Conveying Verbatim Copies.
+  4. Conveying Verbatim Copies.
 
-You may convey verbatim copies of the Program's source code as you
+  You may convey verbatim copies of the Program's source code as you
 receive it, in any medium, provided that you conspicuously and
 appropriately publish on each copy an appropriate copyright notice;
 keep intact all notices stating that this License and any
@@ -207,56 +202,59 @@
 keep intact all notices of the absence of any warranty; and give all
 recipients a copy of this License along with the Program.
 
-You may charge any price or no price for each copy that you convey,
+  You may charge any price or no price for each copy that you convey,
 and you may offer support or warranty protection for a fee.
 
-#### 5. Conveying Modified Source Versions.
+  5. Conveying Modified Source Versions.
 
-You may convey a work based on the Program, or the modifications to
+  You may convey a work based on the Program, or the modifications to
 produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these
-conditions:
+terms of section 4, provided that you also meet all of these conditions:
 
--   a) The work must carry prominent notices stating that you modified
+    a) The work must carry prominent notices stating that you modified
     it, and giving a relevant date.
--   b) The work must carry prominent notices stating that it is
-    released under this License and any conditions added under
-    section 7. This requirement modifies the requirement in section 4
-    to "keep intact all notices".
--   c) You must license the entire work, as a whole, under this
-    License to anyone who comes into possession of a copy. This
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
     License will therefore apply, along with any applicable section 7
     additional terms, to the whole of the work, and all its parts,
-    regardless of how they are packaged. This License gives no
+    regardless of how they are packaged.  This License gives no
     permission to license the work in any other way, but it does not
     invalidate such permission if you have separately received it.
--   d) If the work has interactive user interfaces, each must display
+
+    d) If the work has interactive user interfaces, each must display
     Appropriate Legal Notices; however, if the Program has interactive
     interfaces that do not display Appropriate Legal Notices, your
     work need not make them do so.
 
-A compilation of a covered work with other separate and independent
+  A compilation of a covered work with other separate and independent
 works, which are not by their nature extensions of the covered work,
 and which are not combined with it such as to form a larger program,
 in or on a volume of a storage or distribution medium, is called an
 "aggregate" if the compilation and its resulting copyright are not
 used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit. Inclusion of a covered work
+beyond what the individual works permit.  Inclusion of a covered work
 in an aggregate does not cause this License to apply to the other
 parts of the aggregate.
 
-#### 6. Conveying Non-Source Forms.
+  6. Conveying Non-Source Forms.
 
-You may convey a covered work in object code form under the terms of
-sections 4 and 5, provided that you also convey the machine-readable
-Corresponding Source under the terms of this License, in one of these
-ways:
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
 
--   a) Convey the object code in, or embodied in, a physical product
+    a) Convey the object code in, or embodied in, a physical product
     (including a physical distribution medium), accompanied by the
     Corresponding Source fixed on a durable physical medium
     customarily used for software interchange.
--   b) Convey the object code in, or embodied in, a physical product
+
+    b) Convey the object code in, or embodied in, a physical product
     (including a physical distribution medium), accompanied by a
     written offer, valid for at least three years and valid for as
     long as you offer spare parts or customer support for that product
@@ -265,190 +263,196 @@
     product that is covered by this License, on a durable physical
     medium customarily used for software interchange, for a price no
     more than your reasonable cost of physically performing this
-    conveying of source, or (2) access to copy the Corresponding
-    Source from a network server at no charge.
--   c) Convey individual copies of the object code with a copy of the
-    written offer to provide the Corresponding Source. This
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
     alternative is allowed only occasionally and noncommercially, and
     only if you received the object code with such an offer, in accord
     with subsection 6b.
--   d) Convey the object code by offering access from a designated
+
+    d) Convey the object code by offering access from a designated
     place (gratis or for a charge), and offer equivalent access to the
     Corresponding Source in the same way through the same place at no
-    further charge. You need not require recipients to copy the
-    Corresponding Source along with the object code. If the place to
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
     copy the object code is a network server, the Corresponding Source
     may be on a different server (operated by you or a third party)
     that supports equivalent copying facilities, provided you maintain
     clear directions next to the object code saying where to find the
-    Corresponding Source. Regardless of what server hosts the
+    Corresponding Source.  Regardless of what server hosts the
     Corresponding Source, you remain obligated to ensure that it is
     available for as long as needed to satisfy these requirements.
--   e) Convey the object code using peer-to-peer transmission,
-    provided you inform other peers where the object code and
-    Corresponding Source of the work are being offered to the general
-    public at no charge under subsection 6d.
 
-A separable portion of the object code, whose source code is excluded
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
 from the Corresponding Source as a System Library, need not be
 included in conveying the object code work.
 
-A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal,
-family, or household purposes, or (2) anything designed or sold for
-incorporation into a dwelling. In determining whether a product is a
-consumer product, doubtful cases shall be resolved in favor of
-coverage. For a particular product received by a particular user,
-"normally used" refers to a typical or common use of that class of
-product, regardless of the status of the particular user or of the way
-in which the particular user actually uses, or expects or is expected
-to use, the product. A product is a consumer product regardless of
-whether the product has substantial commercial, industrial or
-non-consumer uses, unless such uses represent the only significant
-mode of use of the product.
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
 
-"Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to
-install and execute modified versions of a covered work in that User
-Product from a modified version of its Corresponding Source. The
-information must suffice to ensure that the continued functioning of
-the modified object code is in no case prevented or interfered with
-solely because modification has been made.
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
 
-If you convey an object code work under this section in, or with, or
+  If you convey an object code work under this section in, or with, or
 specifically for use in, a User Product, and the conveying occurs as
 part of a transaction in which the right of possession and use of the
 User Product is transferred to the recipient in perpetuity or for a
 fixed term (regardless of how the transaction is characterized), the
 Corresponding Source conveyed under this section must be accompanied
-by the Installation Information. But this requirement does not apply
+by the Installation Information.  But this requirement does not apply
 if neither you nor any third party retains the ability to install
 modified object code on the User Product (for example, the work has
 been installed in ROM).
 
-The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or
-updates for a work that has been modified or installed by the
-recipient, or for the User Product in which it has been modified or
-installed. Access to a network may be denied when the modification
-itself materially and adversely affects the operation of the network
-or violates the rules and protocols for communication across the
-network.
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
 
-Corresponding Source conveyed, and Installation Information provided,
+  Corresponding Source conveyed, and Installation Information provided,
 in accord with this section must be in a format that is publicly
 documented (and with an implementation available to the public in
 source code form), and must require no special password or key for
 unpacking, reading or copying.
 
-#### 7. Additional Terms.
+  7. Additional Terms.
 
-"Additional permissions" are terms that supplement the terms of this
+  "Additional permissions" are terms that supplement the terms of this
 License by making exceptions from one or more of its conditions.
 Additional permissions that are applicable to the entire Program shall
 be treated as though they were included in this License, to the extent
-that they are valid under applicable law. If additional permissions
+that they are valid under applicable law.  If additional permissions
 apply only to part of the Program, that part may be used separately
 under those permissions, but the entire Program remains governed by
 this License without regard to the additional permissions.
 
-When you convey a copy of a covered work, you may at your option
+  When you convey a copy of a covered work, you may at your option
 remove any additional permissions from that copy, or from any part of
-it. (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.) You may place
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
 additional permissions on material, added by you to a covered work,
 for which you have or can give appropriate copyright permission.
 
-Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders
-of that material) supplement the terms of this License with terms:
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
 
--   a) Disclaiming warranty or limiting liability differently from the
+    a) Disclaiming warranty or limiting liability differently from the
     terms of sections 15 and 16 of this License; or
--   b) Requiring preservation of specified reasonable legal notices or
+
+    b) Requiring preservation of specified reasonable legal notices or
     author attributions in that material or in the Appropriate Legal
     Notices displayed by works containing it; or
--   c) Prohibiting misrepresentation of the origin of that material,
-    or requiring that modified versions of such material be marked in
-    reasonable ways as different from the original version; or
--   d) Limiting the use for publicity purposes of names of licensors
-    or authors of the material; or
--   e) Declining to grant rights under trademark law for use of some
-    trade names, trademarks, or service marks; or
--   f) Requiring indemnification of licensors and authors of that
-    material by anyone who conveys the material (or modified versions
-    of it) with contractual assumptions of liability to the recipient,
-    for any liability that these contractual assumptions directly
-    impose on those licensors and authors.
 
-All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10. If the Program as you
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
 received it, or any part of it, contains a notice stating that it is
 governed by this License along with a term that is a further
-restriction, you may remove that term. If a license document contains
+restriction, you may remove that term.  If a license document contains
 a further restriction but permits relicensing or conveying under this
 License, you may add to a covered work material governed by the terms
 of that license document, provided that the further restriction does
 not survive such relicensing or conveying.
 
-If you add terms to a covered work in accord with this section, you
+  If you add terms to a covered work in accord with this section, you
 must place, in the relevant source files, a statement of the
 additional terms that apply to those files, or a notice indicating
 where to find the applicable terms.
 
-Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions; the
-above requirements apply either way.
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
 
-#### 8. Termination.
+  8. Termination.
 
-You may not propagate or modify a covered work except as expressly
-provided under this License. Any attempt otherwise to propagate or
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
 modify it is void, and will automatically terminate your rights under
 this License (including any patent licenses granted under the third
 paragraph of section 11).
 
-However, if you cease all violation of this License, then your license
-from a particular copyright holder is reinstated (a) provisionally,
-unless and until the copyright holder explicitly and finally
-terminates your license, and (b) permanently, if the copyright holder
-fails to notify you of the violation by some reasonable means prior to
-60 days after the cessation.
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
 
-Moreover, your license from a particular copyright holder is
+  Moreover, your license from a particular copyright holder is
 reinstated permanently if the copyright holder notifies you of the
 violation by some reasonable means, this is the first time you have
 received notice of violation of this License (for any work) from that
 copyright holder, and you cure the violation prior to 30 days after
 your receipt of the notice.
 
-Termination of your rights under this section does not terminate the
+  Termination of your rights under this section does not terminate the
 licenses of parties who have received copies or rights from you under
-this License. If your rights have been terminated and not permanently
+this License.  If your rights have been terminated and not permanently
 reinstated, you do not qualify to receive new licenses for the same
 material under section 10.
 
-#### 9. Acceptance Not Required for Having Copies.
+  9. Acceptance Not Required for Having Copies.
 
-You are not required to accept this License in order to receive or run
-a copy of the Program. Ancillary propagation of a covered work
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
 occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance. However,
+to receive a copy likewise does not require acceptance.  However,
 nothing other than this License grants you permission to propagate or
-modify any covered work. These actions infringe copyright if you do
-not accept this License. Therefore, by modifying or propagating a
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
 covered work, you indicate your acceptance of this License to do so.
 
-#### 10. Automatic Licensing of Downstream Recipients.
+  10. Automatic Licensing of Downstream Recipients.
 
-Each time you convey a covered work, the recipient automatically
+  Each time you convey a covered work, the recipient automatically
 receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License. You are not responsible
+propagate that work, subject to this License.  You are not responsible
 for enforcing compliance by third parties with this License.
 
-An "entity transaction" is a transaction transferring control of an
+  An "entity transaction" is a transaction transferring control of an
 organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations. If propagation of a covered
+organization, or merging organizations.  If propagation of a covered
 work results from an entity transaction, each party to that
 transaction who receives a copy of the work also receives whatever
 licenses to the work the party's predecessor in interest had or could
@@ -456,43 +460,43 @@
 Corresponding Source of the work from the predecessor in interest, if
 the predecessor has it or can get it with reasonable efforts.
 
-You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License. For example, you may
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
 not impose a license fee, royalty, or other charge for exercise of
 rights granted under this License, and you may not initiate litigation
 (including a cross-claim or counterclaim in a lawsuit) alleging that
 any patent claim is infringed by making, using, selling, offering for
 sale, or importing the Program or any portion of it.
 
-#### 11. Patents.
+  11. Patents.
 
-A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based. The
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
 work thus licensed is called the contributor's "contributor version".
 
-A contributor's "essential patent claims" are all patent claims owned
-or controlled by the contributor, whether already acquired or
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
 hereafter acquired, that would be infringed by some manner, permitted
 by this License, of making, using, or selling its contributor version,
 but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version. For
+consequence of further modification of the contributor version.  For
 purposes of this definition, "control" includes the right to grant
 patent sublicenses in a manner consistent with the requirements of
 this License.
 
-Each contributor grants you a non-exclusive, worldwide, royalty-free
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
 patent license under the contributor's essential patent claims, to
 make, use, sell, offer for sale, import and otherwise run, modify and
 propagate the contents of its contributor version.
 
-In the following three paragraphs, a "patent license" is any express
+  In the following three paragraphs, a "patent license" is any express
 agreement or commitment, however denominated, not to enforce a patent
 (such as an express permission to practice a patent or covenant not to
-sue for patent infringement). To "grant" such a patent license to a
+sue for patent infringement).  To "grant" such a patent license to a
 party means to make such an agreement or commitment not to enforce a
 patent against the party.
 
-If you convey a covered work, knowingly relying on a patent license,
+  If you convey a covered work, knowingly relying on a patent license,
 and the Corresponding Source of the work is not available for anyone
 to copy, free of charge and under the terms of this License, through a
 publicly available network server or other readily accessible means,
@@ -500,13 +504,13 @@
 available, or (2) arrange to deprive yourself of the benefit of the
 patent license for this particular work, or (3) arrange, in a manner
 consistent with the requirements of this License, to extend the patent
-license to downstream recipients. "Knowingly relying" means you have
+license to downstream recipients.  "Knowingly relying" means you have
 actual knowledge that, but for the patent license, your conveying the
 covered work in a country, or your recipient's use of the covered work
 in a country, would infringe one or more identifiable patents in that
 country that you have reason to believe are valid.
 
-If, pursuant to or in connection with a single transaction or
+  If, pursuant to or in connection with a single transaction or
 arrangement, you convey, or propagate by procuring conveyance of, a
 covered work, and grant a patent license to some of the parties
 receiving the covered work authorizing them to use, propagate, modify
@@ -514,162 +518,157 @@
 you grant is automatically extended to all recipients of the covered
 work and works based on it.
 
-A patent license is "discriminatory" if it does not include within the
-scope of its coverage, prohibits the exercise of, or is conditioned on
-the non-exercise of one or more of the rights that are specifically
-granted under this License. You may not convey a covered work if you
-are a party to an arrangement with a third party that is in the
-business of distributing software, under which you make payment to the
-third party based on the extent of your activity of conveying the
-work, and under which the third party grants, to any of the parties
-who would receive the covered work from you, a discriminatory patent
-license (a) in connection with copies of the covered work conveyed by
-you (or copies made from those copies), or (b) primarily for and in
-connection with specific products or compilations that contain the
-covered work, unless you entered into that arrangement, or that patent
-license was granted, prior to 28 March 2007.
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
 
-Nothing in this License shall be construed as excluding or limiting
+  Nothing in this License shall be construed as excluding or limiting
 any implied license or other defenses to infringement that may
 otherwise be available to you under applicable patent law.
 
-#### 12. No Surrender of Others' Freedom.
+  12. No Surrender of Others' Freedom.
 
-If conditions are imposed on you (whether by court order, agreement or
+  If conditions are imposed on you (whether by court order, agreement or
 otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under
-this License and any other pertinent obligations, then as a
-consequence you may not convey it at all. For example, if you agree to
-terms that obligate you to collect a royalty for further conveying
-from those to whom you convey the Program, the only way you could
-satisfy both those terms and this License would be to refrain entirely
-from conveying the Program.
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
 
-#### 13. Use with the GNU Affero General Public License.
+  13. Use with the GNU Affero General Public License.
 
-Notwithstanding any other provision of this License, you have
+  Notwithstanding any other provision of this License, you have
 permission to link or combine any covered work with a work licensed
 under version 3 of the GNU Affero General Public License into a single
-combined work, and to convey the resulting work. The terms of this
+combined work, and to convey the resulting work.  The terms of this
 License will continue to apply to the part which is the covered work,
 but the special requirements of the GNU Affero General Public License,
 section 13, concerning interaction through a network will apply to the
 combination as such.
 
-#### 14. Revised Versions of this License.
+  14. Revised Versions of this License.
 
-The Free Software Foundation may publish revised and/or new versions
-of the GNU General Public License from time to time. Such new versions
-will be similar in spirit to the present version, but may differ in
-detail to address new problems or concerns.
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
 
-Each version is given a distinguishing version number. If the Program
-specifies that a certain numbered version of the GNU General Public
-License "or any later version" applies to it, you have the option of
-following the terms and conditions either of that numbered version or
-of any later version published by the Free Software Foundation. If the
-Program does not specify a version number of the GNU General Public
-License, you may choose any version ever published by the Free
-Software Foundation.
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
 
-If the Program specifies that a proxy can decide which future versions
-of the GNU General Public License can be used, that proxy's public
-statement of acceptance of a version permanently authorizes you to
-choose that version for the Program.
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
 
-Later license versions may give you additional or different
-permissions. However, no additional obligations are imposed on any
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
 author or copyright holder as a result of your choosing to follow a
 later version.
 
-#### 15. Disclaimer of Warranty.
+  15. Disclaimer of Warranty.
 
-THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
-WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
-PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
-DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
-CORRECTION.
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
 
-#### 16. Limitation of Liability.
+  16. Limitation of Liability.
 
-IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
-CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
-ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
-NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
-LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
-TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
-PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
 
-#### 17. Interpretation of Sections 15 and 16.
+  17. Interpretation of Sections 15 and 16.
 
-If the disclaimer of warranty and limitation of liability provided
+  If the disclaimer of warranty and limitation of liability provided
 above cannot be given local legal effect according to their terms,
 reviewing courts shall apply local law that most closely approximates
 an absolute waiver of all civil liability in connection with the
 Program, unless a warranty or assumption of liability accompanies a
 copy of the Program in return for a fee.
 
-END OF TERMS AND CONDITIONS
+                     END OF TERMS AND CONDITIONS
 
-### How to Apply These Terms to Your New Programs
+            How to Apply These Terms to Your New Programs
 
-If you develop a new program, and you want it to be of the greatest
+  If you develop a new program, and you want it to be of the greatest
 possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these
-terms.
+free software which everyone can redistribute and change under these terms.
 
-To do so, attach the following notices to the program. It is safest to
-attach them to the start of each source file to most effectively state
-the exclusion of warranty; and each file should have at least the
-"copyright" line and a pointer to where the full notice is found.
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
 
-        <one line to give the program's name and a brief idea of what it does.>
-        Copyright (C) <year>  <name of author>
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
 
-        This program is free software: you can redistribute it and/or modify
-        it under the terms of the GNU General Public License as published by
-        the Free Software Foundation, either version 3 of the License, or
-        (at your option) any later version.
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
 
-        This program is distributed in the hope that it will be useful,
-        but WITHOUT ANY WARRANTY; without even the implied warranty of
-        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-        GNU General Public License for more details.
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
 
-        You should have received a copy of the GNU General Public License
-        along with this program.  If not, see <http://www.gnu.org/licenses/>.
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
 
-Also add information on how to contact you by electronic and paper
-mail.
+Also add information on how to contact you by electronic and paper mail.
 
-If the program does terminal interaction, make it output a short
+  If the program does terminal interaction, make it output a short
 notice like this when it starts in an interactive mode:
 
-        <program>  Copyright (C) <year>  <name of author>
-        This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
-        This is free software, and you are welcome to redistribute it
-        under certain conditions; type `show c' for details.
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
 
-The hypothetical commands \`show w' and \`show c' should show the
-appropriate parts of the General Public License. Of course, your
-program's commands might be different; for a GUI interface, you would
-use an "about box".
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
 
-You should also get your employer (if you work as a programmer) or
-institute, if any, to sign a "copyright disclaimer" for the program, if
-necessary. For more information on this, and how to apply and follow
-the GNU GPL, see <http://www.gnu.org/licenses/>.
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
 
-The GNU General Public License does not permit incorporating your
-program into proprietary programs. If your program is a subroutine
-library, you may consider it more useful to permit linking proprietary
-applications with the library. If this is what you want to do, use the
-GNU Lesser General Public License instead of this License. But first,
-please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.
\ No newline at end of file
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.