CREATE OR REPLACE VIEW public.view_contract_blocked AS
 SELECT p.number AS purchase_number,
    'contract'::text AS line_type,
    NULL::character varying AS forex_number,
    NULL::numeric AS amount_covered,
    string_agg(DISTINCT (pp.code)::text, ', '::text) AS products,
    max((pl.quantity * (pl.unit_price)::double precision)) AS total_contract_value,
    (max((pl.quantity * (pl.unit_price)::double precision)) - (sum(fcpc.amount))::double precision) AS amount_remaining,
    max((cc.code)::text) AS currency,
    NULL::numeric AS rate,
    NULL::date AS maturity_date
   FROM ((((purchase_purchase p
     LEFT JOIN forex_cover_physical_contract fcpc ON ((fcpc.contract = p.id)))
     LEFT JOIN purchase_line pl ON ((pl.purchase = p.id)))
     LEFT JOIN product_product pp ON ((pl.product = pp.id)))
     LEFT JOIN currency_currency cc ON ((p.currency = cc.id)))
  WHERE (p.currency = 2)
  GROUP BY p.number, pl.id
UNION ALL
 SELECT p.number AS purchase_number,
    'forex'::text AS line_type,
    forex.number AS forex_number,
    fcpc.amount AS amount_covered,
    NULL::text AS products,
    NULL::numeric AS total_contract_value,
    NULL::numeric AS amount_remaining,
    cc.code AS currency,
    forex.rate,
    forex.value_date AS maturity_date
   FROM (((purchase_purchase p
     JOIN forex_cover_physical_contract fcpc ON ((fcpc.contract = p.id)))
     LEFT JOIN forex_forex forex ON ((forex.id = fcpc.forex)))
     LEFT JOIN currency_currency cc ON ((forex.buy_currency = cc.id)))
  ORDER BY 1, 2;;
