-- P5-5349: create datastudio view with discount codes

DROP VIEW IF EXISTS v_analytics_discounts;

CREATE VIEW v_analytics_discounts AS
SELECT
    rows.orderid,
    rows.rowid,
    type.value as type,
    vat.value as vat,
    abs(price.value::double precision / exchange_rate.value::double precision) as price_sek,
    code.value as code,
    no_shipping.value as no_shipping
FROM "order-rows" rows
JOIN "order-rows_details" modifier ON rows.rowid = modifier.rowid AND modifier.fieldid = 113 and modifier.value = 'discount'
LEFT JOIN "order-rows_details" type ON rows.rowid = type.rowid AND type.fieldid = 94
LEFT JOIN "order-rows_details" price ON rows.rowid = price.rowid AND price.fieldid = 98
LEFT JOIN "order-rows_details" vat ON rows.rowid = vat.rowid AND vat.fieldid = 110
LEFT JOIN "order-rows_details" code ON rows.rowid = code.rowid AND code.fieldid = 115
LEFT JOIN "order-rows_details" no_shipping ON rows.rowid = no_shipping.rowid AND no_shipping.fieldid = 130
LEFT JOIN "order-orders_fields" exchange_rate ON rows.orderid = exchange_rate.orderid AND exchange_rate.fieldid = 171;

GRANT SELECT ON v_analytics_discounts TO datastudio;
