SELECT 
 ca.id,
    ca.code,
    res_partner.personal_id as documento,
    res_partner.name  as nombre, 
    ca.emission_date as fecha_emision,
    (SELECT MIN(cad.pa_date) 
     FROM cll_agreement_detail cad 
     WHERE cad.agreement_id = ca.id 
       AND cad.pa_date < CURRENT_DATE 
       AND (cad.all_paid = false OR cad.all_paid IS NULL)
    ) AS fecha_cuota_vencida,  
    (SELECT SUM(cad.pa_amount) 
     FROM cll_agreement_detail cad 
     WHERE cad.agreement_id = ca.id 
    ) AS valor_convenio,  
    (SELECT SUM(cll_agreement_payment.to_paid) 
     FROM cll_agreement_detail cad 
     INNER JOIN cll_agreement_payment ON cad.id = cll_agreement_payment.agreement_detail_id 
     WHERE cad.agreement_id = ca.id 
    ) AS pagado,
    ca.state::text AS estado_convenio,
    ca.cancel_date AS fecha_cancelacion,
	(
SELECT count(*) FROM public.cll_vouchers_line
  inner JOIN cll_collection ON cll_vouchers_line.collection_id = cll_collection.id
  inner join cll_dividend_line on cll_dividend_line.cll_collection_id=cll_collection.id
  inner JOIN cll_tax ON cll_dividend_line.cll_tax_id = cll_tax.id
where  cll_tax.id in(3,5) and cll_vouchers_line.agreement_id=ca.id  group by cll_collection.id limit 1) as predios
FROM cll_agreement ca 
JOIN res_partner ON res_partner.id = ca.taxpayer_id;