ALTER TABLE dsm_organizations ADD COLUMN registered_funder boolean;

CREATE VIEW funders_view AS SELECT
	o.id                AS id, 
	o.legalshortname    AS legalshortname,
	o.legalname         AS legalname,
	o.websiteurl        AS websiteurl, 
	o.logourl           AS logourl, 
	o.country           AS country,
	o.dateofcollection  AS registrationdate,
	o.registered_funder AS registered,
	CASE WHEN count(s.id) = 0 THEN '[]'::jsonb ELSE jsonb_agg(DISTINCT jsonb_build_object('id', s.id,'name', s.officialname,'type',s.eosc_datasource_type)) END AS datasources,
	CASE WHEN count(pids.pid) = 0 THEN '[]'::jsonb ELSE jsonb_agg(DISTINCT jsonb_build_object('type', pids.issuertype,'value', pids.pid)) END AS pids
FROM 
	dsm_organizations o 
	JOIN dsm_service_organization so           ON (o.id = so.organization) 
	JOIN dsm_services s                        ON (so.service = s.id) 
	JOIN projects p                            ON (p.collectedfrom = s.id)
	LEFT OUTER JOIN dsm_organizationpids opids ON (o.id = opids.organization)
	LEFT OUTER JOIN dsm_identities pids        ON (opids.pid = pids.pid)
GROUP BY o.id;
