Merge pull request #32339 from rohitwaghchaure/fixed-opening-entry-trial-balance-issue

fix: opening entry causing discrepancy between stock and trial balance
diff --git a/erpnext/accounts/doctype/journal_entry/journal_entry.py b/erpnext/accounts/doctype/journal_entry/journal_entry.py
index 63c6547..52690e1 100644
--- a/erpnext/accounts/doctype/journal_entry/journal_entry.py
+++ b/erpnext/accounts/doctype/journal_entry/journal_entry.py
@@ -184,7 +184,9 @@
 			}
 		)
 
-		tax_withholding_details = get_party_tax_withholding_details(inv, self.tax_withholding_category)
+		tax_withholding_details, advance_taxes, voucher_wise_amount = get_party_tax_withholding_details(
+			inv, self.tax_withholding_category
+		)
 
 		if not tax_withholding_details:
 			return
diff --git a/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.py b/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.py
index 601fc87..52efd33 100644
--- a/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.py
+++ b/erpnext/accounts/doctype/payment_reconciliation/payment_reconciliation.py
@@ -14,6 +14,7 @@
 	QueryPaymentLedger,
 	get_outstanding_invoices,
 	reconcile_against_document,
+	update_reference_in_payment_entry,
 )
 from erpnext.controllers.accounts_controller import get_advance_payment_entries
 
@@ -212,6 +213,23 @@
 			inv.currency = entry.get("currency")
 			inv.outstanding_amount = flt(entry.get("outstanding_amount"))
 
+	def get_difference_amount(self, allocated_entry):
+		if allocated_entry.get("reference_type") != "Payment Entry":
+			return
+
+		dr_or_cr = (
+			"credit_in_account_currency"
+			if erpnext.get_party_account_type(self.party_type) == "Receivable"
+			else "debit_in_account_currency"
+		)
+
+		row = self.get_payment_details(allocated_entry, dr_or_cr)
+
+		doc = frappe.get_doc(allocated_entry.reference_type, allocated_entry.reference_name)
+		update_reference_in_payment_entry(row, doc, do_not_save=True)
+
+		return doc.difference_amount
+
 	@frappe.whitelist()
 	def allocate_entries(self, args):
 		self.validate_entries()
@@ -227,12 +245,16 @@
 					res = self.get_allocated_entry(pay, inv, pay["amount"])
 					inv["outstanding_amount"] = flt(inv.get("outstanding_amount")) - flt(pay.get("amount"))
 					pay["amount"] = 0
+
+				res.difference_amount = self.get_difference_amount(res)
+
 				if pay.get("amount") == 0:
 					entries.append(res)
 					break
 				elif inv.get("outstanding_amount") == 0:
 					entries.append(res)
 					continue
+
 			else:
 				break
 
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json
index 534b879..986fc03 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json
@@ -83,6 +83,8 @@
   "section_break_51",
   "taxes_and_charges",
   "taxes",
+  "tax_withheld_vouchers_section",
+  "tax_withheld_vouchers",
   "sec_tax_breakup",
   "other_charges_calculation",
   "totals",
@@ -512,7 +514,6 @@
    "fieldname": "ignore_pricing_rule",
    "fieldtype": "Check",
    "label": "Ignore Pricing Rule",
-   "no_copy": 1,
    "permlevel": 1,
    "print_hide": 1
   },
@@ -1367,7 +1368,7 @@
    "width": "50px"
   },
   {
-    "depends_on": "eval:doc.is_subcontracted",
+   "depends_on": "eval:doc.is_subcontracted",
    "fieldname": "supplier_warehouse",
    "fieldtype": "Link",
    "label": "Supplier Warehouse",
@@ -1426,13 +1427,25 @@
    "hidden": 1,
    "label": "Is Old Subcontracting Flow",
    "read_only": 1
-   }
+  },
+  {
+   "fieldname": "tax_withheld_vouchers_section",
+   "fieldtype": "Section Break",
+   "label": "Tax Withheld Vouchers"
+  },
+  {
+   "fieldname": "tax_withheld_vouchers",
+   "fieldtype": "Table",
+   "label": "Tax Withheld Vouchers",
+   "options": "Tax Withheld Vouchers",
+   "read_only": 1
+  }
  ],
  "icon": "fa fa-file-text",
  "idx": 204,
  "is_submittable": 1,
  "links": [],
- "modified": "2022-06-15 15:40:58.527065",
+ "modified": "2022-09-13 23:39:54.525037",
  "modified_by": "Administrator",
  "module": "Accounts",
  "name": "Purchase Invoice",
@@ -1492,6 +1505,7 @@
  "show_name_in_global_search": 1,
  "sort_field": "modified",
  "sort_order": "DESC",
+ "states": [],
  "timeline_field": "supplier",
  "title_field": "title",
  "track_changes": 1
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
index fea81e9..d185300 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.py
@@ -1519,7 +1519,7 @@
 		if not self.tax_withholding_category:
 			return
 
-		tax_withholding_details, advance_taxes = get_party_tax_withholding_details(
+		tax_withholding_details, advance_taxes, voucher_wise_amount = get_party_tax_withholding_details(
 			self, self.tax_withholding_category
 		)
 
@@ -1548,6 +1548,19 @@
 		for d in to_remove:
 			self.remove(d)
 
+		## Add pending vouchers on which tax was withheld
+		self.set("tax_withheld_vouchers", [])
+
+		for voucher_no, voucher_details in voucher_wise_amount.items():
+			self.append(
+				"tax_withheld_vouchers",
+				{
+					"voucher_name": voucher_no,
+					"voucher_type": voucher_details.get("voucher_type"),
+					"taxable_amount": voucher_details.get("amount"),
+				},
+			)
+
 		# calculate totals again after applying TDS
 		self.calculate_taxes_and_totals()
 
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.json b/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
index 1c9d3fb..2da5157 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
@@ -649,7 +649,6 @@
    "hide_days": 1,
    "hide_seconds": 1,
    "label": "Ignore Pricing Rule",
-   "no_copy": 1,
    "print_hide": 1
   },
   {
@@ -2022,7 +2021,7 @@
    "link_fieldname": "consolidated_invoice"
   }
  ],
- "modified": "2022-07-11 17:43:56.435382",
+ "modified": "2022-09-16 17:44:22.227332",
  "modified_by": "Administrator",
  "module": "Accounts",
  "name": "Sales Invoice",
diff --git a/erpnext/accounts/doctype/tax_withheld_vouchers/__init__.py b/erpnext/accounts/doctype/tax_withheld_vouchers/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/accounts/doctype/tax_withheld_vouchers/__init__.py
diff --git a/erpnext/accounts/doctype/tax_withheld_vouchers/tax_withheld_vouchers.json b/erpnext/accounts/doctype/tax_withheld_vouchers/tax_withheld_vouchers.json
new file mode 100644
index 0000000..ce8c0c3
--- /dev/null
+++ b/erpnext/accounts/doctype/tax_withheld_vouchers/tax_withheld_vouchers.json
@@ -0,0 +1,49 @@
+{
+ "actions": [],
+ "autoname": "autoincrement",
+ "creation": "2022-09-13 16:18:59.404842",
+ "doctype": "DocType",
+ "editable_grid": 1,
+ "engine": "InnoDB",
+ "field_order": [
+  "voucher_type",
+  "voucher_name",
+  "taxable_amount"
+ ],
+ "fields": [
+  {
+   "fieldname": "voucher_type",
+   "fieldtype": "Link",
+   "in_list_view": 1,
+   "label": "Voucher Type",
+   "options": "DocType"
+  },
+  {
+   "fieldname": "voucher_name",
+   "fieldtype": "Dynamic Link",
+   "in_list_view": 1,
+   "label": "Voucher Name",
+   "options": "voucher_type"
+  },
+  {
+   "fieldname": "taxable_amount",
+   "fieldtype": "Currency",
+   "in_list_view": 1,
+   "label": "Taxable Amount",
+   "options": "Company:company:default_currency"
+  }
+ ],
+ "index_web_pages_for_search": 1,
+ "istable": 1,
+ "links": [],
+ "modified": "2022-09-13 23:40:41.479208",
+ "modified_by": "Administrator",
+ "module": "Accounts",
+ "name": "Tax Withheld Vouchers",
+ "naming_rule": "Autoincrement",
+ "owner": "Administrator",
+ "permissions": [],
+ "sort_field": "modified",
+ "sort_order": "DESC",
+ "states": []
+}
\ No newline at end of file
diff --git a/erpnext/accounts/doctype/tax_withheld_vouchers/tax_withheld_vouchers.py b/erpnext/accounts/doctype/tax_withheld_vouchers/tax_withheld_vouchers.py
new file mode 100644
index 0000000..ea54c54
--- /dev/null
+++ b/erpnext/accounts/doctype/tax_withheld_vouchers/tax_withheld_vouchers.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 TaxWithheldVouchers(Document):
+	pass
diff --git a/erpnext/accounts/doctype/tax_withholding_category/tax_withholding_category.py b/erpnext/accounts/doctype/tax_withholding_category/tax_withholding_category.py
index 6004e2b..0b5df9e 100644
--- a/erpnext/accounts/doctype/tax_withholding_category/tax_withholding_category.py
+++ b/erpnext/accounts/doctype/tax_withholding_category/tax_withholding_category.py
@@ -109,7 +109,7 @@
 			).format(tax_withholding_category, inv.company, party)
 		)
 
-	tax_amount, tax_deducted, tax_deducted_on_advances = get_tax_amount(
+	tax_amount, tax_deducted, tax_deducted_on_advances, voucher_wise_amount = get_tax_amount(
 		party_type, parties, inv, tax_details, posting_date, pan_no
 	)
 
@@ -119,7 +119,7 @@
 		tax_row = get_tax_row_for_tcs(inv, tax_details, tax_amount, tax_deducted)
 
 	if inv.doctype == "Purchase Invoice":
-		return tax_row, tax_deducted_on_advances
+		return tax_row, tax_deducted_on_advances, voucher_wise_amount
 	else:
 		return tax_row
 
@@ -217,7 +217,9 @@
 
 
 def get_tax_amount(party_type, parties, inv, tax_details, posting_date, pan_no=None):
-	vouchers = get_invoice_vouchers(parties, tax_details, inv.company, party_type=party_type)
+	vouchers, voucher_wise_amount = get_invoice_vouchers(
+		parties, tax_details, inv.company, party_type=party_type
+	)
 	advance_vouchers = get_advance_vouchers(
 		parties,
 		company=inv.company,
@@ -236,6 +238,7 @@
 		tax_deducted = get_deducted_tax(taxable_vouchers, tax_details)
 
 	tax_amount = 0
+
 	if party_type == "Supplier":
 		ldc = get_lower_deduction_certificate(tax_details, pan_no)
 		if tax_deducted:
@@ -261,12 +264,13 @@
 	if cint(tax_details.round_off_tax_amount):
 		tax_amount = round(tax_amount)
 
-	return tax_amount, tax_deducted, tax_deducted_on_advances
+	return tax_amount, tax_deducted, tax_deducted_on_advances, voucher_wise_amount
 
 
 def get_invoice_vouchers(parties, tax_details, company, party_type="Supplier"):
-	dr_or_cr = "credit" if party_type == "Supplier" else "debit"
 	doctype = "Purchase Invoice" if party_type == "Supplier" else "Sales Invoice"
+	voucher_wise_amount = {}
+	vouchers = []
 
 	filters = {
 		"company": company,
@@ -281,29 +285,40 @@
 			{"apply_tds": 1, "tax_withholding_category": tax_details.get("tax_withholding_category")}
 		)
 
-	invoices = frappe.get_all(doctype, filters=filters, pluck="name") or [""]
+	invoices_details = frappe.get_all(doctype, filters=filters, fields=["name", "base_net_total"])
 
-	journal_entries = frappe.db.sql(
+	for d in invoices_details:
+		vouchers.append(d.name)
+		voucher_wise_amount.update({d.name: {"amount": d.base_net_total, "voucher_type": doctype}})
+
+	journal_entries_details = frappe.db.sql(
 		"""
-		SELECT j.name
+		SELECT j.name, ja.credit - ja.debit AS amount
 			FROM `tabJournal Entry` j, `tabJournal Entry Account` ja
 		WHERE
-			j.docstatus = 1
+			j.name = ja.parent
+			AND j.docstatus = 1
 			AND j.is_opening = 'No'
 			AND j.posting_date between %s and %s
-			AND ja.{dr_or_cr} > 0
 			AND ja.party in %s
-	""".format(
-			dr_or_cr=dr_or_cr
+			AND j.apply_tds = 1
+			AND j.tax_withholding_category = %s
+	""",
+		(
+			tax_details.from_date,
+			tax_details.to_date,
+			tuple(parties),
+			tax_details.get("tax_withholding_category"),
 		),
-		(tax_details.from_date, tax_details.to_date, tuple(parties)),
-		as_list=1,
+		as_dict=1,
 	)
 
-	if journal_entries:
-		journal_entries = journal_entries[0]
+	if journal_entries_details:
+		for d in journal_entries_details:
+			vouchers.append(d.name)
+			voucher_wise_amount.update({d.name: {"amount": d.amount, "voucher_type": "Journal Entry"}})
 
-	return invoices + journal_entries
+	return vouchers, voucher_wise_amount
 
 
 def get_advance_vouchers(
@@ -329,23 +344,25 @@
 
 
 def get_taxes_deducted_on_advances_allocated(inv, tax_details):
-	advances = [d.reference_name for d in inv.get("advances")]
 	tax_info = []
 
-	if advances:
-		pe = frappe.qb.DocType("Payment Entry").as_("pe")
-		at = frappe.qb.DocType("Advance Taxes and Charges").as_("at")
+	if inv.get("advances"):
+		advances = [d.reference_name for d in inv.get("advances")]
 
-		tax_info = (
-			frappe.qb.from_(at)
-			.inner_join(pe)
-			.on(pe.name == at.parent)
-			.select(at.parent, at.name, at.tax_amount, at.allocated_amount)
-			.where(pe.tax_withholding_category == tax_details.get("tax_withholding_category"))
-			.where(at.parent.isin(advances))
-			.where(at.account_head == tax_details.account_head)
-			.run(as_dict=True)
-		)
+		if advances:
+			pe = frappe.qb.DocType("Payment Entry").as_("pe")
+			at = frappe.qb.DocType("Advance Taxes and Charges").as_("at")
+
+			tax_info = (
+				frappe.qb.from_(at)
+				.inner_join(pe)
+				.on(pe.name == at.parent)
+				.select(at.parent, at.name, at.tax_amount, at.allocated_amount)
+				.where(pe.tax_withholding_category == tax_details.get("tax_withholding_category"))
+				.where(at.parent.isin(advances))
+				.where(at.account_head == tax_details.account_head)
+				.run(as_dict=True)
+			)
 
 	return tax_info
 
@@ -394,11 +411,6 @@
 	supp_credit_amt += supp_jv_credit_amt
 	supp_credit_amt += inv.net_total
 
-	debit_note_amount = get_debit_note_amount(
-		parties, tax_details.from_date, tax_details.to_date, inv.company
-	)
-	supp_credit_amt -= debit_note_amount
-
 	threshold = tax_details.get("threshold", 0)
 	cumulative_threshold = tax_details.get("cumulative_threshold", 0)
 
@@ -515,22 +527,6 @@
 	return tds_amount
 
 
-def get_debit_note_amount(suppliers, from_date, to_date, company=None):
-
-	filters = {
-		"supplier": ["in", suppliers],
-		"is_return": 1,
-		"docstatus": 1,
-		"posting_date": ["between", (from_date, to_date)],
-	}
-	fields = ["abs(sum(net_total)) as net_total"]
-
-	if company:
-		filters["company"] = company
-
-	return frappe.get_all("Purchase Invoice", filters, fields)[0].get("net_total") or 0.0
-
-
 def get_ltds_amount(current_amount, deducted_amount, certificate_limit, rate, tax_details):
 	if current_amount < (certificate_limit - deducted_amount):
 		return current_amount * rate / 100
diff --git a/erpnext/accounts/doctype/tax_withholding_category/test_tax_withholding_category.py b/erpnext/accounts/doctype/tax_withholding_category/test_tax_withholding_category.py
index 3059f8d..e80fe11 100644
--- a/erpnext/accounts/doctype/tax_withholding_category/test_tax_withholding_category.py
+++ b/erpnext/accounts/doctype/tax_withholding_category/test_tax_withholding_category.py
@@ -52,7 +52,7 @@
 		invoices.append(pi)
 
 		# delete invoices to avoid clashing
-		for d in invoices:
+		for d in reversed(invoices):
 			d.cancel()
 
 	def test_single_threshold_tds(self):
@@ -88,7 +88,7 @@
 		self.assertEqual(pi.taxes_and_charges_deducted, 1000)
 
 		# delete invoices to avoid clashing
-		for d in invoices:
+		for d in reversed(invoices):
 			d.cancel()
 
 	def test_tax_withholding_category_checks(self):
@@ -114,7 +114,7 @@
 		# TDS should be applied only on 1000
 		self.assertEqual(pi1.taxes[0].tax_amount, 1000)
 
-		for d in invoices:
+		for d in reversed(invoices):
 			d.cancel()
 
 	def test_cumulative_threshold_tcs(self):
@@ -148,8 +148,8 @@
 		self.assertEqual(tcs_charged, 500)
 		invoices.append(si)
 
-		# delete invoices to avoid clashing
-		for d in invoices:
+		# cancel invoices to avoid clashing
+		for d in reversed(invoices):
 			d.cancel()
 
 	def test_tds_calculation_on_net_total(self):
@@ -182,8 +182,8 @@
 
 		self.assertEqual(pi1.taxes[0].tax_amount, 4000)
 
-		# delete invoices to avoid clashing
-		for d in invoices:
+		# cancel invoices to avoid clashing
+		for d in reversed(invoices):
 			d.cancel()
 
 	def test_multi_category_single_supplier(self):
@@ -207,8 +207,50 @@
 
 		self.assertEqual(pi1.taxes[0].tax_amount, 250)
 
-		# delete invoices to avoid clashing
-		for d in invoices:
+		# cancel invoices to avoid clashing
+		for d in reversed(invoices):
+			d.cancel()
+
+	def test_tax_withholding_category_voucher_display(self):
+		frappe.db.set_value(
+			"Supplier", "Test TDS Supplier6", "tax_withholding_category", "Test Multi Invoice Category"
+		)
+		invoices = []
+
+		pi = create_purchase_invoice(supplier="Test TDS Supplier6", rate=4000, do_not_save=True)
+		pi.apply_tds = 1
+		pi.tax_withholding_category = "Test Multi Invoice Category"
+		pi.save()
+		pi.submit()
+		invoices.append(pi)
+
+		pi1 = create_purchase_invoice(supplier="Test TDS Supplier6", rate=2000, do_not_save=True)
+		pi1.apply_tds = 1
+		pi1.is_return = 1
+		pi1.items[0].qty = -1
+		pi1.tax_withholding_category = "Test Multi Invoice Category"
+		pi1.save()
+		pi1.submit()
+		invoices.append(pi1)
+
+		pi2 = create_purchase_invoice(supplier="Test TDS Supplier6", rate=9000, do_not_save=True)
+		pi2.apply_tds = 1
+		pi2.tax_withholding_category = "Test Multi Invoice Category"
+		pi2.save()
+		pi2.submit()
+		invoices.append(pi2)
+
+		pi2.load_from_db()
+
+		self.assertTrue(pi2.taxes[0].tax_amount, 1100)
+
+		self.assertTrue(pi2.tax_withheld_vouchers[0].voucher_name == pi1.name)
+		self.assertTrue(pi2.tax_withheld_vouchers[0].taxable_amount == pi1.net_total)
+		self.assertTrue(pi2.tax_withheld_vouchers[1].voucher_name == pi.name)
+		self.assertTrue(pi2.tax_withheld_vouchers[1].taxable_amount == pi.net_total)
+
+		# cancel invoices to avoid clashing
+		for d in reversed(invoices):
 			d.cancel()
 
 
@@ -308,6 +350,7 @@
 		"Test TDS Supplier3",
 		"Test TDS Supplier4",
 		"Test TDS Supplier5",
+		"Test TDS Supplier6",
 	]:
 		if frappe.db.exists("Supplier", name):
 			continue
@@ -498,3 +541,22 @@
 				"accounts": [{"company": "_Test Company", "account": "TDS - _TC"}],
 			}
 		).insert()
+
+	if not frappe.db.exists("Tax Withholding Category", "Test Multi Invoice Category"):
+		frappe.get_doc(
+			{
+				"doctype": "Tax Withholding Category",
+				"name": "Test Multi Invoice Category",
+				"category_name": "Test Multi Invoice Category",
+				"rates": [
+					{
+						"from_date": fiscal_year[1],
+						"to_date": fiscal_year[2],
+						"tax_withholding_rate": 10,
+						"single_threshold": 5000,
+						"cumulative_threshold": 10000,
+					}
+				],
+				"accounts": [{"company": "_Test Company", "account": "TDS - _TC"}],
+			}
+		).insert()
diff --git a/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.py b/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.py
index 9d56678..cd5f366 100644
--- a/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.py
+++ b/erpnext/accounts/report/gross_and_net_profit_report/gross_and_net_profit_report.py
@@ -155,7 +155,6 @@
 	for d in data:
 		for period in period_list:
 			key = period if consolidated else period.key
-			d[key] = totals[d["account"]]
 			d["total"] = totals[d["account"]]
 	return data
 
diff --git a/erpnext/assets/doctype/asset/asset.js b/erpnext/assets/doctype/asset/asset.js
index f414930..a43a16c 100644
--- a/erpnext/assets/doctype/asset/asset.js
+++ b/erpnext/assets/doctype/asset/asset.js
@@ -239,8 +239,10 @@
 
 
 	item_code: function(frm) {
-		if(frm.doc.item_code) {
+		if(frm.doc.item_code && frm.doc.calculate_depreciation) {
 			frm.trigger('set_finance_book');
+		} else {
+			frm.set_value('finance_books', []);
 		}
 	},
 
@@ -381,6 +383,11 @@
 
 	calculate_depreciation: function(frm) {
 		frm.toggle_reqd("finance_books", frm.doc.calculate_depreciation);
+		if (frm.doc.item_code && frm.doc.calculate_depreciation ) {
+			frm.trigger("set_finance_book");
+		} else {
+			frm.set_value("finance_books", []);
+		}
 	},
 
 	gross_purchase_amount: function(frm) {
diff --git a/erpnext/buying/doctype/purchase_order/purchase_order.json b/erpnext/buying/doctype/purchase_order/purchase_order.json
index acca380..fb8f25a 100644
--- a/erpnext/buying/doctype/purchase_order/purchase_order.json
+++ b/erpnext/buying/doctype/purchase_order/purchase_order.json
@@ -441,7 +441,6 @@
    "fieldname": "ignore_pricing_rule",
    "fieldtype": "Check",
    "label": "Ignore Pricing Rule",
-   "no_copy": 1,
    "permlevel": 1,
    "print_hide": 1
   },
@@ -1180,7 +1179,7 @@
  "idx": 105,
  "is_submittable": 1,
  "links": [],
- "modified": "2022-09-07 11:06:46.035093",
+ "modified": "2022-09-16 17:45:04.954055",
  "modified_by": "Administrator",
  "module": "Buying",
  "name": "Purchase Order",
diff --git a/erpnext/buying/report/purchase_order_trends/purchase_order_trends.py b/erpnext/buying/report/purchase_order_trends/purchase_order_trends.py
index dbdc62e..d089473 100644
--- a/erpnext/buying/report/purchase_order_trends/purchase_order_trends.py
+++ b/erpnext/buying/report/purchase_order_trends/purchase_order_trends.py
@@ -53,4 +53,5 @@
 		},
 		"type": "line",
 		"lineOptions": {"regionFill": 1},
+		"fieldtype": "Currency",
 	}
diff --git a/erpnext/controllers/buying_controller.py b/erpnext/controllers/buying_controller.py
index 5659ad0..48fe7cb 100644
--- a/erpnext/controllers/buying_controller.py
+++ b/erpnext/controllers/buying_controller.py
@@ -194,16 +194,16 @@
 
 		if self.meta.get_field("base_in_words"):
 			if self.meta.get_field("base_rounded_total") and not self.is_rounded_total_disabled():
-				amount = self.base_rounded_total
+				amount = abs(self.base_rounded_total)
 			else:
-				amount = self.base_grand_total
+				amount = abs(self.base_grand_total)
 			self.base_in_words = money_in_words(amount, self.company_currency)
 
 		if self.meta.get_field("in_words"):
 			if self.meta.get_field("rounded_total") and not self.is_rounded_total_disabled():
-				amount = self.rounded_total
+				amount = abs(self.rounded_total)
 			else:
-				amount = self.grand_total
+				amount = abs(self.grand_total)
 
 			self.in_words = money_in_words(amount, self.currency)
 
diff --git a/erpnext/crm/report/opportunity_summary_by_sales_stage/opportunity_summary_by_sales_stage.js b/erpnext/crm/report/opportunity_summary_by_sales_stage/opportunity_summary_by_sales_stage.js
index 116db2f..7cd1710 100644
--- a/erpnext/crm/report/opportunity_summary_by_sales_stage/opportunity_summary_by_sales_stage.js
+++ b/erpnext/crm/report/opportunity_summary_by_sales_stage/opportunity_summary_by_sales_stage.js
@@ -44,7 +44,7 @@
 		},
 		{
 			fieldname: "opportunity_source",
-			label: __("Oppoturnity Source"),
+			label: __("Opportunity Source"),
 			fieldtype: "Link",
 			options: "Lead Source",
 		},
@@ -62,4 +62,4 @@
 			default: frappe.defaults.get_user_default("Company")
 		}
 	]
-};
\ No newline at end of file
+};
diff --git a/erpnext/manufacturing/doctype/bom/bom.py b/erpnext/manufacturing/doctype/bom/bom.py
index 70637d3..ff84991 100644
--- a/erpnext/manufacturing/doctype/bom/bom.py
+++ b/erpnext/manufacturing/doctype/bom/bom.py
@@ -1019,7 +1019,6 @@
 			where
 				bom_item.docstatus < 2
 				and bom.name = %(bom)s
-				and ifnull(item.has_variants, 0) = 0
 				and item.is_stock_item in (1, {is_stock_item})
 				{where_conditions}
 				group by item_code, stock_uom
diff --git a/erpnext/manufacturing/doctype/production_plan/production_plan.py b/erpnext/manufacturing/doctype/production_plan/production_plan.py
index f1d40c2..4bb4dcc 100644
--- a/erpnext/manufacturing/doctype/production_plan/production_plan.py
+++ b/erpnext/manufacturing/doctype/production_plan/production_plan.py
@@ -894,6 +894,7 @@
 		.select(
 			(IfNull(Sum(bei.stock_qty / IfNull(bom.quantity, 1)), 0) * planned_qty).as_("qty"),
 			item.item_name,
+			item.name.as_("item_code"),
 			bei.description,
 			bei.stock_uom,
 			item.min_order_qty,
diff --git a/erpnext/manufacturing/report/bom_stock_calculated/bom_stock_calculated.py b/erpnext/manufacturing/report/bom_stock_calculated/bom_stock_calculated.py
index ec4b25c..550445c 100644
--- a/erpnext/manufacturing/report/bom_stock_calculated/bom_stock_calculated.py
+++ b/erpnext/manufacturing/report/bom_stock_calculated/bom_stock_calculated.py
@@ -146,7 +146,7 @@
 				)
 			)
 		else:
-			query = query.where(bin.warehouse == frappe.db.escape(filters.get("warehouse")))
+			query = query.where(bin.warehouse == filters.get("warehouse"))
 
 	return query.run(as_dict=True)
 
diff --git a/erpnext/manufacturing/report/bom_stock_report/bom_stock_report.py b/erpnext/manufacturing/report/bom_stock_report/bom_stock_report.py
index 34e9826..1e1b435 100644
--- a/erpnext/manufacturing/report/bom_stock_report/bom_stock_report.py
+++ b/erpnext/manufacturing/report/bom_stock_report/bom_stock_report.py
@@ -4,6 +4,8 @@
 
 import frappe
 from frappe import _
+from frappe.query_builder.functions import Floor, Sum
+from pypika.terms import ExistsCriterion
 
 
 def execute(filters=None):
@@ -11,7 +13,6 @@
 		filters = {}
 
 	columns = get_columns()
-
 	data = get_bom_stock(filters)
 
 	return columns, data
@@ -33,59 +34,57 @@
 
 
 def get_bom_stock(filters):
-	conditions = ""
-	bom = filters.get("bom")
-
-	table = "`tabBOM Item`"
-	qty_field = "stock_qty"
-
-	qty_to_produce = filters.get("qty_to_produce", 1)
-	if int(qty_to_produce) <= 0:
+	qty_to_produce = filters.get("qty_to_produce") or 1
+	if int(qty_to_produce) < 0:
 		frappe.throw(_("Quantity to Produce can not be less than Zero"))
 
 	if filters.get("show_exploded_view"):
-		table = "`tabBOM Explosion Item`"
+		bom_item_table = "BOM Explosion Item"
+	else:
+		bom_item_table = "BOM Item"
+
+	bin = frappe.qb.DocType("Bin")
+	bom = frappe.qb.DocType("BOM")
+	bom_item = frappe.qb.DocType(bom_item_table)
+
+	query = (
+		frappe.qb.from_(bom)
+		.inner_join(bom_item)
+		.on(bom.name == bom_item.parent)
+		.left_join(bin)
+		.on(bom_item.item_code == bin.item_code)
+		.select(
+			bom_item.item_code,
+			bom_item.description,
+			bom_item.stock_qty,
+			bom_item.stock_uom,
+			bom_item.stock_qty * qty_to_produce / bom.quantity,
+			Sum(bin.actual_qty).as_("actual_qty"),
+			Sum(Floor(bin.actual_qty / (bom_item.stock_qty * qty_to_produce / bom.quantity))),
+		)
+		.where((bom_item.parent == filters.get("bom")) & (bom_item.parenttype == "BOM"))
+		.groupby(bom_item.item_code)
+	)
 
 	if filters.get("warehouse"):
 		warehouse_details = frappe.db.get_value(
 			"Warehouse", filters.get("warehouse"), ["lft", "rgt"], as_dict=1
 		)
+
 		if warehouse_details:
-			conditions += (
-				" and exists (select name from `tabWarehouse` wh \
-				where wh.lft >= %s and wh.rgt <= %s and ledger.warehouse = wh.name)"
-				% (warehouse_details.lft, warehouse_details.rgt)
+			wh = frappe.qb.DocType("Warehouse")
+			query = query.where(
+				ExistsCriterion(
+					frappe.qb.from_(wh)
+					.select(wh.name)
+					.where(
+						(wh.lft >= warehouse_details.lft)
+						& (wh.rgt <= warehouse_details.rgt)
+						& (bin.warehouse == wh.name)
+					)
+				)
 			)
 		else:
-			conditions += " and ledger.warehouse = %s" % frappe.db.escape(filters.get("warehouse"))
+			query = query.where(bin.warehouse == filters.get("warehouse"))
 
-	else:
-		conditions += ""
-
-	return frappe.db.sql(
-		"""
-			SELECT
-				bom_item.item_code,
-				bom_item.description ,
-				bom_item.{qty_field},
-				bom_item.stock_uom,
-				bom_item.{qty_field} * {qty_to_produce} / bom.quantity,
-				sum(ledger.actual_qty) as actual_qty,
-				sum(FLOOR(ledger.actual_qty / (bom_item.{qty_field} * {qty_to_produce} / bom.quantity)))
-			FROM
-				`tabBOM` AS bom INNER JOIN {table} AS bom_item
-					ON bom.name = bom_item.parent
-				LEFT JOIN `tabBin` AS ledger
-					ON bom_item.item_code = ledger.item_code
-				{conditions}
-			WHERE
-				bom_item.parent = {bom} and bom_item.parenttype='BOM'
-
-			GROUP BY bom_item.item_code""".format(
-			qty_field=qty_field,
-			table=table,
-			conditions=conditions,
-			bom=frappe.db.escape(bom),
-			qty_to_produce=qty_to_produce or 1,
-		)
-	)
+	return query.run()
diff --git a/erpnext/manufacturing/report/bom_variance_report/bom_variance_report.py b/erpnext/manufacturing/report/bom_variance_report/bom_variance_report.py
index da28343..70a1850 100644
--- a/erpnext/manufacturing/report/bom_variance_report/bom_variance_report.py
+++ b/erpnext/manufacturing/report/bom_variance_report/bom_variance_report.py
@@ -64,22 +64,21 @@
 
 
 def get_data(filters):
-	cond = "1=1"
+	wo = frappe.qb.DocType("Work Order")
+	query = (
+		frappe.qb.from_(wo)
+		.select(wo.name.as_("work_order"), wo.qty, wo.produced_qty, wo.production_item, wo.bom_no)
+		.where((wo.produced_qty > wo.qty) & (wo.docstatus == 1))
+	)
 
 	if filters.get("bom_no") and not filters.get("work_order"):
-		cond += " and bom_no = '%s'" % filters.get("bom_no")
+		query = query.where(wo.bom_no == filters.get("bom_no"))
 
 	if filters.get("work_order"):
-		cond += " and name = '%s'" % filters.get("work_order")
+		query = query.where(wo.name == filters.get("work_order"))
 
 	results = []
-	for d in frappe.db.sql(
-		""" select name as work_order, qty, produced_qty, production_item, bom_no
-		from `tabWork Order` where produced_qty > qty and docstatus = 1 and {0}""".format(
-			cond
-		),
-		as_dict=1,
-	):
+	for d in query.run(as_dict=True):
 		results.append(d)
 
 		for data in frappe.get_all(
@@ -95,16 +94,17 @@
 @frappe.whitelist()
 @frappe.validate_and_sanitize_search_inputs
 def get_work_orders(doctype, txt, searchfield, start, page_len, filters):
-	cond = "1=1"
-	if filters.get("bom_no"):
-		cond += " and bom_no = '%s'" % filters.get("bom_no")
-
-	return frappe.db.sql(
-		"""select name from `tabWork Order`
-		where name like %(name)s and {0} and produced_qty > qty and docstatus = 1
-		order by name limit {2} offset {1}""".format(
-			cond, start, page_len
-		),
-		{"name": "%%%s%%" % txt},
-		as_list=1,
+	wo = frappe.qb.DocType("Work Order")
+	query = (
+		frappe.qb.from_(wo)
+		.select(wo.name)
+		.where((wo.name.like(f"{txt}%")) & (wo.produced_qty > wo.qty) & (wo.docstatus == 1))
+		.orderby(wo.name)
+		.limit(page_len)
+		.offset(start)
 	)
+
+	if filters.get("bom_no"):
+		query = query.where(wo.bom_no == filters.get("bom_no"))
+
+	return query.run(as_list=True)
diff --git a/erpnext/manufacturing/report/exponential_smoothing_forecasting/exponential_smoothing_forecasting.py b/erpnext/manufacturing/report/exponential_smoothing_forecasting/exponential_smoothing_forecasting.py
index 7500744..d3bce83 100644
--- a/erpnext/manufacturing/report/exponential_smoothing_forecasting/exponential_smoothing_forecasting.py
+++ b/erpnext/manufacturing/report/exponential_smoothing_forecasting/exponential_smoothing_forecasting.py
@@ -96,38 +96,39 @@
 					value["avg"] = flt(sum(list_of_period_value)) / flt(sum(total_qty))
 
 	def get_data_for_forecast(self):
-		cond = ""
-		if self.filters.item_code:
-			cond = " AND soi.item_code = %s" % (frappe.db.escape(self.filters.item_code))
-
-		warehouses = []
-		if self.filters.warehouse:
-			warehouses = get_child_warehouses(self.filters.warehouse)
-			cond += " AND soi.warehouse in ({})".format(",".join(["%s"] * len(warehouses)))
-
-		input_data = [self.filters.from_date, self.filters.company]
-		if warehouses:
-			input_data.extend(warehouses)
+		parent = frappe.qb.DocType(self.doctype)
+		child = frappe.qb.DocType(self.child_doctype)
 
 		date_field = "posting_date" if self.doctype == "Delivery Note" else "transaction_date"
 
-		return frappe.db.sql(
-			"""
-			SELECT
-				so.{date_field} as posting_date, soi.item_code, soi.warehouse,
-				soi.item_name, soi.stock_qty as qty, soi.base_amount as amount
-			FROM
-				`tab{doc}` so, `tab{child_doc}` soi
-			WHERE
-				so.docstatus = 1 AND so.name = soi.parent AND
-				so.{date_field} < %s AND so.company = %s {cond}
-		""".format(
-				doc=self.doctype, child_doc=self.child_doctype, date_field=date_field, cond=cond
-			),
-			tuple(input_data),
-			as_dict=1,
+		query = (
+			frappe.qb.from_(parent)
+			.from_(child)
+			.select(
+				parent[date_field].as_("posting_date"),
+				child.item_code,
+				child.warehouse,
+				child.item_name,
+				child.stock_qty.as_("qty"),
+				child.base_amount.as_("amount"),
+			)
+			.where(
+				(parent.docstatus == 1)
+				& (parent.name == child.parent)
+				& (parent[date_field] < self.filters.from_date)
+				& (parent.company == self.filters.company)
+			)
 		)
 
+		if self.filters.item_code:
+			query = query.where(child.item_code == self.filters.item_code)
+
+		if self.filters.warehouse:
+			warehouses = get_child_warehouses(self.filters.warehouse) or []
+			query = query.where(child.warehouse.isin(warehouses))
+
+		return query.run(as_dict=True)
+
 	def prepare_final_data(self):
 		self.data = []
 
diff --git a/erpnext/manufacturing/report/job_card_summary/job_card_summary.py b/erpnext/manufacturing/report/job_card_summary/job_card_summary.py
index 5083b73..63c2d97 100644
--- a/erpnext/manufacturing/report/job_card_summary/job_card_summary.py
+++ b/erpnext/manufacturing/report/job_card_summary/job_card_summary.py
@@ -85,8 +85,8 @@
 		open_job_cards.append(periodic_data.get("Open").get(d))
 		completed.append(periodic_data.get("Completed").get(d))
 
-	datasets.append({"name": "Open", "values": open_job_cards})
-	datasets.append({"name": "Completed", "values": completed})
+	datasets.append({"name": _("Open"), "values": open_job_cards})
+	datasets.append({"name": _("Completed"), "values": completed})
 
 	chart = {"data": {"labels": labels, "datasets": datasets}, "type": "bar"}
 
diff --git a/erpnext/manufacturing/report/production_planning_report/production_planning_report.py b/erpnext/manufacturing/report/production_planning_report/production_planning_report.py
index 1404888..16c25ce 100644
--- a/erpnext/manufacturing/report/production_planning_report/production_planning_report.py
+++ b/erpnext/manufacturing/report/production_planning_report/production_planning_report.py
@@ -4,42 +4,10 @@
 
 import frappe
 from frappe import _
+from pypika import Order
 
 from erpnext.stock.doctype.warehouse.warehouse import get_child_warehouses
 
-# and bom_no is not null and bom_no !=''
-
-mapper = {
-	"Sales Order": {
-		"fields": """ item_code as production_item, item_name as production_item_name, stock_uom,
-			stock_qty as qty_to_manufacture, `tabSales Order Item`.parent as name, bom_no, warehouse,
-			`tabSales Order Item`.delivery_date, `tabSales Order`.base_grand_total """,
-		"filters": """`tabSales Order Item`.docstatus = 1 and stock_qty > produced_qty
-			and `tabSales Order`.per_delivered < 100.0""",
-	},
-	"Material Request": {
-		"fields": """ item_code as production_item, item_name as production_item_name, stock_uom,
-			stock_qty as qty_to_manufacture, `tabMaterial Request Item`.parent as name, bom_no, warehouse,
-			`tabMaterial Request Item`.schedule_date """,
-		"filters": """`tabMaterial Request`.docstatus = 1 and `tabMaterial Request`.per_ordered < 100
-			and `tabMaterial Request`.material_request_type = 'Manufacture' """,
-	},
-	"Work Order": {
-		"fields": """ production_item, item_name as production_item_name, planned_start_date,
-			stock_uom, qty as qty_to_manufacture, name, bom_no, fg_warehouse as warehouse """,
-		"filters": "docstatus = 1 and status not in ('Completed', 'Stopped')",
-	},
-}
-
-order_mapper = {
-	"Sales Order": {
-		"Delivery Date": "`tabSales Order Item`.delivery_date asc",
-		"Total Amount": "`tabSales Order`.base_grand_total desc",
-	},
-	"Material Request": {"Required Date": "`tabMaterial Request Item`.schedule_date asc"},
-	"Work Order": {"Planned Start Date": "planned_start_date asc"},
-}
-
 
 def execute(filters=None):
 	return ProductionPlanReport(filters).execute_report()
@@ -63,40 +31,78 @@
 		return self.columns, self.data
 
 	def get_open_orders(self):
-		doctype = (
-			"`tabWork Order`"
-			if self.filters.based_on == "Work Order"
-			else "`tab{doc}`, `tab{doc} Item`".format(doc=self.filters.based_on)
-		)
+		doctype, order_by = self.filters.based_on, self.filters.order_by
 
-		filters = mapper.get(self.filters.based_on)["filters"]
-		filters = self.prepare_other_conditions(filters, self.filters.based_on)
-		order_by = " ORDER BY %s" % (order_mapper[self.filters.based_on][self.filters.order_by])
+		parent = frappe.qb.DocType(doctype)
+		query = None
 
-		self.orders = frappe.db.sql(
-			""" SELECT {fields} from {doctype}
-			WHERE {filters} {order_by}""".format(
-				doctype=doctype,
-				filters=filters,
-				order_by=order_by,
-				fields=mapper.get(self.filters.based_on)["fields"],
-			),
-			tuple(self.filters.docnames),
-			as_dict=1,
-		)
+		if doctype == "Work Order":
+			query = (
+				frappe.qb.from_(parent)
+				.select(
+					parent.production_item,
+					parent.item_name.as_("production_item_name"),
+					parent.planned_start_date,
+					parent.stock_uom,
+					parent.qty.as_("qty_to_manufacture"),
+					parent.name,
+					parent.bom_no,
+					parent.fg_warehouse.as_("warehouse"),
+				)
+				.where(parent.status.notin(["Completed", "Stopped"]))
+			)
 
-	def prepare_other_conditions(self, filters, doctype):
-		if self.filters.docnames:
-			field = "name" if doctype == "Work Order" else "`tab{} Item`.parent".format(doctype)
-			filters += " and %s in (%s)" % (field, ",".join(["%s"] * len(self.filters.docnames)))
+			if order_by == "Planned Start Date":
+				query = query.orderby(parent.planned_start_date, order=Order.asc)
 
-		if doctype != "Work Order":
-			filters += " and `tab{doc}`.name = `tab{doc} Item`.parent".format(doc=doctype)
+			if self.filters.docnames:
+				query = query.where(parent.name.isin(self.filters.docnames))
+
+		else:
+			child = frappe.qb.DocType(f"{doctype} Item")
+			query = (
+				frappe.qb.from_(parent)
+				.from_(child)
+				.select(
+					child.bom_no,
+					child.stock_uom,
+					child.warehouse,
+					child.parent.as_("name"),
+					child.item_code.as_("production_item"),
+					child.stock_qty.as_("qty_to_manufacture"),
+					child.item_name.as_("production_item_name"),
+				)
+				.where(parent.name == child.parent)
+			)
+
+			if self.filters.docnames:
+				query = query.where(child.parent.isin(self.filters.docnames))
+
+			if doctype == "Sales Order":
+				query = query.select(
+					child.delivery_date,
+					parent.base_grand_total,
+				).where((child.stock_qty > child.produced_qty) & (parent.per_delivered < 100.0))
+
+				if order_by == "Delivery Date":
+					query = query.orderby(child.delivery_date, order=Order.asc)
+				elif order_by == "Total Amount":
+					query = query.orderby(parent.base_grand_total, order=Order.desc)
+
+			elif doctype == "Material Request":
+				query = query.select(child.schedule_date,).where(
+					(parent.per_ordered < 100) & (parent.material_request_type == "Manufacture")
+				)
+
+				if order_by == "Required Date":
+					query = query.orderby(child.schedule_date, order=Order.asc)
+
+		query = query.where(parent.docstatus == 1)
 
 		if self.filters.company:
-			filters += " and `tab%s`.company = %s" % (doctype, frappe.db.escape(self.filters.company))
+			query = query.where(parent.company == self.filters.company)
 
-		return filters
+		self.orders = query.run(as_dict=True)
 
 	def get_raw_materials(self):
 		if not self.orders:
@@ -134,29 +140,29 @@
 
 				bom_nos.append(bom_no)
 
-			bom_doctype = (
+			bom_item_doctype = (
 				"BOM Explosion Item" if self.filters.include_subassembly_raw_materials else "BOM Item"
 			)
 
-			qty_field = (
-				"qty_consumed_per_unit"
-				if self.filters.include_subassembly_raw_materials
-				else "(bom_item.qty / bom.quantity)"
-			)
+			bom = frappe.qb.DocType("BOM")
+			bom_item = frappe.qb.DocType(bom_item_doctype)
 
-			raw_materials = frappe.db.sql(
-				""" SELECT bom_item.parent, bom_item.item_code,
-					bom_item.item_name as raw_material_name, {0} as required_qty_per_unit
-				FROM
-					`tabBOM` as bom, `tab{1}` as bom_item
-				WHERE
-					bom_item.parent in ({2}) and bom_item.parent = bom.name and bom.docstatus = 1
-			""".format(
-					qty_field, bom_doctype, ",".join(["%s"] * len(bom_nos))
-				),
-				tuple(bom_nos),
-				as_dict=1,
-			)
+			if self.filters.include_subassembly_raw_materials:
+				qty_field = bom_item.qty_consumed_per_unit
+			else:
+				qty_field = bom_item.qty / bom.quantity
+
+			raw_materials = (
+				frappe.qb.from_(bom)
+				.from_(bom_item)
+				.select(
+					bom_item.parent,
+					bom_item.item_code,
+					bom_item.item_name.as_("raw_material_name"),
+					qty_field.as_("required_qty_per_unit"),
+				)
+				.where((bom_item.parent.isin(bom_nos)) & (bom_item.parent == bom.name) & (bom.docstatus == 1))
+			).run(as_dict=True)
 
 		if not raw_materials:
 			return
diff --git a/erpnext/manufacturing/report/work_order_summary/work_order_summary.py b/erpnext/manufacturing/report/work_order_summary/work_order_summary.py
index 2368bfd..41ffcbb 100644
--- a/erpnext/manufacturing/report/work_order_summary/work_order_summary.py
+++ b/erpnext/manufacturing/report/work_order_summary/work_order_summary.py
@@ -83,6 +83,7 @@
 	for d in data:
 		status_wise_data[d.status] += 1
 
+	labels = [_(label) for label in labels]
 	values = [status_wise_data[label] for label in labels]
 
 	chart = {
@@ -95,7 +96,7 @@
 
 
 def get_chart_based_on_age(data):
-	labels = ["0-30 Days", "30-60 Days", "60-90 Days", "90 Above"]
+	labels = [_("0-30 Days"), _("30-60 Days"), _("60-90 Days"), _("90 Above")]
 
 	age_wise_data = {"0-30 Days": 0, "30-60 Days": 0, "60-90 Days": 0, "90 Above": 0}
 
@@ -135,8 +136,8 @@
 		pending.append(periodic_data.get("Pending").get(d))
 		completed.append(periodic_data.get("Completed").get(d))
 
-	datasets.append({"name": "Pending", "values": pending})
-	datasets.append({"name": "Completed", "values": completed})
+	datasets.append({"name": _("Pending"), "values": pending})
+	datasets.append({"name": _("Completed"), "values": completed})
 
 	chart = {
 		"data": {"labels": labels, "datasets": datasets},
diff --git a/erpnext/projects/report/project_summary/project_summary.py b/erpnext/projects/report/project_summary/project_summary.py
index 606c0c2..7a35fd2 100644
--- a/erpnext/projects/report/project_summary/project_summary.py
+++ b/erpnext/projects/report/project_summary/project_summary.py
@@ -91,9 +91,9 @@
 		"data": {
 			"labels": labels[:30],
 			"datasets": [
-				{"name": "Overdue", "values": overdue[:30]},
-				{"name": "Completed", "values": completed[:30]},
-				{"name": "Total Tasks", "values": total[:30]},
+				{"name": _("Overdue"), "values": overdue[:30]},
+				{"name": _("Completed"), "values": completed[:30]},
+				{"name": _("Total Tasks"), "values": total[:30]},
 			],
 		},
 		"type": "bar",
diff --git a/erpnext/public/js/help_links.js b/erpnext/public/js/help_links.js
index b643cca..1c3f43e 100644
--- a/erpnext/public/js/help_links.js
+++ b/erpnext/public/js/help_links.js
@@ -671,7 +671,7 @@
 		label: "Item Valuation",
 		url:
 			docsUrl +
-			"user/manual/en/stock/articles/item-valuation-fifo-and-moving-average",
+			"user/manual/en/stock/articles/calculation-of-valuation-rate-in-fifo-and-moving-average",
 	},
 ];
 
diff --git a/erpnext/public/js/utils/barcode_scanner.js b/erpnext/public/js/utils/barcode_scanner.js
index a6bff2c..83b108b 100644
--- a/erpnext/public/js/utils/barcode_scanner.js
+++ b/erpnext/public/js/utils/barcode_scanner.js
@@ -21,6 +21,11 @@
 		this.items_table_name = opts.items_table_name || "items";
 		this.items_table = this.frm.doc[this.items_table_name];
 
+		// optional sound name to play when scan either fails or passes.
+		// see https://frappeframework.com/docs/v14/user/en/python-api/hooks#sounds
+		this.success_sound = opts.play_success_sound;
+		this.fail_sound = opts.play_fail_sound;
+
 		// any API that takes `search_value` as input and returns dictionary as follows
 		// {
 		//     item_code: "HORSESHOE", // present if any item was found
@@ -54,19 +59,24 @@
 					if (!data || Object.keys(data).length === 0) {
 						this.show_alert(__("Cannot find Item with this Barcode"), "red");
 						this.clean_up();
+						this.play_fail_sound();
 						reject();
 						return;
 					}
 
 					me.update_table(data).then(row => {
-						row ? resolve(row) : reject();
+						this.play_success_sound();
+						resolve(row);
+					}).catch(() => {
+						this.play_fail_sound();
+						reject();
 					});
 				});
 		});
 	}
 
 	update_table(data) {
-		return new Promise(resolve => {
+		return new Promise((resolve, reject) => {
 			let cur_grid = this.frm.fields_dict[this.items_table_name].grid;
 
 			const {item_code, barcode, batch_no, serial_no, uom} = data;
@@ -77,6 +87,7 @@
 				if (this.dont_allow_new_row) {
 					this.show_alert(__("Maximum quantity scanned for item {0}.", [item_code]), "red");
 					this.clean_up();
+					reject();
 					return;
 				}
 
@@ -88,6 +99,7 @@
 
 			if (this.is_duplicate_serial_no(row, serial_no)) {
 				this.clean_up();
+				reject();
 				return;
 			}
 
@@ -219,6 +231,14 @@
 		return this.items_table.find((d) => !d.item_code);
 	}
 
+	play_success_sound() {
+		this.success_sound && frappe.utils.play_sound(this.success_sound);
+	}
+
+	play_fail_sound() {
+		this.fail_sound && frappe.utils.play_sound(this.fail_sound);
+	}
+
 	clean_up() {
 		this.scan_barcode_field.set_value("");
 		refresh_field(this.items_table_name);
diff --git a/erpnext/selling/doctype/quotation/quotation.json b/erpnext/selling/doctype/quotation/quotation.json
index bb2f95d..c58a46b 100644
--- a/erpnext/selling/doctype/quotation/quotation.json
+++ b/erpnext/selling/doctype/quotation/quotation.json
@@ -402,7 +402,6 @@
    "fieldname": "ignore_pricing_rule",
    "fieldtype": "Check",
    "label": "Ignore Pricing Rule",
-   "no_copy": 1,
    "permlevel": 1,
    "print_hide": 1
   },
@@ -986,7 +985,7 @@
  "idx": 82,
  "is_submittable": 1,
  "links": [],
- "modified": "2022-06-11 20:35:32.635804",
+ "modified": "2022-09-16 17:44:43.221804",
  "modified_by": "Administrator",
  "module": "Selling",
  "name": "Quotation",
diff --git a/erpnext/selling/doctype/sales_order/sales_order.json b/erpnext/selling/doctype/sales_order/sales_order.json
index 74c5c07..ff269d0 100644
--- a/erpnext/selling/doctype/sales_order/sales_order.json
+++ b/erpnext/selling/doctype/sales_order/sales_order.json
@@ -544,7 +544,6 @@
    "hide_days": 1,
    "hide_seconds": 1,
    "label": "Ignore Pricing Rule",
-   "no_copy": 1,
    "permlevel": 1,
    "print_hide": 1
   },
@@ -1549,7 +1548,7 @@
  "idx": 105,
  "is_submittable": 1,
  "links": [],
- "modified": "2022-06-10 03:52:22.212953",
+ "modified": "2022-09-16 17:43:57.007441",
  "modified_by": "Administrator",
  "module": "Selling",
  "name": "Sales Order",
diff --git a/erpnext/stock/doctype/delivery_note/delivery_note.json b/erpnext/stock/doctype/delivery_note/delivery_note.json
index f9e9349..a8f907e 100644
--- a/erpnext/stock/doctype/delivery_note/delivery_note.json
+++ b/erpnext/stock/doctype/delivery_note/delivery_note.json
@@ -490,7 +490,6 @@
    "fieldname": "ignore_pricing_rule",
    "fieldtype": "Check",
    "label": "Ignore Pricing Rule",
-   "no_copy": 1,
    "permlevel": 1,
    "print_hide": 1
   },
@@ -1336,7 +1335,7 @@
  "idx": 146,
  "is_submittable": 1,
  "links": [],
- "modified": "2022-06-10 03:52:04.197415",
+ "modified": "2022-09-16 17:46:17.701904",
  "modified_by": "Administrator",
  "module": "Stock",
  "name": "Delivery Note",
diff --git a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.json b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.json
index a70415d..acaac92 100755
--- a/erpnext/stock/doctype/purchase_receipt/purchase_receipt.json
+++ b/erpnext/stock/doctype/purchase_receipt/purchase_receipt.json
@@ -405,7 +405,6 @@
    "fieldname": "ignore_pricing_rule",
    "fieldtype": "Check",
    "label": "Ignore Pricing Rule",
-   "no_copy": 1,
    "permlevel": 1,
    "print_hide": 1
   },
@@ -1158,7 +1157,7 @@
  "idx": 261,
  "is_submittable": 1,
  "links": [],
- "modified": "2022-06-15 15:43:40.664382",
+ "modified": "2022-09-16 17:45:58.430132",
  "modified_by": "Administrator",
  "module": "Stock",
  "name": "Purchase Receipt",
diff --git a/erpnext/stock/report/delivery_note_trends/delivery_note_trends.py b/erpnext/stock/report/delivery_note_trends/delivery_note_trends.py
index 7a1b8c0..0ec4e1c 100644
--- a/erpnext/stock/report/delivery_note_trends/delivery_note_trends.py
+++ b/erpnext/stock/report/delivery_note_trends/delivery_note_trends.py
@@ -45,4 +45,5 @@
 			"datasets": [{"name": _("Total Delivered Amount"), "values": datapoints}],
 		},
 		"type": "bar",
+		"fieldtype": "Currency",
 	}
diff --git a/erpnext/stock/report/incorrect_stock_value_report/incorrect_stock_value_report.py b/erpnext/stock/report/incorrect_stock_value_report/incorrect_stock_value_report.py
index 23e3c8a..df01b14 100644
--- a/erpnext/stock/report/incorrect_stock_value_report/incorrect_stock_value_report.py
+++ b/erpnext/stock/report/incorrect_stock_value_report/incorrect_stock_value_report.py
@@ -4,6 +4,8 @@
 
 import frappe
 from frappe import _
+from frappe.query_builder import Field
+from frappe.query_builder.functions import Min, Timestamp
 from frappe.utils import add_days, getdate, today
 
 import erpnext
@@ -28,7 +30,7 @@
 def get_unsync_date(filters):
 	date = filters.from_date
 	if not date:
-		date = frappe.db.sql(""" SELECT min(posting_date) from `tabStock Ledger Entry`""")
+		date = (frappe.qb.from_("Stock Ledger Entry").select(Min(Field("posting_date")))).run()
 		date = date[0][0]
 
 	if not date:
@@ -54,22 +56,27 @@
 	result = []
 
 	voucher_wise_dict = {}
-	data = frappe.db.sql(
-		"""
-			SELECT
-				name, posting_date, posting_time, voucher_type, voucher_no,
-				stock_value_difference, stock_value, warehouse, item_code
-			FROM
-				`tabStock Ledger Entry`
-			WHERE
-				posting_date
-				= %s and company = %s
-				and is_cancelled = 0
-			ORDER BY timestamp(posting_date, posting_time) asc, creation asc
-		""",
-		(from_date, report_filters.company),
-		as_dict=1,
-	)
+	sle = frappe.qb.DocType("Stock Ledger Entry")
+	data = (
+		frappe.qb.from_(sle)
+		.select(
+			sle.name,
+			sle.posting_date,
+			sle.posting_time,
+			sle.voucher_type,
+			sle.voucher_no,
+			sle.stock_value_difference,
+			sle.stock_value,
+			sle.warehouse,
+			sle.item_code,
+		)
+		.where(
+			(sle.posting_date == from_date)
+			& (sle.company == report_filters.company)
+			& (sle.is_cancelled == 0)
+		)
+		.orderby(Timestamp(sle.posting_date, sle.posting_time), sle.creation)
+	).run(as_dict=True)
 
 	for d in data:
 		voucher_wise_dict.setdefault((d.item_code, d.warehouse), []).append(d)
diff --git a/erpnext/stock/report/item_price_stock/item_price_stock.py b/erpnext/stock/report/item_price_stock/item_price_stock.py
index 15218e6..1b07f59 100644
--- a/erpnext/stock/report/item_price_stock/item_price_stock.py
+++ b/erpnext/stock/report/item_price_stock/item_price_stock.py
@@ -62,22 +62,28 @@
 
 
 def get_item_price_qty_data(filters):
-	conditions = ""
-	if filters.get("item_code"):
-		conditions += "where a.item_code=%(item_code)s"
+	item_price = frappe.qb.DocType("Item Price")
+	bin = frappe.qb.DocType("Bin")
 
-	item_results = frappe.db.sql(
-		"""select a.item_code, a.item_name, a.name as price_list_name,
-		a.brand as brand, b.warehouse as warehouse, b.actual_qty as actual_qty
-		from `tabItem Price` a left join `tabBin` b
-		ON a.item_code = b.item_code
-		{conditions}""".format(
-			conditions=conditions
-		),
-		filters,
-		as_dict=1,
+	query = (
+		frappe.qb.from_(item_price)
+		.left_join(bin)
+		.on(item_price.item_code == bin.item_code)
+		.select(
+			item_price.item_code,
+			item_price.item_name,
+			item_price.name.as_("price_list_name"),
+			item_price.brand.as_("brand"),
+			bin.warehouse.as_("warehouse"),
+			bin.actual_qty.as_("actual_qty"),
+		)
 	)
 
+	if filters.get("item_code"):
+		query = query.where(item_price.item_code == filters.get("item_code"))
+
+	item_results = query.run(as_dict=True)
+
 	price_list_names = list(set(item.price_list_name for item in item_results))
 
 	buying_price_map = get_price_map(price_list_names, buying=1)
diff --git a/erpnext/stock/report/item_shortage_report/item_shortage_report.py b/erpnext/stock/report/item_shortage_report/item_shortage_report.py
index 03a3a6a..9fafe91 100644
--- a/erpnext/stock/report/item_shortage_report/item_shortage_report.py
+++ b/erpnext/stock/report/item_shortage_report/item_shortage_report.py
@@ -8,8 +8,7 @@
 
 def execute(filters=None):
 	columns = get_columns()
-	conditions = get_conditions(filters)
-	data = get_data(conditions, filters)
+	data = get_data(filters)
 
 	if not data:
 		return [], [], None, []
@@ -19,49 +18,39 @@
 	return columns, data, None, chart_data
 
 
-def get_conditions(filters):
-	conditions = ""
+def get_data(filters):
+	bin = frappe.qb.DocType("Bin")
+	wh = frappe.qb.DocType("Warehouse")
+	item = frappe.qb.DocType("Item")
 
-	if filters.get("warehouse"):
-		conditions += "AND warehouse in %(warehouse)s"
-	if filters.get("company"):
-		conditions += "AND company = %(company)s"
-
-	return conditions
-
-
-def get_data(conditions, filters):
-	data = frappe.db.sql(
-		"""
-		SELECT
+	query = (
+		frappe.qb.from_(bin)
+		.from_(wh)
+		.from_(item)
+		.select(
 			bin.warehouse,
 			bin.item_code,
-			bin.actual_qty ,
-			bin.ordered_qty ,
-			bin.planned_qty ,
-			bin.reserved_qty ,
+			bin.actual_qty,
+			bin.ordered_qty,
+			bin.planned_qty,
+			bin.reserved_qty,
 			bin.reserved_qty_for_production,
-			bin.projected_qty ,
-			warehouse.company,
-			item.item_name ,
-			item.description
-		FROM
-			`tabBin` bin,
-			`tabWarehouse` warehouse,
-			`tabItem` item
-		WHERE
-			bin.projected_qty<0
-			AND warehouse.name = bin.warehouse
-			AND bin.item_code=item.name
-			{0}
-		ORDER BY bin.projected_qty;""".format(
-			conditions
-		),
-		filters,
-		as_dict=1,
+			bin.projected_qty,
+			wh.company,
+			item.item_name,
+			item.description,
+		)
+		.where((bin.projected_qty < 0) & (wh.name == bin.warehouse) & (bin.item_code == item.name))
+		.orderby(bin.projected_qty)
 	)
 
-	return data
+	if filters.get("warehouse"):
+		query = query.where(bin.warehouse.isin(filters.get("warehouse")))
+
+	if filters.get("company"):
+		query = query.where(wh.company == filters.get("company"))
+
+	return query.run(as_dict=True)
 
 
 def get_chart_data(data):
diff --git a/erpnext/stock/report/item_shortage_report/test_item_shortage_report.py b/erpnext/stock/report/item_shortage_report/test_item_shortage_report.py
new file mode 100644
index 0000000..5884c32
--- /dev/null
+++ b/erpnext/stock/report/item_shortage_report/test_item_shortage_report.py
@@ -0,0 +1,51 @@
+# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
+# For license information, please see license.txt
+
+import frappe
+from frappe.tests.utils import FrappeTestCase
+
+from erpnext.selling.doctype.sales_order.test_sales_order import make_sales_order
+from erpnext.stock.doctype.item.test_item import make_item
+from erpnext.stock.report.item_shortage_report.item_shortage_report import (
+	execute as item_shortage_report,
+)
+
+
+class TestItemShortageReport(FrappeTestCase):
+	def test_item_shortage_report(self):
+		item = make_item().name
+		so = make_sales_order(item_code=item)
+
+		reserved_qty, projected_qty = frappe.db.get_value(
+			"Bin",
+			{
+				"item_code": item,
+				"warehouse": so.items[0].warehouse,
+			},
+			["reserved_qty", "projected_qty"],
+		)
+		self.assertEqual(reserved_qty, so.items[0].qty)
+		self.assertEqual(projected_qty, -(so.items[0].qty))
+
+		filters = {
+			"company": so.company,
+		}
+		report_data = item_shortage_report(filters)[1]
+		item_code_list = [row.get("item_code") for row in report_data]
+		self.assertIn(item, item_code_list)
+
+		filters = {
+			"company": so.company,
+			"warehouse": [so.items[0].warehouse],
+		}
+		report_data = item_shortage_report(filters)[1]
+		item_code_list = [row.get("item_code") for row in report_data]
+		self.assertIn(item, item_code_list)
+
+		filters = {
+			"company": so.company,
+			"warehouse": ["Work In Progress - _TC"],
+		}
+		report_data = item_shortage_report(filters)[1]
+		item_code_list = [row.get("item_code") for row in report_data]
+		self.assertNotIn(item, item_code_list)
diff --git a/erpnext/stock/report/purchase_receipt_trends/purchase_receipt_trends.py b/erpnext/stock/report/purchase_receipt_trends/purchase_receipt_trends.py
index fe2d55a..b62a6ee 100644
--- a/erpnext/stock/report/purchase_receipt_trends/purchase_receipt_trends.py
+++ b/erpnext/stock/report/purchase_receipt_trends/purchase_receipt_trends.py
@@ -46,4 +46,5 @@
 		},
 		"type": "bar",
 		"colors": ["#5e64ff"],
+		"fieldtype": "Currency",
 	}
diff --git a/erpnext/www/lms/__init__.py b/erpnext/www/lms/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/erpnext/www/lms/__init__.py