Merge pull request #27348 from deepeshgarg007/advance_tds_allocation_gl

fix (refactor): Tax Withholding for Advances using Payment Entry against suppliers
diff --git a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
index b5453ac..37bea70 100644
--- a/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
+++ b/erpnext/accounts/doctype/sales_invoice/test_sales_invoice.py
@@ -2397,6 +2397,32 @@
 
 		frappe.db.set_value('Accounts Settings', None, 'acc_frozen_upto', None)
 
+	def test_over_billing_case_against_delivery_note(self):
+		'''
+			Test a case where duplicating the item with qty = 1 in the invoice
+			allows overbilling even if it is disabled
+		'''
+		from erpnext.stock.doctype.delivery_note.test_delivery_note import create_delivery_note
+
+		over_billing_allowance = frappe.db.get_single_value('Accounts Settings', 'over_billing_allowance')
+		frappe.db.set_value('Accounts Settings', None, 'over_billing_allowance', 0)
+
+		dn = create_delivery_note()
+		dn.submit()
+
+		si = make_sales_invoice(dn.name)
+		# make a copy of first item and add it to invoice
+		item_copy = frappe.copy_doc(si.items[0])
+		si.append('items', item_copy)
+		si.save()
+
+		with self.assertRaises(frappe.ValidationError) as err:
+			si.submit()
+
+		self.assertTrue("cannot overbill" in str(err.exception).lower())
+
+		frappe.db.set_value('Accounts Settings', None, 'over_billing_allowance', over_billing_allowance)
+
 def get_sales_invoice_for_e_invoice():
 	si = make_sales_invoice_for_ewaybill()
 	si.naming_series = 'INV-2020-.#####'
diff --git a/erpnext/buying/doctype/supplier/supplier.py b/erpnext/buying/doctype/supplier/supplier.py
index 32659d6..14d2ccd 100644
--- a/erpnext/buying/doctype/supplier/supplier.py
+++ b/erpnext/buying/doctype/supplier/supplier.py
@@ -11,7 +11,11 @@
 )
 from frappe.model.naming import set_name_by_naming_series, set_name_from_naming_options
 
-from erpnext.accounts.party import get_dashboard_info, validate_party_accounts
+from erpnext.accounts.party import (  # noqa
+	get_dashboard_info,
+	get_timeline_data,
+	validate_party_accounts,
+)
 from erpnext.utilities.transaction_base import TransactionBase
 
 
diff --git a/erpnext/controllers/accounts_controller.py b/erpnext/controllers/accounts_controller.py
index 56e03e1..0ee884e 100644
--- a/erpnext/controllers/accounts_controller.py
+++ b/erpnext/controllers/accounts_controller.py
@@ -939,6 +939,7 @@
 
 	def validate_multiple_billing(self, ref_dt, item_ref_dn, based_on, parentfield):
 		from erpnext.controllers.status_updater import get_allowance_for
+
 		item_allowance = {}
 		global_qty_allowance, global_amount_allowance = None, None
 
@@ -959,12 +960,7 @@
 						.format(item.item_code, ref_dt), title=_("Warning"), indicator="orange")
 				continue
 
-			already_billed = frappe.db.sql("""
-				select sum(%s)
-				from `tab%s`
-				where %s=%s and docstatus=1 and parent != %s
-			""" % (based_on, self.doctype + " Item", item_ref_dn, '%s', '%s'),
-				(item.get(item_ref_dn), self.name))[0][0]
+			already_billed = self.get_billed_amount_for_item(item, item_ref_dn, based_on)
 
 			total_billed_amt = flt(flt(already_billed) + flt(item.get(based_on)),
 				self.precision(based_on, item))
@@ -992,6 +988,43 @@
 			frappe.msgprint(_("Overbilling of {} ignored because you have {} role.")
 					.format(total_overbilled_amt, role_allowed_to_over_bill), indicator="orange", alert=True)
 
+	def get_billed_amount_for_item(self, item, item_ref_dn, based_on):
+		'''
+			Returns Sum of Amount of
+			Sales/Purchase Invoice Items
+			that are linked to `item_ref_dn` (`dn_detail` / `pr_detail`)
+			that are submitted OR not submitted but are under current invoice
+		'''
+
+		from frappe.query_builder import Criterion
+		from frappe.query_builder.functions import Sum
+
+		item_doctype = frappe.qb.DocType(item.doctype)
+		based_on_field = frappe.qb.Field(based_on)
+		join_field = frappe.qb.Field(item_ref_dn)
+
+		result = (
+			frappe.qb.from_(item_doctype)
+			.select(Sum(based_on_field))
+			.where(
+				join_field == item.get(item_ref_dn)
+			).where(
+				Criterion.any([ # select all items from other invoices OR current invoices
+					Criterion.all([ # for selecting items from other invoices
+						item_doctype.docstatus == 1,
+						item_doctype.parent != self.name
+					]),
+					Criterion.all([ # for selecting items from current invoice, that are linked to same reference
+						item_doctype.docstatus == 0,
+						item_doctype.parent == self.name,
+						item_doctype.name != item.name
+					])
+				])
+			)
+		).run()
+
+		return result[0][0] if result else 0
+
 	def throw_overbill_exception(self, item, max_allowed_amt):
 		frappe.throw(_("Cannot overbill for Item {0} in row {1} more than {2}. To allow over-billing, please set allowance in Accounts Settings")
 			.format(item.item_code, item.idx, max_allowed_amt))
diff --git a/erpnext/controllers/stock_controller.py b/erpnext/controllers/stock_controller.py
index aba15b4..ae17094 100644
--- a/erpnext/controllers/stock_controller.py
+++ b/erpnext/controllers/stock_controller.py
@@ -17,7 +17,7 @@
 from erpnext.accounts.utils import get_fiscal_year
 from erpnext.controllers.accounts_controller import AccountsController
 from erpnext.stock import get_warehouse_account_map
-from erpnext.stock.stock_ledger import get_valuation_rate
+from erpnext.stock.stock_ledger import get_items_to_be_repost, get_valuation_rate
 
 
 class QualityInspectionRequiredError(frappe.ValidationError): pass
@@ -544,7 +544,12 @@
 			"company": self.company
 		})
 		if future_sle_exists(args):
-			create_repost_item_valuation_entry(args)
+			item_based_reposting =  cint(frappe.db.get_single_value("Stock Reposting Settings", "item_based_reposting"))
+			if item_based_reposting:
+				create_item_wise_repost_entries(voucher_type=self.doctype, voucher_no=self.name)
+			else:
+				create_repost_item_valuation_entry(args)
+
 
 @frappe.whitelist()
 def make_quality_inspections(doctype, docname, items):
@@ -679,3 +684,35 @@
 	repost_entry.flags.ignore_permissions = True
 	repost_entry.save()
 	repost_entry.submit()
+
+
+def create_item_wise_repost_entries(voucher_type, voucher_no, allow_zero_rate=False):
+	"""Using a voucher create repost item valuation records for all item-warehouse pairs."""
+
+	stock_ledger_entries = get_items_to_be_repost(voucher_type, voucher_no)
+
+	distinct_item_warehouses = set()
+	repost_entries = []
+
+	for sle in stock_ledger_entries:
+		item_wh = (sle.item_code, sle.warehouse)
+		if item_wh in distinct_item_warehouses:
+			continue
+		distinct_item_warehouses.add(item_wh)
+
+		repost_entry = frappe.new_doc("Repost Item Valuation")
+		repost_entry.based_on = "Item and Warehouse"
+		repost_entry.voucher_type = voucher_type
+		repost_entry.voucher_no = voucher_no
+
+		repost_entry.item_code = sle.item_code
+		repost_entry.warehouse = sle.warehouse
+		repost_entry.posting_date = sle.posting_date
+		repost_entry.posting_time = sle.posting_time
+		repost_entry.allow_zero_rate = allow_zero_rate
+		repost_entry.flags.ignore_links = True
+		repost_entry.flags.ignore_permissions = True
+		repost_entry.submit()
+		repost_entries.append(repost_entry)
+
+	return repost_entries
diff --git a/erpnext/education/api.py b/erpnext/education/api.py
index 53d1482..d9013b0 100644
--- a/erpnext/education/api.py
+++ b/erpnext/education/api.py
@@ -125,7 +125,7 @@
 
 	:param student: Student.
 	"""
-	guardians = frappe.get_list("Student Guardian", fields=["guardian"] ,
+	guardians = frappe.get_all("Student Guardian", fields=["guardian"] ,
 		filters={"parent": student})
 	return guardians
 
@@ -137,10 +137,10 @@
 	:param student_group: Student Group.
 	"""
 	if include_inactive:
-		students = frappe.get_list("Student Group Student", fields=["student", "student_name"] ,
+		students = frappe.get_all("Student Group Student", fields=["student", "student_name"] ,
 			filters={"parent": student_group}, order_by= "group_roll_number")
 	else:
-		students = frappe.get_list("Student Group Student", fields=["student", "student_name"] ,
+		students = frappe.get_all("Student Group Student", fields=["student", "student_name"] ,
 			filters={"parent": student_group, "active": 1}, order_by= "group_roll_number")
 	return students
 
@@ -164,7 +164,7 @@
 	:param fee_structure: Fee Structure.
 	"""
 	if fee_structure:
-		fs = frappe.get_list("Fee Component", fields=["fees_category", "description", "amount"] , filters={"parent": fee_structure}, order_by= "idx")
+		fs = frappe.get_all("Fee Component", fields=["fees_category", "description", "amount"] , filters={"parent": fee_structure}, order_by= "idx")
 		return fs
 
 
@@ -175,7 +175,7 @@
 	:param program: Program.
 	:param student_category: Student Category
 	"""
-	fs = frappe.get_list("Program Fee", fields=["academic_term", "fee_structure", "due_date", "amount"] ,
+	fs = frappe.get_all("Program Fee", fields=["academic_term", "fee_structure", "due_date", "amount"] ,
 		filters={"parent": program, "student_category": student_category }, order_by= "idx")
 	return fs
 
@@ -220,7 +220,7 @@
 
 	:param Course: Course
 	"""
-	return frappe.get_list("Course Assessment Criteria", \
+	return frappe.get_all("Course Assessment Criteria",
 		fields=["assessment_criteria", "weightage"], filters={"parent": course}, order_by= "idx")
 
 
@@ -253,7 +253,7 @@
 
 	:param Assessment Plan: Assessment Plan
 	"""
-	return frappe.get_list("Assessment Plan Criteria", \
+	return frappe.get_all("Assessment Plan Criteria",
 		fields=["assessment_criteria", "maximum_score", "docstatus"], filters={"parent": assessment_plan}, order_by= "idx")
 
 
diff --git a/erpnext/education/doctype/course_schedule/course_schedule.json b/erpnext/education/doctype/course_schedule/course_schedule.json
index 8c6746b..38d9b50 100644
--- a/erpnext/education/doctype/course_schedule/course_schedule.json
+++ b/erpnext/education/doctype/course_schedule/course_schedule.json
@@ -1,520 +1,143 @@
 {
- "allow_copy": 0,
- "allow_guest_to_view": 0,
+ "actions": [],
  "allow_import": 1,
- "allow_rename": 0,
  "autoname": "naming_series:",
- "beta": 0,
  "creation": "2015-09-09 16:34:04.960369",
- "custom": 0,
- "docstatus": 0,
  "doctype": "DocType",
  "document_type": "Document",
- "editable_grid": 0,
  "engine": "InnoDB",
+ "field_order": [
+  "student_group",
+  "instructor",
+  "instructor_name",
+  "column_break_2",
+  "naming_series",
+  "course",
+  "color",
+  "section_break_6",
+  "schedule_date",
+  "room",
+  "column_break_9",
+  "from_time",
+  "to_time",
+  "title"
+ ],
  "fields": [
   {
-   "allow_bulk_edit": 0,
-   "allow_in_quick_entry": 0,
-   "allow_on_submit": 0,
-   "bold": 0,
-   "collapsible": 0,
-   "columns": 0,
    "fieldname": "student_group",
    "fieldtype": "Link",
-   "hidden": 0,
-   "ignore_user_permissions": 0,
-   "ignore_xss_filter": 0,
-   "in_filter": 0,
    "in_global_search": 1,
-   "in_list_view": 0,
    "in_standard_filter": 1,
    "label": "Student Group",
-   "length": 0,
-   "no_copy": 0,
    "options": "Student Group",
-   "permlevel": 0,
-   "precision": "",
-   "print_hide": 0,
-   "print_hide_if_no_value": 0,
-   "read_only": 0,
-   "remember_last_selected_value": 0,
-   "report_hide": 0,
-   "reqd": 1,
-   "search_index": 0,
-   "set_only_once": 0,
-   "translatable": 0,
-   "unique": 0
+   "reqd": 1
   },
   {
-   "allow_bulk_edit": 0,
-   "allow_in_quick_entry": 0,
-   "allow_on_submit": 0,
-   "bold": 0,
-   "collapsible": 0,
-   "columns": 0,
    "fieldname": "instructor",
    "fieldtype": "Link",
-   "hidden": 0,
-   "ignore_user_permissions": 0,
-   "ignore_xss_filter": 0,
-   "in_filter": 0,
-   "in_global_search": 0,
-   "in_list_view": 0,
    "in_standard_filter": 1,
    "label": "Instructor",
-   "length": 0,
-   "no_copy": 0,
    "options": "Instructor",
-   "permlevel": 0,
-   "precision": "",
-   "print_hide": 0,
-   "print_hide_if_no_value": 0,
-   "read_only": 0,
-   "remember_last_selected_value": 0,
-   "report_hide": 0,
-   "reqd": 1,
-   "search_index": 0,
-   "set_only_once": 0,
-   "translatable": 0,
-   "unique": 0
+   "reqd": 1
   },
   {
-   "allow_bulk_edit": 0,
-   "allow_in_quick_entry": 0,
-   "allow_on_submit": 0,
-   "bold": 0,
-   "collapsible": 0,
-   "columns": 0,
-   "fetch_from": "instructor.Instructor_name",
+   "fetch_from": "instructor.instructor_name",
    "fieldname": "instructor_name",
    "fieldtype": "Read Only",
-   "hidden": 0,
-   "ignore_user_permissions": 0,
-   "ignore_xss_filter": 0,
-   "in_filter": 0,
    "in_global_search": 1,
-   "in_list_view": 0,
-   "in_standard_filter": 0,
    "label": "Instructor Name",
-   "length": 0,
-   "no_copy": 0,
-   "options": "",
-   "permlevel": 0,
-   "precision": "",
-   "print_hide": 0,
-   "print_hide_if_no_value": 0,
-   "read_only": 1,
-   "remember_last_selected_value": 0,
-   "report_hide": 0,
-   "reqd": 0,
-   "search_index": 0,
-   "set_only_once": 0,
-   "translatable": 0,
-   "unique": 0
+   "read_only": 1
   },
   {
-   "allow_bulk_edit": 0,
-   "allow_in_quick_entry": 0,
-   "allow_on_submit": 0,
-   "bold": 0,
-   "collapsible": 0,
-   "columns": 0,
    "fieldname": "column_break_2",
-   "fieldtype": "Column Break",
-   "hidden": 0,
-   "ignore_user_permissions": 0,
-   "ignore_xss_filter": 0,
-   "in_filter": 0,
-   "in_global_search": 0,
-   "in_list_view": 0,
-   "in_standard_filter": 0,
-   "length": 0,
-   "no_copy": 0,
-   "permlevel": 0,
-   "precision": "",
-   "print_hide": 0,
-   "print_hide_if_no_value": 0,
-   "read_only": 0,
-   "remember_last_selected_value": 0,
-   "report_hide": 0,
-   "reqd": 0,
-   "search_index": 0,
-   "set_only_once": 0,
-   "translatable": 0,
-   "unique": 0
+   "fieldtype": "Column Break"
   },
   {
-   "allow_bulk_edit": 0,
-   "allow_in_quick_entry": 0,
-   "allow_on_submit": 0,
-   "bold": 0,
-   "collapsible": 0,
-   "columns": 0,
-   "default": "",
    "fieldname": "naming_series",
    "fieldtype": "Select",
-   "hidden": 0,
-   "ignore_user_permissions": 0,
-   "ignore_xss_filter": 0,
-   "in_filter": 0,
-   "in_global_search": 0,
-   "in_list_view": 0,
-   "in_standard_filter": 0,
    "label": "Naming Series",
-   "length": 0,
-   "no_copy": 0,
    "options": "EDU-CSH-.YYYY.-",
-   "permlevel": 0,
-   "precision": "",
-   "print_hide": 0,
-   "print_hide_if_no_value": 0,
-   "read_only": 0,
-   "remember_last_selected_value": 0,
-   "report_hide": 0,
-   "reqd": 0,
-   "search_index": 0,
-   "set_only_once": 1,
-   "translatable": 0,
-   "unique": 0
+   "set_only_once": 1
   },
   {
-   "allow_bulk_edit": 0,
-   "allow_in_quick_entry": 0,
-   "allow_on_submit": 0,
-   "bold": 0,
-   "collapsible": 0,
-   "columns": 0,
    "fieldname": "course",
    "fieldtype": "Link",
-   "hidden": 0,
-   "ignore_user_permissions": 0,
-   "ignore_xss_filter": 0,
-   "in_filter": 0,
    "in_global_search": 1,
-   "in_list_view": 0,
-   "in_standard_filter": 0,
    "label": "Course",
-   "length": 0,
-   "no_copy": 0,
    "options": "Course",
-   "permlevel": 0,
-   "precision": "",
-   "print_hide": 0,
-   "print_hide_if_no_value": 0,
-   "read_only": 0,
-   "remember_last_selected_value": 0,
-   "report_hide": 0,
-   "reqd": 1,
-   "search_index": 0,
-   "set_only_once": 0,
-   "translatable": 0,
-   "unique": 0
+   "reqd": 1
   },
   {
-   "allow_bulk_edit": 0,
-   "allow_in_quick_entry": 0,
-   "allow_on_submit": 0,
-   "bold": 0,
-   "collapsible": 0,
-   "columns": 0,
    "fieldname": "color",
    "fieldtype": "Color",
-   "hidden": 0,
-   "ignore_user_permissions": 0,
-   "ignore_xss_filter": 0,
-   "in_filter": 0,
-   "in_global_search": 0,
-   "in_list_view": 0,
-   "in_standard_filter": 0,
    "label": "Color",
-   "length": 0,
-   "no_copy": 0,
-   "permlevel": 0,
-   "precision": "",
-   "print_hide": 1,
-   "print_hide_if_no_value": 0,
-   "read_only": 0,
-   "remember_last_selected_value": 0,
-   "report_hide": 0,
-   "reqd": 0,
-   "search_index": 0,
-   "set_only_once": 0,
-   "translatable": 0,
-   "unique": 0
+   "print_hide": 1
   },
   {
-   "allow_bulk_edit": 0,
-   "allow_in_quick_entry": 0,
-   "allow_on_submit": 0,
-   "bold": 0,
-   "collapsible": 0,
-   "columns": 0,
    "fieldname": "section_break_6",
-   "fieldtype": "Section Break",
-   "hidden": 0,
-   "ignore_user_permissions": 0,
-   "ignore_xss_filter": 0,
-   "in_filter": 0,
-   "in_global_search": 0,
-   "in_list_view": 0,
-   "in_standard_filter": 0,
-   "length": 0,
-   "no_copy": 0,
-   "permlevel": 0,
-   "precision": "",
-   "print_hide": 0,
-   "print_hide_if_no_value": 0,
-   "read_only": 0,
-   "remember_last_selected_value": 0,
-   "report_hide": 0,
-   "reqd": 0,
-   "search_index": 0,
-   "set_only_once": 0,
-   "translatable": 0,
-   "unique": 0
+   "fieldtype": "Section Break"
   },
   {
-   "allow_bulk_edit": 0,
-   "allow_in_quick_entry": 0,
-   "allow_on_submit": 0,
-   "bold": 0,
-   "collapsible": 0,
-   "columns": 0,
    "default": "Today",
    "fieldname": "schedule_date",
    "fieldtype": "Date",
-   "hidden": 0,
-   "ignore_user_permissions": 0,
-   "ignore_xss_filter": 0,
-   "in_filter": 0,
-   "in_global_search": 0,
-   "in_list_view": 0,
-   "in_standard_filter": 0,
-   "label": "Schedule Date",
-   "length": 0,
-   "no_copy": 0,
-   "permlevel": 0,
-   "precision": "",
-   "print_hide": 0,
-   "print_hide_if_no_value": 0,
-   "read_only": 0,
-   "remember_last_selected_value": 0,
-   "report_hide": 0,
-   "reqd": 0,
-   "search_index": 0,
-   "set_only_once": 0,
-   "translatable": 0,
-   "unique": 0
+   "label": "Schedule Date"
   },
   {
-   "allow_bulk_edit": 0,
-   "allow_in_quick_entry": 0,
-   "allow_on_submit": 0,
-   "bold": 0,
-   "collapsible": 0,
-   "columns": 0,
    "fieldname": "room",
    "fieldtype": "Link",
-   "hidden": 0,
-   "ignore_user_permissions": 0,
-   "ignore_xss_filter": 0,
-   "in_filter": 0,
-   "in_global_search": 0,
-   "in_list_view": 0,
-   "in_standard_filter": 0,
    "label": "Room",
-   "length": 0,
-   "no_copy": 0,
    "options": "Room",
-   "permlevel": 0,
-   "precision": "",
-   "print_hide": 0,
-   "print_hide_if_no_value": 0,
-   "read_only": 0,
-   "remember_last_selected_value": 0,
-   "report_hide": 0,
-   "reqd": 1,
-   "search_index": 0,
-   "set_only_once": 0,
-   "translatable": 0,
-   "unique": 0
+   "reqd": 1
   },
   {
-   "allow_bulk_edit": 0,
-   "allow_in_quick_entry": 0,
-   "allow_on_submit": 0,
-   "bold": 0,
-   "collapsible": 0,
-   "columns": 0,
    "fieldname": "column_break_9",
-   "fieldtype": "Column Break",
-   "hidden": 0,
-   "ignore_user_permissions": 0,
-   "ignore_xss_filter": 0,
-   "in_filter": 0,
-   "in_global_search": 0,
-   "in_list_view": 0,
-   "in_standard_filter": 0,
-   "length": 0,
-   "no_copy": 0,
-   "permlevel": 0,
-   "precision": "",
-   "print_hide": 0,
-   "print_hide_if_no_value": 0,
-   "read_only": 0,
-   "remember_last_selected_value": 0,
-   "report_hide": 0,
-   "reqd": 0,
-   "search_index": 0,
-   "set_only_once": 0,
-   "translatable": 0,
-   "unique": 0
+   "fieldtype": "Column Break"
   },
   {
-   "allow_bulk_edit": 0,
-   "allow_in_quick_entry": 0,
-   "allow_on_submit": 0,
-   "bold": 0,
-   "collapsible": 0,
-   "columns": 0,
    "fieldname": "from_time",
    "fieldtype": "Time",
-   "hidden": 0,
-   "ignore_user_permissions": 0,
-   "ignore_xss_filter": 0,
-   "in_filter": 0,
-   "in_global_search": 0,
    "in_list_view": 1,
-   "in_standard_filter": 0,
    "label": "From Time",
-   "length": 0,
-   "no_copy": 0,
-   "permlevel": 0,
-   "precision": "",
-   "print_hide": 0,
-   "print_hide_if_no_value": 0,
-   "read_only": 0,
-   "remember_last_selected_value": 0,
-   "report_hide": 0,
-   "reqd": 1,
-   "search_index": 0,
-   "set_only_once": 0,
-   "translatable": 0,
-   "unique": 0
+   "reqd": 1
   },
   {
-   "allow_bulk_edit": 0,
-   "allow_in_quick_entry": 0,
-   "allow_on_submit": 0,
-   "bold": 0,
-   "collapsible": 0,
-   "columns": 0,
    "fieldname": "to_time",
    "fieldtype": "Time",
-   "hidden": 0,
-   "ignore_user_permissions": 0,
-   "ignore_xss_filter": 0,
-   "in_filter": 0,
-   "in_global_search": 0,
    "in_list_view": 1,
-   "in_standard_filter": 0,
    "label": "To Time",
-   "length": 0,
-   "no_copy": 0,
-   "permlevel": 0,
-   "precision": "",
-   "print_hide": 0,
-   "print_hide_if_no_value": 0,
-   "read_only": 0,
-   "remember_last_selected_value": 0,
-   "report_hide": 0,
-   "reqd": 1,
-   "search_index": 0,
-   "set_only_once": 0,
-   "translatable": 0,
-   "unique": 0
+   "reqd": 1
   },
   {
-   "allow_bulk_edit": 0,
-   "allow_in_quick_entry": 0,
-   "allow_on_submit": 0,
-   "bold": 0,
-   "collapsible": 0,
-   "columns": 0,
    "fieldname": "title",
    "fieldtype": "Data",
    "hidden": 1,
-   "ignore_user_permissions": 0,
-   "ignore_xss_filter": 0,
-   "in_filter": 0,
-   "in_global_search": 0,
-   "in_list_view": 0,
-   "in_standard_filter": 0,
-   "label": "Title",
-   "length": 0,
-   "no_copy": 0,
-   "permlevel": 0,
-   "precision": "",
-   "print_hide": 0,
-   "print_hide_if_no_value": 0,
-   "read_only": 0,
-   "remember_last_selected_value": 0,
-   "report_hide": 0,
-   "reqd": 0,
-   "search_index": 0,
-   "set_only_once": 0,
-   "translatable": 0,
-   "unique": 0
+   "label": "Title"
   }
  ],
- "has_web_view": 0,
- "hide_heading": 0,
- "hide_toolbar": 0,
- "idx": 0,
- "image_view": 0,
- "in_create": 0,
- "is_submittable": 0,
- "issingle": 0,
- "istable": 0,
- "max_attachments": 0,
- "menu_index": 0,
- "modified": "2018-08-21 14:44:51.827225",
+ "links": [],
+ "modified": "2021-11-24 11:57:08.164449",
  "modified_by": "Administrator",
  "module": "Education",
  "name": "Course Schedule",
- "name_case": "",
+ "naming_rule": "By \"Naming Series\" field",
  "owner": "Administrator",
  "permissions": [
   {
-   "amend": 0,
-   "cancel": 0,
    "create": 1,
    "delete": 1,
    "email": 1,
    "export": 1,
-   "if_owner": 0,
-   "import": 0,
-   "permlevel": 0,
    "print": 1,
    "read": 1,
    "report": 1,
    "role": "Academics User",
-   "set_user_permissions": 0,
    "share": 1,
-   "submit": 0,
    "write": 1
   }
  ],
- "quick_entry": 0,
- "read_only": 0,
- "read_only_onload": 0,
  "restrict_to_domain": "Education",
- "show_name_in_global_search": 0,
  "sort_field": "schedule_date",
  "sort_order": "DESC",
- "title_field": "title",
- "track_changes": 0,
- "track_seen": 0,
- "track_views": 0
+ "title_field": "title"
 }
\ No newline at end of file
diff --git a/erpnext/education/doctype/student_attendance_tool/student_attendance_tool.py b/erpnext/education/doctype/student_attendance_tool/student_attendance_tool.py
index 4e3f98d..7deb6b1 100644
--- a/erpnext/education/doctype/student_attendance_tool/student_attendance_tool.py
+++ b/erpnext/education/doctype/student_attendance_tool/student_attendance_tool.py
@@ -14,24 +14,36 @@
 	student_list = []
 	student_attendance_list = []
 
-	if based_on=="Course Schedule":
+	if based_on == "Course Schedule":
 		student_group = frappe.db.get_value("Course Schedule", course_schedule, "student_group")
 		if student_group:
-			student_list = frappe.get_list("Student Group Student", fields=["student", "student_name", "group_roll_number"] , \
+			student_list = frappe.get_all("Student Group Student", fields=["student", "student_name", "group_roll_number"],
 			filters={"parent": student_group, "active": 1}, order_by= "group_roll_number")
 
 	if not student_list:
-		student_list = frappe.get_list("Student Group Student", fields=["student", "student_name", "group_roll_number"] ,
+		student_list = frappe.get_all("Student Group Student", fields=["student", "student_name", "group_roll_number"],
 			filters={"parent": student_group, "active": 1}, order_by= "group_roll_number")
 
+	table = frappe.qb.DocType("Student Attendance")
+
 	if course_schedule:
-		student_attendance_list= frappe.db.sql('''select student, status from `tabStudent Attendance` where \
-			course_schedule= %s''', (course_schedule), as_dict=1)
+		student_attendance_list = (
+			frappe.qb.from_(table)
+				.select(table.student, table.status)
+				.where(
+					(table.course_schedule == course_schedule)
+				)
+			).run(as_dict=True)
 	else:
-		student_attendance_list= frappe.db.sql('''select student, status from `tabStudent Attendance` where \
-			student_group= %s and date= %s and \
-			(course_schedule is Null or course_schedule='')''',
-			(student_group, date), as_dict=1)
+		student_attendance_list = (
+			frappe.qb.from_(table)
+				.select(table.student, table.status)
+				.where(
+					(table.student_group == student_group)
+					& (table.date == date)
+					& (table.course_schedule == "") | (table.course_schedule.isnull())
+				)
+			).run(as_dict=True)
 
 	for attendance in student_attendance_list:
 		for student in student_list:
diff --git a/erpnext/manufacturing/doctype/production_plan/production_plan.js b/erpnext/manufacturing/doctype/production_plan/production_plan.js
index b171086..0babf87 100644
--- a/erpnext/manufacturing/doctype/production_plan/production_plan.js
+++ b/erpnext/manufacturing/doctype/production_plan/production_plan.js
@@ -238,6 +238,12 @@
 			method: "get_items",
 			freeze: true,
 			doc: frm.doc,
+			callback: function() {
+				frm.refresh_field("po_items");
+				if (frm.doc.sub_assembly_items.length > 0) {
+					frm.trigger("get_sub_assembly_items");
+				}
+			}
 		});
 	},
 
diff --git a/erpnext/manufacturing/doctype/work_order/work_order.js b/erpnext/manufacturing/doctype/work_order/work_order.js
index bfce1b8..5ffbb03 100644
--- a/erpnext/manufacturing/doctype/work_order/work_order.js
+++ b/erpnext/manufacturing/doctype/work_order/work_order.js
@@ -442,7 +442,7 @@
 	additional_operating_cost: function(frm) {
 		erpnext.work_order.calculate_cost(frm.doc);
 		erpnext.work_order.calculate_total_cost(frm);
-	}
+	},
 });
 
 frappe.ui.form.on("Work Order Item", {
diff --git a/erpnext/manufacturing/doctype/work_order/work_order.json b/erpnext/manufacturing/doctype/work_order/work_order.json
index df7ee53..12cd58f 100644
--- a/erpnext/manufacturing/doctype/work_order/work_order.json
+++ b/erpnext/manufacturing/doctype/work_order/work_order.json
@@ -326,6 +326,7 @@
    "label": "Expected Delivery Date"
   },
   {
+   "collapsible": 1,
    "fieldname": "operations_section",
    "fieldtype": "Section Break",
    "label": "Operations",
@@ -337,7 +338,7 @@
    "fieldname": "transfer_material_against",
    "fieldtype": "Select",
    "label": "Transfer Material Against",
-   "options": "\nWork Order\nJob Card"
+   "options": "Work Order\nJob Card"
   },
   {
    "fieldname": "operations",
@@ -573,8 +574,7 @@
  "image_field": "image",
  "is_submittable": 1,
  "links": [],
- "migration_hash": "a18118963f4fcdb7f9d326de5f4063ba",
- "modified": "2021-10-29 15:12:32.203605",
+ "modified": "2021-11-08 17:36:07.016300",
  "modified_by": "Administrator",
  "module": "Manufacturing",
  "name": "Work Order",
diff --git a/erpnext/manufacturing/doctype/work_order_operation/work_order_operation.json b/erpnext/manufacturing/doctype/work_order_operation/work_order_operation.json
index f7b8787..647c14b 100644
--- a/erpnext/manufacturing/doctype/work_order_operation/work_order_operation.json
+++ b/erpnext/manufacturing/doctype/work_order_operation/work_order_operation.json
@@ -6,27 +6,27 @@
  "field_order": [
   "details",
   "operation",
-  "bom",
-  "column_break_4",
-  "description",
-  "sequence_id",
-  "col_break1",
-  "completed_qty",
   "status",
+  "completed_qty",
+  "column_break_4",
+  "bom",
   "workstation",
+  "sequence_id",
+  "section_break_10",
+  "description",
   "estimated_time_and_cost",
   "planned_start_time",
-  "planned_end_time",
-  "column_break_10",
-  "time_in_mins",
   "hour_rate",
+  "time_in_mins",
+  "column_break_10",
+  "planned_end_time",
   "batch_size",
   "planned_operating_cost",
   "section_break_9",
   "actual_start_time",
-  "actual_end_time",
-  "column_break_11",
   "actual_operation_time",
+  "column_break_11",
+  "actual_end_time",
   "actual_operating_cost"
  ],
  "fields": [
@@ -42,7 +42,6 @@
    "oldfieldname": "operation_no",
    "oldfieldtype": "Data",
    "options": "Operation",
-   "read_only": 1,
    "reqd": 1
   },
   {
@@ -52,20 +51,14 @@
    "label": "BOM",
    "no_copy": 1,
    "options": "BOM",
-   "print_hide": 1,
-   "read_only": 1
+   "print_hide": 1
   },
   {
    "fieldname": "description",
    "fieldtype": "Text Editor",
    "label": "Operation Description",
    "oldfieldname": "opn_description",
-   "oldfieldtype": "Text",
-   "read_only": 1
-  },
-  {
-   "fieldname": "col_break1",
-   "fieldtype": "Column Break"
+   "oldfieldtype": "Text"
   },
   {
    "columns": 1,
@@ -74,19 +67,16 @@
    "fieldtype": "Float",
    "in_list_view": 1,
    "label": "Completed Qty",
-   "no_copy": 1,
-   "read_only": 1
+   "no_copy": 1
   },
   {
    "columns": 1,
    "default": "Pending",
    "fieldname": "status",
    "fieldtype": "Select",
-   "in_list_view": 1,
    "label": "Status",
    "no_copy": 1,
-   "options": "Pending\nWork in Progress\nCompleted",
-   "read_only": 1
+   "options": "Pending\nWork in Progress\nCompleted"
   },
   {
    "fieldname": "workstation",
@@ -106,15 +96,13 @@
    "fieldname": "planned_start_time",
    "fieldtype": "Datetime",
    "label": "Planned Start Time",
-   "no_copy": 1,
-   "read_only": 1
+   "no_copy": 1
   },
   {
    "fieldname": "planned_end_time",
    "fieldtype": "Datetime",
    "label": "Planned End Time",
-   "no_copy": 1,
-   "read_only": 1
+   "no_copy": 1
   },
   {
    "fieldname": "column_break_10",
@@ -122,7 +110,7 @@
   },
   {
    "columns": 1,
-   "description": "in Minutes",
+   "description": "In Minutes",
    "fieldname": "time_in_mins",
    "fieldtype": "Float",
    "in_list_view": 1,
@@ -152,6 +140,7 @@
    "label": "Actual Time and Cost"
   },
   {
+   "description": "Updated via 'Time Log' (In Minutes)",
    "fieldname": "actual_start_time",
    "fieldtype": "Datetime",
    "label": "Actual Start Time",
@@ -159,7 +148,7 @@
    "read_only": 1
   },
   {
-   "description": "Updated via 'Time Log'",
+   "description": "Updated via 'Time Log' (In Minutes)",
    "fieldname": "actual_end_time",
    "fieldtype": "Datetime",
    "label": "Actual End Time",
@@ -171,7 +160,7 @@
    "fieldtype": "Column Break"
   },
   {
-   "description": "in Minutes\nUpdated via 'Time Log'",
+   "description": "Updated via 'Time Log' (In Minutes)",
    "fieldname": "actual_operation_time",
    "fieldtype": "Float",
    "label": "Actual Operation Time",
@@ -190,25 +179,28 @@
   {
    "fieldname": "batch_size",
    "fieldtype": "Int",
-   "label": "Batch Size",
-   "read_only": 1
+   "label": "Batch Size"
   },
   {
    "fieldname": "sequence_id",
    "fieldtype": "Int",
+   "hidden": 1,
    "label": "Sequence ID",
-   "print_hide": 1,
-   "read_only": 1
+   "print_hide": 1
   },
   {
    "fieldname": "column_break_4",
    "fieldtype": "Column Break"
+  },
+  {
+   "fieldname": "section_break_10",
+   "fieldtype": "Section Break"
   }
  ],
  "index_web_pages_for_search": 1,
  "istable": 1,
  "links": [],
- "modified": "2021-06-24 14:36:12.835543",
+ "modified": "2021-11-24 04:52:54.295168",
  "modified_by": "Administrator",
  "module": "Manufacturing",
  "name": "Work Order Operation",
@@ -217,4 +209,4 @@
  "sort_field": "modified",
  "sort_order": "DESC",
  "track_changes": 1
-}
+}
\ No newline at end of file
diff --git a/erpnext/manufacturing/report/cost_of_poor_quality_report/cost_of_poor_quality_report.py b/erpnext/manufacturing/report/cost_of_poor_quality_report/cost_of_poor_quality_report.py
index b9ddc9f..7741823 100644
--- a/erpnext/manufacturing/report/cost_of_poor_quality_report/cost_of_poor_quality_report.py
+++ b/erpnext/manufacturing/report/cost_of_poor_quality_report/cost_of_poor_quality_report.py
@@ -1,7 +1,6 @@
-# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
+# Copyright (c) 2021, Frappe Technologies Pvt. Ltd. and contributors
 # For license information, please see license.txt
 
-
 import frappe
 from frappe import _
 from frappe.utils import flt
@@ -30,7 +29,6 @@
 
 		for row in job_cards:
 			row.operating_cost = flt(row.hour_rate) * (flt(row.total_time_in_mins) / 60.0)
-			update_raw_material_cost(row, report_filters)
 			data.append(row)
 
 	return data
@@ -46,12 +44,6 @@
 
 	return filters
 
-def update_raw_material_cost(row, filters):
-	row.rm_cost = 0.0
-	for data in frappe.get_all("Job Card Item", fields = ["amount"],
-		filters={"parent": row.name, "docstatus": 1}):
-		row.rm_cost += data.amount
-
 def get_columns(filters):
 	return [
 		{
@@ -59,7 +51,7 @@
 			"fieldtype": "Link",
 			"fieldname": "name",
 			"options": "Job Card",
-			"width": "100"
+			"width": "120"
 		},
 		{
 			"label": _("Work Order"),
@@ -111,18 +103,12 @@
 			"label": _("Operating Cost"),
 			"fieldtype": "Currency",
 			"fieldname": "operating_cost",
-			"width": "100"
-		},
-		{
-			"label": _("Raw Material Cost"),
-			"fieldtype": "Currency",
-			"fieldname": "rm_cost",
-			"width": "100"
+			"width": "150"
 		},
 		{
 			"label": _("Total Time (in Mins)"),
 			"fieldtype": "Float",
 			"fieldname": "total_time_in_mins",
-			"width": "100"
+			"width": "150"
 		}
 	]
diff --git a/erpnext/patches/v12_0/move_target_distribution_from_parent_to_child.py b/erpnext/patches/v12_0/move_target_distribution_from_parent_to_child.py
index 1e230a7..36fe18d 100644
--- a/erpnext/patches/v12_0/move_target_distribution_from_parent_to_child.py
+++ b/erpnext/patches/v12_0/move_target_distribution_from_parent_to_child.py
@@ -7,6 +7,7 @@
 
 def execute():
     frappe.reload_doc("setup", "doctype", "target_detail")
+    frappe.reload_doc("core", "doctype", "prepared_report")
 
     for d in ['Sales Person', 'Sales Partner', 'Territory']:
         frappe.db.sql("""
diff --git a/erpnext/payroll/doctype/gratuity/gratuity.py b/erpnext/payroll/doctype/gratuity/gratuity.py
index f563c08..476990a 100644
--- a/erpnext/payroll/doctype/gratuity/gratuity.py
+++ b/erpnext/payroll/doctype/gratuity/gratuity.py
@@ -193,7 +193,7 @@
 	sal_slip  = get_last_salary_slip(employee)
 	if not sal_slip:
 		frappe.throw(_("No Salary Slip is found for Employee: {0}").format(bold(employee)))
-	component_and_amounts = frappe.get_list("Salary Detail",
+	component_and_amounts = frappe.get_all("Salary Detail",
 		filters={
 			"docstatus": 1,
 			'parent': sal_slip,
diff --git a/erpnext/payroll/doctype/gratuity/test_gratuity.py b/erpnext/payroll/doctype/gratuity/test_gratuity.py
index 78355ca..93cba06 100644
--- a/erpnext/payroll/doctype/gratuity/test_gratuity.py
+++ b/erpnext/payroll/doctype/gratuity/test_gratuity.py
@@ -48,7 +48,7 @@
 		self.assertEqual(floor(experience), gratuity.current_work_experience)
 
 		#amount Calculation
-		component_amount = frappe.get_list("Salary Detail",
+		component_amount = frappe.get_all("Salary Detail",
 		filters={
 			"docstatus": 1,
 			'parent': sal_slip,
@@ -84,7 +84,7 @@
 		self.assertEqual(floor(experience), gratuity.current_work_experience)
 
 		#amount Calculation
-		component_amount = frappe.get_list("Salary Detail",
+		component_amount = frappe.get_all("Salary Detail",
 		filters={
 			"docstatus": 1,
 			'parent': sal_slip,
diff --git a/erpnext/selling/doctype/customer/customer.py b/erpnext/selling/doctype/customer/customer.py
index 2e2b8b7..0c8c53a 100644
--- a/erpnext/selling/doctype/customer/customer.py
+++ b/erpnext/selling/doctype/customer/customer.py
@@ -18,7 +18,11 @@
 from frappe.utils import cint, cstr, flt, get_formatted_email, today
 from frappe.utils.user import get_users_with_role
 
-from erpnext.accounts.party import get_dashboard_info, validate_party_accounts
+from erpnext.accounts.party import (  # noqa
+	get_dashboard_info,
+	get_timeline_data,
+	validate_party_accounts,
+)
 from erpnext.utilities.transaction_base import TransactionBase
 
 
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 3ff0f60..cd7e63b 100644
--- a/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.json
+++ b/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.json
@@ -64,7 +64,7 @@
    "in_standard_filter": 1,
    "label": "Status",
    "no_copy": 1,
-   "options": "Queued\nIn Progress\nCompleted\nFailed",
+   "options": "Queued\nIn Progress\nCompleted\nSkipped\nFailed",
    "read_only": 1
   },
   {
@@ -177,7 +177,7 @@
  "index_web_pages_for_search": 1,
  "is_submittable": 1,
  "links": [],
- "modified": "2021-11-18 02:18:10.524560",
+ "modified": "2021-11-24 02:18:10.524560",
  "modified_by": "Administrator",
  "module": "Stock",
  "name": "Repost Item Valuation",
@@ -228,4 +228,4 @@
  ],
  "sort_field": "modified",
  "sort_order": "DESC"
-}
\ No newline at end of file
+}
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 59d191f..965a32d 100644
--- a/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py
+++ b/erpnext/stock/doctype/repost_item_valuation/repost_item_valuation.py
@@ -1,7 +1,6 @@
 # Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and contributors
 # For license information, please see license.txt
 
-
 import frappe
 from frappe import _
 from frappe.model.document import Document
@@ -19,7 +18,7 @@
 
 class RepostItemValuation(Document):
 	def validate(self):
-		self.set_status()
+		self.set_status(write=False)
 		self.reset_field_values()
 		self.set_company()
 
@@ -27,26 +26,27 @@
 		if self.based_on == 'Transaction':
 			self.item_code = None
 			self.warehouse = None
-		else:
-			self.voucher_type = None
-			self.voucher_no = None
 
 		self.allow_negative_stock = self.allow_negative_stock or \
 				cint(frappe.db.get_single_value("Stock Settings", "allow_negative_stock"))
 
 	def set_company(self):
-		if self.voucher_type and self.voucher_no:
+		if self.based_on == "Transaction":
 			self.company = frappe.get_cached_value(self.voucher_type, self.voucher_no, "company")
 		elif self.warehouse:
 			self.company = frappe.get_cached_value("Warehouse", self.warehouse, "company")
 
-	def set_status(self, status=None):
+	def set_status(self, status=None, write=True):
+		status = status or self.status
 		if not status:
-			status = 'Queued'
-		self.db_set('status', status)
+			self.status = 'Queued'
+		else:
+			self.status = status
+		if write:
+			self.db_set('status', self.status)
 
 	def on_submit(self):
-		if not frappe.flags.in_test:
+		if not frappe.flags.in_test or self.flags.dont_run_in_test:
 			return
 
 		frappe.enqueue(repost, timeout=1800, queue='long',
@@ -58,6 +58,37 @@
 		frappe.enqueue(repost, timeout=1800, queue='long',
 			job_name='repost_sle', now=True, doc=self)
 
+	def deduplicate_similar_repost(self):
+		""" Deduplicate similar reposts based on item-warehouse-posting combination."""
+		if self.based_on != "Item and Warehouse":
+			return
+
+		filters = {
+			"item_code": self.item_code,
+			"warehouse": self.warehouse,
+			"name": self.name,
+			"posting_date": self.posting_date,
+			"posting_time": self.posting_time,
+		}
+
+		frappe.db.sql("""
+			update `tabRepost Item Valuation`
+			set status = 'Skipped'
+			WHERE item_code = %(item_code)s
+				and warehouse = %(warehouse)s
+				and name != %(name)s
+				and TIMESTAMP(posting_date, posting_time) > TIMESTAMP(%(posting_date)s, %(posting_time)s)
+				and docstatus = 1
+				and status = 'Queued'
+				and based_on = 'Item and Warehouse'
+				""",
+			filters
+		)
+
+def on_doctype_update():
+	frappe.db.add_index("Repost Item Valuation", ["warehouse", "item_code"], "item_warehouse")
+
+
 def repost(doc):
 	try:
 		if not frappe.db.exists("Repost Item Valuation", doc.name):
@@ -134,7 +165,9 @@
 
 	for row in riv_entries:
 		doc = frappe.get_doc('Repost Item Valuation', row.name)
-		repost(doc)
+		if doc.status in ('Queued', 'In Progress'):
+			doc.deduplicate_similar_repost()
+			repost(doc)
 
 	riv_entries = get_repost_item_valuation_entries()
 	if riv_entries:
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 c086f93..de79316 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
@@ -5,6 +5,8 @@
 
 import frappe
 
+from erpnext.controllers.stock_controller import create_item_wise_repost_entries
+from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import make_purchase_receipt
 from erpnext.stock.doctype.repost_item_valuation.repost_item_valuation import (
 	in_configured_timeslot,
 )
@@ -70,3 +72,69 @@
 				in_configured_timeslot(repost_settings, case.get("current_time")),
 				msg=f"Exepcted false from : {case}",
 			)
+
+	def test_create_item_wise_repost_item_valuation_entries(self):
+		pr = make_purchase_receipt(
+			company="_Test Company with perpetual inventory",
+			warehouse="Stores - TCP1",
+			get_multiple_items=True,
+		)
+
+		rivs = create_item_wise_repost_entries(pr.doctype, pr.name)
+		self.assertGreaterEqual(len(rivs), 2)
+		self.assertIn("_Test Item", [d.item_code for d in rivs])
+
+		for riv in rivs:
+			self.assertEqual(riv.company, "_Test Company with perpetual inventory")
+			self.assertEqual(riv.warehouse, "Stores - TCP1")
+
+	def test_deduplication(self):
+		def _assert_status(doc, status):
+			doc.load_from_db()
+			self.assertEqual(doc.status, status)
+
+		riv_args = frappe._dict(
+			doctype="Repost Item Valuation",
+			item_code="_Test Item",
+			warehouse="_Test Warehouse - _TC",
+			based_on="Item and Warehouse",
+			voucher_type="Sales Invoice",
+			voucher_no="SI-1",
+			posting_date="2021-01-02",
+			posting_time="00:01:00",
+		)
+
+		# new repost without any duplicates
+		riv1 = frappe.get_doc(riv_args)
+		riv1.flags.dont_run_in_test = True
+		riv1.submit()
+		_assert_status(riv1, "Queued")
+		self.assertEqual(riv1.voucher_type, "Sales Invoice")  # traceability
+		self.assertEqual(riv1.voucher_no, "SI-1")
+
+		# newer than existing duplicate - riv1
+		riv2 = frappe.get_doc(riv_args.update({"posting_date": "2021-01-03"}))
+		riv2.flags.dont_run_in_test = True
+		riv2.submit()
+		riv1.deduplicate_similar_repost()
+		_assert_status(riv2, "Skipped")
+
+		# older than exisitng duplicate - riv1
+		riv3 = frappe.get_doc(riv_args.update({"posting_date": "2021-01-01"}))
+		riv3.flags.dont_run_in_test = True
+		riv3.submit()
+		riv3.deduplicate_similar_repost()
+		_assert_status(riv3, "Queued")
+		_assert_status(riv1, "Skipped")
+
+		# unrelated reposts, shouldn't do anything to others.
+		riv4 = frappe.get_doc(riv_args.update({"warehouse": "Stores - _TC"}))
+		riv4.flags.dont_run_in_test = True
+		riv4.submit()
+		riv4.deduplicate_similar_repost()
+		_assert_status(riv4, "Queued")
+		_assert_status(riv3, "Queued")
+
+		# to avoid breaking other tests accidentaly
+		riv4.set_status("Skipped")
+		riv3.set_status("Skipped")
diff --git a/erpnext/stock/doctype/stock_reposting_settings/stock_reposting_settings.json b/erpnext/stock/doctype/stock_reposting_settings/stock_reposting_settings.json
index 2474059..0facae8 100644
--- a/erpnext/stock/doctype/stock_reposting_settings/stock_reposting_settings.json
+++ b/erpnext/stock/doctype/stock_reposting_settings/stock_reposting_settings.json
@@ -1,6 +1,7 @@
 {
  "actions": [],
  "allow_rename": 1,
+ "beta": 1,
  "creation": "2021-10-01 10:56:30.814787",
  "doctype": "DocType",
  "editable_grid": 1,
@@ -10,7 +11,8 @@
   "limit_reposting_timeslot",
   "start_time",
   "end_time",
-  "limits_dont_apply_on"
+  "limits_dont_apply_on",
+  "item_based_reposting"
  ],
  "fields": [
   {
@@ -44,12 +46,18 @@
    "fieldname": "limit_reposting_timeslot",
    "fieldtype": "Check",
    "label": "Limit timeslot for Stock Reposting"
+  },
+  {
+   "default": "0",
+   "fieldname": "item_based_reposting",
+   "fieldtype": "Check",
+   "label": "Use Item based reposting"
   }
  ],
  "index_web_pages_for_search": 1,
  "issingle": 1,
  "links": [],
- "modified": "2021-10-01 11:27:28.981594",
+ "modified": "2021-11-02 01:22:45.155841",
  "modified_by": "Administrator",
  "module": "Stock",
  "name": "Stock Reposting Settings",
diff --git a/erpnext/stock/report/total_stock_summary/total_stock_summary.js b/erpnext/stock/report/total_stock_summary/total_stock_summary.js
index 90648f1..88054aa 100644
--- a/erpnext/stock/report/total_stock_summary/total_stock_summary.js
+++ b/erpnext/stock/report/total_stock_summary/total_stock_summary.js
@@ -10,23 +10,8 @@
 			"fieldtype": "Select",
 			"width": "80",
 			"reqd": 1,
-			"options": ["", "Warehouse", "Company"],
-			"change": function() {
-				let group_by = frappe.query_report.get_filter_value("group_by")
-				let company_filter = frappe.query_report.get_filter("company")
-				if (group_by == "Company") {
-					company_filter.df.reqd = 0;
-					company_filter.df.hidden = 1;
-					frappe.query_report.set_filter_value("company", "");
-					company_filter.refresh();
-				}
-				else {
-					company_filter.df.reqd = 1;
-					company_filter.df.hidden = 0;
-					company_filter.refresh();
-					frappe.query_report.refresh();
-				}
-			}
+			"options": ["Warehouse", "Company"],
+			"default": "Warehouse",
 		},
 		{
 			"fieldname": "company",
@@ -34,8 +19,9 @@
 			"fieldtype": "Link",
 			"width": "80",
 			"options": "Company",
+			"reqd": 1,
 			"default": frappe.defaults.get_user_default("Company"),
-			"reqd": 1
+			"depends_on": "eval: doc.group_by != 'Company'",
 		},
 	]
 }
diff --git a/erpnext/stock/report/total_stock_summary/total_stock_summary.py b/erpnext/stock/report/total_stock_summary/total_stock_summary.py
index 7e47b50..6f27558 100644
--- a/erpnext/stock/report/total_stock_summary/total_stock_summary.py
+++ b/erpnext/stock/report/total_stock_summary/total_stock_summary.py
@@ -7,8 +7,9 @@
 
 
 def execute(filters=None):
-	if not filters: filters = {}
-	validate_filters(filters)
+
+	if not filters:
+		filters = {}
 	columns = get_columns()
 	stock = get_total_stock(filters)
 
@@ -53,9 +54,3 @@
 				ON warehouse.name = ledger.warehouse
 			WHERE
 				ledger.actual_qty != 0 %s""" % (columns, conditions))
-
-def validate_filters(filters):
-	if filters.get("group_by") == 'Company' and \
-		filters.get("company"):
-
-		frappe.throw(_("Please set Company filter blank if Group By is 'Company'"))