Merge pull request #33222 from ruthra-kumar/data_import_errors_for_sales_invoice

fix: data import mandatory account_head, charge_type
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/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 b7a80c1..5a051e3 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -2311,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
 
 
@@ -2323,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/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/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.py b/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py
index 8e914e6..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,6 +5,8 @@
 from frappe import _
 from frappe.exceptions import QueryDeadlockError, QueryTimeoutError
 from frappe.model.document import Document
+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,6 +23,18 @@
 
 
 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()
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 f166775..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",
diff --git a/erpnext/stock/doctype/stock_entry/stock_entry.py b/erpnext/stock/doctype/stock_entry/stock_entry.py
index b116735..83c280f 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(
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);
-		}
-	}
 }