CREATE OR REPLACE VIEW public.vw_forex AS
 SELECT forex.number AS forex_number,
    p.number AS purchase_number,
    ((((pp.code)::text || ' ('::text) || pl.quantity) || ')'::text) AS purchase_line,
    ai.number AS invoice_number,
    forex.for_amount AS forex_amount,
    fcpc.amount AS amount_covered,
    sum(fcpc.amount) OVER (PARTITION BY forex.id ORDER BY fcpc.id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cumulative_covered,
    (forex.for_amount - sum(fcpc.amount) OVER (PARTITION BY forex.id ORDER BY fcpc.id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)) AS balance
   FROM ((((((forex_forex forex
     LEFT JOIN forex_cover_physical_contract fcpc ON ((forex.id = fcpc.forex)))
     LEFT JOIN purchase_purchase p 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 account_invoice_line ail ON (((split_part((ail.origin)::text, ','::text, 1) = 'purchase.line'::text) AND (pl.id = (split_part((ail.origin)::text, ','::text, 2))::integer))))
     LEFT JOIN account_invoice ai ON ((ail.invoice = ai.id)))
  ORDER BY forex.number, fcpc.id;;
