fix: tds calculation, skip invoices with "Apply Tax Withholding Amount" has disabled
diff --git a/erpnext/accounts/doctype/tax_withholding_category/tax_withholding_category.py b/erpnext/accounts/doctype/tax_withholding_category/tax_withholding_category.py
index 8b5e68b..32ad4cb 100644
--- a/erpnext/accounts/doctype/tax_withholding_category/tax_withholding_category.py
+++ b/erpnext/accounts/doctype/tax_withholding_category/tax_withholding_category.py
@@ -140,9 +140,9 @@
 		else:
 			tds_amount = _get_tds(net_total, tax_details.rate)
 	else:
-		supplier_credit_amount = frappe.get_all('Purchase Invoice Item',
-			fields = ['sum(net_amount)'],
-			filters = {'parent': ('in', vouchers), 'docstatus': 1}, as_list=1)
+		supplier_credit_amount = frappe.get_all('Purchase Invoice',
+			fields = ['sum(net_total)'],
+			filters = {'name': ('in', vouchers), 'docstatus': 1, "apply_tds": 1}, as_list=1)
 
 		supplier_credit_amount = (supplier_credit_amount[0][0]
 			if supplier_credit_amount and supplier_credit_amount[0][0] else 0)
diff --git a/erpnext/accounts/doctype/tax_withholding_category/test_tax_withholding_category.py b/erpnext/accounts/doctype/tax_withholding_category/test_tax_withholding_category.py
index b146899..a0b0cbb 100644
--- a/erpnext/accounts/doctype/tax_withholding_category/test_tax_withholding_category.py
+++ b/erpnext/accounts/doctype/tax_withholding_category/test_tax_withholding_category.py
@@ -101,6 +101,29 @@
 		for d in invoices:
 			d.cancel()
 
+	def test_single_threshold_tds_with_previous_vouchers_and_no_tds(self):
+		invoices = []
+		frappe.db.set_value("Supplier", "Test TDS Supplier2", "tax_withholding_category", "Single Threshold TDS")
+		pi = create_purchase_invoice(supplier="Test TDS Supplier2")
+		pi.submit()
+		invoices.append(pi)
+
+		# TDS not applied
+		pi = create_purchase_invoice(supplier="Test TDS Supplier2", do_not_apply_tds=True)
+		pi.submit()
+		invoices.append(pi)
+
+		pi = create_purchase_invoice(supplier="Test TDS Supplier2")
+		pi.submit()
+		invoices.append(pi)
+
+		self.assertEqual(pi.taxes_and_charges_deducted, 2000)
+		self.assertEqual(pi.grand_total, 8000)
+
+		# delete invoices to avoid clashing
+		for d in invoices:
+			d.cancel()
+
 def create_purchase_invoice(**args):
 	# return sales invoice doc object
 	item = frappe.get_doc('Item', {'item_name': 'TDS Item'})
@@ -109,7 +132,7 @@
 	pi = frappe.get_doc({
 		"doctype": "Purchase Invoice",
 		"posting_date": today(),
-		"apply_tds": 1,
+		"apply_tds": 0 if args.do_not_apply_tds else 1,
 		"supplier": args.supplier,
 		"company": '_Test Company',
 		"taxes_and_charges": "",