Merge branch 'develop' of https://github.com/frappe/erpnext into move_taxjar_integration_new
diff --git a/erpnext/accounts/doctype/journal_entry/journal_entry.js b/erpnext/accounts/doctype/journal_entry/journal_entry.js
index a5ff7f1..30a3201 100644
--- a/erpnext/accounts/doctype/journal_entry/journal_entry.js
+++ b/erpnext/accounts/doctype/journal_entry/journal_entry.js
@@ -253,9 +253,6 @@
 				var party_account_field = jvd.reference_type==="Sales Invoice" ? "debit_to": "credit_to";
 				out.filters.push([jvd.reference_type, party_account_field, "=", jvd.account]);
 
-				if (in_list(['Debit Note', 'Credit Note'], doc.voucher_type)) {
-					out.filters.push([jvd.reference_type, "is_return", "=", 1]);
-				}
 			}
 
 			if(in_list(["Sales Order", "Purchase Order"], jvd.reference_type)) {
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
index 39a6235..a098e8d 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.js
@@ -81,7 +81,7 @@
 		}
 
 		if(doc.docstatus == 1 && doc.outstanding_amount != 0
-			&& !(doc.is_return && doc.return_against)) {
+			&& !(doc.is_return && doc.return_against) && !doc.on_hold) {
 			this.frm.add_custom_button(__('Payment'), this.make_payment_entry, __('Create'));
 			cur_frm.page.set_inner_btn_group_as_primary(__('Create'));
 		}
@@ -99,7 +99,7 @@
 			}
 		}
 
-		if (doc.outstanding_amount > 0 && !cint(doc.is_return)) {
+		if (doc.outstanding_amount > 0 && !cint(doc.is_return) && !doc.on_hold) {
 			cur_frm.add_custom_button(__('Payment Request'), function() {
 				me.make_payment_request()
 			}, __('Create'));
diff --git a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json
index 370c0fc..a5981fd 100644
--- a/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json
+++ b/erpnext/accounts/doctype/purchase_invoice/purchase_invoice.json
@@ -25,6 +25,10 @@
   "apply_tds",
   "tax_withholding_category",
   "amended_from",
+  "supplier_invoice_details",
+  "bill_no",
+  "column_break_15",
+  "bill_date",
   "accounting_dimensions_section",
   "cost_center",
   "dimension_col_break",
@@ -151,10 +155,6 @@
   "status",
   "column_break_177",
   "per_received",
-  "supplier_invoice_details",
-  "bill_no",
-  "column_break_15",
-  "bill_date",
   "accounting_details_section",
   "credit_to",
   "party_account_currency",
@@ -1540,7 +1540,7 @@
  "idx": 204,
  "is_submittable": 1,
  "links": [],
- "modified": "2022-11-04 01:02:44.544878",
+ "modified": "2022-11-22 12:44:29.935567",
  "modified_by": "Administrator",
  "module": "Accounts",
  "name": "Purchase Invoice",
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 40c732b..23caac0 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
@@ -226,6 +226,42 @@
 		for d in reversed(invoices):
 			d.cancel()
 
+		orders = []
+
+		po = create_purchase_order(supplier="Test TDS Supplier4", rate=20000, do_not_save=True)
+		po.extend(
+			"items",
+			[
+				{
+					"doctype": "Purchase Order Item",
+					"item_code": frappe.db.get_value("Item", {"item_name": "TDS Item"}, "name"),
+					"qty": 1,
+					"rate": 20000,
+					"cost_center": "Main - _TC",
+					"expense_account": "Stock Received But Not Billed - _TC",
+					"apply_tds": 0,
+				},
+				{
+					"doctype": "Purchase Order Item",
+					"item_code": frappe.db.get_value("Item", {"item_name": "TDS Item"}, "name"),
+					"qty": 1,
+					"rate": 35000,
+					"cost_center": "Main - _TC",
+					"expense_account": "Stock Received But Not Billed - _TC",
+					"apply_tds": 1,
+				},
+			],
+		)
+		po.save()
+		po.submit()
+		orders.append(po)
+
+		self.assertEqual(po.taxes[0].tax_amount, 5500)
+
+		# cancel orders to avoid clashing
+		for d in reversed(orders):
+			d.cancel()
+
 	def test_multi_category_single_supplier(self):
 		frappe.db.set_value(
 			"Supplier", "Test TDS Supplier5", "tax_withholding_category", "Test Service Category"
@@ -348,6 +384,39 @@
 	return pi
 
 
+def create_purchase_order(**args):
+	# return purchase order doc object
+	item = frappe.db.get_value("Item", {"item_name": "TDS Item"}, "name")
+
+	args = frappe._dict(args)
+	po = frappe.get_doc(
+		{
+			"doctype": "Purchase Order",
+			"transaction_date": today(),
+			"schedule_date": today(),
+			"apply_tds": 0 if args.do_not_apply_tds else 1,
+			"supplier": args.supplier,
+			"company": "_Test Company",
+			"taxes_and_charges": "",
+			"currency": "INR",
+			"taxes": [],
+			"items": [
+				{
+					"doctype": "Purchase Order Item",
+					"item_code": item,
+					"qty": args.qty or 1,
+					"rate": args.rate or 10000,
+					"cost_center": "Main - _TC",
+					"expense_account": "Stock Received But Not Billed - _TC",
+				}
+			],
+		}
+	)
+
+	po.save()
+	return po
+
+
 def create_sales_invoice(**args):
 	# return sales invoice doc object
 	item = frappe.db.get_value("Item", {"item_name": "TCS Item"}, "name")
diff --git a/erpnext/accounts/general_ledger.py b/erpnext/accounts/general_ledger.py
index 6d164ee..c757057 100644
--- a/erpnext/accounts/general_ledger.py
+++ b/erpnext/accounts/general_ledger.py
@@ -394,20 +394,22 @@
 	round_off_account, round_off_cost_center = get_round_off_account_and_cost_center(
 		gl_map[0].company, gl_map[0].voucher_type, gl_map[0].voucher_no
 	)
-	round_off_account_exists = False
 	round_off_gle = frappe._dict()
-	for d in gl_map:
-		if d.account == round_off_account:
-			round_off_gle = d
-			if d.debit:
-				debit_credit_diff -= flt(d.debit)
-			else:
-				debit_credit_diff += flt(d.credit)
-			round_off_account_exists = True
+	round_off_account_exists = False
 
-	if round_off_account_exists and abs(debit_credit_diff) < (1.0 / (10**precision)):
-		gl_map.remove(round_off_gle)
-		return
+	if gl_map[0].voucher_type != "Period Closing Voucher":
+		for d in gl_map:
+			if d.account == round_off_account:
+				round_off_gle = d
+				if d.debit:
+					debit_credit_diff -= flt(d.debit) - flt(d.credit)
+				else:
+					debit_credit_diff += flt(d.credit)
+				round_off_account_exists = True
+
+		if round_off_account_exists and abs(debit_credit_diff) < (1.0 / (10**precision)):
+			gl_map.remove(round_off_gle)
+			return
 
 	if not round_off_gle:
 		for k in ["voucher_type", "voucher_no", "company", "posting_date", "remarks"]:
@@ -430,7 +432,6 @@
 	)
 
 	update_accounting_dimensions(round_off_gle)
-
 	if not round_off_account_exists:
 		gl_map.append(round_off_gle)
 
diff --git a/erpnext/buying/doctype/purchase_order/purchase_order.json b/erpnext/buying/doctype/purchase_order/purchase_order.json
index ded45b8..e2a70c2 100644
--- a/erpnext/buying/doctype/purchase_order/purchase_order.json
+++ b/erpnext/buying/doctype/purchase_order/purchase_order.json
@@ -54,6 +54,8 @@
   "column_break_26",
   "total",
   "net_total",
+  "tax_withholding_net_total",
+  "base_tax_withholding_net_total",
   "section_break_48",
   "pricing_rules",
   "raw_material_details",
@@ -1221,6 +1223,26 @@
    "oldfieldtype": "Section Break"
   },
   {
+   "default": "0",
+   "fieldname": "tax_withholding_net_total",
+   "fieldtype": "Currency",
+   "hidden": 1,
+   "label": "Tax Withholding Net Total",
+   "no_copy": 1,
+   "options": "currency",
+   "read_only": 1
+  },
+  {
+   "fieldname": "base_tax_withholding_net_total",
+   "fieldtype": "Currency",
+   "hidden": 1,
+   "label": "Base Tax Withholding Net Total",
+   "no_copy": 1,
+   "options": "currency",
+   "print_hide": 1,
+   "read_only": 1
+  },
+  {
    "fieldname": "column_break_99",
    "fieldtype": "Column Break"
   },
diff --git a/erpnext/buying/doctype/purchase_order/test_purchase_order.py b/erpnext/buying/doctype/purchase_order/test_purchase_order.py
index 5206a42..291d756 100644
--- a/erpnext/buying/doctype/purchase_order/test_purchase_order.py
+++ b/erpnext/buying/doctype/purchase_order/test_purchase_order.py
@@ -736,27 +736,29 @@
 	def test_advance_paid_upon_payment_entry_cancellation(self):
 		from erpnext.accounts.doctype.payment_entry.test_payment_entry import get_payment_entry
 
-		po_doc = create_purchase_order()
+		po_doc = create_purchase_order(supplier="_Test Supplier USD", currency="USD", do_not_submit=1)
+		po_doc.conversion_rate = 80
+		po_doc.submit()
 
-		pe = get_payment_entry("Purchase Order", po_doc.name, bank_account="_Test Bank - _TC")
-		pe.reference_no = "1"
-		pe.reference_date = nowdate()
-		pe.paid_from_account_currency = po_doc.currency
-		pe.paid_to_account_currency = po_doc.currency
-		pe.source_exchange_rate = 1
+		pe = get_payment_entry("Purchase Order", po_doc.name)
+		pe.mode_of_payment = "Cash"
+		pe.paid_from = "Cash - _TC"
+		pe.source_exchange_rate = 80
 		pe.target_exchange_rate = 1
 		pe.paid_amount = po_doc.grand_total
 		pe.save(ignore_permissions=True)
 		pe.submit()
 
 		po_doc.reload()
-		self.assertEqual(po_doc.advance_paid, po_doc.base_grand_total)
+		self.assertEqual(po_doc.advance_paid, po_doc.grand_total)
+		self.assertEqual(po_doc.party_account_currency, "USD")
 
 		pe_doc = frappe.get_doc("Payment Entry", pe.name)
 		pe_doc.cancel()
 
 		po_doc.reload()
 		self.assertEqual(po_doc.advance_paid, 0)
+		self.assertEqual(po_doc.party_account_currency, "USD")
 
 	def test_schedule_date(self):
 		po = create_purchase_order(do_not_submit=True)
diff --git a/erpnext/buying/doctype/purchase_order_item/purchase_order_item.json b/erpnext/buying/doctype/purchase_order_item/purchase_order_item.json
index b8203bd..d471783 100644
--- a/erpnext/buying/doctype/purchase_order_item/purchase_order_item.json
+++ b/erpnext/buying/doctype/purchase_order_item/purchase_order_item.json
@@ -44,6 +44,7 @@
   "discount_amount",
   "base_rate_with_margin",
   "sec_break2",
+  "apply_tds",
   "rate",
   "amount",
   "item_tax_template",
@@ -889,6 +890,12 @@
   {
    "fieldname": "column_break_54",
    "fieldtype": "Column Break"
+  },
+  {
+   "default": "1",
+   "fieldname": "apply_tds",
+   "fieldtype": "Check",
+   "label": "Apply TDS"
   }
  ],
  "idx": 1,
diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index 216c9f4..1849e8b 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -1352,12 +1352,12 @@
 		party = self.customer if self.doctype == "Sales Order" else self.supplier
 		advance = (
 			frappe.qb.from_(ple)
-			.select(ple.account_currency, Abs(Sum(ple.amount)).as_("amount"))
+			.select(ple.account_currency, Abs(Sum(ple.amount_in_account_currency)).as_("amount"))
 			.where(
 				(ple.against_voucher_type == self.doctype)
 				& (ple.against_voucher_no == self.name)
 				& (ple.party == party)
-				& (ple.delinked == 0)
+				& (ple.docstatus == 1)
 				& (ple.company == self.company)
 			)
 			.run(as_dict=True)
diff --git a/erpnext/patches.txt b/erpnext/patches.txt
index 03bf831..639809d 100644
--- a/erpnext/patches.txt
+++ b/erpnext/patches.txt
@@ -316,4 +316,4 @@
 erpnext.patches.v14_0.migrate_remarks_from_gl_to_payment_ledger
 erpnext.patches.v13_0.update_schedule_type_in_loans
 erpnext.patches.v14_0.create_accounting_dimensions_for_asset_capitalization
-erpnext.patches.v14_0.update_tds_fields
+erpnext.patches.v14_0.update_partial_tds_fields
diff --git a/erpnext/patches/v14_0/update_tds_fields.py b/erpnext/patches/v14_0/update_partial_tds_fields.py
similarity index 64%
rename from erpnext/patches/v14_0/update_tds_fields.py
rename to erpnext/patches/v14_0/update_partial_tds_fields.py
index a333c5d..5ccc2dc 100644
--- a/erpnext/patches/v14_0/update_tds_fields.py
+++ b/erpnext/patches/v14_0/update_partial_tds_fields.py
@@ -25,5 +25,21 @@
 			).where(
 				purchase_invoice.docstatus == 1
 			).run()
+
+			purchase_order = frappe.qb.DocType("Purchase Order")
+
+			frappe.qb.update(purchase_order).set(
+				purchase_order.tax_withholding_net_total, purchase_order.net_total
+			).set(
+				purchase_order.base_tax_withholding_net_total, purchase_order.base_net_total
+			).where(
+				purchase_order.company == company.name
+			).where(
+				purchase_order.apply_tds == 1
+			).where(
+				purchase_order.transaction_date >= fiscal_year_details.year_start_date
+			).where(
+				purchase_order.docstatus == 1
+			).run()
 		except FiscalYearError:
 			pass
diff --git a/erpnext/stock/doctype/inventory_dimension/inventory_dimension.js b/erpnext/stock/doctype/inventory_dimension/inventory_dimension.js
index 79e7895..ba1023a 100644
--- a/erpnext/stock/doctype/inventory_dimension/inventory_dimension.js
+++ b/erpnext/stock/doctype/inventory_dimension/inventory_dimension.js
@@ -71,6 +71,8 @@
 					if (r.message && r.message.length) {
 						frm.set_df_property("fetch_from_parent", "options",
 							[""].concat(r.message));
+					} else {
+						frm.set_df_property("fetch_from_parent", "hidden", 1);
 					}
 				}
 			});
diff --git a/erpnext/stock/doctype/inventory_dimension/inventory_dimension.json b/erpnext/stock/doctype/inventory_dimension/inventory_dimension.json
index 09f4f63..4397e11 100644
--- a/erpnext/stock/doctype/inventory_dimension/inventory_dimension.json
+++ b/erpnext/stock/doctype/inventory_dimension/inventory_dimension.json
@@ -11,20 +11,20 @@
   "reference_document",
   "column_break_4",
   "disabled",
-  "section_break_7",
   "field_mapping_section",
   "source_fieldname",
   "column_break_9",
   "target_fieldname",
   "applicable_for_documents_tab",
   "apply_to_all_doctypes",
+  "column_break_13",
   "document_type",
-  "istable",
   "type_of_transaction",
   "fetch_from_parent",
-  "column_break_16",
-  "condition",
+  "istable",
   "applicable_condition_example_section",
+  "condition",
+  "conditional_rule_examples_section",
   "html_19"
  ],
  "fields": [
@@ -52,13 +52,13 @@
   {
    "fieldname": "applicable_for_documents_tab",
    "fieldtype": "Tab Break",
-   "label": "Applicable For Documents"
+   "label": "Applicable For"
   },
   {
    "depends_on": "eval:!doc.apply_to_all_doctypes",
    "fieldname": "document_type",
    "fieldtype": "Link",
-   "label": "Applicable to Document",
+   "label": "Apply to Document",
    "mandatory_depends_on": "eval:!doc.apply_to_all_doctypes",
    "options": "DocType"
   },
@@ -72,6 +72,7 @@
    "fetch_from": "document_type.istable",
    "fieldname": "istable",
    "fieldtype": "Check",
+   "hidden": 1,
    "label": " Is Child Table",
    "read_only": 1
   },
@@ -79,13 +80,13 @@
    "depends_on": "eval:!doc.apply_to_all_doctypes",
    "fieldname": "condition",
    "fieldtype": "Code",
-   "label": "Applicable Condition"
+   "label": "Conditional Rule"
   },
   {
-   "default": "0",
+   "default": "1",
    "fieldname": "apply_to_all_doctypes",
    "fieldtype": "Check",
-   "label": "Apply to All Inventory Document Types"
+   "label": "Apply to All Inventory Documents"
   },
   {
    "default": "0",
@@ -94,10 +95,6 @@
    "label": "Disabled"
   },
   {
-   "fieldname": "section_break_7",
-   "fieldtype": "Section Break"
-  },
-  {
    "fieldname": "target_fieldname",
    "fieldtype": "Data",
    "label": "Target Fieldname (Stock Ledger Entry)",
@@ -115,13 +112,11 @@
    "collapsible": 1,
    "fieldname": "field_mapping_section",
    "fieldtype": "Section Break",
+   "hidden": 1,
    "label": "Field Mapping"
   },
   {
-   "fieldname": "column_break_16",
-   "fieldtype": "Column Break"
-  },
-  {
+   "depends_on": "eval:!doc.apply_to_all_doctypes",
    "fieldname": "type_of_transaction",
    "fieldtype": "Select",
    "label": "Type of Transaction",
@@ -136,23 +131,33 @@
    "collapsible": 1,
    "depends_on": "eval:!doc.apply_to_all_doctypes",
    "fieldname": "applicable_condition_example_section",
-   "fieldtype": "Section Break",
-   "label": "Applicable Condition Examples"
+   "fieldtype": "Column Break"
   },
   {
    "fieldname": "column_break_4",
    "fieldtype": "Column Break"
   },
   {
-   "description": "Set fieldname or DocType name like Supplier, Customer etc.",
+   "depends_on": "eval:!doc.apply_to_all_doctypes",
+   "description": "Set fieldname from which you want to fetch the data from the parent form.",
    "fieldname": "fetch_from_parent",
    "fieldtype": "Select",
-   "label": "Fetch Value From Parent Form"
+   "label": "Fetch Value From"
+  },
+  {
+   "fieldname": "column_break_13",
+   "fieldtype": "Section Break"
+  },
+  {
+   "depends_on": "eval:!doc.apply_to_all_doctypes",
+   "fieldname": "conditional_rule_examples_section",
+   "fieldtype": "Section Break",
+   "label": "Conditional Rule Examples"
   }
  ],
  "index_web_pages_for_search": 1,
  "links": [],
- "modified": "2022-09-02 13:29:04.098469",
+ "modified": "2022-11-15 15:50:16.767105",
  "modified_by": "Administrator",
  "module": "Stock",
  "name": "Inventory Dimension",
diff --git a/erpnext/stock/doctype/inventory_dimension/inventory_dimension.py b/erpnext/stock/doctype/inventory_dimension/inventory_dimension.py
index 7b99b00..009548a 100644
--- a/erpnext/stock/doctype/inventory_dimension/inventory_dimension.py
+++ b/erpnext/stock/doctype/inventory_dimension/inventory_dimension.py
@@ -33,10 +33,22 @@
 		)
 
 	def validate(self):
+		self.validate_reference_document()
+
+	def before_save(self):
 		self.do_not_update_document()
 		self.reset_value()
-		self.validate_reference_document()
 		self.set_source_and_target_fieldname()
+		self.set_type_of_transaction()
+		self.set_fetch_value_from()
+
+	def set_type_of_transaction(self):
+		if self.apply_to_all_doctypes:
+			self.type_of_transaction = "Both"
+
+	def set_fetch_value_from(self):
+		if self.apply_to_all_doctypes:
+			self.fetch_from_parent = self.reference_document
 
 	def do_not_update_document(self):
 		if self.is_new() or not self.has_stock_ledger():
diff --git a/erpnext/stock/doctype/inventory_dimension/test_inventory_dimension.py b/erpnext/stock/doctype/inventory_dimension/test_inventory_dimension.py
index 52b3deb..edff3fd 100644
--- a/erpnext/stock/doctype/inventory_dimension/test_inventory_dimension.py
+++ b/erpnext/stock/doctype/inventory_dimension/test_inventory_dimension.py
@@ -140,14 +140,13 @@
 		self.assertRaises(DoNotChangeError, inv_dim1.save)
 
 	def test_inventory_dimension_for_purchase_receipt_and_delivery_note(self):
-		create_inventory_dimension(
-			reference_document="Rack",
-			type_of_transaction="Both",
-			dimension_name="Rack",
-			apply_to_all_doctypes=1,
-			fetch_from_parent="Rack",
+		inv_dimension = create_inventory_dimension(
+			reference_document="Rack", dimension_name="Rack", apply_to_all_doctypes=1
 		)
 
+		self.assertEqual(inv_dimension.type_of_transaction, "Both")
+		self.assertEqual(inv_dimension.fetch_from_parent, "Rack")
+
 		create_custom_field(
 			"Purchase Receipt", dict(fieldname="rack", label="Rack", fieldtype="Link", options="Rack")
 		)
diff --git a/erpnext/stock/report/stock_ledger/stock_ledger.py b/erpnext/stock/report/stock_ledger/stock_ledger.py
index b725d49..8b63c0f 100644
--- a/erpnext/stock/report/stock_ledger/stock_ledger.py
+++ b/erpnext/stock/report/stock_ledger/stock_ledger.py
@@ -58,6 +58,12 @@
 		if sle.serial_no:
 			update_available_serial_nos(available_serial_nos, sle)
 
+		if sle.actual_qty:
+			sle["in_out_rate"] = flt(sle.stock_value_difference / sle.actual_qty, precision)
+
+		elif sle.voucher_type == "Stock Reconciliation":
+			sle["in_out_rate"] = sle.valuation_rate
+
 		data.append(sle)
 
 		if include_uom:
@@ -185,10 +191,18 @@
 				"convertible": "rate",
 			},
 			{
-				"label": _("Valuation Rate"),
+				"label": _("Avg Rate (Balance Stock)"),
 				"fieldname": "valuation_rate",
 				"fieldtype": "Currency",
-				"width": 110,
+				"width": 180,
+				"options": "Company:company:default_currency",
+				"convertible": "rate",
+			},
+			{
+				"label": _("Valuation Rate"),
+				"fieldname": "in_out_rate",
+				"fieldtype": "Currency",
+				"width": 140,
 				"options": "Company:company:default_currency",
 				"convertible": "rate",
 			},