CREATE MATERIALIZED VIEW alinma_bff.orders_mv AS
SELECT
id AS order_id,
etag,
client_order_id,
customer_relationship_id,
portfolio_id,
security_account_id,
asset_id,
side AS order_side,
workflow_state,
execution_state,
termination_reason,
termination_detail,
instruction,
execution_spec,
cost_estimate,
es.execution_summary,
initiator,
filled_quantity,
created_at,
executed_at
FROM (
SELECT
id,
etag,
client_order_id,
customer_relationship_id,
portfolio_id,
security_account_id,
asset_id,
side,
workflow_state,
execution_state,
termination_reason,
termination_detail,
instruction,
execution_spec,
cost_estimate,
initiator,
filled_quantity,
created_at,
executed_at,
deleted_at,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY created_at DESC) AS rn
FROM order_service.orders
) AS ranked_orders
LEFT JOIN alinma_bff.order_execution_summaries_mv AS es
ON es.order_id = ranked_orders.id
WHERE
rn = 1 AND deleted_at IS NULL