Merge pull request #32866 from ruthra-kumar/gross_profit_fix_buying_amount

fix: incorrect buying amount on Gross Profit
diff --git a/.github/workflows/server-tests-mariadb.yml b/.github/workflows/server-tests-mariadb.yml
index ed731b8..b40faa7 100644
--- a/.github/workflows/server-tests-mariadb.yml
+++ b/.github/workflows/server-tests-mariadb.yml
@@ -59,7 +59,7 @@
       - name: Setup Python
         uses: actions/setup-python@v2
         with:
-          python-version: '3.10'
+          python-version: '3.11'
 
       - name: Check for valid Python & Merge Conflicts
         run: |
diff --git a/erpnext/accounts/doctype/chart_of_accounts_importer/chart_of_accounts_importer.py b/erpnext/accounts/doctype/chart_of_accounts_importer/chart_of_accounts_importer.py
index 01bf1c2..83c206a 100644
--- a/erpnext/accounts/doctype/chart_of_accounts_importer/chart_of_accounts_importer.py
+++ b/erpnext/accounts/doctype/chart_of_accounts_importer/chart_of_accounts_importer.py
@@ -52,7 +52,7 @@
 	if parent_company and (not allow_account_creation_against_child_company):
 		msg = _("{} is a child company.").format(frappe.bold(company)) + " "
 		msg += _("Please import accounts against parent company or enable {} in company master.").format(
-			frappe.bold("Allow Account Creation Against Child Company")
+			frappe.bold(_("Allow Account Creation Against Child Company"))
 		)
 		frappe.throw(msg, title=_("Wrong Company"))
 
diff --git a/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.json b/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.json
index 83e6370..16602d3 100644
--- a/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.json
+++ b/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.json
@@ -23,6 +23,7 @@
   "fetch_customers",
   "column_break_6",
   "primary_mandatory",
+  "show_net_values_in_party_account",
   "column_break_17",
   "customers",
   "preferences",
@@ -291,10 +292,16 @@
    "fieldname": "include_break",
    "fieldtype": "Check",
    "label": "Page Break After Each SoA"
+  },
+  {
+   "default": "0",
+   "fieldname": "show_net_values_in_party_account",
+   "fieldtype": "Check",
+   "label": "Show Net Values in Party Account"
   }
  ],
  "links": [],
- "modified": "2022-10-17 17:47:08.662475",
+ "modified": "2022-11-10 17:44:17.165991",
  "modified_by": "Administrator",
  "module": "Accounts",
  "name": "Process Statement Of Accounts",
diff --git a/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.py b/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.py
index c6b0c57..a48c027 100644
--- a/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.py
+++ b/erpnext/accounts/doctype/process_statement_of_accounts/process_statement_of_accounts.py
@@ -95,6 +95,7 @@
 				"show_opening_entries": 0,
 				"include_default_book_entries": 0,
 				"tax_id": tax_id if tax_id else None,
+				"show_net_values_in_party_account": doc.show_net_values_in_party_account,
 			}
 		)
 		col, res = get_soa(filters)
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
index 882a374..9a31aaf 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
@@ -1410,7 +1410,7 @@
 			self.repost_future_sle_and_gle()
 
 		self.update_project()
-		frappe.db.set(self, "status", "Cancelled")
+		self.db_set("status", "Cancelled")
 
 		unlink_inter_company_doc(self.doctype, self.name, self.inter_company_invoice_reference)
 		self.ignore_linked_doctypes = (
@@ -1463,6 +1463,7 @@
 
 	def update_billing_status_in_pr(self, update_modified=True):
 		updated_pr = []
+		po_details = []
 		for d in self.get("items"):
 			if d.pr_detail:
 				billed_amt = frappe.db.sql(
@@ -1480,7 +1481,10 @@
 				)
 				updated_pr.append(d.purchase_receipt)
 			elif d.po_detail:
-				updated_pr += update_billed_amount_based_on_po(d.po_detail, update_modified)
+				po_details.append(d.po_detail)
+
+		if po_details:
+			updated_pr += update_billed_amount_based_on_po(po_details, update_modified)
 
 		for pr in set(updated_pr):
 			from erpnext.stock.doctype.purchase_receipt.purchase_receipt import update_billing_percentage
diff --git a/erpnext/accounts/doctype/repost_payment_ledger/__init__.py b/erpnext/accounts/doctype/repost_payment_ledger/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/accounts/doctype/repost_payment_ledger/__init__.py
diff --git a/erpnext/accounts/doctype/repost_payment_ledger/repost_payment_ledger.js b/erpnext/accounts/doctype/repost_payment_ledger/repost_payment_ledger.js
new file mode 100644
index 0000000..6801408
--- /dev/null
+++ b/erpnext/accounts/doctype/repost_payment_ledger/repost_payment_ledger.js
@@ -0,0 +1,53 @@
+// Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
+// For license information, please see license.txt
+
+frappe.ui.form.on('Repost Payment Ledger', {
+	setup: function(frm) {
+		frm.set_query("voucher_type", () => {
+			return {
+				filters: {
+					name: ['in', ['Purchase Invoice', 'Sales Invoice', 'Payment Entry', 'Journal Entry']]
+				}
+			};
+		});
+
+		frm.fields_dict['repost_vouchers'].grid.get_field('voucher_type').get_query = function(doc) {
+			return {
+				filters: {
+					name: ['in', ['Purchase Invoice', 'Sales Invoice', 'Payment Entry', 'Journal Entry']]
+				}
+			}
+		}
+
+		frm.fields_dict['repost_vouchers'].grid.get_field('voucher_no').get_query = function(doc) {
+			if (doc.company) {
+				return {
+					filters: {
+						company: doc.company,
+						docstatus: 1
+					}
+				}
+			}
+		}
+
+	},
+	refresh: function(frm) {
+
+		if (frm.doc.docstatus==1 && ['Queued', 'Failed'].find(x => x == frm.doc.repost_status)) {
+			frm.set_intro(__("Use 'Repost in background' button to trigger background job. Job can only be triggered when document is in Queued or Failed status."));
+			var btn_label = __("Repost in background")
+
+			frm.add_custom_button(btn_label, () => {
+				frappe.call({
+					method: 'erpnext.accounts.doctype.repost_payment_ledger.repost_payment_ledger.execute_repost_payment_ledger',
+					args: {
+						docname: frm.doc.name,
+					}
+				});
+				frappe.msgprint(__('Reposting in the background.'));
+			});
+		}
+
+	}
+});
+
diff --git a/erpnext/accounts/doctype/repost_payment_ledger/repost_payment_ledger.json b/erpnext/accounts/doctype/repost_payment_ledger/repost_payment_ledger.json
new file mode 100644
index 0000000..5175fd1
--- /dev/null
+++ b/erpnext/accounts/doctype/repost_payment_ledger/repost_payment_ledger.json
@@ -0,0 +1,159 @@
+{
+ "actions": [],
+ "allow_rename": 1,
+ "creation": "2022-10-19 21:59:33.553852",
+ "doctype": "DocType",
+ "editable_grid": 1,
+ "engine": "InnoDB",
+ "field_order": [
+  "filters_section",
+  "company",
+  "posting_date",
+  "column_break_4",
+  "voucher_type",
+  "add_manually",
+  "status_section",
+  "repost_status",
+  "repost_error_log",
+  "selected_vouchers_section",
+  "repost_vouchers",
+  "amended_from"
+ ],
+ "fields": [
+  {
+   "default": "Today",
+   "fieldname": "posting_date",
+   "fieldtype": "Date",
+   "label": "Posting Date",
+   "reqd": 1
+  },
+  {
+   "fieldname": "voucher_type",
+   "fieldtype": "Link",
+   "label": "Voucher Type",
+   "options": "DocType"
+  },
+  {
+   "fieldname": "amended_from",
+   "fieldtype": "Link",
+   "label": "Amended From",
+   "no_copy": 1,
+   "options": "Repost Payment Ledger",
+   "print_hide": 1,
+   "read_only": 1
+  },
+  {
+   "fieldname": "company",
+   "fieldtype": "Link",
+   "in_list_view": 1,
+   "label": "Company",
+   "options": "Company",
+   "reqd": 1
+  },
+  {
+   "fieldname": "selected_vouchers_section",
+   "fieldtype": "Section Break",
+   "label": "Vouchers"
+  },
+  {
+   "fieldname": "filters_section",
+   "fieldtype": "Section Break",
+   "label": "Filters"
+  },
+  {
+   "fieldname": "column_break_4",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "repost_vouchers",
+   "fieldtype": "Table",
+   "label": "Selected Vouchers",
+   "options": "Repost Payment Ledger Items"
+  },
+  {
+   "fieldname": "repost_status",
+   "fieldtype": "Select",
+   "label": "Repost Status",
+   "options": "\nQueued\nFailed\nCompleted",
+   "read_only": 1
+  },
+  {
+   "fieldname": "status_section",
+   "fieldtype": "Section Break",
+   "label": "Status"
+  },
+  {
+   "default": "0",
+   "description": "Ignore Voucher Type filter and Select Vouchers Manually",
+   "fieldname": "add_manually",
+   "fieldtype": "Check",
+   "label": "Add Manually"
+  },
+  {
+   "depends_on": "eval:doc.repost_error_log",
+   "fieldname": "repost_error_log",
+   "fieldtype": "Long Text",
+   "label": "Repost Error Log"
+  }
+ ],
+ "index_web_pages_for_search": 1,
+ "is_submittable": 1,
+ "links": [],
+ "modified": "2022-11-08 07:38:40.079038",
+ "modified_by": "Administrator",
+ "module": "Accounts",
+ "name": "Repost Payment Ledger",
+ "owner": "Administrator",
+ "permissions": [
+  {
+   "create": 1,
+   "delete": 1,
+   "email": 1,
+   "export": 1,
+   "print": 1,
+   "read": 1,
+   "report": 1,
+   "role": "System Manager",
+   "share": 1,
+   "write": 1
+  },
+  {
+   "create": 1,
+   "delete": 1,
+   "email": 1,
+   "export": 1,
+   "print": 1,
+   "read": 1,
+   "report": 1,
+   "role": "Accounts Manager",
+   "share": 1,
+   "submit": 1,
+   "write": 1
+  },
+  {
+   "create": 1,
+   "email": 1,
+   "export": 1,
+   "print": 1,
+   "read": 1,
+   "report": 1,
+   "role": "Accounts User",
+   "share": 1,
+   "write": 1
+  },
+  {
+   "email": 1,
+   "export": 1,
+   "permlevel": 1,
+   "print": 1,
+   "read": 1,
+   "report": 1,
+   "role": "Accounts Manager",
+   "share": 1,
+   "write": 1
+  }
+ ],
+ "sort_field": "modified",
+ "sort_order": "DESC",
+ "states": []
+}
\ No newline at end of file
diff --git a/erpnext/accounts/doctype/repost_payment_ledger/repost_payment_ledger.py b/erpnext/accounts/doctype/repost_payment_ledger/repost_payment_ledger.py
new file mode 100644
index 0000000..9f6828f
--- /dev/null
+++ b/erpnext/accounts/doctype/repost_payment_ledger/repost_payment_ledger.py
@@ -0,0 +1,111 @@
+# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
+# For license information, please see license.txt
+
+import copy
+
+import frappe
+from frappe import _, qb
+from frappe.model.document import Document
+from frappe.query_builder.custom import ConstantColumn
+from frappe.utils.background_jobs import is_job_queued
+
+from erpnext.accounts.utils import _delete_pl_entries, create_payment_ledger_entry
+
+VOUCHER_TYPES = ["Sales Invoice", "Purchase Invoice", "Payment Entry", "Journal Entry"]
+
+
+def repost_ple_for_voucher(voucher_type, voucher_no, gle_map=None):
+	if voucher_type and voucher_no and gle_map:
+		_delete_pl_entries(voucher_type, voucher_no)
+		create_payment_ledger_entry(gle_map, cancel=0)
+
+
+@frappe.whitelist()
+def start_payment_ledger_repost(docname=None):
+	"""
+	Repost Payment Ledger Entries for Vouchers through Background Job
+	"""
+	if docname:
+		repost_doc = frappe.get_doc("Repost Payment Ledger", docname)
+		if repost_doc.docstatus == 1 and repost_doc.repost_status in ["Queued", "Failed"]:
+			try:
+				for entry in repost_doc.repost_vouchers:
+					doc = frappe.get_doc(entry.voucher_type, entry.voucher_no)
+
+					if doc.doctype in ["Payment Entry", "Journal Entry"]:
+						gle_map = doc.build_gl_map()
+					else:
+						gle_map = doc.get_gl_entries()
+
+					repost_ple_for_voucher(entry.voucher_type, entry.voucher_no, gle_map)
+
+				frappe.db.set_value(repost_doc.doctype, repost_doc.name, "repost_error_log", "")
+				frappe.db.set_value(repost_doc.doctype, repost_doc.name, "repost_status", "Completed")
+			except Exception as e:
+				frappe.db.rollback()
+
+				traceback = frappe.get_traceback()
+				if traceback:
+					message = "Traceback: <br>" + traceback
+					frappe.db.set_value(repost_doc.doctype, repost_doc.name, "repost_error_log", message)
+
+				frappe.db.set_value(repost_doc.doctype, repost_doc.name, "repost_status", "Failed")
+
+
+class RepostPaymentLedger(Document):
+	def __init__(self, *args, **kwargs):
+		super(RepostPaymentLedger, self).__init__(*args, **kwargs)
+		self.vouchers = []
+
+	def before_validate(self):
+		self.load_vouchers_based_on_filters()
+		self.set_status()
+
+	def load_vouchers_based_on_filters(self):
+		if not self.add_manually:
+			self.repost_vouchers.clear()
+			self.get_vouchers()
+			self.extend("repost_vouchers", copy.deepcopy(self.vouchers))
+
+	def get_vouchers(self):
+		self.vouchers.clear()
+
+		filter_on_voucher_types = [self.voucher_type] if self.voucher_type else VOUCHER_TYPES
+
+		for vtype in filter_on_voucher_types:
+			doc = qb.DocType(vtype)
+			doctype_name = ConstantColumn(vtype)
+			query = (
+				qb.from_(doc)
+				.select(doctype_name.as_("voucher_type"), doc.name.as_("voucher_no"))
+				.where(
+					(doc.docstatus == 1)
+					& (doc.company == self.company)
+					& (doc.posting_date.gte(self.posting_date))
+				)
+			)
+			entries = query.run(as_dict=True)
+			self.vouchers.extend(entries)
+
+	def set_status(self):
+		if self.docstatus == 0:
+			self.repost_status = "Queued"
+
+	def on_submit(self):
+		execute_repost_payment_ledger(self.name)
+		frappe.msgprint(_("Repost started in the background"))
+
+
+@frappe.whitelist()
+def execute_repost_payment_ledger(docname):
+	"""Repost Payment Ledger Entries by background job."""
+
+	job_name = "payment_ledger_repost_" + docname
+
+	if not is_job_queued(job_name):
+		frappe.enqueue(
+			method="erpnext.accounts.doctype.repost_payment_ledger.repost_payment_ledger.start_payment_ledger_repost",
+			docname=docname,
+			is_async=True,
+			job_name=job_name,
+		)
diff --git a/erpnext/accounts/doctype/repost_payment_ledger/repost_payment_ledger_list.js b/erpnext/accounts/doctype/repost_payment_ledger/repost_payment_ledger_list.js
new file mode 100644
index 0000000..e045184
--- /dev/null
+++ b/erpnext/accounts/doctype/repost_payment_ledger/repost_payment_ledger_list.js
@@ -0,0 +1,12 @@
+frappe.listview_settings["Repost Payment Ledger"] = {
+	add_fields: ["repost_status"],
+	get_indicator: function(doc) {
+		var colors = {
+			'Queued': 'orange',
+			'Completed': 'green',
+			'Failed': 'red',
+		};
+		let status = doc.repost_status;
+		return [__(status), colors[status], 'status,=,'+status];
+	},
+};
diff --git a/erpnext/accounts/doctype/repost_payment_ledger/test_repost_payment_ledger.py b/erpnext/accounts/doctype/repost_payment_ledger/test_repost_payment_ledger.py
new file mode 100644
index 0000000..781726a
--- /dev/null
+++ b/erpnext/accounts/doctype/repost_payment_ledger/test_repost_payment_ledger.py
@@ -0,0 +1,9 @@
+# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors
+# See license.txt
+
+# import frappe
+from frappe.tests.utils import FrappeTestCase
+
+
+class TestRepostPaymentLedger(FrappeTestCase):
+	pass
diff --git a/erpnext/accounts/doctype/repost_payment_ledger_items/__init__.py b/erpnext/accounts/doctype/repost_payment_ledger_items/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/accounts/doctype/repost_payment_ledger_items/__init__.py
diff --git a/erpnext/accounts/doctype/repost_payment_ledger_items/repost_payment_ledger_items.json b/erpnext/accounts/doctype/repost_payment_ledger_items/repost_payment_ledger_items.json
new file mode 100644
index 0000000..93005ee
--- /dev/null
+++ b/erpnext/accounts/doctype/repost_payment_ledger_items/repost_payment_ledger_items.json
@@ -0,0 +1,35 @@
+{
+ "actions": [],
+ "creation": "2022-10-20 10:44:18.796489",
+ "doctype": "DocType",
+ "engine": "InnoDB",
+ "field_order": [
+  "voucher_type",
+  "voucher_no"
+ ],
+ "fields": [
+  {
+   "fieldname": "voucher_type",
+   "fieldtype": "Link",
+   "label": "Voucher Type",
+   "options": "DocType"
+  },
+  {
+   "fieldname": "voucher_no",
+   "fieldtype": "Dynamic Link",
+   "label": "Voucher No",
+   "options": "voucher_type"
+  }
+ ],
+ "istable": 1,
+ "links": [],
+ "modified": "2022-10-28 14:47:11.838109",
+ "modified_by": "Administrator",
+ "module": "Accounts",
+ "name": "Repost Payment Ledger Items",
+ "owner": "Administrator",
+ "permissions": [],
+ "sort_field": "modified",
+ "sort_order": "DESC",
+ "states": []
+}
\ No newline at end of file
diff --git a/erpnext/accounts/doctype/repost_payment_ledger_items/repost_payment_ledger_items.py b/erpnext/accounts/doctype/repost_payment_ledger_items/repost_payment_ledger_items.py
new file mode 100644
index 0000000..fb19e84
--- /dev/null
+++ b/erpnext/accounts/doctype/repost_payment_ledger_items/repost_payment_ledger_items.py
@@ -0,0 +1,9 @@
+# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
+# For license information, please see license.txt
+
+# import frappe
+from frappe.model.document import Document
+
+
+class RepostPaymentLedgerItems(Document):
+	pass
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
index 73ec051..7abf3f3 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.js
@@ -64,6 +64,25 @@
 
 		this.frm.toggle_reqd("due_date", !this.frm.doc.is_return);
 
+		if (this.frm.doc.repost_required && this.frm.doc.docstatus===1) {
+			this.frm.set_intro(__("Accounting entries for this invoice needs to be reposted. Please click on 'Repost' button to update."));
+			this.frm.add_custom_button(__('Repost Accounting Entries'),
+				() => {
+					this.frm.call({
+						doc: this.frm.doc,
+						method: 'repost_accounting_entries',
+						freeze: true,
+						freeze_message: __('Reposting...'),
+						callback: (r) => {
+							if (!r.exc) {
+								frappe.msgprint(__('Accounting Entries are reposted'));
+								me.frm.refresh();
+							}
+						}
+					});
+				}).removeClass('btn-default').addClass('btn-warning');
+		}
+
 		if (this.frm.doc.is_return) {
 			this.frm.return_print_format = "Sales Invoice Return";
 		}
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.json b/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
index 97e5f40..15d1d25 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
@@ -207,6 +207,7 @@
   "is_internal_customer",
   "is_discounted",
   "remarks",
+  "repost_required",
   "connections_tab"
  ],
  "fields": [
@@ -1035,6 +1036,7 @@
    "read_only": 1
   },
   {
+   "allow_on_submit": 1,
    "depends_on": "redeem_loyalty_points",
    "fieldname": "loyalty_redemption_account",
    "fieldtype": "Link",
@@ -1333,6 +1335,7 @@
    "options": "fa fa-money"
   },
   {
+   "allow_on_submit": 1,
    "depends_on": "is_pos",
    "fieldname": "cash_bank_account",
    "fieldtype": "Link",
@@ -1432,6 +1435,7 @@
    "print_hide": 1
   },
   {
+   "allow_on_submit": 1,
    "depends_on": "is_pos",
    "fieldname": "account_for_change_amount",
    "fieldtype": "Link",
@@ -1480,6 +1484,7 @@
    "hide_seconds": 1
   },
   {
+   "allow_on_submit": 1,
    "fieldname": "write_off_account",
    "fieldtype": "Link",
    "hide_days": 1,
@@ -1703,6 +1708,7 @@
    "read_only": 1
   },
   {
+   "allow_on_submit": 1,
    "default": "No",
    "fieldname": "is_opening",
    "fieldtype": "Select",
@@ -1917,6 +1923,7 @@
    "read_only": 1
   },
   {
+   "allow_on_submit": 1,
    "depends_on": "eval:doc.is_internal_customer",
    "description": "Unrealized Profit / Loss account for intra-company transfers",
    "fieldname": "unrealized_profit_loss_account",
@@ -1959,6 +1966,7 @@
    "label": "Disable Rounded Total"
   },
   {
+   "allow_on_submit": 1,
    "fieldname": "additional_discount_account",
    "fieldtype": "Link",
    "label": "Discount Account",
@@ -2097,6 +2105,15 @@
    "hide_seconds": 1,
    "label": "Write Off",
    "width": "50%"
+  },
+  {
+   "default": "0",
+   "fieldname": "repost_required",
+   "fieldtype": "Check",
+   "hidden": 1,
+   "label": "Repost Required",
+   "no_copy": 1,
+   "read_only": 1
   }
  ],
  "icon": "fa fa-file-text",
@@ -2109,7 +2126,7 @@
    "link_fieldname": "consolidated_invoice"
   }
  ],
- "modified": "2022-10-11 13:07:36.488095",
+ "modified": "2022-11-07 16:02:07.972258",
  "modified_by": "Administrator",
  "module": "Accounts",
  "name": "Sales Invoice",
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
index 0c03c55..911440f 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.py
@@ -11,6 +11,9 @@
 
 import erpnext
 from erpnext.accounts.deferred_revenue import validate_service_stop_date
+from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import (
+	get_accounting_dimensions,
+)
 from erpnext.accounts.doctype.loyalty_program.loyalty_program import (
 	get_loyalty_program_details_with_points,
 	validate_loyalty_points,
@@ -100,13 +103,11 @@
 		self.validate_debit_to_acc()
 		self.clear_unallocated_advances("Sales Invoice Advance", "advances")
 		self.add_remarks()
-		self.validate_write_off_account()
-		self.validate_account_for_change_amount()
 		self.validate_fixed_asset()
 		self.set_income_account_for_fixed_assets()
 		self.validate_item_cost_centers()
-		self.validate_income_account()
 		self.check_conversion_rate()
+		self.validate_accounts()
 
 		validate_inter_company_party(
 			self.doctype, self.customer, self.company, self.inter_company_invoice_reference
@@ -170,6 +171,11 @@
 
 		self.reset_default_field_value("set_warehouse", "items", "warehouse")
 
+	def validate_accounts(self):
+		self.validate_write_off_account()
+		self.validate_account_for_change_amount()
+		self.validate_income_account()
+
 	def validate_fixed_asset(self):
 		for d in self.get("items"):
 			if d.is_fixed_asset and d.meta.get_field("asset") and d.asset:
@@ -367,7 +373,8 @@
 		if self.update_stock == 1:
 			self.repost_future_sle_and_gle()
 
-		frappe.db.set(self, "status", "Cancelled")
+		self.db_set("status", "Cancelled")
+		self.db_set("repost_required", 0)
 
 		if (
 			frappe.db.get_single_value("Selling Settings", "sales_update_frequency") == "Each Transaction"
@@ -514,6 +521,92 @@
 	def on_update(self):
 		self.set_paid_amount()
 
+	def on_update_after_submit(self):
+		if hasattr(self, "repost_required"):
+			needs_repost = 0
+
+			# Check if any field affecting accounting entry is altered
+			doc_before_update = self.get_doc_before_save()
+			accounting_dimensions = get_accounting_dimensions() + ["cost_center", "project"]
+
+			# Check if opening entry check updated
+			if doc_before_update.get("is_opening") != self.is_opening:
+				needs_repost = 1
+
+			if not needs_repost:
+				# Parent Level Accounts excluding party account
+				for field in (
+					"additional_discount_account",
+					"cash_bank_account",
+					"account_for_change_amount",
+					"write_off_account",
+					"loyalty_redemption_account",
+					"unrealized_profit_loss_account",
+				):
+					if doc_before_update.get(field) != self.get(field):
+						needs_repost = 1
+						break
+
+				# Check for parent accounting dimensions
+				for dimension in accounting_dimensions:
+					if doc_before_update.get(dimension) != self.get(dimension):
+						needs_repost = 1
+						break
+
+				# Check for child tables
+				if self.check_if_child_table_updated(
+					"items",
+					doc_before_update,
+					("income_account", "expense_account", "discount_account"),
+					accounting_dimensions,
+				):
+					needs_repost = 1
+
+				if self.check_if_child_table_updated(
+					"taxes", doc_before_update, ("account_head",), accounting_dimensions
+				):
+					needs_repost = 1
+
+			self.validate_accounts()
+
+			# validate if deferred revenue is enabled for any item
+			# Don't allow to update the invoice if deferred revenue is enabled
+			for item in self.get("items"):
+				if item.enable_deferred_revenue:
+					frappe.throw(
+						_(
+							"Deferred Revenue is enabled for item {0}. You cannot update the invoice after submission."
+						).format(item.item_code)
+					)
+
+			self.db_set("repost_required", needs_repost)
+
+	def check_if_child_table_updated(
+		self, child_table, doc_before_update, fields_to_check, accounting_dimensions
+	):
+		# Check if any field affecting accounting entry is altered
+		for index, item in enumerate(self.get(child_table)):
+			for field in fields_to_check:
+				if doc_before_update.get(child_table)[index].get(field) != item.get(field):
+					return True
+
+			for dimension in accounting_dimensions:
+				if doc_before_update.get(child_table)[index].get(dimension) != item.get(dimension):
+					return True
+
+		return False
+
+	@frappe.whitelist()
+	def repost_accounting_entries(self):
+		if self.repost_required:
+			self.docstatus = 2
+			self.make_gl_entries_on_cancel()
+			self.docstatus = 1
+			self.make_gl_entries()
+			self.db_set("repost_required", 0)
+		else:
+			frappe.throw(_("No updates pending for reposting"))
+
 	def set_paid_amount(self):
 		paid_amount = 0.0
 		base_paid_amount = 0.0
@@ -2306,7 +2399,7 @@
 	lp_details = get_loyalty_programs(customer)
 
 	if len(lp_details) == 1:
-		frappe.db.set(customer, "loyalty_program", lp_details[0])
+		customer.db_set("loyalty_program", lp_details[0])
 		return lp_details
 	else:
 		return lp_details
diff --git a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
index cb0d1a7..855380e 100644
--- a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
@@ -2729,6 +2729,31 @@
 
 		check_gl_entries(self, si.name, expected_gle, add_days(nowdate(), -1))
 
+		# Update Invoice post submit and then check GL Entries again
+
+		si.load_from_db()
+		si.items[0].income_account = "Service - _TC"
+		si.additional_discount_account = "_Test Account Sales - _TC"
+		si.taxes[0].account_head = "TDS Payable - _TC"
+		si.save()
+
+		si.load_from_db()
+		self.assertTrue(si.repost_required)
+
+		si.repost_accounting_entries()
+
+		expected_gle = [
+			["_Test Account Sales - _TC", 22.0, 0.0, nowdate()],
+			["Debtors - _TC", 88, 0.0, nowdate()],
+			["Service - _TC", 0.0, 100.0, nowdate()],
+			["TDS Payable - _TC", 0.0, 10.0, nowdate()],
+		]
+
+		check_gl_entries(self, si.name, expected_gle, add_days(nowdate(), -1))
+
+		si.load_from_db()
+		self.assertFalse(si.repost_required)
+
 	def test_asset_depreciation_on_sale_with_pro_rata(self):
 		"""
 		Tests if an Asset set to depreciate yearly on June 30, that gets sold on Sept 30, creates an additional depreciation entry on its date of sale.
@@ -3286,6 +3311,7 @@
 		"""select account, debit, credit, posting_date
 		from `tabGL Entry`
 		where voucher_type='Sales Invoice' and voucher_no=%s and posting_date > %s
+		and is_cancelled = 0
 		order by posting_date asc, account asc""",
 		(voucher_no, posting_date),
 		as_dict=1,
diff --git a/erpnext/accounts/doctype/sales_invoice_item/sales_invoice_item.json b/erpnext/accounts/doctype/sales_invoice_item/sales_invoice_item.json
index 77055f9..62c3ced 100644
--- a/erpnext/accounts/doctype/sales_invoice_item/sales_invoice_item.json
+++ b/erpnext/accounts/doctype/sales_invoice_item/sales_invoice_item.json
@@ -438,6 +438,7 @@
    "label": "Accounting Details"
   },
   {
+   "allow_on_submit": 1,
    "fieldname": "income_account",
    "fieldtype": "Link",
    "label": "Income Account",
@@ -450,6 +451,7 @@
    "width": "120px"
   },
   {
+   "allow_on_submit": 1,
    "fieldname": "expense_account",
    "fieldtype": "Link",
    "label": "Expense Account",
@@ -469,6 +471,7 @@
    "print_hide": 1
   },
   {
+   "allow_on_submit": 1,
    "default": ":Company",
    "fieldname": "cost_center",
    "fieldtype": "Link",
@@ -800,6 +803,7 @@
    "options": "Finance Book"
   },
   {
+   "allow_on_submit": 1,
    "fieldname": "project",
    "fieldtype": "Link",
    "label": "Project",
@@ -822,7 +826,6 @@
    "label": "Incoming Rate (Costing)",
    "no_copy": 1,
    "options": "Company:company:default_currency",
-   "precision": "6",
    "print_hide": 1
   },
   {
@@ -835,6 +838,7 @@
    "read_only": 1
   },
   {
+   "allow_on_submit": 1,
    "fieldname": "discount_account",
    "fieldtype": "Link",
    "label": "Discount Account",
diff --git a/erpnext/accounts/doctype/sales_taxes_and_charges/sales_taxes_and_charges.json b/erpnext/accounts/doctype/sales_taxes_and_charges/sales_taxes_and_charges.json
index 3a871bf..e236577 100644
--- a/erpnext/accounts/doctype/sales_taxes_and_charges/sales_taxes_and_charges.json
+++ b/erpnext/accounts/doctype/sales_taxes_and_charges/sales_taxes_and_charges.json
@@ -51,6 +51,7 @@
    "oldfieldtype": "Data"
   },
   {
+   "allow_on_submit": 1,
    "columns": 2,
    "fieldname": "account_head",
    "fieldtype": "Link",
@@ -63,6 +64,7 @@
    "search_index": 1
   },
   {
+   "allow_on_submit": 1,
    "default": ":Company",
    "fieldname": "cost_center",
    "fieldtype": "Link",
@@ -216,12 +218,13 @@
  "index_web_pages_for_search": 1,
  "istable": 1,
  "links": [],
- "modified": "2021-08-05 20:04:01.726867",
+ "modified": "2022-10-17 13:08:17.776528",
  "modified_by": "Administrator",
  "module": "Accounts",
  "name": "Sales Taxes and Charges",
  "owner": "Administrator",
  "permissions": [],
  "sort_field": "modified",
- "sort_order": "ASC"
+ "sort_order": "ASC",
+ "states": []
 }
\ No newline at end of file
diff --git a/erpnext/accounts/utils.py b/erpnext/accounts/utils.py
index d7bf991..103c154 100644
--- a/erpnext/accounts/utils.py
+++ b/erpnext/accounts/utils.py
@@ -1146,10 +1146,10 @@
 				if not existing_gle or not compare_existing_and_expected_gle(
 					existing_gle, expected_gle, precision
 				):
-					_delete_gl_entries(voucher_type, voucher_no)
+					_delete_accounting_ledger_entries(voucher_type, voucher_no)
 					voucher_obj.make_gl_entries(gl_entries=expected_gle, from_repost=True)
 			else:
-				_delete_gl_entries(voucher_type, voucher_no)
+				_delete_accounting_ledger_entries(voucher_type, voucher_no)
 
 		if not frappe.flags.in_test:
 			frappe.db.commit()
@@ -1161,18 +1161,28 @@
 			)
 
 
-def _delete_gl_entries(voucher_type, voucher_no):
-	frappe.db.sql(
-		"""delete from `tabGL Entry`
-		where voucher_type=%s and voucher_no=%s""",
-		(voucher_type, voucher_no),
-	)
+def _delete_pl_entries(voucher_type, voucher_no):
 	ple = qb.DocType("Payment Ledger Entry")
 	qb.from_(ple).delete().where(
 		(ple.voucher_type == voucher_type) & (ple.voucher_no == voucher_no)
 	).run()
 
 
+def _delete_gl_entries(voucher_type, voucher_no):
+	gle = qb.DocType("GL Entry")
+	qb.from_(gle).delete().where(
+		(gle.voucher_type == voucher_type) & (gle.voucher_no == voucher_no)
+	).run()
+
+
+def _delete_accounting_ledger_entries(voucher_type, voucher_no):
+	"""
+	Remove entries from both General and Payment Ledger for specified Voucher
+	"""
+	_delete_gl_entries(voucher_type, voucher_no)
+	_delete_pl_entries(voucher_type, voucher_no)
+
+
 def sort_stock_vouchers_by_posting_date(
 	stock_vouchers: List[Tuple[str, str]]
 ) -> List[Tuple[str, str]]:
diff --git a/erpnext/buying/doctype/purchase_order/purchase_order.py b/erpnext/buying/doctype/purchase_order/purchase_order.py
index c224b61..4c10b48 100644
--- a/erpnext/buying/doctype/purchase_order/purchase_order.py
+++ b/erpnext/buying/doctype/purchase_order/purchase_order.py
@@ -361,7 +361,7 @@
 		self.update_reserved_qty_for_subcontract()
 		self.check_on_hold_or_closed_status()
 
-		frappe.db.set(self, "status", "Cancelled")
+		self.db_set("status", "Cancelled")
 
 		self.update_prevdoc_status()
 
diff --git a/erpnext/buying/doctype/request_for_quotation/request_for_quotation.py b/erpnext/buying/doctype/request_for_quotation/request_for_quotation.py
index ee28eb6..a560bda 100644
--- a/erpnext/buying/doctype/request_for_quotation/request_for_quotation.py
+++ b/erpnext/buying/doctype/request_for_quotation/request_for_quotation.py
@@ -31,7 +31,7 @@
 
 		if self.docstatus < 1:
 			# after amend and save, status still shows as cancelled, until submit
-			frappe.db.set(self, "status", "Draft")
+			self.db_set("status", "Draft")
 
 	def validate_duplicate_supplier(self):
 		supplier_list = [d.supplier for d in self.suppliers]
@@ -73,14 +73,14 @@
 			)
 
 	def on_submit(self):
-		frappe.db.set(self, "status", "Submitted")
+		self.db_set("status", "Submitted")
 		for supplier in self.suppliers:
 			supplier.email_sent = 0
 			supplier.quote_status = "Pending"
 		self.send_to_supplier()
 
 	def on_cancel(self):
-		frappe.db.set(self, "status", "Cancelled")
+		self.db_set("status", "Cancelled")
 
 	@frappe.whitelist()
 	def get_supplier_email_preview(self, supplier):
diff --git a/erpnext/buying/doctype/supplier/supplier.json b/erpnext/buying/doctype/supplier/supplier.json
index e0ee658..66eafe9 100644
--- a/erpnext/buying/doctype/supplier/supplier.json
+++ b/erpnext/buying/doctype/supplier/supplier.json
@@ -10,34 +10,37 @@
  "document_type": "Setup",
  "engine": "InnoDB",
  "field_order": [
-  "basic_info",
   "naming_series",
   "supplier_name",
   "country",
-  "default_bank_account",
-  "tax_id",
-  "tax_category",
-  "tax_withholding_category",
-  "image",
   "column_break0",
   "supplier_group",
   "supplier_type",
-  "allow_purchase_invoice_creation_without_purchase_order",
-  "allow_purchase_invoice_creation_without_purchase_receipt",
-  "is_internal_supplier",
-  "represents_company",
-  "disabled",
   "is_transporter",
-  "warn_rfqs",
-  "warn_pos",
-  "prevent_rfqs",
-  "prevent_pos",
-  "allowed_to_transact_section",
-  "companies",
-  "section_break_7",
+  "image",
+  "defaults_section",
   "default_currency",
+  "default_bank_account",
   "column_break_10",
   "default_price_list",
+  "payment_terms",
+  "internal_supplier_section",
+  "is_internal_supplier",
+  "represents_company",
+  "column_break_16",
+  "companies",
+  "column_break2",
+  "supplier_details",
+  "column_break_30",
+  "website",
+  "language",
+  "dashboard_tab",
+  "tax_tab",
+  "tax_id",
+  "column_break_27",
+  "tax_category",
+  "tax_withholding_category",
+  "contact_and_address_tab",
   "address_contacts",
   "address_html",
   "column_break1",
@@ -49,31 +52,26 @@
   "column_break_44",
   "supplier_primary_address",
   "primary_address",
-  "default_payable_accounts",
+  "accounting_tab",
   "accounts",
-  "section_credit_limit",
-  "payment_terms",
-  "cb_21",
+  "settings_tab",
+  "allow_purchase_invoice_creation_without_purchase_order",
+  "allow_purchase_invoice_creation_without_purchase_receipt",
+  "column_break_54",
+  "is_frozen",
+  "disabled",
+  "warn_rfqs",
+  "warn_pos",
+  "prevent_rfqs",
+  "prevent_pos",
+  "block_supplier_section",
   "on_hold",
   "hold_type",
-  "release_date",
-  "default_tax_withholding_config",
-  "column_break2",
-  "website",
-  "supplier_details",
-  "column_break_30",
-  "language",
-  "is_frozen"
+  "column_break_59",
+  "release_date"
  ],
  "fields": [
   {
-   "fieldname": "basic_info",
-   "fieldtype": "Section Break",
-   "label": "Name and Type",
-   "oldfieldtype": "Section Break",
-   "options": "fa fa-user"
-  },
-  {
    "fieldname": "naming_series",
    "fieldtype": "Select",
    "label": "Series",
@@ -192,6 +190,7 @@
    "default": "0",
    "fieldname": "warn_rfqs",
    "fieldtype": "Check",
+   "hidden": 1,
    "label": "Warn RFQs",
    "read_only": 1
   },
@@ -199,6 +198,7 @@
    "default": "0",
    "fieldname": "warn_pos",
    "fieldtype": "Check",
+   "hidden": 1,
    "label": "Warn POs",
    "read_only": 1
   },
@@ -206,6 +206,7 @@
    "default": "0",
    "fieldname": "prevent_rfqs",
    "fieldtype": "Check",
+   "hidden": 1,
    "label": "Prevent RFQs",
    "read_only": 1
   },
@@ -213,29 +214,18 @@
    "default": "0",
    "fieldname": "prevent_pos",
    "fieldtype": "Check",
+   "hidden": 1,
    "label": "Prevent POs",
    "read_only": 1
   },
   {
    "depends_on": "represents_company",
-   "fieldname": "allowed_to_transact_section",
-   "fieldtype": "Section Break",
-   "label": "Allowed To Transact With"
-  },
-  {
-   "depends_on": "represents_company",
    "fieldname": "companies",
    "fieldtype": "Table",
    "label": "Allowed To Transact With",
    "options": "Allowed To Transact With"
   },
   {
-   "collapsible": 1,
-   "fieldname": "section_break_7",
-   "fieldtype": "Section Break",
-   "label": "Currency and Price List"
-  },
-  {
    "fieldname": "default_currency",
    "fieldtype": "Link",
    "ignore_user_permissions": 1,
@@ -255,22 +245,12 @@
    "options": "Price List"
   },
   {
-   "collapsible": 1,
-   "fieldname": "section_credit_limit",
-   "fieldtype": "Section Break",
-   "label": "Payment Terms"
-  },
-  {
    "fieldname": "payment_terms",
    "fieldtype": "Link",
    "label": "Default Payment Terms Template",
    "options": "Payment Terms Template"
   },
   {
-   "fieldname": "cb_21",
-   "fieldtype": "Column Break"
-  },
-  {
    "default": "0",
    "fieldname": "on_hold",
    "fieldtype": "Check",
@@ -316,13 +296,6 @@
    "read_only": 1
   },
   {
-   "collapsible": 1,
-   "collapsible_depends_on": "accounts",
-   "fieldname": "default_payable_accounts",
-   "fieldtype": "Section Break",
-   "label": "Default Payable Accounts"
-  },
-  {
    "description": "Mention if non-standard payable account",
    "fieldname": "accounts",
    "fieldtype": "Table",
@@ -331,12 +304,6 @@
   },
   {
    "collapsible": 1,
-   "fieldname": "default_tax_withholding_config",
-   "fieldtype": "Section Break",
-   "label": "Default Tax Withholding Config"
-  },
-  {
-   "collapsible": 1,
    "collapsible_depends_on": "supplier_details",
    "fieldname": "column_break2",
    "fieldtype": "Section Break",
@@ -383,7 +350,7 @@
   {
    "fieldname": "primary_address_and_contact_detail_section",
    "fieldtype": "Section Break",
-   "label": "Primary Address and Contact Detail"
+   "label": "Primary Address and Contact"
   },
   {
    "description": "Reselect, if the chosen contact is edited after save",
@@ -420,6 +387,64 @@
    "fieldtype": "Link",
    "label": "Supplier Primary Address",
    "options": "Address"
+  },
+  {
+   "fieldname": "dashboard_tab",
+   "fieldtype": "Tab Break",
+   "label": "Dashboard",
+   "show_dashboard": 1
+  },
+  {
+   "fieldname": "settings_tab",
+   "fieldtype": "Tab Break",
+   "label": "Settings"
+  },
+  {
+   "fieldname": "contact_and_address_tab",
+   "fieldtype": "Tab Break",
+   "label": "Contact & Address"
+  },
+  {
+   "fieldname": "accounting_tab",
+   "fieldtype": "Tab Break",
+   "label": "Accounting"
+  },
+  {
+   "fieldname": "defaults_section",
+   "fieldtype": "Section Break",
+   "label": "Defaults"
+  },
+  {
+   "fieldname": "tax_tab",
+   "fieldtype": "Tab Break",
+   "label": "Tax"
+  },
+  {
+   "collapsible": 1,
+   "fieldname": "internal_supplier_section",
+   "fieldtype": "Section Break",
+   "label": "Internal Supplier"
+  },
+  {
+   "fieldname": "column_break_16",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "column_break_27",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "column_break_54",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "block_supplier_section",
+   "fieldtype": "Section Break",
+   "label": "Block Supplier"
+  },
+  {
+   "fieldname": "column_break_59",
+   "fieldtype": "Column Break"
   }
  ],
  "icon": "fa fa-user",
@@ -432,7 +457,7 @@
    "link_fieldname": "party"
   }
  ],
- "modified": "2022-04-16 18:02:27.838623",
+ "modified": "2022-11-09 18:02:59.075203",
  "modified_by": "Administrator",
  "module": "Buying",
  "name": "Supplier",
diff --git a/erpnext/buying/doctype/supplier/supplier.py b/erpnext/buying/doctype/supplier/supplier.py
index 43152e8..bebff1c 100644
--- a/erpnext/buying/doctype/supplier/supplier.py
+++ b/erpnext/buying/doctype/supplier/supplier.py
@@ -145,7 +145,7 @@
 
 	def after_rename(self, olddn, newdn, merge=False):
 		if frappe.defaults.get_global_default("supp_master_name") == "Supplier Name":
-			frappe.db.set(self, "supplier_name", newdn)
+			self.db_set("supplier_name", newdn)
 
 
 @frappe.whitelist()
diff --git a/erpnext/buying/doctype/supplier_quotation/supplier_quotation.py b/erpnext/buying/doctype/supplier_quotation/supplier_quotation.py
index c19c1df..2dd748b 100644
--- a/erpnext/buying/doctype/supplier_quotation/supplier_quotation.py
+++ b/erpnext/buying/doctype/supplier_quotation/supplier_quotation.py
@@ -30,11 +30,11 @@
 		self.validate_valid_till()
 
 	def on_submit(self):
-		frappe.db.set(self, "status", "Submitted")
+		self.db_set("status", "Submitted")
 		self.update_rfq_supplier_status(1)
 
 	def on_cancel(self):
-		frappe.db.set(self, "status", "Cancelled")
+		self.db_set("status", "Cancelled")
 		self.update_rfq_supplier_status(0)
 
 	def on_trash(self):
diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index 756fc6c..216c9f4 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -227,7 +227,7 @@
 		for item in self.get("items"):
 			if item.get("enable_deferred_revenue") or item.get("enable_deferred_expense"):
 				if not item.get(field_map.get(self.doctype)):
-					default_deferred_account = frappe.db.get_value(
+					default_deferred_account = frappe.get_cached_value(
 						"Company", self.company, "default_" + field_map.get(self.doctype)
 					)
 					if not default_deferred_account:
@@ -676,7 +676,7 @@
 
 	def validate_enabled_taxes_and_charges(self):
 		taxes_and_charges_doctype = self.meta.get_options("taxes_and_charges")
-		if frappe.db.get_value(taxes_and_charges_doctype, self.taxes_and_charges, "disabled"):
+		if frappe.get_cached_value(taxes_and_charges_doctype, self.taxes_and_charges, "disabled"):
 			frappe.throw(
 				_("{0} '{1}' is disabled").format(taxes_and_charges_doctype, self.taxes_and_charges)
 			)
@@ -684,7 +684,7 @@
 	def validate_tax_account_company(self):
 		for d in self.get("taxes"):
 			if d.account_head:
-				tax_account_company = frappe.db.get_value("Account", d.account_head, "company")
+				tax_account_company = frappe.get_cached_value("Account", d.account_head, "company")
 				if tax_account_company != self.company:
 					frappe.throw(
 						_("Row #{0}: Account {1} does not belong to company {2}").format(
@@ -929,7 +929,9 @@
 					party_account = self.credit_to if is_purchase_invoice else self.debit_to
 					party_type = "Supplier" if is_purchase_invoice else "Customer"
 
-					gain_loss_account = frappe.db.get_value("Company", self.company, "exchange_gain_loss_account")
+					gain_loss_account = frappe.get_cached_value(
+						"Company", self.company, "exchange_gain_loss_account"
+					)
 					if not gain_loss_account:
 						frappe.throw(
 							_("Please set default Exchange Gain/Loss Account in Company {}").format(self.get("company"))
@@ -1026,7 +1028,7 @@
 							else self.grand_total
 						),
 						"outstanding_amount": self.outstanding_amount,
-						"difference_account": frappe.db.get_value(
+						"difference_account": frappe.get_cached_value(
 							"Company", self.company, "exchange_gain_loss_account"
 						),
 						"exchange_gain_loss": flt(d.get("exchange_gain_loss")),
@@ -1394,7 +1396,7 @@
 	@property
 	def company_abbr(self):
 		if not hasattr(self, "_abbr"):
-			self._abbr = frappe.db.get_value("Company", self.company, "abbr")
+			self._abbr = frappe.get_cached_value("Company", self.company, "abbr")
 
 		return self._abbr
 
@@ -1780,7 +1782,7 @@
 		"""
 
 		if self.is_internal_transfer() and not self.unrealized_profit_loss_account:
-			unrealized_profit_loss_account = frappe.db.get_value(
+			unrealized_profit_loss_account = frappe.get_cached_value(
 				"Company", self.company, "unrealized_profit_loss_account"
 			)
 
@@ -1895,7 +1897,9 @@
 
 @frappe.whitelist()
 def get_tax_rate(account_head):
-	return frappe.db.get_value("Account", account_head, ["tax_rate", "account_name"], as_dict=True)
+	return frappe.get_cached_value(
+		"Account", account_head, ["tax_rate", "account_name"], as_dict=True
+	)
 
 
 @frappe.whitelist()
@@ -1904,7 +1908,7 @@
 		return {}
 
 	if tax_template and company:
-		tax_template_company = frappe.db.get_value(master_doctype, tax_template, "company")
+		tax_template_company = frappe.get_cached_value(master_doctype, tax_template, "company")
 		if tax_template_company == company:
 			return
 
diff --git a/erpnext/controllers/sales_and_purchase_return.py b/erpnext/controllers/sales_and_purchase_return.py
index 0054edb..39ef68a 100644
--- a/erpnext/controllers/sales_and_purchase_return.py
+++ b/erpnext/controllers/sales_and_purchase_return.py
@@ -326,7 +326,7 @@
 	from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
 
 	company = frappe.db.get_value("Delivery Note", source_name, "company")
-	default_warehouse_for_sales_return = frappe.db.get_value(
+	default_warehouse_for_sales_return = frappe.get_cached_value(
 		"Company", company, "default_warehouse_for_sales_return"
 	)
 
@@ -340,11 +340,11 @@
 
 			# look for Print Heading "Credit Note"
 			if not doc.select_print_heading:
-				doc.select_print_heading = frappe.db.get_value("Print Heading", _("Credit Note"))
+				doc.select_print_heading = frappe.get_cached_value("Print Heading", _("Credit Note"))
 
 		elif doctype == "Purchase Invoice":
 			# look for Print Heading "Debit Note"
-			doc.select_print_heading = frappe.db.get_value("Print Heading", _("Debit Note"))
+			doc.select_print_heading = frappe.get_cached_value("Print Heading", _("Debit Note"))
 
 		for tax in doc.get("taxes") or []:
 			if tax.charge_type == "Actual":
diff --git a/erpnext/controllers/stock_controller.py b/erpnext/controllers/stock_controller.py
index 98dc586..1e4fabe 100644
--- a/erpnext/controllers/stock_controller.py
+++ b/erpnext/controllers/stock_controller.py
@@ -57,7 +57,7 @@
 			make_reverse_gl_entries(voucher_type=self.doctype, voucher_no=self.name)
 
 		provisional_accounting_for_non_stock_items = cint(
-			frappe.db.get_value(
+			frappe.get_cached_value(
 				"Company", self.company, "enable_provisional_accounting_for_non_stock_items"
 			)
 		)
@@ -200,7 +200,7 @@
 				elif self.get("is_internal_supplier"):
 					warehouse_asset_account = warehouse_account[item_row.get("warehouse")]["account"]
 
-				expense_account = frappe.db.get_value("Company", self.company, "default_expense_account")
+				expense_account = frappe.get_cached_value("Company", self.company, "default_expense_account")
 
 				gl_list.append(
 					self.get_gl_dict(
@@ -235,7 +235,7 @@
 
 		if warehouse_with_no_account:
 			for wh in warehouse_with_no_account:
-				if frappe.db.get_value("Warehouse", wh, "company"):
+				if frappe.get_cached_value("Warehouse", wh, "company"):
 					frappe.throw(
 						_(
 							"Warehouse {0} is not linked to any account, please mention the account in the warehouse record or set default inventory account in company {1}."
@@ -449,15 +449,15 @@
 
 				# Get value based on doctype name
 				if not sl_dict.get(dimension.target_fieldname):
-					fieldname = frappe.get_cached_value(
-						"DocField", {"parent": self.doctype, "options": dimension.fetch_from_parent}, "fieldname"
+					fieldname = next(
+						(
+							field.fieldname
+							for field in frappe.get_meta(self.doctype).fields
+							if field.options == dimension.fetch_from_parent
+						),
+						None,
 					)
 
-					if not fieldname:
-						fieldname = frappe.get_cached_value(
-							"Custom Field", {"dt": self.doctype, "options": dimension.fetch_from_parent}, "fieldname"
-						)
-
 					if fieldname and self.get(fieldname):
 						sl_dict[dimension.target_fieldname] = self.get(fieldname)
 
diff --git a/erpnext/controllers/subcontracting_controller.py b/erpnext/controllers/subcontracting_controller.py
index 8d67e30..7819fa5 100644
--- a/erpnext/controllers/subcontracting_controller.py
+++ b/erpnext/controllers/subcontracting_controller.py
@@ -100,7 +100,7 @@
 			and self._doc_before_save
 		):
 			for row in self._doc_before_save.get("items"):
-				item_dict[row.name] = (row.item_code, row.qty)
+				item_dict[row.name] = (row.item_code, row.received_qty or row.qty)
 
 		return item_dict
 
@@ -118,7 +118,9 @@
 
 		for row in self.items:
 			self.__reference_name.append(row.name)
-			if (row.name not in item_dict) or (row.item_code, row.qty) != item_dict[row.name]:
+			if (row.name not in item_dict) or (row.item_code, row.received_qty or row.qty) != item_dict[
+				row.name
+			]:
 				self.__changed_name.append(row.name)
 
 			if item_dict.get(row.name):
@@ -461,12 +463,13 @@
 
 	def __get_qty_based_on_material_transfer(self, item_row, transfer_item):
 		key = (item_row.item_code, item_row.get(self.subcontract_data.order_field))
+		item_qty = item_row.received_qty or item_row.qty
 
-		if self.qty_to_be_received == item_row.qty:
+		if self.qty_to_be_received.get(key) == item_qty:
 			return transfer_item.qty
 
 		if self.qty_to_be_received:
-			qty = (flt(item_row.qty) * flt(transfer_item.qty)) / flt(self.qty_to_be_received.get(key, 0))
+			qty = (flt(item_qty) * flt(transfer_item.qty)) / flt(self.qty_to_be_received.get(key, 0))
 			transfer_item.item_details.required_qty = transfer_item.qty
 
 			if transfer_item.serial_no or frappe.get_cached_value(
@@ -491,7 +494,11 @@
 				for bom_item in self.__get_materials_from_bom(
 					row.item_code, row.bom, row.get("include_exploded_items")
 				):
-					qty = flt(bom_item.qty_consumed_per_unit) * flt(row.qty) * row.conversion_factor
+					qty = (
+						flt(bom_item.qty_consumed_per_unit)
+						* flt(row.received_qty or row.qty)
+						* row.conversion_factor
+					)
 					bom_item.main_item_code = row.item_code
 					self.__update_reserve_warehouse(bom_item, row)
 					self.__set_alternative_item(bom_item)
diff --git a/erpnext/controllers/taxes_and_totals.py b/erpnext/controllers/taxes_and_totals.py
index 81de682..c6a634b 100644
--- a/erpnext/controllers/taxes_and_totals.py
+++ b/erpnext/controllers/taxes_and_totals.py
@@ -1056,7 +1056,7 @@
 		company_currency = erpnext.get_company_currency(self.doc.company)
 		for d in self.doc.get(self.tax_field):
 			if not d.account_currency:
-				account_currency = frappe.db.get_value("Account", d.expense_account, "account_currency")
+				account_currency = frappe.get_cached_value("Account", d.expense_account, "account_currency")
 				d.account_currency = account_currency or company_currency
 
 	def set_exchange_rate(self):
diff --git a/erpnext/controllers/trends.py b/erpnext/controllers/trends.py
index 1d6c5dc..1fb722e 100644
--- a/erpnext/controllers/trends.py
+++ b/erpnext/controllers/trends.py
@@ -80,7 +80,7 @@
 	if conditions.get("trans") == "Quotation" and filters.get("group_by") == "Customer":
 		cond += " and t1.quotation_to = 'Customer'"
 
-	year_start_date, year_end_date = frappe.db.get_value(
+	year_start_date, year_end_date = frappe.get_cached_value(
 		"Fiscal Year", filters.get("fiscal_year"), ["year_start_date", "year_end_date"]
 	)
 
@@ -275,7 +275,7 @@
 	from dateutil.relativedelta import relativedelta
 
 	if not year_start_date:
-		year_start_date, year_end_date = frappe.db.get_value(
+		year_start_date, year_end_date = frappe.get_cached_value(
 			"Fiscal Year", fiscal_year, ["year_start_date", "year_end_date"]
 		)
 
diff --git a/erpnext/crm/doctype/opportunity/opportunity.py b/erpnext/crm/doctype/opportunity/opportunity.py
index 08eb472..f4b6e91 100644
--- a/erpnext/crm/doctype/opportunity/opportunity.py
+++ b/erpnext/crm/doctype/opportunity/opportunity.py
@@ -60,7 +60,7 @@
 			if not self.get(field) and frappe.db.field_exists(self.opportunity_from, field):
 				try:
 					value = frappe.db.get_value(self.opportunity_from, self.party_name, field)
-					frappe.db.set(self, field, value)
+					self.db_set(field, value)
 				except Exception:
 					continue
 
diff --git a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
index e9fa2ad..8a185f8 100644
--- a/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
+++ b/erpnext/loan_management/doctype/loan_repayment/loan_repayment.py
@@ -576,8 +576,8 @@
 	loan_doc = frappe.get_doc("Loan", loan)
 	next_accrual_date = None
 	accrued_entries = 0
-	last_repayment_amount = 0
-	last_balance_amount = 0
+	last_repayment_amount = None
+	last_balance_amount = None
 
 	for term in reversed(loan_doc.get("repayment_schedule")):
 		if not term.is_accrued:
@@ -585,9 +585,9 @@
 			loan_doc.remove(term)
 		else:
 			accrued_entries += 1
-			if not last_repayment_amount:
+			if last_repayment_amount is None:
 				last_repayment_amount = term.total_payment
-			if not last_balance_amount:
+			if last_balance_amount is None:
 				last_balance_amount = term.balance_loan_amount
 
 	loan_doc.save()
diff --git a/erpnext/maintenance/doctype/maintenance_schedule/maintenance_schedule.py b/erpnext/maintenance/doctype/maintenance_schedule/maintenance_schedule.py
index 3dc6b0f..95e2d69 100644
--- a/erpnext/maintenance/doctype/maintenance_schedule/maintenance_schedule.py
+++ b/erpnext/maintenance/doctype/maintenance_schedule/maintenance_schedule.py
@@ -119,7 +119,7 @@
 				event.add_participant(self.doctype, self.name)
 				event.insert(ignore_permissions=1)
 
-		frappe.db.set(self, "status", "Submitted")
+		self.db_set("status", "Submitted")
 
 	def create_schedule_list(self, start_date, end_date, no_of_visit, sales_person):
 		schedule_list = []
@@ -245,7 +245,7 @@
 			self.generate_schedule()
 
 	def on_update(self):
-		frappe.db.set(self, "status", "Draft")
+		self.db_set("status", "Draft")
 
 	def update_amc_date(self, serial_nos, amc_expiry_date=None):
 		for serial_no in serial_nos:
@@ -344,7 +344,7 @@
 			if d.serial_no:
 				serial_nos = get_valid_serial_nos(d.serial_no)
 				self.update_amc_date(serial_nos)
-		frappe.db.set(self, "status", "Cancelled")
+		self.db_set("status", "Cancelled")
 		delete_events(self.doctype, self.name)
 
 	def on_trash(self):
diff --git a/erpnext/maintenance/doctype/maintenance_visit/maintenance_visit.py b/erpnext/maintenance/doctype/maintenance_visit/maintenance_visit.py
index 66f4426..0d319bf 100644
--- a/erpnext/maintenance/doctype/maintenance_visit/maintenance_visit.py
+++ b/erpnext/maintenance/doctype/maintenance_visit/maintenance_visit.py
@@ -125,12 +125,12 @@
 
 	def on_submit(self):
 		self.update_customer_issue(1)
-		frappe.db.set(self, "status", "Submitted")
+		self.db_set("status", "Submitted")
 		self.update_status_and_actual_date()
 
 	def on_cancel(self):
 		self.check_if_last_visit()
-		frappe.db.set(self, "status", "Cancelled")
+		self.db_set("status", "Cancelled")
 		self.update_status_and_actual_date(cancel=True)
 
 	def on_update(self):
diff --git a/erpnext/manufacturing/doctype/bom/bom.py b/erpnext/manufacturing/doctype/bom/bom.py
index 580838e..ca4f63d 100644
--- a/erpnext/manufacturing/doctype/bom/bom.py
+++ b/erpnext/manufacturing/doctype/bom/bom.py
@@ -206,8 +206,8 @@
 		self.manage_default_bom()
 
 	def on_cancel(self):
-		frappe.db.set(self, "is_active", 0)
-		frappe.db.set(self, "is_default", 0)
+		self.db_set("is_active", 0)
+		self.db_set("is_default", 0)
 
 		# check if used in any other bom
 		self.validate_bom_links()
@@ -449,10 +449,10 @@
 			not frappe.db.exists(dict(doctype="BOM", docstatus=1, item=self.item, is_default=1))
 			and self.is_active
 		):
-			frappe.db.set(self, "is_default", 1)
+			self.db_set("is_default", 1)
 			frappe.db.set_value("Item", self.item, "default_bom", self.name)
 		else:
-			frappe.db.set(self, "is_default", 0)
+			self.db_set("is_default", 0)
 			item = frappe.get_doc("Item", self.item)
 			if item.default_bom == self.name:
 				frappe.db.set_value("Item", self.item, "default_bom", None)
diff --git a/erpnext/manufacturing/doctype/job_card/job_card.py b/erpnext/manufacturing/doctype/job_card/job_card.py
index fb94e8a..75e652e 100644
--- a/erpnext/manufacturing/doctype/job_card/job_card.py
+++ b/erpnext/manufacturing/doctype/job_card/job_card.py
@@ -54,6 +54,9 @@
 		self.set_onload("job_card_excess_transfer", excess_transfer)
 		self.set_onload("work_order_closed", self.is_work_order_closed())
 
+	def before_validate(self):
+		self.set_wip_warehouse()
+
 	def validate(self):
 		self.validate_time_logs()
 		self.set_status()
@@ -639,6 +642,12 @@
 		if update_status:
 			self.db_set("status", self.status)
 
+	def set_wip_warehouse(self):
+		if not self.wip_warehouse:
+			self.wip_warehouse = frappe.db.get_single_value(
+				"Manufacturing Settings", "default_wip_warehouse"
+			)
+
 	def validate_operation_id(self):
 		if (
 			self.get("operation_id")
diff --git a/erpnext/manufacturing/doctype/work_order/work_order.js b/erpnext/manufacturing/doctype/work_order/work_order.js
index 4aab3fa..6247618 100644
--- a/erpnext/manufacturing/doctype/work_order/work_order.js
+++ b/erpnext/manufacturing/doctype/work_order/work_order.js
@@ -589,66 +589,69 @@
 				}
 			}
 
-			if(!frm.doc.skip_transfer){
+			if (frm.doc.status != 'Stopped') {
 				// If "Material Consumption is check in Manufacturing Settings, allow Material Consumption
-				if (flt(doc.material_transferred_for_manufacturing) > 0 && frm.doc.status != 'Stopped') {
-					if ((flt(doc.produced_qty) < flt(doc.material_transferred_for_manufacturing))) {
-						frm.has_finish_btn = true;
-
-						if (frm.doc.__onload && frm.doc.__onload.material_consumption == 1) {
-							// Only show "Material Consumption" when required_qty > consumed_qty
-							var counter = 0;
-							var tbl = frm.doc.required_items || [];
-							var tbl_lenght = tbl.length;
-							for (var i = 0, len = tbl_lenght; i < len; i++) {
-								let wo_item_qty = frm.doc.required_items[i].transferred_qty || frm.doc.required_items[i].required_qty;
-								if (flt(wo_item_qty) > flt(frm.doc.required_items[i].consumed_qty)) {
-									counter += 1;
-								}
-							}
-							if (counter > 0) {
-								var consumption_btn = frm.add_custom_button(__('Material Consumption'), function() {
-									const backflush_raw_materials_based_on = frm.doc.__onload.backflush_raw_materials_based_on;
-									erpnext.work_order.make_consumption_se(frm, backflush_raw_materials_based_on);
-								});
-								consumption_btn.addClass('btn-primary');
+				if (frm.doc.__onload && frm.doc.__onload.material_consumption == 1) {
+					if (flt(doc.material_transferred_for_manufacturing) > 0 || frm.doc.skip_transfer) {
+						// Only show "Material Consumption" when required_qty > consumed_qty
+						var counter = 0;
+						var tbl = frm.doc.required_items || [];
+						var tbl_lenght = tbl.length;
+						for (var i = 0, len = tbl_lenght; i < len; i++) {
+							let wo_item_qty = frm.doc.required_items[i].transferred_qty || frm.doc.required_items[i].required_qty;
+							if (flt(wo_item_qty) > flt(frm.doc.required_items[i].consumed_qty)) {
+								counter += 1;
 							}
 						}
+						if (counter > 0) {
+							var consumption_btn = frm.add_custom_button(__('Material Consumption'), function() {
+								const backflush_raw_materials_based_on = frm.doc.__onload.backflush_raw_materials_based_on;
+								erpnext.work_order.make_consumption_se(frm, backflush_raw_materials_based_on);
+							});
+							consumption_btn.addClass('btn-primary');
+						}
+					}
+				}
 
+				if(!frm.doc.skip_transfer){
+					if (flt(doc.material_transferred_for_manufacturing) > 0) {
+						if ((flt(doc.produced_qty) < flt(doc.material_transferred_for_manufacturing))) {
+							frm.has_finish_btn = true;
+
+							var finish_btn = frm.add_custom_button(__('Finish'), function() {
+								erpnext.work_order.make_se(frm, 'Manufacture');
+							});
+
+							if(doc.material_transferred_for_manufacturing>=doc.qty) {
+								// all materials transferred for manufacturing, make this primary
+								finish_btn.addClass('btn-primary');
+							}
+						} else {
+							frappe.db.get_doc("Manufacturing Settings").then((doc) => {
+								let allowance_percentage = doc.overproduction_percentage_for_work_order;
+
+								if (allowance_percentage > 0) {
+									let allowed_qty = frm.doc.qty + ((allowance_percentage / 100) * frm.doc.qty);
+
+									if ((flt(doc.produced_qty) < allowed_qty)) {
+										frm.add_custom_button(__('Finish'), function() {
+											erpnext.work_order.make_se(frm, 'Manufacture');
+										});
+									}
+								}
+							});
+						}
+					}
+				} else {
+					if ((flt(doc.produced_qty) < flt(doc.qty))) {
 						var finish_btn = frm.add_custom_button(__('Finish'), function() {
 							erpnext.work_order.make_se(frm, 'Manufacture');
 						});
-
-						if(doc.material_transferred_for_manufacturing>=doc.qty) {
-							// all materials transferred for manufacturing, make this primary
-							finish_btn.addClass('btn-primary');
-						}
-					} else {
-						frappe.db.get_doc("Manufacturing Settings").then((doc) => {
-							let allowance_percentage = doc.overproduction_percentage_for_work_order;
-
-							if (allowance_percentage > 0) {
-								let allowed_qty = frm.doc.qty + ((allowance_percentage / 100) * frm.doc.qty);
-
-								if ((flt(doc.produced_qty) < allowed_qty)) {
-									frm.add_custom_button(__('Finish'), function() {
-										erpnext.work_order.make_se(frm, 'Manufacture');
-									});
-								}
-							}
-						});
+						finish_btn.addClass('btn-primary');
 					}
 				}
-			} else {
-				if ((flt(doc.produced_qty) < flt(doc.qty)) && frm.doc.status != 'Stopped') {
-					var finish_btn = frm.add_custom_button(__('Finish'), function() {
-						erpnext.work_order.make_se(frm, 'Manufacture');
-					});
-					finish_btn.addClass('btn-primary');
-				}
 			}
 		}
-
 	},
 	calculate_cost: function(doc) {
 		if (doc.operations){
diff --git a/erpnext/manufacturing/doctype/work_order/work_order.py b/erpnext/manufacturing/doctype/work_order/work_order.py
index 1e6d982..8167385 100644
--- a/erpnext/manufacturing/doctype/work_order/work_order.py
+++ b/erpnext/manufacturing/doctype/work_order/work_order.py
@@ -146,7 +146,7 @@
 			frappe.throw(_("Sales Order {0} is {1}").format(self.sales_order, status))
 
 	def set_default_warehouse(self):
-		if not self.wip_warehouse:
+		if not self.wip_warehouse and not self.skip_transfer:
 			self.wip_warehouse = frappe.db.get_single_value(
 				"Manufacturing Settings", "default_wip_warehouse"
 			)
@@ -373,7 +373,7 @@
 
 	def on_cancel(self):
 		self.validate_cancel()
-		frappe.db.set(self, "status", "Cancelled")
+		self.db_set("status", "Cancelled")
 
 		if self.production_plan and frappe.db.exists(
 			"Production Plan Item Reference", {"parent": self.production_plan}
diff --git a/erpnext/manufacturing/doctype/workstation/workstation.py b/erpnext/manufacturing/doctype/workstation/workstation.py
index 59e5318..3c25622 100644
--- a/erpnext/manufacturing/doctype/workstation/workstation.py
+++ b/erpnext/manufacturing/doctype/workstation/workstation.py
@@ -100,9 +100,7 @@
 
 def check_if_within_operating_hours(workstation, operation, from_datetime, to_datetime):
 	if from_datetime and to_datetime:
-		if not cint(
-			frappe.db.get_value("Manufacturing Settings", "None", "allow_production_on_holidays")
-		):
+		if not frappe.db.get_single_value("Manufacturing Settings", "allow_production_on_holidays"):
 			check_workstation_for_holiday(workstation, from_datetime, to_datetime)
 
 		if not cint(frappe.db.get_value("Manufacturing Settings", None, "allow_overtime")):
diff --git a/erpnext/projects/doctype/timesheet/timesheet.js b/erpnext/projects/doctype/timesheet/timesheet.js
index e1486de..a376bf4 100644
--- a/erpnext/projects/doctype/timesheet/timesheet.js
+++ b/erpnext/projects/doctype/timesheet/timesheet.js
@@ -92,18 +92,26 @@
 			frm.fields_dict["time_logs"].grid.toggle_enable("billing_hours", false);
 			frm.fields_dict["time_logs"].grid.toggle_enable("is_billable", false);
 		}
+
+		let filters = {
+			"status": "Open"
+		};
+
+		if (frm.doc.customer) {
+			filters["customer"] = frm.doc.customer;
+		}
+
+		frm.set_query('parent_project', function(doc) {
+			return {
+				filters: filters
+			};
+		});
+
 		frm.trigger('setup_filters');
 		frm.trigger('set_dynamic_field_label');
 	},
 
 	customer: function(frm) {
-		frm.set_query('parent_project', function(doc) {
-			return {
-				filters: {
-					"customer": doc.customer
-				}
-			};
-		});
 		frm.set_query('project', 'time_logs', function(doc) {
 			return {
 				filters: {
diff --git a/erpnext/public/js/controllers/accounts.js b/erpnext/public/js/controllers/accounts.js
index c1fe72b..a07f75d 100644
--- a/erpnext/public/js/controllers/accounts.js
+++ b/erpnext/public/js/controllers/accounts.js
@@ -143,6 +143,12 @@
 
 cur_frm.cscript.account_head = function(doc, cdt, cdn) {
 	var d = locals[cdt][cdn];
+
+	if (doc.docstatus == 1) {
+		// Should not trigger any changes on change post submit
+		return;
+	}
+
 	if(!d.charge_type && d.account_head){
 		frappe.msgprint(__("Please select Charge Type first"));
 		frappe.model.set_value(cdt, cdn, "account_head", "");
diff --git a/erpnext/regional/united_states/setup.py b/erpnext/regional/united_states/setup.py
index b8f8572..47f24ef 100644
--- a/erpnext/regional/united_states/setup.py
+++ b/erpnext/regional/united_states/setup.py
@@ -49,7 +49,7 @@
 			dict(
 				fieldname="exempt_from_sales_tax",
 				fieldtype="Check",
-				insert_after="represents_company",
+				insert_after="dn_required",
 				label="Is customer exempted from sales tax?",
 			)
 		],
diff --git a/erpnext/selling/doctype/customer/customer.json b/erpnext/selling/doctype/customer/customer.json
index 7cba141..7482a33 100644
--- a/erpnext/selling/doctype/customer/customer.json
+++ b/erpnext/selling/doctype/customer/customer.json
@@ -14,30 +14,35 @@
   "naming_series",
   "salutation",
   "customer_name",
+  "customer_type",
+  "customer_group",
+  "column_break0",
+  "territory",
   "gender",
-  "default_bank_account",
-  "tax_id",
-  "tax_category",
-  "tax_withholding_category",
   "lead_name",
   "opportunity_name",
-  "image",
-  "column_break0",
-  "customer_group",
-  "customer_type",
-  "territory",
   "account_manager",
-  "so_required",
-  "dn_required",
+  "image",
+  "defaults_tab",
+  "default_price_list",
+  "default_bank_account",
+  "column_break_14",
+  "default_currency",
+  "internal_customer_section",
   "is_internal_customer",
   "represents_company",
-  "disabled",
-  "allowed_to_transact_section",
+  "column_break_70",
   "companies",
-  "currency_and_price_list",
-  "default_currency",
-  "column_break_14",
-  "default_price_list",
+  "more_info",
+  "market_segment",
+  "industry",
+  "customer_pos_id",
+  "website",
+  "language",
+  "column_break_45",
+  "customer_details",
+  "dashboard_tab",
+  "contact_and_address_tab",
   "address_contacts",
   "address_html",
   "column_break1",
@@ -49,34 +54,39 @@
   "column_break_26",
   "customer_primary_address",
   "primary_address",
-  "default_receivable_accounts",
-  "accounts",
+  "tax_tab",
+  "taxation_section",
+  "tax_id",
+  "column_break_21",
+  "tax_category",
+  "tax_withholding_category",
+  "accounting_tab",
   "credit_limit_section",
   "payment_terms",
   "credit_limits",
-  "more_info",
-  "customer_details",
-  "column_break_45",
-  "market_segment",
-  "industry",
-  "website",
-  "language",
-  "is_frozen",
-  "column_break_38",
+  "default_receivable_accounts",
+  "accounts",
+  "loyalty_points_tab",
   "loyalty_program",
+  "column_break_54",
   "loyalty_program_tier",
-  "sales_team_section_break",
-  "default_sales_partner",
-  "default_commission_rate",
-  "sales_team_section",
+  "sales_team_tab",
   "sales_team",
-  "customer_pos_id"
+  "sales_team_section",
+  "default_sales_partner",
+  "column_break_66",
+  "default_commission_rate",
+  "settings_tab",
+  "so_required",
+  "dn_required",
+  "column_break_53",
+  "is_frozen",
+  "disabled"
  ],
  "fields": [
   {
    "fieldname": "basic_info",
    "fieldtype": "Section Break",
-   "label": "Name and Type",
    "oldfieldtype": "Section Break",
    "options": "fa fa-user"
   },
@@ -217,24 +227,12 @@
   },
   {
    "depends_on": "represents_company",
-   "fieldname": "allowed_to_transact_section",
-   "fieldtype": "Section Break",
-   "label": "Allowed To Transact With"
-  },
-  {
-   "depends_on": "represents_company",
    "fieldname": "companies",
    "fieldtype": "Table",
    "label": "Allowed To Transact With",
    "options": "Allowed To Transact With"
   },
   {
-   "collapsible": 1,
-   "fieldname": "currency_and_price_list",
-   "fieldtype": "Section Break",
-   "label": "Currency and Price List"
-  },
-  {
    "fieldname": "default_currency",
    "fieldtype": "Link",
    "ignore_user_permissions": 1,
@@ -295,7 +293,7 @@
    "description": "Select, to make the customer searchable with these fields",
    "fieldname": "primary_address_and_contact_detail",
    "fieldtype": "Section Break",
-   "label": "Primary Address and Contact Detail"
+   "label": "Primary Address and Contact"
   },
   {
    "description": "Reselect, if the chosen contact is edited after save",
@@ -334,20 +332,18 @@
    "read_only": 1
   },
   {
-   "collapsible": 1,
    "fieldname": "default_receivable_accounts",
    "fieldtype": "Section Break",
    "label": "Default Receivable Accounts"
   },
   {
-   "description": "Mention if non-standard receivable account",
+   "description": "Mention if a non-standard receivable account",
    "fieldname": "accounts",
    "fieldtype": "Table",
-   "label": "Accounts",
+   "label": "Receivable Accounts",
    "options": "Party Account"
   },
   {
-   "collapsible": 1,
    "fieldname": "credit_limit_section",
    "fieldtype": "Section Break",
    "label": "Credit Limit and Payment Terms"
@@ -398,12 +394,6 @@
    "label": "Is Frozen"
   },
   {
-   "collapsible": 1,
-   "fieldname": "column_break_38",
-   "fieldtype": "Section Break",
-   "label": "Loyalty Points"
-  },
-  {
    "fieldname": "loyalty_program",
    "fieldtype": "Link",
    "label": "Loyalty Program",
@@ -418,15 +408,6 @@
    "read_only": 1
   },
   {
-   "collapsible": 1,
-   "collapsible_depends_on": "default_sales_partner",
-   "fieldname": "sales_team_section_break",
-   "fieldtype": "Section Break",
-   "label": "Sales Partner and Commission",
-   "oldfieldtype": "Section Break",
-   "options": "fa fa-group"
-  },
-  {
    "fieldname": "default_sales_partner",
    "fieldtype": "Link",
    "ignore_user_permissions": 1,
@@ -446,13 +427,12 @@
    "collapsible": 1,
    "collapsible_depends_on": "sales_team",
    "fieldname": "sales_team_section",
-   "fieldtype": "Section Break",
-   "label": "Sales Team"
+   "fieldtype": "Section Break"
   },
   {
    "fieldname": "sales_team",
    "fieldtype": "Table",
-   "label": "Sales Team Details",
+   "label": "Sales Team",
    "oldfieldname": "sales_team",
    "oldfieldtype": "Table",
    "options": "Sales Team"
@@ -498,6 +478,83 @@
    "no_copy": 1,
    "options": "Opportunity",
    "print_hide": 1
+  },
+  {
+   "fieldname": "contact_and_address_tab",
+   "fieldtype": "Tab Break",
+   "label": "Contact & Address"
+  },
+  {
+   "fieldname": "defaults_tab",
+   "fieldtype": "Section Break",
+   "label": "Defaults"
+  },
+  {
+   "fieldname": "settings_tab",
+   "fieldtype": "Tab Break",
+   "label": "Settings"
+  },
+  {
+   "collapsible": 1,
+   "collapsible_depends_on": "default_sales_partner",
+   "fieldname": "sales_team_tab",
+   "fieldtype": "Tab Break",
+   "label": "Sales Team",
+   "oldfieldtype": "Section Break",
+   "options": "fa fa-group"
+  },
+  {
+   "fieldname": "column_break_66",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "column_break_21",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "dashboard_tab",
+   "fieldtype": "Tab Break",
+   "label": "Dashboard",
+   "show_dashboard": 1
+  },
+  {
+   "fieldname": "column_break_53",
+   "fieldtype": "Column Break"
+  },
+  {
+   "collapsible": 1,
+   "fieldname": "loyalty_points_tab",
+   "fieldtype": "Section Break",
+   "label": "Loyalty Points"
+  },
+  {
+   "fieldname": "taxation_section",
+   "fieldtype": "Section Break"
+  },
+  {
+   "fieldname": "accounting_tab",
+   "fieldtype": "Tab Break",
+   "label": "Accounting"
+  },
+  {
+   "fieldname": "tax_tab",
+   "fieldtype": "Tab Break",
+   "label": "Tax"
+  },
+  {
+   "collapsible": 1,
+   "collapsible_depends_on": "is_internal_customer",
+   "fieldname": "internal_customer_section",
+   "fieldtype": "Section Break",
+   "label": "Internal Customer"
+  },
+  {
+   "fieldname": "column_break_70",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "column_break_54",
+   "fieldtype": "Column Break"
   }
  ],
  "icon": "fa fa-user",
@@ -511,7 +568,7 @@
    "link_fieldname": "party"
   }
  ],
- "modified": "2022-04-16 20:32:34.000304",
+ "modified": "2022-11-08 15:52:34.462657",
  "modified_by": "Administrator",
  "module": "Selling",
  "name": "Customer",
diff --git a/erpnext/selling/doctype/customer/customer.py b/erpnext/selling/doctype/customer/customer.py
index 6605685..d0eb377 100644
--- a/erpnext/selling/doctype/customer/customer.py
+++ b/erpnext/selling/doctype/customer/customer.py
@@ -294,7 +294,7 @@
 
 	def after_rename(self, olddn, newdn, merge=False):
 		if frappe.defaults.get_global_default("cust_master_name") == "Customer Name":
-			frappe.db.set(self, "customer_name", newdn)
+			self.db_set("customer_name", newdn)
 
 	def set_loyalty_program(self):
 		if self.loyalty_program:
diff --git a/erpnext/selling/doctype/customer_credit_limit/customer_credit_limit.json b/erpnext/selling/doctype/customer_credit_limit/customer_credit_limit.json
index 800cb57..2fd0c67 100644
--- a/erpnext/selling/doctype/customer_credit_limit/customer_credit_limit.json
+++ b/erpnext/selling/doctype/customer_credit_limit/customer_credit_limit.json
@@ -12,7 +12,7 @@
  ],
  "fields": [
   {
-   "columns": 4,
+   "columns": 3,
    "fieldname": "credit_limit",
    "fieldtype": "Currency",
    "in_list_view": 1,
@@ -31,6 +31,7 @@
    "options": "Company"
   },
   {
+   "columns": 3,
    "default": "0",
    "fieldname": "bypass_credit_limit_check",
    "fieldtype": "Check",
@@ -40,7 +41,7 @@
  ],
  "istable": 1,
  "links": [],
- "modified": "2019-12-31 15:43:05.822328",
+ "modified": "2022-11-08 15:19:13.927194",
  "modified_by": "Administrator",
  "module": "Selling",
  "name": "Customer Credit Limit",
@@ -48,5 +49,6 @@
  "permissions": [],
  "quick_entry": 1,
  "sort_field": "modified",
- "sort_order": "DESC"
+ "sort_order": "DESC",
+ "states": []
 }
\ No newline at end of file
diff --git a/erpnext/selling/doctype/installation_note/installation_note.py b/erpnext/selling/doctype/installation_note/installation_note.py
index dd0b1e8..0ef4754 100644
--- a/erpnext/selling/doctype/installation_note/installation_note.py
+++ b/erpnext/selling/doctype/installation_note/installation_note.py
@@ -87,13 +87,13 @@
 			frappe.throw(_("Please pull items from Delivery Note"))
 
 	def on_update(self):
-		frappe.db.set(self, "status", "Draft")
+		self.db_set("status", "Draft")
 
 	def on_submit(self):
 		self.validate_serial_no()
 		self.update_prevdoc_status()
-		frappe.db.set(self, "status", "Submitted")
+		self.db_set("status", "Submitted")
 
 	def on_cancel(self):
 		self.update_prevdoc_status()
-		frappe.db.set(self, "status", "Cancelled")
+		self.db_set("status", "Cancelled")
diff --git a/erpnext/selling/doctype/quotation/quotation.py b/erpnext/selling/doctype/quotation/quotation.py
index 96092b1..484b8c9 100644
--- a/erpnext/selling/doctype/quotation/quotation.py
+++ b/erpnext/selling/doctype/quotation/quotation.py
@@ -119,10 +119,10 @@
 		if not (self.is_fully_ordered() or self.is_partially_ordered()):
 			get_lost_reasons = frappe.get_list("Quotation Lost Reason", fields=["name"])
 			lost_reasons_lst = [reason.get("name") for reason in get_lost_reasons]
-			frappe.db.set(self, "status", "Lost")
+			self.db_set("status", "Lost")
 
 			if detailed_reason:
-				frappe.db.set(self, "order_lost_reason", detailed_reason)
+				self.db_set("order_lost_reason", detailed_reason)
 
 			for reason in lost_reasons_list:
 				if reason.get("lost_reason") in lost_reasons_lst:
@@ -247,7 +247,7 @@
 			"Quotation": {"doctype": "Sales Order", "validation": {"docstatus": ["=", 1]}},
 			"Quotation Item": {
 				"doctype": "Sales Order Item",
-				"field_map": {"parent": "prevdoc_docname"},
+				"field_map": {"parent": "prevdoc_docname", "name": "quotation_item"},
 				"postprocess": update_item,
 				"condition": lambda doc: doc.qty > 0,
 			},
diff --git a/erpnext/selling/doctype/sales_order/sales_order.py b/erpnext/selling/doctype/sales_order/sales_order.py
index 1f3419f..78e2370 100755
--- a/erpnext/selling/doctype/sales_order/sales_order.py
+++ b/erpnext/selling/doctype/sales_order/sales_order.py
@@ -193,6 +193,9 @@
 			{"Quotation": {"ref_dn_field": "prevdoc_docname", "compare_fields": [["company", "="]]}}
 		)
 
+		if cint(frappe.db.get_single_value("Selling Settings", "maintain_same_sales_rate")):
+			self.validate_rate_with_reference_doc([["Quotation", "prev_docname", "quotation_item"]])
+
 	def update_enquiry_status(self, prevdoc, flag):
 		enq = frappe.db.sql(
 			"select t2.prevdoc_docname from `tabQuotation` t1, `tabQuotation Item` t2 where t2.parent = t1.name and t1.name=%s",
@@ -246,7 +249,7 @@
 		self.update_project()
 		self.update_prevdoc_status("cancel")
 
-		frappe.db.set(self, "status", "Cancelled")
+		self.db_set("status", "Cancelled")
 
 		self.update_blanket_order()
 
diff --git a/erpnext/selling/doctype/sales_order_item/sales_order_item.json b/erpnext/selling/doctype/sales_order_item/sales_order_item.json
index ea0b25f..8c7c552 100644
--- a/erpnext/selling/doctype/sales_order_item/sales_order_item.json
+++ b/erpnext/selling/doctype/sales_order_item/sales_order_item.json
@@ -70,6 +70,7 @@
   "warehouse",
   "target_warehouse",
   "prevdoc_docname",
+  "quotation_item",
   "col_break4",
   "against_blanket_order",
   "blanket_order",
@@ -838,12 +839,20 @@
    "label": "Purchase Order Item",
    "print_hide": 1,
    "read_only": 1
+  },
+  {
+   "fieldname": "quotation_item",
+   "fieldtype": "Data",
+   "hidden": 1,
+   "label": "quotation_item",
+   "no_copy": 1,
+   "read_only": 1
   }
  ],
  "idx": 1,
  "istable": 1,
  "links": [],
- "modified": "2022-10-26 16:05:02.712705",
+ "modified": "2022-11-10 18:20:30.137455",
  "modified_by": "Administrator",
  "module": "Selling",
  "name": "Sales Order Item",
diff --git a/erpnext/setup/doctype/company/company.py b/erpnext/setup/doctype/company/company.py
index 490504a..875f63d 100644
--- a/erpnext/setup/doctype/company/company.py
+++ b/erpnext/setup/doctype/company/company.py
@@ -207,15 +207,14 @@
 		frappe.local.flags.ignore_root_company_validation = True
 		create_charts(self.name, self.chart_of_accounts, self.existing_company)
 
-		frappe.db.set(
-			self,
+		self.db_set(
 			"default_receivable_account",
 			frappe.db.get_value(
 				"Account", {"company": self.name, "account_type": "Receivable", "is_group": 0}
 			),
 		)
-		frappe.db.set(
-			self,
+
+		self.db_set(
 			"default_payable_account",
 			frappe.db.get_value(
 				"Account", {"company": self.name, "account_type": "Payable", "is_group": 0}
@@ -491,12 +490,12 @@
 				cc_doc.flags.ignore_mandatory = True
 			cc_doc.insert()
 
-		frappe.db.set(self, "cost_center", _("Main") + " - " + self.abbr)
-		frappe.db.set(self, "round_off_cost_center", _("Main") + " - " + self.abbr)
-		frappe.db.set(self, "depreciation_cost_center", _("Main") + " - " + self.abbr)
+		self.db_set("cost_center", _("Main") + " - " + self.abbr)
+		self.db_set("round_off_cost_center", _("Main") + " - " + self.abbr)
+		self.db_set("depreciation_cost_center", _("Main") + " - " + self.abbr)
 
 	def after_rename(self, olddn, newdn, merge=False):
-		frappe.db.set(self, "company_name", newdn)
+		self.db_set("company_name", newdn)
 
 		frappe.db.sql(
 			"""update `tabDefaultValue` set defvalue=%s
diff --git a/erpnext/stock/doctype/material_request/material_request.py b/erpnext/stock/doctype/material_request/material_request.py
index 2614a7f..817248e 100644
--- a/erpnext/stock/doctype/material_request/material_request.py
+++ b/erpnext/stock/doctype/material_request/material_request.py
@@ -120,7 +120,6 @@
 			self.title = _("{0} Request for {1}").format(self.material_request_type, items)[:100]
 
 	def on_submit(self):
-		# frappe.db.set(self, 'status', 'Submitted')
 		self.update_requested_qty()
 		self.update_requested_qty_in_production_plan()
 		if self.material_request_type == "Purchase":
diff --git a/erpnext/stock/doctype/material_request/test_material_request.py b/erpnext/stock/doctype/material_request/test_material_request.py
index f02462c..f0a9499 100644
--- a/erpnext/stock/doctype/material_request/test_material_request.py
+++ b/erpnext/stock/doctype/material_request/test_material_request.py
@@ -216,7 +216,7 @@
 		po.load_from_db()
 		mr.update_status("Stopped")
 		self.assertRaises(frappe.InvalidStatusError, po.submit)
-		frappe.db.set(po, "docstatus", 1)
+		po.db_set("docstatus", 1)
 		self.assertRaises(frappe.InvalidStatusError, po.cancel)
 
 		# resubmit and check for per complete
diff --git a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
index f85c478..673fcb5 100644
--- a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
+++ b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.py
@@ -6,7 +6,9 @@
 from frappe import _, throw
 from frappe.desk.notifications import clear_doctype_notifications
 from frappe.model.mapper import get_mapped_doc
+from frappe.query_builder.functions import CombineDatetime
 from frappe.utils import cint, flt, getdate, nowdate
+from pypika import functions as fn
 
 import erpnext
 from erpnext.accounts.utils import get_account_currency
@@ -750,48 +752,38 @@
 
 	def update_billing_status(self, update_modified=True):
 		updated_pr = [self.name]
+		po_details = []
 		for d in self.get("items"):
 			if d.get("purchase_invoice") and d.get("purchase_invoice_item"):
 				d.db_set("billed_amt", d.amount, update_modified=update_modified)
 			elif d.purchase_order_item:
-				updated_pr += update_billed_amount_based_on_po(d.purchase_order_item, update_modified)
+				po_details.append(d.purchase_order_item)
+
+		if po_details:
+			updated_pr += update_billed_amount_based_on_po(po_details, update_modified)
 
 		for pr in set(updated_pr):
-			pr_doc = self if (pr == self.name) else frappe.get_doc("Purchase Receipt", pr)
+			pr_doc = self if (pr == self.name) else frappe.get_cached_doc("Purchase Receipt", pr)
 			update_billing_percentage(pr_doc, update_modified=update_modified)
 
 		self.load_from_db()
 
 
-def update_billed_amount_based_on_po(po_detail, update_modified=True):
-	# Billed against Sales Order directly
-	billed_against_po = frappe.db.sql(
-		"""select sum(amount) from `tabPurchase Invoice Item`
-		where po_detail=%s and (pr_detail is null or pr_detail = '') and docstatus=1""",
-		po_detail,
-	)
-	billed_against_po = billed_against_po and billed_against_po[0][0] or 0
+def update_billed_amount_based_on_po(po_details, update_modified=True):
+	po_billed_amt_details = get_billed_amount_against_po(po_details)
 
-	# Get all Purchase Receipt Item rows against the Purchase Order Item row
-	pr_details = frappe.db.sql(
-		"""select pr_item.name, pr_item.amount, pr_item.parent
-		from `tabPurchase Receipt Item` pr_item, `tabPurchase Receipt` pr
-		where pr.name=pr_item.parent and pr_item.purchase_order_item=%s
-			and pr.docstatus=1 and pr.is_return = 0
-		order by pr.posting_date asc, pr.posting_time asc, pr.name asc""",
-		po_detail,
-		as_dict=1,
-	)
+	# Get all Purchase Receipt Item rows against the Purchase Order Items
+	pr_details = get_purchase_receipts_against_po_details(po_details)
+
+	pr_items = [pr_detail.name for pr_detail in pr_details]
+	pr_items_billed_amount = get_billed_amount_against_pr(pr_items)
 
 	updated_pr = []
 	for pr_item in pr_details:
+		billed_against_po = flt(po_billed_amt_details.get(pr_item.purchase_order_item))
+
 		# Get billed amount directly against Purchase Receipt
-		billed_amt_agianst_pr = frappe.db.sql(
-			"""select sum(amount) from `tabPurchase Invoice Item`
-			where pr_detail=%s and docstatus=1""",
-			pr_item.name,
-		)
-		billed_amt_agianst_pr = billed_amt_agianst_pr and billed_amt_agianst_pr[0][0] or 0
+		billed_amt_agianst_pr = flt(pr_items_billed_amount.get(pr_item.name, 0))
 
 		# Distribute billed amount directly against PO between PRs based on FIFO
 		if billed_against_po and billed_amt_agianst_pr < pr_item.amount:
@@ -803,19 +795,90 @@
 				billed_amt_agianst_pr += billed_against_po
 				billed_against_po = 0
 
-		frappe.db.set_value(
-			"Purchase Receipt Item",
-			pr_item.name,
-			"billed_amt",
-			billed_amt_agianst_pr,
-			update_modified=update_modified,
-		)
+		po_billed_amt_details[pr_item.purchase_order_item] = billed_against_po
 
-		updated_pr.append(pr_item.parent)
+		if pr_item.billed_amt != billed_amt_agianst_pr:
+			frappe.db.set_value(
+				"Purchase Receipt Item",
+				pr_item.name,
+				"billed_amt",
+				billed_amt_agianst_pr,
+				update_modified=update_modified,
+			)
+
+			updated_pr.append(pr_item.parent)
 
 	return updated_pr
 
 
+def get_purchase_receipts_against_po_details(po_details):
+	# Get Purchase Receipts against Purchase Order Items
+
+	purchase_receipt = frappe.qb.DocType("Purchase Receipt")
+	purchase_receipt_item = frappe.qb.DocType("Purchase Receipt Item")
+
+	query = (
+		frappe.qb.from_(purchase_receipt)
+		.inner_join(purchase_receipt_item)
+		.on(purchase_receipt.name == purchase_receipt_item.parent)
+		.select(
+			purchase_receipt_item.name,
+			purchase_receipt_item.parent,
+			purchase_receipt_item.amount,
+			purchase_receipt_item.billed_amt,
+			purchase_receipt_item.purchase_order_item,
+		)
+		.where(
+			(purchase_receipt_item.purchase_order_item.isin(po_details))
+			& (purchase_receipt.docstatus == 1)
+			& (purchase_receipt.is_return == 0)
+		)
+		.orderby(CombineDatetime(purchase_receipt.posting_date, purchase_receipt.posting_time))
+		.orderby(purchase_receipt.name)
+	)
+
+	return query.run(as_dict=True)
+
+
+def get_billed_amount_against_pr(pr_items):
+	# Get billed amount directly against Purchase Receipt
+
+	if not pr_items:
+		return {}
+
+	purchase_invoice_item = frappe.qb.DocType("Purchase Invoice Item")
+
+	query = (
+		frappe.qb.from_(purchase_invoice_item)
+		.select(fn.Sum(purchase_invoice_item.amount).as_("billed_amt"), purchase_invoice_item.pr_detail)
+		.where((purchase_invoice_item.pr_detail.isin(pr_items)) & (purchase_invoice_item.docstatus == 1))
+		.groupby(purchase_invoice_item.pr_detail)
+	).run(as_dict=1)
+
+	return {d.pr_detail: flt(d.billed_amt) for d in query}
+
+
+def get_billed_amount_against_po(po_items):
+	# Get billed amount directly against Purchase Order
+	if not po_items:
+		return {}
+
+	purchase_invoice_item = frappe.qb.DocType("Purchase Invoice Item")
+
+	query = (
+		frappe.qb.from_(purchase_invoice_item)
+		.select(fn.Sum(purchase_invoice_item.amount).as_("billed_amt"), purchase_invoice_item.po_detail)
+		.where(
+			(purchase_invoice_item.po_detail.isin(po_items))
+			& (purchase_invoice_item.docstatus == 1)
+			& (purchase_invoice_item.pr_detail.isnull())
+		)
+		.groupby(purchase_invoice_item.po_detail)
+	).run(as_dict=1)
+
+	return {d.po_detail: flt(d.billed_amt) for d in query}
+
+
 def update_billing_percentage(pr_doc, update_modified=True):
 	# Reload as billed amount was set in db directly
 	pr_doc.load_from_db()
diff --git a/erpnext/stock/doctype/stock_entry/stock_entry_list.js b/erpnext/stock/doctype/stock_entry/stock_entry_list.js
index 4eb0da1..af29d49 100644
--- a/erpnext/stock/doctype/stock_entry/stock_entry_list.js
+++ b/erpnext/stock/doctype/stock_entry/stock_entry_list.js
@@ -3,7 +3,6 @@
 		"`tabStock Entry`.`purpose`", "`tabStock Entry`.`work_order`", "`tabStock Entry`.`bom_no`",
 		"`tabStock Entry`.`is_return`"],
 	get_indicator: function (doc) {
-		debugger
 		if(doc.is_return===1 && doc.purpose === "Material Transfer for Manufacture") {
 			return [__("Material Returned from WIP"), "orange",
 				"is_return,=,1|purpose,=,Material Transfer for Manufacture|docstatus,<,2"];
diff --git a/erpnext/stock/get_item_details.py b/erpnext/stock/get_item_details.py
index e83182f..108611c 100644
--- a/erpnext/stock/get_item_details.py
+++ b/erpnext/stock/get_item_details.py
@@ -330,6 +330,9 @@
 		else:
 			args.uom = item.stock_uom
 
+	# Set stock UOM in args, so that it can be used while fetching item price
+	args.stock_uom = item.stock_uom
+
 	if args.get("batch_no") and item.name != frappe.get_cached_value(
 		"Batch", args.get("batch_no"), "item"
 	):
diff --git a/erpnext/stock/report/warehouse_wise_item_balance_age_and_value/warehouse_wise_item_balance_age_and_value.py b/erpnext/stock/report/warehouse_wise_item_balance_age_and_value/warehouse_wise_item_balance_age_and_value.py
index eedf1a0..b5c6764 100644
--- a/erpnext/stock/report/warehouse_wise_item_balance_age_and_value/warehouse_wise_item_balance_age_and_value.py
+++ b/erpnext/stock/report/warehouse_wise_item_balance_age_and_value/warehouse_wise_item_balance_age_and_value.py
@@ -91,8 +91,8 @@
 	columns = [
 		_("Item") + ":Link/Item:180",
 		_("Item Group") + "::100",
-		_("Value") + ":Currency:100",
-		_("Age") + ":Float:60",
+		_("Value") + ":Currency:120",
+		_("Age") + ":Float:80",
 	]
 	return columns
 
@@ -123,7 +123,7 @@
 
 def add_warehouse_column(columns, warehouse_list):
 	if len(warehouse_list) > 1:
-		columns += [_("Total Qty") + ":Int:50"]
+		columns += [_("Total Qty") + ":Int:90"]
 
 	for wh in warehouse_list:
-		columns += [_(wh.name) + ":Int:54"]
+		columns += [_(wh.name) + ":Int:120"]
diff --git a/erpnext/subcontracting/doctype/subcontracting_receipt/subcontracting_receipt.js b/erpnext/subcontracting/doctype/subcontracting_receipt/subcontracting_receipt.js
index aff76eb..b6bef8c 100644
--- a/erpnext/subcontracting/doctype/subcontracting_receipt/subcontracting_receipt.js
+++ b/erpnext/subcontracting/doctype/subcontracting_receipt/subcontracting_receipt.js
@@ -57,6 +57,18 @@
 				filters: { 'company': frm.doc.company }
 			};
 		});
+
+		frappe.db.get_single_value('Buying Settings', 'backflush_raw_materials_of_subcontract_based_on').then(val => {
+			if (val == 'Material Transferred for Subcontract') {
+				frm.fields_dict['supplied_items'].grid.grid_rows.forEach((grid_row) => {
+					grid_row.docfields.forEach((df) => {
+						if (df.fieldname == 'consumed_qty') {
+							df.read_only = 0;
+						}
+					});
+				});
+			}
+		});
 	},
 
 	refresh: (frm) => {
diff --git a/erpnext/subcontracting/doctype/subcontracting_receipt/subcontracting_receipt.py b/erpnext/subcontracting/doctype/subcontracting_receipt/subcontracting_receipt.py
index bce5360..c7f592b 100644
--- a/erpnext/subcontracting/doctype/subcontracting_receipt/subcontracting_receipt.py
+++ b/erpnext/subcontracting/doctype/subcontracting_receipt/subcontracting_receipt.py
@@ -58,6 +58,7 @@
 	def before_validate(self):
 		super(SubcontractingReceipt, self).before_validate()
 		self.set_items_bom()
+		self.set_received_qty()
 		self.set_items_cost_center()
 		self.set_items_expense_account()
 
@@ -212,6 +213,10 @@
 						"bom",
 					)
 
+	def set_received_qty(self):
+		for item in self.items:
+			item.received_qty = flt(item.qty) + flt(item.rejected_qty)
+
 	def set_items_cost_center(self):
 		if self.company:
 			cost_center = frappe.get_cached_value("Company", self.company, "cost_center")
diff --git a/erpnext/subcontracting/doctype/subcontracting_receipt/subcontracting_receipt_dashboard.py b/erpnext/subcontracting/doctype/subcontracting_receipt/subcontracting_receipt_dashboard.py
index a9e5193..deb8342 100644
--- a/erpnext/subcontracting/doctype/subcontracting_receipt/subcontracting_receipt_dashboard.py
+++ b/erpnext/subcontracting/doctype/subcontracting_receipt/subcontracting_receipt_dashboard.py
@@ -4,6 +4,9 @@
 def get_data():
 	return {
 		"fieldname": "subcontracting_receipt_no",
+		"non_standard_fieldnames": {
+			"Subcontracting Receipt": "return_against",
+		},
 		"internal_links": {
 			"Subcontracting Order": ["items", "subcontracting_order"],
 			"Project": ["items", "project"],
@@ -11,5 +14,6 @@
 		},
 		"transactions": [
 			{"label": _("Reference"), "items": ["Subcontracting Order", "Quality Inspection", "Project"]},
+			{"label": _("Returns"), "items": ["Subcontracting Receipt"]},
 		],
 	}
diff --git a/erpnext/subcontracting/doctype/subcontracting_receipt/test_subcontracting_receipt.py b/erpnext/subcontracting/doctype/subcontracting_receipt/test_subcontracting_receipt.py
index 34e7842..ca72ddf 100644
--- a/erpnext/subcontracting/doctype/subcontracting_receipt/test_subcontracting_receipt.py
+++ b/erpnext/subcontracting/doctype/subcontracting_receipt/test_subcontracting_receipt.py
@@ -468,6 +468,65 @@
 		scr.cancel()
 		self.assertTrue(get_gl_entries("Subcontracting Receipt", scr.name))
 
+	def test_supplied_items_consumed_qty(self):
+		# Set Backflush Based On as "Material Transferred for Subcontracting" to transfer RM's more than the required qty
+		set_backflush_based_on("Material Transferred for Subcontract")
+
+		# Create Material Receipt for RM's
+		make_stock_entry(
+			item_code="_Test Item", qty=100, target="_Test Warehouse 1 - _TC", basic_rate=100
+		)
+		make_stock_entry(
+			item_code="_Test Item Home Desktop 100",
+			qty=100,
+			target="_Test Warehouse 1 - _TC",
+			basic_rate=100,
+		)
+
+		service_items = [
+			{
+				"warehouse": "_Test Warehouse - _TC",
+				"item_code": "Subcontracted Service Item 1",
+				"qty": 10,
+				"rate": 100,
+				"fg_item": "_Test FG Item",
+				"fg_item_qty": 10,
+			},
+		]
+
+		# Create Subcontracting Order
+		sco = get_subcontracting_order(service_items=service_items)
+
+		# Transfer RM's
+		rm_items = get_rm_items(sco.supplied_items)
+		rm_items[0]["qty"] = 20  # Extra 10 Qty
+		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 Subcontracting Receipt
+		scr = make_subcontracting_receipt(sco.name)
+		scr.rejected_warehouse = "_Test Warehouse 1 - _TC"
+
+		scr.items[0].qty = 5  # Accepted Qty
+		scr.items[0].rejected_qty = 3
+		scr.save()
+
+		# consumed_qty should be ((received_qty) * (transfered_qty / qty)) = ((5 + 3) * (20 / 10)) = 16
+		self.assertEqual(scr.supplied_items[0].consumed_qty, 16)
+
+		# Set Backflush Based On as "BOM"
+		set_backflush_based_on("BOM")
+
+		scr.items[0].rejected_qty = 4
+		scr.save()
+
+		# consumed_qty should be ((received_qty) * (qty_consumed_per_unit)) = ((5 + 4) * (1)) = 9
+		self.assertEqual(scr.supplied_items[0].consumed_qty, 9)
+
 
 def make_return_subcontracting_receipt(**args):
 	args = frappe._dict(args)
diff --git a/erpnext/subcontracting/doctype/subcontracting_receipt_supplied_item/subcontracting_receipt_supplied_item.json b/erpnext/subcontracting/doctype/subcontracting_receipt_supplied_item/subcontracting_receipt_supplied_item.json
index ddbb806..d21bc22 100644
--- a/erpnext/subcontracting/doctype/subcontracting_receipt_supplied_item/subcontracting_receipt_supplied_item.json
+++ b/erpnext/subcontracting/doctype/subcontracting_receipt_supplied_item/subcontracting_receipt_supplied_item.json
@@ -1,207 +1,208 @@
 {
-    "actions": [],
-    "creation": "2022-04-18 10:45:16.538479",
-    "doctype": "DocType",
-    "editable_grid": 1,
-    "engine": "InnoDB",
-    "field_order": [
-        "main_item_code",
-        "rm_item_code",
-        "item_name",
-        "bom_detail_no",
-        "col_break1",
-        "description",
-        "stock_uom",
-        "conversion_factor",
-        "reference_name",
-        "secbreak_1",
-        "rate",
-        "col_break2",
-        "amount",
-        "secbreak_2",
-        "available_qty_for_consumption",
-        "required_qty",
-        "col_break3",
-        "consumed_qty",
-        "current_stock",
-        "secbreak_3",
-        "batch_no",
-        "col_break4",
-        "serial_no",
-        "subcontracting_order"
-    ],
-    "fields": [
-        {
-            "fieldname": "main_item_code",
-            "fieldtype": "Link",
-            "in_list_view": 1,
-            "label": "Item Code",
-            "options": "Item",
-            "read_only": 1
-        },
-        {
-            "fieldname": "rm_item_code",
-            "fieldtype": "Link",
-            "in_list_view": 1,
-            "label": "Raw Material Item Code",
-            "options": "Item",
-            "read_only": 1
-        },
-        {
-            "fieldname": "description",
-            "fieldtype": "Text Editor",
-            "in_global_search": 1,
-            "label": "Description",
-            "print_width": "300px",
-            "read_only": 1,
-            "width": "300px"
-        },
-        {
-            "fieldname": "batch_no",
-            "fieldtype": "Link",
-            "label": "Batch No",
-            "no_copy": 1,
-            "options": "Batch"
-        },
-        {
-            "fieldname": "serial_no",
-            "fieldtype": "Text",
-            "label": "Serial No",
-            "no_copy": 1
-        },
-        {
-            "fieldname": "col_break1",
-            "fieldtype": "Column Break"
-        },
-        {
-            "fieldname": "required_qty",
-            "fieldtype": "Float",
-            "label": "Required Qty",
-            "print_hide": 1,
-            "read_only": 1
-        },
-        {
-            "columns": 2,
-            "fieldname": "consumed_qty",
-            "fieldtype": "Float",
-            "in_list_view": 1,
-            "label": "Consumed Qty",
-            "reqd": 1
-        },
-        {
-            "fieldname": "stock_uom",
-            "fieldtype": "Link",
-            "label": "Stock Uom",
-            "options": "UOM",
-            "read_only": 1
-        },
-        {
-            "fieldname": "rate",
-            "fieldtype": "Currency",
-            "label": "Rate",
-            "options": "Company:company:default_currency",
-            "read_only": 1
-        },
-        {
-            "fieldname": "amount",
-            "fieldtype": "Currency",
-            "label": "Amount",
-            "options": "Company:company:default_currency",
-            "read_only": 1
-        },
-        {
-            "default": "1",
-            "fieldname": "conversion_factor",
-            "fieldtype": "Float",
-            "hidden": 1,
-            "label": "Conversion Factor",
-            "read_only": 1
-        },
-        {
-            "fieldname": "current_stock",
-            "fieldtype": "Float",
-            "in_list_view": 1,
-            "label": "Current Stock",
-            "read_only": 1
-        },
-        {
-            "fieldname": "reference_name",
-            "fieldtype": "Data",
-            "hidden": 1,
-            "in_list_view": 1,
-            "label": "Reference Name",
-            "read_only": 1
-        },
-        {
-            "fieldname": "bom_detail_no",
-            "fieldtype": "Data",
-            "hidden": 1,
-            "in_list_view": 1,
-            "label": "BOM Detail No",
-            "read_only": 1
-        },
-        {
-            "fieldname": "secbreak_1",
-            "fieldtype": "Section Break"
-        },
-        {
-            "fieldname": "col_break2",
-            "fieldtype": "Column Break"
-        },
-        {
-            "fieldname": "secbreak_2",
-            "fieldtype": "Section Break"
-        },
-        {
-            "fieldname": "col_break3",
-            "fieldtype": "Column Break"
-        },
-        {
-            "fieldname": "secbreak_3",
-            "fieldtype": "Section Break"
-        },
-        {
-            "fieldname": "col_break4",
-            "fieldtype": "Column Break"
-        },
-        {
-            "fieldname": "item_name",
-            "fieldtype": "Data",
-            "label": "Item Name",
-            "read_only": 1
-        },
-        {
-            "fieldname": "subcontracting_order",
-            "fieldtype": "Link",
-            "hidden": 1,
-            "label": "Subcontracting Order",
-            "no_copy": 1,
-            "options": "Subcontracting Order",
-            "print_hide": 1,
-            "read_only": 1
-        },
-        {
-            "default": "0",
-            "fieldname": "available_qty_for_consumption",
-            "fieldtype": "Float",
-            "in_list_view": 1,
-            "label": "Available Qty For Consumption",
-            "print_hide": 1,
-            "read_only": 1
-        }
-    ],
-    "idx": 1,
-    "istable": 1,
-    "links": [],
-    "modified": "2022-09-02 22:28:53.392381",
-    "modified_by": "Administrator",
-    "module": "Subcontracting",
-    "name": "Subcontracting Receipt Supplied Item",
-    "naming_rule": "Autoincrement",
-    "owner": "Administrator",
-    "permissions": [],
-    "sort_field": "modified",
-    "sort_order": "DESC",
-    "states": [],
-    "track_changes": 1
+ "actions": [],
+ "creation": "2022-04-18 10:45:16.538479",
+ "doctype": "DocType",
+ "editable_grid": 1,
+ "engine": "InnoDB",
+ "field_order": [
+  "main_item_code",
+  "rm_item_code",
+  "item_name",
+  "bom_detail_no",
+  "col_break1",
+  "description",
+  "stock_uom",
+  "conversion_factor",
+  "reference_name",
+  "secbreak_1",
+  "rate",
+  "col_break2",
+  "amount",
+  "secbreak_2",
+  "available_qty_for_consumption",
+  "required_qty",
+  "col_break3",
+  "consumed_qty",
+  "current_stock",
+  "secbreak_3",
+  "batch_no",
+  "col_break4",
+  "serial_no",
+  "subcontracting_order"
+ ],
+ "fields": [
+  {
+   "fieldname": "main_item_code",
+   "fieldtype": "Link",
+   "in_list_view": 1,
+   "label": "Item Code",
+   "options": "Item",
+   "read_only": 1
+  },
+  {
+   "fieldname": "rm_item_code",
+   "fieldtype": "Link",
+   "in_list_view": 1,
+   "label": "Raw Material Item Code",
+   "options": "Item",
+   "read_only": 1
+  },
+  {
+   "fieldname": "description",
+   "fieldtype": "Text Editor",
+   "in_global_search": 1,
+   "label": "Description",
+   "print_width": "300px",
+   "read_only": 1,
+   "width": "300px"
+  },
+  {
+   "fieldname": "batch_no",
+   "fieldtype": "Link",
+   "label": "Batch No",
+   "no_copy": 1,
+   "options": "Batch"
+  },
+  {
+   "fieldname": "serial_no",
+   "fieldtype": "Text",
+   "label": "Serial No",
+   "no_copy": 1
+  },
+  {
+   "fieldname": "col_break1",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "required_qty",
+   "fieldtype": "Float",
+   "label": "Required Qty",
+   "print_hide": 1,
+   "read_only": 1
+  },
+  {
+   "columns": 2,
+   "fieldname": "consumed_qty",
+   "fieldtype": "Float",
+   "in_list_view": 1,
+   "label": "Consumed Qty",
+   "read_only": 1,
+   "reqd": 1
+  },
+  {
+   "fieldname": "stock_uom",
+   "fieldtype": "Link",
+   "label": "Stock Uom",
+   "options": "UOM",
+   "read_only": 1
+  },
+  {
+   "fieldname": "rate",
+   "fieldtype": "Currency",
+   "label": "Rate",
+   "options": "Company:company:default_currency",
+   "read_only": 1
+  },
+  {
+   "fieldname": "amount",
+   "fieldtype": "Currency",
+   "label": "Amount",
+   "options": "Company:company:default_currency",
+   "read_only": 1
+  },
+  {
+   "default": "1",
+   "fieldname": "conversion_factor",
+   "fieldtype": "Float",
+   "hidden": 1,
+   "label": "Conversion Factor",
+   "read_only": 1
+  },
+  {
+   "fieldname": "current_stock",
+   "fieldtype": "Float",
+   "in_list_view": 1,
+   "label": "Current Stock",
+   "read_only": 1
+  },
+  {
+   "fieldname": "reference_name",
+   "fieldtype": "Data",
+   "hidden": 1,
+   "in_list_view": 1,
+   "label": "Reference Name",
+   "read_only": 1
+  },
+  {
+   "fieldname": "bom_detail_no",
+   "fieldtype": "Data",
+   "hidden": 1,
+   "in_list_view": 1,
+   "label": "BOM Detail No",
+   "read_only": 1
+  },
+  {
+   "fieldname": "secbreak_1",
+   "fieldtype": "Section Break"
+  },
+  {
+   "fieldname": "col_break2",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "secbreak_2",
+   "fieldtype": "Section Break"
+  },
+  {
+   "fieldname": "col_break3",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "secbreak_3",
+   "fieldtype": "Section Break"
+  },
+  {
+   "fieldname": "col_break4",
+   "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "item_name",
+   "fieldtype": "Data",
+   "label": "Item Name",
+   "read_only": 1
+  },
+  {
+   "fieldname": "subcontracting_order",
+   "fieldtype": "Link",
+   "hidden": 1,
+   "label": "Subcontracting Order",
+   "no_copy": 1,
+   "options": "Subcontracting Order",
+   "print_hide": 1,
+   "read_only": 1
+  },
+  {
+   "default": "0",
+   "fieldname": "available_qty_for_consumption",
+   "fieldtype": "Float",
+   "in_list_view": 1,
+   "label": "Available Qty For Consumption",
+   "print_hide": 1,
+   "read_only": 1
+  }
+ ],
+ "idx": 1,
+ "istable": 1,
+ "links": [],
+ "modified": "2022-11-07 17:17:21.670761",
+ "modified_by": "Administrator",
+ "module": "Subcontracting",
+ "name": "Subcontracting Receipt Supplied Item",
+ "naming_rule": "Autoincrement",
+ "owner": "Administrator",
+ "permissions": [],
+ "sort_field": "modified",
+ "sort_order": "DESC",
+ "states": [],
+ "track_changes": 1
 }
\ No newline at end of file
diff --git a/erpnext/support/doctype/warranty_claim/warranty_claim.py b/erpnext/support/doctype/warranty_claim/warranty_claim.py
index 5e2ea06..c86356f 100644
--- a/erpnext/support/doctype/warranty_claim/warranty_claim.py
+++ b/erpnext/support/doctype/warranty_claim/warranty_claim.py
@@ -35,7 +35,7 @@
 			lst1 = ",".join(x[0] for x in lst)
 			frappe.throw(_("Cancel Material Visit {0} before cancelling this Warranty Claim").format(lst1))
 		else:
-			frappe.db.set(self, "status", "Cancelled")
+			self.db_set("status", "Cancelled")
 
 	def on_update(self):
 		pass
diff --git a/erpnext/translations/de.csv b/erpnext/translations/de.csv
index ca16403..0caea25 100644
--- a/erpnext/translations/de.csv
+++ b/erpnext/translations/de.csv
@@ -9899,3 +9899,7 @@
 Website Item,Webseiten-Artikel,
 Update Property,Eigenschaft aktualisieren,
 Recurring Sales Invoice,Wiederkehrende Ausgangsrechnung,
+Total Asset,Aktiva,
+Total Liability,Verbindlichkeiten,
+Total Equity,Eigenkapital,
+Warehouse wise Stock Value,Warenwert nach Lager,