SELECT
  p.id,
  p.proforma_reference,
  p.tax_mode,
  p.default_iva_code,
  p.uses_equivalence_surcharge,
  p.default_rec_code,
  p.uses_retention,
  p.default_retention_code
FROM proformas p
WHERE p.tax_mode NOT IN ('single', 'per_line')
   OR (p.uses_equivalence_surcharge = 1 AND p.default_iva_code IS NULL)
   OR (p.uses_equivalence_surcharge = 0 AND p.default_rec_code IS NOT NULL)
   OR (p.uses_retention = 0 AND p.default_retention_code IS NOT NULL);

SELECT
  p.id,
  p.proforma_reference,
  COUNT(DISTINCT pi.item_id) AS item_rows,
  COUNT(DISTINCT pt.tax_id) AS tax_rows
FROM proformas p
LEFT JOIN proforma_items pi
  ON pi.proforma_id = p.id
LEFT JOIN proforma_taxes pt
  ON pt.proforma_id = p.id
GROUP BY p.id, p.proforma_reference
HAVING COUNT(DISTINCT pi.item_id) = 0
   AND COUNT(DISTINCT pt.tax_id) > 0;
