Merge branch 'develop' into reload-currency-exchange-settings
diff --git a/erpnext/accounts/doctype/bank_clearance/bank_clearance.js b/erpnext/accounts/doctype/bank_clearance/bank_clearance.js
index 7e57c2f..ceba99a 100644
--- a/erpnext/accounts/doctype/bank_clearance/bank_clearance.js
+++ b/erpnext/accounts/doctype/bank_clearance/bank_clearance.js
@@ -37,6 +37,14 @@
 
 	refresh: function(frm) {
 		frm.disable_save();
+
+		if (frm.doc.account && frm.doc.from_date && frm.doc.to_date) {
+			frm.add_custom_button(__('Get Payment Entries'), () =>
+				frm.trigger("get_payment_entries")
+			);
+
+			frm.change_custom_button_type('Get Payment Entries', null, 'primary');
+		}
 	},
 
 	update_clearance_date: function(frm) {
@@ -46,22 +54,30 @@
 			callback: function(r, rt) {
 				frm.refresh_field("payment_entries");
 				frm.refresh_fields();
+
+				if (!frm.doc.payment_entries.length) {
+					frm.change_custom_button_type('Get Payment Entries', null, 'primary');
+					frm.change_custom_button_type('Update Clearance Date', null, 'default');
+				}
 			}
 		});
 	},
+
 	get_payment_entries: function(frm) {
 		return frappe.call({
 			method: "get_payment_entries",
 			doc: frm.doc,
 			callback: function(r, rt) {
 				frm.refresh_field("payment_entries");
-				frm.refresh_fields();
 
-				$(frm.fields_dict.payment_entries.wrapper).find("[data-fieldname=amount]").each(function(i,v){
-					if (i !=0){
-						$(v).addClass("text-right")
-					}
-				})
+				if (frm.doc.payment_entries.length) {
+					frm.add_custom_button(__('Update Clearance Date'), () =>
+						frm.trigger("update_clearance_date")
+					);
+
+					frm.change_custom_button_type('Get Payment Entries', null, 'default');
+					frm.change_custom_button_type('Update Clearance Date', null, 'primary');
+				}
 			}
 		});
 	}
diff --git a/erpnext/accounts/doctype/bank_clearance/bank_clearance.json b/erpnext/accounts/doctype/bank_clearance/bank_clearance.json
index a436d1e..591d019 100644
--- a/erpnext/accounts/doctype/bank_clearance/bank_clearance.json
+++ b/erpnext/accounts/doctype/bank_clearance/bank_clearance.json
@@ -1,4 +1,5 @@
 {
+ "actions": [],
  "allow_copy": 1,
  "creation": "2013-01-10 16:34:05",
  "doctype": "DocType",
@@ -13,11 +14,8 @@
   "bank_account",
   "include_reconciled_entries",
   "include_pos_transactions",
-  "get_payment_entries",
   "section_break_10",
-  "payment_entries",
-  "update_clearance_date",
-  "total_amount"
+  "payment_entries"
  ],
  "fields": [
   {
@@ -77,11 +75,6 @@
    "label": "Include POS Transactions"
   },
   {
-   "fieldname": "get_payment_entries",
-   "fieldtype": "Button",
-   "label": "Get Payment Entries"
-  },
-  {
    "fieldname": "section_break_10",
    "fieldtype": "Section Break"
   },
@@ -91,25 +84,14 @@
    "fieldtype": "Table",
    "label": "Payment Entries",
    "options": "Bank Clearance Detail"
-  },
-  {
-   "fieldname": "update_clearance_date",
-   "fieldtype": "Button",
-   "label": "Update Clearance Date"
-  },
-  {
-   "fieldname": "total_amount",
-   "fieldtype": "Currency",
-   "label": "Total Amount",
-   "options": "account_currency",
-   "read_only": 1
   }
  ],
  "hide_toolbar": 1,
  "icon": "fa fa-check",
  "idx": 1,
  "issingle": 1,
- "modified": "2020-04-06 16:12:06.628008",
+ "links": [],
+ "modified": "2022-11-28 17:24:13.008692",
  "modified_by": "Administrator",
  "module": "Accounts",
  "name": "Bank Clearance",
@@ -126,5 +108,6 @@
  "quick_entry": 1,
  "read_only": 1,
  "sort_field": "modified",
- "sort_order": "ASC"
+ "sort_order": "ASC",
+ "states": []
 }
\ No newline at end of file
diff --git a/erpnext/accounts/doctype/bank_clearance/bank_clearance.py b/erpnext/accounts/doctype/bank_clearance/bank_clearance.py
index 78c3526..80878ac 100644
--- a/erpnext/accounts/doctype/bank_clearance/bank_clearance.py
+++ b/erpnext/accounts/doctype/bank_clearance/bank_clearance.py
@@ -179,7 +179,6 @@
 		)
 
 		self.set("payment_entries", [])
-		self.total_amount = 0.0
 		default_currency = erpnext.get_default_currency()
 
 		for d in entries:
@@ -198,7 +197,6 @@
 			d.pop("debit")
 			d.pop("account_currency")
 			row.update(d)
-			self.total_amount += flt(amount)
 
 	@frappe.whitelist()
 	def update_clearance_date(self):
diff --git a/erpnext/accounts/doctype/pos_invoice/pos_invoice.js b/erpnext/accounts/doctype/pos_invoice/pos_invoice.js
index 15c2922..56b8579 100644
--- a/erpnext/accounts/doctype/pos_invoice/pos_invoice.js
+++ b/erpnext/accounts/doctype/pos_invoice/pos_invoice.js
@@ -5,6 +5,8 @@
 frappe.provide("erpnext.accounts");
 
 erpnext.selling.POSInvoiceController = class POSInvoiceController extends erpnext.selling.SellingController {
+	settings = {};
+
 	setup(doc) {
 		this.setup_posting_date_time_check();
 		super.setup(doc);
@@ -12,21 +14,37 @@
 
 	company() {
 		erpnext.accounts.dimensions.update_dimension(this.frm, this.frm.doctype);
+		this.frm.set_value("set_warehouse", "");
+		this.frm.set_value("taxes_and_charges", "");
 	}
 
 	onload(doc) {
 		super.onload();
 		this.frm.ignore_doctypes_on_cancel_all = ['POS Invoice Merge Log', 'POS Closing Entry'];
+
 		if(doc.__islocal && doc.is_pos && frappe.get_route_str() !== 'point-of-sale') {
 			this.frm.script_manager.trigger("is_pos");
 			this.frm.refresh_fields();
 		}
 
+		this.frm.set_query("set_warehouse", function(doc) {
+			return {
+				filters: {
+					company: doc.company ? doc.company : '',
+				}
+			}
+		});
+
 		erpnext.accounts.dimensions.setup_dimension_filters(this.frm, this.frm.doctype);
 	}
 
+	onload_post_render(frm) {
+		this.pos_profile(frm);
+	}
+
 	refresh(doc) {
 		super.refresh();
+
 		if (doc.docstatus == 1 && !doc.is_return) {
 			this.frm.add_custom_button(__('Return'), this.make_sales_return, __('Create'));
 			this.frm.page.set_inner_btn_group_as_primary(__('Create'));
@@ -36,6 +54,18 @@
 			this.frm.return_print_format = "Sales Invoice Return";
 			this.frm.set_value('consolidated_invoice', '');
 		}
+
+		this.frm.set_query("customer", (function () {
+			const customer_groups = this.settings?.customer_groups;
+
+			if (!customer_groups?.length) return {};
+
+			return {
+				filters: {
+					customer_group: ["in", customer_groups],
+				}
+			}
+		}).bind(this));
 	}
 
 	is_pos() {
@@ -88,6 +118,25 @@
 			});
 	}
 
+	pos_profile(frm) {
+		if (!frm.pos_profile || frm.pos_profile == '') {
+			this.update_customer_groups_settings([]);
+			return;
+		}
+
+		frappe.call({
+			method: "erpnext.selling.page.point_of_sale.point_of_sale.get_pos_profile_data",
+			args: { "pos_profile": frm.pos_profile },
+			callback: ({ message: profile }) => {
+				this.update_customer_groups_settings(profile?.customer_groups);
+			},
+		});
+	}
+
+	update_customer_groups_settings(customer_groups) {
+		this.settings.customer_groups = customer_groups?.map((group) => group.name)
+	}
+
 	amount(){
 		this.write_off_outstanding_amount_automatically()
 	}
diff --git a/erpnext/accounts/doctype/purchase_invoice_item/purchase_invoice_item.json b/erpnext/accounts/doctype/purchase_invoice_item/purchase_invoice_item.json
index 5c1cb0d..1fa7e7f 100644
--- a/erpnext/accounts/doctype/purchase_invoice_item/purchase_invoice_item.json
+++ b/erpnext/accounts/doctype/purchase_invoice_item/purchase_invoice_item.json
@@ -40,7 +40,6 @@
   "discount_amount",
   "base_rate_with_margin",
   "sec_break2",
-  "apply_tds",
   "rate",
   "amount",
   "item_tax_template",
@@ -50,6 +49,7 @@
   "pricing_rules",
   "stock_uom_rate",
   "is_free_item",
+  "apply_tds",
   "section_break_22",
   "net_rate",
   "net_amount",
@@ -871,16 +871,16 @@
    "read_only": 1
   },
   {
-    "default": "1",
-    "fieldname": "apply_tds",
-    "fieldtype": "Check",
-    "label": "Apply TDS"
+   "default": "1",
+   "fieldname": "apply_tds",
+   "fieldtype": "Check",
+   "label": "Apply TDS"
   }
  ],
  "idx": 1,
  "istable": 1,
  "links": [],
- "modified": "2022-10-26 16:05:37.304788",
+ "modified": "2022-11-29 13:01:20.438217",
  "modified_by": "Administrator",
  "module": "Accounts",
  "name": "Purchase Invoice Item",
diff --git a/erpnext/accounts/doctype/sales_invoice/sales_invoice.json b/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
index 18d2b5c..b38bce7 100644
--- a/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
+++ b/erpnext/accounts/doctype/sales_invoice/sales_invoice.json
@@ -921,6 +921,7 @@
    "fieldtype": "Table",
    "hide_days": 1,
    "hide_seconds": 1,
+   "label": "Sales Taxes and Charges",
    "oldfieldname": "other_charges",
    "oldfieldtype": "Table",
    "options": "Sales Taxes and Charges"
@@ -2133,7 +2134,7 @@
    "link_fieldname": "consolidated_invoice"
   }
  ],
- "modified": "2022-11-17 17:17:10.883487",
+ "modified": "2022-12-05 16:18:14.532114",
  "modified_by": "Administrator",
  "module": "Accounts",
  "name": "Sales Invoice",
diff --git a/erpnext/accounts/report/tds_computation_summary/tds_computation_summary.py b/erpnext/accounts/report/tds_computation_summary/tds_computation_summary.py
index db3d5d4..c6aa21c 100644
--- a/erpnext/accounts/report/tds_computation_summary/tds_computation_summary.py
+++ b/erpnext/accounts/report/tds_computation_summary/tds_computation_summary.py
@@ -14,9 +14,17 @@
 	filters.naming_series = frappe.db.get_single_value("Buying Settings", "supp_master_name")
 
 	columns = get_columns(filters)
-	tds_docs, tds_accounts, tax_category_map, journal_entry_party_map = get_tds_docs(filters)
+	(
+		tds_docs,
+		tds_accounts,
+		tax_category_map,
+		journal_entry_party_map,
+		invoice_total_map,
+	) = get_tds_docs(filters)
 
-	res = get_result(filters, tds_docs, tds_accounts, tax_category_map, journal_entry_party_map)
+	res = get_result(
+		filters, tds_docs, tds_accounts, tax_category_map, journal_entry_party_map, invoice_total_map
+	)
 	final_result = group_by_supplier_and_category(res)
 
 	return columns, final_result
diff --git a/erpnext/accounts/report/tds_payable_monthly/tds_payable_monthly.py b/erpnext/accounts/report/tds_payable_monthly/tds_payable_monthly.py
index f2809a9..9883890 100644
--- a/erpnext/accounts/report/tds_payable_monthly/tds_payable_monthly.py
+++ b/erpnext/accounts/report/tds_payable_monthly/tds_payable_monthly.py
@@ -8,11 +8,19 @@
 
 def execute(filters=None):
 	validate_filters(filters)
-	tds_docs, tds_accounts, tax_category_map, journal_entry_party_map = get_tds_docs(filters)
+	(
+		tds_docs,
+		tds_accounts,
+		tax_category_map,
+		journal_entry_party_map,
+		invoice_net_total_map,
+	) = get_tds_docs(filters)
 
 	columns = get_columns(filters)
 
-	res = get_result(filters, tds_docs, tds_accounts, tax_category_map, journal_entry_party_map)
+	res = get_result(
+		filters, tds_docs, tds_accounts, tax_category_map, journal_entry_party_map, invoice_net_total_map
+	)
 	return columns, res
 
 
@@ -22,7 +30,9 @@
 		frappe.throw(_("From Date must be before To Date"))
 
 
-def get_result(filters, tds_docs, tds_accounts, tax_category_map, journal_entry_party_map):
+def get_result(
+	filters, tds_docs, tds_accounts, tax_category_map, journal_entry_party_map, invoice_net_total_map
+):
 	supplier_map = get_supplier_pan_map()
 	tax_rate_map = get_tax_rate_map(filters)
 	gle_map = get_gle_map(tds_docs)
@@ -50,7 +60,10 @@
 			if entry.account in tds_accounts:
 				tds_deducted += entry.credit - entry.debit
 
-			total_amount_credited += entry.credit
+			if invoice_net_total_map.get(name):
+				total_amount_credited = invoice_net_total_map.get(name)
+			else:
+				total_amount_credited += entry.credit
 
 		if tds_deducted:
 			row = {
@@ -179,9 +192,10 @@
 	purchase_invoices = []
 	payment_entries = []
 	journal_entries = []
-	tax_category_map = {}
-	or_filters = {}
-	journal_entry_party_map = {}
+	tax_category_map = frappe._dict()
+	invoice_net_total_map = frappe._dict()
+	or_filters = frappe._dict()
+	journal_entry_party_map = frappe._dict()
 	bank_accounts = frappe.get_all("Account", {"is_group": 0, "account_type": "Bank"}, pluck="name")
 
 	tds_accounts = frappe.get_all(
@@ -218,16 +232,22 @@
 		tds_documents.append(d.voucher_no)
 
 	if purchase_invoices:
-		get_tax_category_map(purchase_invoices, "Purchase Invoice", tax_category_map)
+		get_doc_info(purchase_invoices, "Purchase Invoice", tax_category_map, invoice_net_total_map)
 
 	if payment_entries:
-		get_tax_category_map(payment_entries, "Payment Entry", tax_category_map)
+		get_doc_info(payment_entries, "Payment Entry", tax_category_map)
 
 	if journal_entries:
 		journal_entry_party_map = get_journal_entry_party_map(journal_entries)
-		get_tax_category_map(journal_entries, "Journal Entry", tax_category_map)
+		get_doc_info(journal_entries, "Journal Entry", tax_category_map)
 
-	return tds_documents, tds_accounts, tax_category_map, journal_entry_party_map
+	return (
+		tds_documents,
+		tds_accounts,
+		tax_category_map,
+		journal_entry_party_map,
+		invoice_net_total_map,
+	)
 
 
 def get_journal_entry_party_map(journal_entries):
@@ -244,17 +264,18 @@
 	return journal_entry_party_map
 
 
-def get_tax_category_map(vouchers, doctype, tax_category_map):
-	tax_category_map.update(
-		frappe._dict(
-			frappe.get_all(
-				doctype,
-				filters={"name": ("in", vouchers)},
-				fields=["name", "tax_withholding_category"],
-				as_list=1,
-			)
-		)
-	)
+def get_doc_info(vouchers, doctype, tax_category_map, invoice_net_total_map=None):
+	if doctype == "Purchase Invoice":
+		fields = ["name", "tax_withholding_category", "base_tax_withholding_net_total"]
+	else:
+		fields = ["name", "tax_withholding_category"]
+
+	entries = frappe.get_all(doctype, filters={"name": ("in", vouchers)}, fields=fields)
+
+	for entry in entries:
+		tax_category_map.update({entry.name: entry.tax_withholding_category})
+		if doctype == "Purchase Invoice":
+			invoice_net_total_map.update({entry.name: entry.base_tax_withholding_net_total})
 
 
 def get_tax_rate_map(filters):
diff --git a/erpnext/assets/doctype/asset/test_asset.py b/erpnext/assets/doctype/asset/test_asset.py
index 136a033..2bec273 100644
--- a/erpnext/assets/doctype/asset/test_asset.py
+++ b/erpnext/assets/doctype/asset/test_asset.py
@@ -12,6 +12,7 @@
 	get_first_day,
 	get_last_day,
 	getdate,
+	is_last_day_of_the_month,
 	nowdate,
 )
 
@@ -264,7 +265,7 @@
 			asset.gross_purchase_amount - asset.finance_books[0].value_after_depreciation,
 			asset.precision("gross_purchase_amount"),
 		)
-		this_month_depr_amount = 9000.0 if get_last_day(date) == date else 0
+		this_month_depr_amount = 9000.0 if is_last_day_of_the_month(date) else 0
 
 		self.assertEquals(accumulated_depr_amount, 18000.0 + this_month_depr_amount)
 
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 d471783..c645b04 100644
--- a/erpnext/buying/doctype/purchase_order_item/purchase_order_item.json
+++ b/erpnext/buying/doctype/purchase_order_item/purchase_order_item.json
@@ -44,7 +44,6 @@
   "discount_amount",
   "base_rate_with_margin",
   "sec_break2",
-  "apply_tds",
   "rate",
   "amount",
   "item_tax_template",
@@ -54,6 +53,7 @@
   "pricing_rules",
   "stock_uom_rate",
   "is_free_item",
+  "apply_tds",
   "section_break_29",
   "net_rate",
   "net_amount",
@@ -902,7 +902,7 @@
  "index_web_pages_for_search": 1,
  "istable": 1,
  "links": [],
- "modified": "2022-10-26 16:47:41.364387",
+ "modified": "2022-11-29 16:47:41.364387",
  "modified_by": "Administrator",
  "module": "Buying",
  "name": "Purchase Order Item",
diff --git a/erpnext/buying/doctype/request_for_quotation/request_for_quotation.js b/erpnext/buying/doctype/request_for_quotation/request_for_quotation.js
index 31a4837..98c7dc9 100644
--- a/erpnext/buying/doctype/request_for_quotation/request_for_quotation.js
+++ b/erpnext/buying/doctype/request_for_quotation/request_for_quotation.js
@@ -22,6 +22,13 @@
 				}
 			};
 		}
+
+		frm.set_query('warehouse', 'items', () => ({
+			filters: {
+				company: frm.doc.company,
+				is_group: 0
+			}
+		}));
 	},
 
 	onload: function(frm) {
diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index 1849e8b..5a051e3 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -239,6 +239,14 @@
 					else:
 						item.set(field_map.get(self.doctype), default_deferred_account)
 
+	def validate_auto_repeat_subscription_dates(self):
+		if (
+			self.get("from_date")
+			and self.get("to_date")
+			and getdate(self.from_date) > getdate(self.to_date)
+		):
+			frappe.throw(_("To Date cannot be before From Date"), title=_("Invalid Auto Repeat Date"))
+
 	def validate_deferred_start_and_end_date(self):
 		for d in self.items:
 			if d.get("enable_deferred_revenue") or d.get("enable_deferred_expense"):
@@ -2303,7 +2311,7 @@
 	elif term.due_date_based_on == "Day(s) after the end of the invoice month":
 		due_date = add_days(get_last_day(date), term.credit_days)
 	elif term.due_date_based_on == "Month(s) after the end of the invoice month":
-		due_date = add_months(get_last_day(date), term.credit_months)
+		due_date = get_last_day(add_months(date, term.credit_months))
 	return due_date
 
 
@@ -2315,7 +2323,7 @@
 	elif term.discount_validity_based_on == "Day(s) after the end of the invoice month":
 		discount_validity = add_days(get_last_day(date), term.discount_validity)
 	elif term.discount_validity_based_on == "Month(s) after the end of the invoice month":
-		discount_validity = add_months(get_last_day(date), term.discount_validity)
+		discount_validity = get_last_day(add_months(date, term.discount_validity))
 	return discount_validity
 
 
diff --git a/erpnext/controllers/buying_controller.py b/erpnext/controllers/buying_controller.py
index 48fe7cb..0514604 100644
--- a/erpnext/controllers/buying_controller.py
+++ b/erpnext/controllers/buying_controller.py
@@ -41,6 +41,7 @@
 		self.validate_from_warehouse()
 		self.set_supplier_address()
 		self.validate_asset_return()
+		self.validate_auto_repeat_subscription_dates()
 
 		if self.doctype == "Purchase Invoice":
 			self.validate_purchase_receipt_if_update_stock()
diff --git a/erpnext/controllers/selling_controller.py b/erpnext/controllers/selling_controller.py
index 88d2f06..965335b 100644
--- a/erpnext/controllers/selling_controller.py
+++ b/erpnext/controllers/selling_controller.py
@@ -40,6 +40,7 @@
 		self.set_customer_address()
 		self.validate_for_duplicate_items()
 		self.validate_target_warehouse()
+		self.validate_auto_repeat_subscription_dates()
 
 	def set_missing_values(self, for_validate=False):
 
diff --git a/erpnext/crm/report/sales_pipeline_analytics/sales_pipeline_analytics.py b/erpnext/crm/report/sales_pipeline_analytics/sales_pipeline_analytics.py
index d23a22a..dea3f2d 100644
--- a/erpnext/crm/report/sales_pipeline_analytics/sales_pipeline_analytics.py
+++ b/erpnext/crm/report/sales_pipeline_analytics/sales_pipeline_analytics.py
@@ -217,7 +217,7 @@
 
 	def check_for_assigned_to(self, period, value, count_or_amount, assigned_to, info):
 		if self.filters.get("assigned_to"):
-			for data in json.loads(info.get("opportunity_owner")):
+			for data in json.loads(info.get("opportunity_owner") or "[]"):
 				if data == self.filters.get("assigned_to"):
 					self.set_formatted_data(period, data, count_or_amount, assigned_to)
 		else:
diff --git a/erpnext/manufacturing/doctype/work_order/test_work_order.py b/erpnext/manufacturing/doctype/work_order/test_work_order.py
index 694dc79..36466ff 100644
--- a/erpnext/manufacturing/doctype/work_order/test_work_order.py
+++ b/erpnext/manufacturing/doctype/work_order/test_work_order.py
@@ -635,6 +635,10 @@
 			bom.submit()
 			bom_name = bom.name
 
+		ste1 = test_stock_entry.make_stock_entry(
+			item_code=rm1, target="_Test Warehouse - _TC", qty=32, basic_rate=5000.0
+		)
+
 		work_order = make_wo_order_test_record(
 			item=fg_item, skip_transfer=True, planned_start_date=now(), qty=1
 		)
@@ -659,11 +663,29 @@
 		work_order.insert()
 		work_order.submit()
 		self.assertEqual(work_order.has_batch_no, 1)
-		ste1 = frappe.get_doc(make_stock_entry(work_order.name, "Manufacture", 30))
+		batches = frappe.get_all("Batch", filters={"reference_name": work_order.name})
+		self.assertEqual(len(batches), 3)
+		batches = [batch.name for batch in batches]
+
+		ste1 = frappe.get_doc(make_stock_entry(work_order.name, "Manufacture", 10))
 		for row in ste1.get("items"):
 			if row.is_finished_item:
 				self.assertEqual(row.item_code, fg_item)
 				self.assertEqual(row.qty, 10)
+				self.assertTrue(row.batch_no in batches)
+				batches.remove(row.batch_no)
+
+		ste1.submit()
+
+		remaining_batches = []
+		ste1 = frappe.get_doc(make_stock_entry(work_order.name, "Manufacture", 20))
+		for row in ste1.get("items"):
+			if row.is_finished_item:
+				self.assertEqual(row.item_code, fg_item)
+				self.assertEqual(row.qty, 10)
+				remaining_batches.append(row.batch_no)
+
+		self.assertEqual(sorted(remaining_batches), sorted(batches))
 
 		frappe.db.set_value("Manufacturing Settings", None, "make_serial_no_batch_from_work_order", 0)
 
diff --git a/erpnext/patches.txt b/erpnext/patches.txt
index 166faf9..0aad1d3 100644
--- a/erpnext/patches.txt
+++ b/erpnext/patches.txt
@@ -318,3 +318,4 @@
 erpnext.patches.v14_0.create_accounting_dimensions_for_asset_capitalization
 erpnext.patches.v14_0.update_partial_tds_fields
 erpnext.patches.v14_0.create_incoterms_and_migrate_shipment
+erpnext.patches.v14_0.setup_clear_repost_logs
\ No newline at end of file
diff --git a/erpnext/patches/v14_0/setup_clear_repost_logs.py b/erpnext/patches/v14_0/setup_clear_repost_logs.py
new file mode 100644
index 0000000..be9ddca
--- /dev/null
+++ b/erpnext/patches/v14_0/setup_clear_repost_logs.py
@@ -0,0 +1,8 @@
+# Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors
+# License: MIT. See LICENSE
+
+from erpnext.setup.install import setup_log_settings
+
+
+def execute():
+	setup_log_settings()
diff --git a/erpnext/public/js/controllers/taxes_and_totals.js b/erpnext/public/js/controllers/taxes_and_totals.js
index 4c3e9dc..7481000 100644
--- a/erpnext/public/js/controllers/taxes_and_totals.js
+++ b/erpnext/public/js/controllers/taxes_and_totals.js
@@ -47,29 +47,36 @@
 
 		await this.calculate_shipping_charges();
 
-		// Advance calculation applicable to Sales /Purchase Invoice
-		if(in_list(["Sales Invoice", "POS Invoice", "Purchase Invoice"], this.frm.doc.doctype)
-			&& this.frm.doc.docstatus < 2 && !this.frm.doc.is_return) {
+		// Advance calculation applicable to Sales/Purchase Invoice
+		if (
+			in_list(["Sales Invoice", "POS Invoice", "Purchase Invoice"], this.frm.doc.doctype)
+			&& this.frm.doc.docstatus < 2
+			&& !this.frm.doc.is_return
+		) {
 			this.calculate_total_advance(update_paid_amount);
 		}
 
-		if (in_list(["Sales Invoice", "POS Invoice"], this.frm.doc.doctype) && this.frm.doc.is_pos &&
-			this.frm.doc.is_return) {
-			if (this.frm.doc.doctype == "Sales Invoice") {
-				this.set_total_amount_to_default_mop();
-			}
+		if (
+			in_list(["Sales Invoice", "POS Invoice"], this.frm.doc.doctype)
+			&& this.frm.doc.s_pos
+			&& this.frm.doc.is_return
+		) {
+			this.set_total_amount_to_default_mop();
 			this.calculate_paid_amount();
 		}
 
 		// Sales person's commission
-		if(in_list(["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"], this.frm.doc.doctype)) {
+		if (in_list(["Quotation", "Sales Order", "Delivery Note", "Sales Invoice"], this.frm.doc.doctype)) {
 			this.calculate_commission();
 			this.calculate_contribution();
 		}
 
 		// Update paid amount on return/debit note creation
-		if(this.frm.doc.doctype === "Purchase Invoice" && this.frm.doc.is_return
-			&& (this.frm.doc.grand_total > this.frm.doc.paid_amount)) {
+		if (
+			this.frm.doc.doctype === "Purchase Invoice"
+			&& this.frm.doc.is_return
+			&& (this.frm.doc.grand_total > this.frm.doc.paid_amount)
+		) {
 			this.frm.doc.paid_amount = flt(this.frm.doc.grand_total, precision("grand_total"));
 		}
 
@@ -775,21 +782,30 @@
 		let grand_total = this.frm.doc.rounded_total || this.frm.doc.grand_total;
 		let base_grand_total = this.frm.doc.base_rounded_total || this.frm.doc.base_grand_total;
 
-		if(this.frm.doc.party_account_currency == this.frm.doc.currency) {
-			var total_amount_to_pay = flt((grand_total - this.frm.doc.total_advance
-				- this.frm.doc.write_off_amount), precision("grand_total"));
+		if (this.frm.doc.party_account_currency == this.frm.doc.currency) {
+			var total_amount_to_pay = flt(
+				grand_total - this.frm.doc.total_advance - this.frm.doc.write_off_amount,
+				precision("grand_total")
+			);
 		} else {
 			var total_amount_to_pay = flt(
-				(flt(base_grand_total, precision("base_grand_total"))
-					- this.frm.doc.total_advance - this.frm.doc.base_write_off_amount),
+				(
+					flt(
+						base_grand_total,
+						precision("base_grand_total")
+					)
+					- this.frm.doc.total_advance - this.frm.doc.base_write_off_amount
+				),
 				precision("base_grand_total")
 			);
 		}
+
 		this.frm.doc.payments.find(pay => {
 			if (pay.default) {
 				pay.amount = total_amount_to_pay;
 			}
 		});
+
 		this.frm.refresh_fields();
 	}
 
diff --git a/erpnext/setup/install.py b/erpnext/setup/install.py
index d3b47f9..1f7dddf 100644
--- a/erpnext/setup/install.py
+++ b/erpnext/setup/install.py
@@ -30,6 +30,7 @@
 	add_company_to_session_defaults()
 	add_standard_navbar_items()
 	add_app_name()
+	setup_log_settings()
 	frappe.db.commit()
 
 
@@ -197,3 +198,10 @@
 
 def add_app_name():
 	frappe.db.set_value("System Settings", None, "app_name", "ERPNext")
+
+
+def setup_log_settings():
+	log_settings = frappe.get_single("Log Settings")
+	log_settings.append("logs_to_clear", {"ref_doctype": "Repost Item Valuation", "days": 60})
+
+	log_settings.save(ignore_permissions=True)
diff --git a/erpnext/stock/doctype/material_request/material_request.py b/erpnext/stock/doctype/material_request/material_request.py
index 04aee42..afad751 100644
--- a/erpnext/stock/doctype/material_request/material_request.py
+++ b/erpnext/stock/doctype/material_request/material_request.py
@@ -596,7 +596,9 @@
 		if source.material_request_type == "Customer Provided":
 			target.purpose = "Material Receipt"
 
-		target.set_missing_values()
+		target.set_transfer_qty()
+		target.set_actual_qty()
+		target.calculate_rate_and_amount(raise_error_if_no_rate=False)
 		target.set_stock_entry_type()
 		target.set_job_card_data()
 
diff --git a/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.js b/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.js
index d595a80..8aec532 100644
--- a/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.js
+++ b/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.js
@@ -34,6 +34,22 @@
 		frm.trigger('setup_realtime_progress');
 	},
 
+	based_on: function(frm) {
+		var fields_to_reset = [];
+
+		if (frm.doc.based_on == 'Transaction') {
+			fields_to_reset = ['item_code', 'warehouse'];
+		} else if (frm.doc.based_on == 'Item and Warehouse') {
+			fields_to_reset = ['voucher_type', 'voucher_no'];
+		}
+
+		if (fields_to_reset) {
+			fields_to_reset.forEach(field => {
+				frm.set_value(field, undefined);
+			});
+		}
+	},
+
 	setup_realtime_progress: function(frm) {
 		frappe.realtime.on('item_reposting_progress', data => {
 			if (frm.doc.name !== data.name) {
diff --git a/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.json b/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.json
index e093933..8a5309c 100644
--- a/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.json
+++ b/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.json
@@ -50,13 +50,15 @@
    "fieldname": "posting_date",
    "fieldtype": "Date",
    "label": "Posting Date",
+   "read_only_depends_on": "eval: doc.based_on == \"Transaction\"",
    "reqd": 1
   },
   {
    "fetch_from": "voucher_no.posting_time",
    "fieldname": "posting_time",
    "fieldtype": "Time",
-   "label": "Posting Time"
+   "label": "Posting Time",
+   "read_only_depends_on": "eval: doc.based_on == \"Transaction\""
   },
   {
    "default": "Queued",
@@ -195,7 +197,7 @@
  "index_web_pages_for_search": 1,
  "is_submittable": 1,
  "links": [],
- "modified": "2022-06-13 12:20:22.182322",
+ "modified": "2022-11-28 16:00:05.637440",
  "modified_by": "Administrator",
  "module": "Stock",
  "name": "Repost Item Valuation",
diff --git a/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py b/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py
index d6f9bae..bbed099 100644
--- a/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py
+++ b/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py
@@ -5,7 +5,9 @@
 from frappe import _
 from frappe.exceptions import QueryDeadlockError, QueryTimeoutError
 from frappe.model.document import Document
-from frappe.utils import cint, get_link_to_form, get_weekday, now, nowtime
+from frappe.query_builder import DocType, Interval
+from frappe.query_builder.functions import Now
+from frappe.utils import cint, get_link_to_form, get_weekday, getdate, now, nowtime
 from frappe.utils.user import get_users_with_role
 from rq.timeouts import JobTimeoutException
 
@@ -21,10 +23,43 @@
 
 
 class RepostItemValuation(Document):
+	@staticmethod
+	def clear_old_logs(days=None):
+		days = days or 90
+		table = DocType("Repost Item Valuation")
+		frappe.db.delete(
+			table,
+			filters=(
+				(table.modified < (Now() - Interval(days=days)))
+				& (table.status.isin(["Completed", "Skipped"]))
+			),
+		)
+
 	def validate(self):
 		self.set_status(write=False)
 		self.reset_field_values()
 		self.set_company()
+		self.validate_accounts_freeze()
+
+	def validate_accounts_freeze(self):
+		acc_settings = frappe.db.get_value(
+			"Accounts Settings",
+			"Accounts Settings",
+			["acc_frozen_upto", "frozen_accounts_modifier"],
+			as_dict=1,
+		)
+		if not acc_settings.acc_frozen_upto:
+			return
+		if getdate(self.posting_date) <= getdate(acc_settings.acc_frozen_upto):
+			if (
+				acc_settings.frozen_accounts_modifier
+				and frappe.session.user in get_users_with_role(acc_settings.frozen_accounts_modifier)
+			):
+				frappe.msgprint(_("Caution: This might alter frozen accounts."))
+				return
+			frappe.throw(
+				_("You cannot repost item valuation before {}").format(acc_settings.acc_frozen_upto)
+			)
 
 	def reset_field_values(self):
 		if self.based_on == "Transaction":
@@ -240,7 +275,7 @@
 def notify_error_to_stock_managers(doc, traceback):
 	recipients = get_users_with_role("Stock Manager")
 	if not recipients:
-		get_users_with_role("System Manager")
+		recipients = get_users_with_role("System Manager")
 
 	subject = _("Error while reposting item valuation")
 	message = (
diff --git a/erpnext/stock/doctype/repost_item_valuation/test_repost_item_valuation.py b/erpnext/stock/doctype/repost_item_valuation/test_repost_item_valuation.py
index e0f2479..96ac435 100644
--- a/erpnext/stock/doctype/repost_item_valuation/test_repost_item_valuation.py
+++ b/erpnext/stock/doctype/repost_item_valuation/test_repost_item_valuation.py
@@ -6,8 +6,7 @@
 
 import frappe
 from frappe.tests.utils import FrappeTestCase
-from frappe.utils import nowdate
-from frappe.utils.data import add_to_date, today
+from frappe.utils import add_days, add_to_date, now, nowdate, today
 
 from erpnext.accounts.doctype.sales_invoice.test_sales_invoice import create_sales_invoice
 from erpnext.accounts.utils import repost_gle_for_stock_vouchers
@@ -86,6 +85,33 @@
 				msg=f"Exepcted false from : {case}",
 			)
 
+	def test_clear_old_logs(self):
+		# create 10 logs
+		for i in range(1, 20):
+			repost_doc = frappe.get_doc(
+				doctype="Repost Item Valuation",
+				item_code="_Test Item",
+				warehouse="_Test Warehouse - _TC",
+				based_on="Item and Warehouse",
+				posting_date=nowdate(),
+				status="Skipped",
+				posting_time="00:01:00",
+			).insert(ignore_permissions=True)
+
+			repost_doc.load_from_db()
+			repost_doc.modified = add_days(now(), days=-i * 10)
+			repost_doc.db_update_all()
+
+		logs = frappe.get_all("Repost Item Valuation", filters={"status": "Skipped"})
+		self.assertTrue(len(logs) > 10)
+
+		from erpnext.stock.doctype.repost_item_valuation.repost_item_valuation import RepostItemValuation
+
+		RepostItemValuation.clear_old_logs(days=1)
+
+		logs = frappe.get_all("Repost Item Valuation", filters={"status": "Skipped"})
+		self.assertTrue(len(logs) == 0)
+
 	def test_create_item_wise_repost_item_valuation_entries(self):
 		pr = make_purchase_receipt(
 			company="_Test Company with perpetual inventory",
@@ -327,3 +353,26 @@
 		# outstanding should not be affected
 		sinv.reload()
 		self.assertEqual(sinv.outstanding_amount, 100)
+
+	def test_account_freeze_validation(self):
+		today = nowdate()
+
+		riv = frappe.get_doc(
+			doctype="Repost Item Valuation",
+			item_code="_Test Item",
+			warehouse="_Test Warehouse - _TC",
+			based_on="Item and Warehouse",
+			posting_date=today,
+			posting_time="00:01:00",
+		)
+		riv.flags.dont_run_in_test = True  # keep it queued
+
+		accounts_settings = frappe.get_doc("Accounts Settings")
+		accounts_settings.acc_frozen_upto = today
+		accounts_settings.frozen_accounts_modifier = ""
+		accounts_settings.save()
+
+		self.assertRaises(frappe.ValidationError, riv.save)
+
+		accounts_settings.acc_frozen_upto = ""
+		accounts_settings.save()
diff --git a/erpnext/stock/doctype/stock_entry/stock_entry.js b/erpnext/stock/doctype/stock_entry/stock_entry.js
index 266ea5f..b910244 100644
--- a/erpnext/stock/doctype/stock_entry/stock_entry.js
+++ b/erpnext/stock/doctype/stock_entry/stock_entry.js
@@ -1079,7 +1079,8 @@
 	if (frm.doc.purpose === 'Material Receipt') return;
 
 	frappe.require("assets/erpnext/js/utils/serial_no_batch_selector.js", function() {
-		new erpnext.SerialNoBatchSelector({
+		if (frm.batch_selector?.dialog?.display) return;
+		frm.batch_selector = new erpnext.SerialNoBatchSelector({
 			frm: frm,
 			item: item,
 			warehouse_details: get_warehouse_type_and_name(item),
diff --git a/erpnext/stock/doctype/stock_entry/stock_entry.py b/erpnext/stock/doctype/stock_entry/stock_entry.py
index b116735..f6c53f7 100644
--- a/erpnext/stock/doctype/stock_entry/stock_entry.py
+++ b/erpnext/stock/doctype/stock_entry/stock_entry.py
@@ -659,6 +659,13 @@
 
 			if d.allow_zero_valuation_rate:
 				d.basic_rate = 0.0
+				frappe.msgprint(
+					_(
+						"Row {0}: Item rate has been updated to zero as Allow Zero Valuation Rate is checked for item {1}"
+					).format(d.idx, d.item_code),
+					alert=1,
+				)
+
 			elif d.is_finished_item:
 				if self.purpose == "Manufacture":
 					d.basic_rate = self.get_basic_rate_for_manufactured_item(
@@ -1538,6 +1545,7 @@
 			"reference_name": self.pro_doc.name,
 			"reference_doctype": self.pro_doc.doctype,
 			"qty_to_produce": (">", 0),
+			"batch_qty": ("=", 0),
 		}
 
 		fields = ["qty_to_produce as qty", "produced_qty", "name"]
@@ -2231,14 +2239,14 @@
 			d.qty -= process_loss_dict[d.item_code][1]
 
 	def set_serial_no_batch_for_finished_good(self):
-		args = {}
+		serial_nos = ""
 		if self.pro_doc.serial_no:
-			self.get_serial_nos_for_fg(args)
+			serial_nos = self.get_serial_nos_for_fg()
 
 		for row in self.items:
 			if row.is_finished_item and row.item_code == self.pro_doc.production_item:
-				if args.get("serial_no"):
-					row.serial_no = "\n".join(args["serial_no"][0 : cint(row.qty)])
+				if serial_nos:
+					row.serial_no = "\n".join(serial_nos[0 : cint(row.qty)])
 
 	def get_serial_nos_for_fg(self, args):
 		fields = [
@@ -2251,14 +2259,14 @@
 		filters = [
 			["Stock Entry", "work_order", "=", self.work_order],
 			["Stock Entry", "purpose", "=", "Manufacture"],
-			["Stock Entry", "docstatus", "=", 1],
+			["Stock Entry", "docstatus", "<", 2],
 			["Stock Entry Detail", "item_code", "=", self.pro_doc.production_item],
 		]
 
 		stock_entries = frappe.get_all("Stock Entry", fields=fields, filters=filters)
 
 		if self.pro_doc.serial_no:
-			args["serial_no"] = self.get_available_serial_nos(stock_entries)
+			return self.get_available_serial_nos(stock_entries)
 
 	def get_available_serial_nos(self, stock_entries):
 		used_serial_nos = []
diff --git a/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.py b/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.py
index d92d0f1..3a0b38a 100644
--- a/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.py
+++ b/erpnext/stock/doctype/stock_reconciliation/stock_reconciliation.py
@@ -230,7 +230,7 @@
 
 			if item.has_serial_no or item.has_batch_no:
 				has_serial_no = True
-				self.get_sle_for_serialized_items(row, sl_entries)
+				self.get_sle_for_serialized_items(row, sl_entries, item)
 			else:
 				if row.serial_no or row.batch_no:
 					frappe.throw(
@@ -282,7 +282,7 @@
 		if has_serial_no and sl_entries:
 			self.update_valuation_rate_for_serial_no()
 
-	def get_sle_for_serialized_items(self, row, sl_entries):
+	def get_sle_for_serialized_items(self, row, sl_entries, item):
 		from erpnext.stock.stock_ledger import get_previous_sle
 
 		serial_nos = get_serial_nos(row.serial_no)
@@ -348,6 +348,9 @@
 		if row.qty:
 			args = self.get_sle_for_items(row)
 
+			if item.has_serial_no and item.has_batch_no:
+				args["qty_after_transaction"] = row.qty
+
 			args.update(
 				{
 					"actual_qty": row.qty,
diff --git a/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py b/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
index 7b984d3..eaea301 100644
--- a/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
+++ b/erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py
@@ -644,6 +644,38 @@
 		)
 		self.assertEqual(len(active_sr_no), 0)
 
+	def test_serial_no_batch_no_item(self):
+		item = self.make_item(
+			"Test Serial No Batch No Item",
+			{
+				"is_stock_item": 1,
+				"has_serial_no": 1,
+				"has_batch_no": 1,
+				"serial_no_series": "SRS9.####",
+				"batch_number_series": "BNS9.####",
+				"create_new_batch": 1,
+			},
+		)
+
+		warehouse = "_Test Warehouse - _TC"
+
+		sr = create_stock_reconciliation(
+			item_code=item.name,
+			warehouse=warehouse,
+			qty=1,
+			rate=100,
+		)
+
+		sl_entry = frappe.db.get_value(
+			"Stock Ledger Entry",
+			{"voucher_type": "Stock Reconciliation", "voucher_no": sr.name},
+			["actual_qty", "qty_after_transaction"],
+			as_dict=1,
+		)
+
+		self.assertEqual(flt(sl_entry.actual_qty), 1.0)
+		self.assertEqual(flt(sl_entry.qty_after_transaction), 1.0)
+
 
 def create_batch_item_with_batch(item_name, batch_id):
 	batch_item_doc = create_item(item_name, is_stock_item=1)
diff --git a/erpnext/stock/doctype/warehouse/warehouse.py b/erpnext/stock/doctype/warehouse/warehouse.py
index 6e06d23..430a8d1 100644
--- a/erpnext/stock/doctype/warehouse/warehouse.py
+++ b/erpnext/stock/doctype/warehouse/warehouse.py
@@ -2,12 +2,10 @@
 # License: GNU General Public License v3. See license.txt
 
 
-from collections import defaultdict
-
 import frappe
 from frappe import _, throw
 from frappe.contacts.address_and_contact import load_address_and_contact
-from frappe.utils import cint, flt
+from frappe.utils import cint
 from frappe.utils.nestedset import NestedSet
 from pypika.terms import ExistsCriterion
 
@@ -166,60 +164,7 @@
 		["company", "in", (company, None, "")],
 	]
 
-	warehouses = frappe.get_list(doctype, fields=fields, filters=filters, order_by="name")
-
-	company_currency = ""
-	if company:
-		company_currency = frappe.get_cached_value("Company", company, "default_currency")
-
-	warehouse_wise_value = get_warehouse_wise_stock_value(company)
-
-	# return warehouses
-	for wh in warehouses:
-		wh["balance"] = warehouse_wise_value.get(wh.value)
-		if company_currency:
-			wh["company_currency"] = company_currency
-	return warehouses
-
-
-def get_warehouse_wise_stock_value(company):
-	warehouses = frappe.get_all(
-		"Warehouse", fields=["name", "parent_warehouse"], filters={"company": company}
-	)
-	parent_warehouse = {d.name: d.parent_warehouse for d in warehouses}
-
-	filters = {"warehouse": ("in", [data.name for data in warehouses])}
-	bin_data = frappe.get_all(
-		"Bin",
-		fields=["sum(stock_value) as stock_value", "warehouse"],
-		filters=filters,
-		group_by="warehouse",
-	)
-
-	warehouse_wise_stock_value = defaultdict(float)
-	for row in bin_data:
-		if not row.stock_value:
-			continue
-
-		warehouse_wise_stock_value[row.warehouse] = row.stock_value
-		update_value_in_parent_warehouse(
-			warehouse_wise_stock_value, parent_warehouse, row.warehouse, row.stock_value
-		)
-
-	return warehouse_wise_stock_value
-
-
-def update_value_in_parent_warehouse(
-	warehouse_wise_stock_value, parent_warehouse_dict, warehouse, stock_value
-):
-	parent_warehouse = parent_warehouse_dict.get(warehouse)
-	if not parent_warehouse:
-		return
-
-	warehouse_wise_stock_value[parent_warehouse] += flt(stock_value)
-	update_value_in_parent_warehouse(
-		warehouse_wise_stock_value, parent_warehouse_dict, parent_warehouse, stock_value
-	)
+	return frappe.get_list(doctype, fields=fields, filters=filters, order_by="name")
 
 
 @frappe.whitelist()
diff --git a/erpnext/stock/doctype/warehouse/warehouse_tree.js b/erpnext/stock/doctype/warehouse/warehouse_tree.js
index e9e14c7..eb635e6 100644
--- a/erpnext/stock/doctype/warehouse/warehouse_tree.js
+++ b/erpnext/stock/doctype/warehouse/warehouse_tree.js
@@ -17,11 +17,4 @@
 			description: __("Child nodes can be only created under 'Group' type nodes")}
 	],
 	ignore_fields:["parent_warehouse"],
-	onrender: function(node) {
-		if (node.data && node.data.balance!==undefined) {
-			$('<span class="balance-area pull-right">'
-			+ format_currency((node.data.balance), node.data.company_currency)
-			+ '</span>').insertBefore(node.$ul);
-		}
-	}
 }