CREATE OR REPLACE VIEW public.vw_fx_running AS
 WITH forex_event AS (
         SELECT max(forex.value_date) AS event_date,
            'Execution FX'::text AS type,
            max(forex.buy_amount) AS amount,
            forex.number AS event_ref,
            string_agg((p.number)::text, ', '::text) AS linked_purchase
           FROM ((forex_forex forex
             LEFT JOIN forex_cover_physical_contract fcpc ON ((fcpc.forex = forex.id)))
             LEFT JOIN purchase_purchase p ON ((fcpc.contract = p.id)))
          WHERE (forex.move IS NOT NULL)
          GROUP BY forex.number
        ), all_events AS (
         SELECT forex_event.event_date,
            forex_event.type,
            forex_event.amount,
            forex_event.event_ref,
            forex_event.linked_purchase
           FROM forex_event
        UNION ALL
         SELECT max(am.post_date) AS event_date,
            'Payment P'::text AS type,
            (- max(aml.amount_second_currency)) AS amount,
            max((p.number)::text) AS event_ref,
            max(fe.linked_purchase) AS linked_purchase
           FROM (((((((((((forex_forex forex
             LEFT JOIN forex_event fe ON (((fe.event_ref)::text = (forex.number)::text)))
             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 lot_lot ll ON ((pl.id = ll.line)))
             LEFT JOIN account_invoice_line ail ON ((ll.invoice_line_prov = ail.id)))
             LEFT JOIN account_invoice_line ail2 ON ((ll.invoice_line = ail2.id)))
             LEFT JOIN account_invoice ai ON ((ail.invoice = ai.id)))
             LEFT JOIN account_invoice ai2 ON ((ail2.invoice = ai2.id)))
             LEFT JOIN account_move am ON (((split_part((am.origin)::text, ','::text, 1) = 'account.invoice'::text) AND ((ai.id = (split_part((am.origin)::text, ','::text, 2))::integer) OR (ai2.id = (split_part((am.origin)::text, ','::text, 2))::integer)))))
             LEFT JOIN account_move_line aml ON ((am.id = aml.move)))
          WHERE ((forex.move IS NOT NULL) AND (aml.reconciliation > 0))
          GROUP BY forex.number
        )
 SELECT event_date,
    type,
    amount,
    event_ref,
    linked_purchase,
    sum(amount) OVER (ORDER BY event_date) AS running_amount
   FROM all_events
  ORDER BY event_date;;
