-- P5-4750: Create view for unshipped order rows

DROP VIEW IF EXISTS v_analytics_orders_rows_not_delivered;

CREATE VIEW v_analytics_orders_rows_not_delivered AS
SELECT
    rows.rowid as order_row_id,
    orders.orderid as orderid,
    orders.inserted as order_date,
    product_group.value as product_group,
    artno.value as artno,
    status.value as status,
    name.value as name
FROM "order-rows" rows
JOIN "order-orders" orders ON rows.orderid = orders.orderid
LEFT JOIN "order-orders_fields" order_confirmed on orders.orderid = order_confirmed.orderid AND order_confirmed.fieldid = 175
LEFT JOIN "order-orders_fields" order_delivered on orders.orderid = order_delivered.orderid AND order_delivered.fieldid = 176
LEFT JOIN "order-orders_fields" order_canceled on orders.orderid = order_canceled.orderid AND order_canceled.fieldid = 200
LEFT JOIN "order-orders_fields" order_paid on orders.orderid = order_paid.orderid AND order_paid.fieldid = 168
LEFT JOIN "order-orders_fields" order_ready_for_handling on orders.orderid = order_ready_for_handling.orderid AND order_ready_for_handling.fieldid = 195
LEFT JOIN "order-rows_details" product_group ON rows.rowid = product_group.rowid AND product_group.fieldid = 93
LEFT JOIN "order-rows_details" artno ON rows.rowid = artno.rowid AND artno.fieldid = 95
LEFT JOIN "order-rows_details" status ON rows.rowid = status.rowid AND status.fieldid = 108
LEFT JOIN "order-rows_details" name ON rows.rowid = name.rowid AND name.fieldid = 97
LEFT JOIN "order-rows_details" modifier ON rows.rowid = modifier.rowid AND modifier.fieldid = 113
WHERE
    modifier.value IS NULL
    and order_confirmed.value = 'true'
    and order_delivered.value = 'false'
    and order_canceled.value IS NULL
    and order_paid.value = 'true'
    and order_ready_for_handling.value = 'true'
;

GRANT SELECT ON v_analytics_orders_rows_not_delivered TO datastudio;
