-- P5-5126: fix name and address in v_analytics_orders_not_delivered

DROP VIEW IF EXISTS v_analytics_orders_not_delivered;

CREATE VIEW v_analytics_orders_not_delivered AS
SELECT
    CASE
        WHEN billing_address.country_code  IS NULL THEN 'Unknown'::text
        WHEN billing_address.country_code  = 'GB'::text THEN 'Photowall UK'::text
        WHEN billing_address.country_code  = ANY (ARRAY['SE'::text, 'NO'::text, 'DE'::text, 'AT'::text, 'FR'::text, 'ES'::text, 'FI'::text, 'DK'::text, 'PL'::text, 'US'::text, 'NL'::text]) THEN 'Photowall '::text || billing_address.country_code
        ELSE 'Photowall OTHER'::text
    END AS account,
    orders.inserted::date AS orderdate,
    orders.orderid,
    md5(billing_address.first_name || 'secret'::text) AS first_name,
    md5(billing_address.last_name || 'secret'::text) AS last_name,
    md5(billing_address.company_name || 'secret'::text) AS company,
    md5(billing_address.address1 || 'secret'::text) AS address,
    billing_address.zipcode AS postal_code,
    billing_address.city AS city,
    billing_address.country_code AS country,
    md5(email.value || 'secret'::text) AS email,
    order_sum.value::double precision / exchange_rate.value::double precision AS order_value_sek
FROM "order-orders" orders
LEFT JOIN "order-orders_fields" confirmed ON orders.orderid = confirmed.orderid AND confirmed.fieldid = 175
LEFT JOIN "order-orders_fields" delivered ON orders.orderid = delivered.orderid AND delivered.fieldid = 176
LEFT JOIN "order-orders_fields" paid ON orders.orderid = paid.orderid AND paid.fieldid = 168
LEFT JOIN "order-orders_fields" email ON orders.orderid = email.orderid AND email.fieldid = 184
LEFT JOIN "order-orders_fields" order_sum ON orders.orderid = order_sum.orderid AND order_sum.fieldid = 246
LEFT JOIN "order-orders_fields" exchange_rate ON orders.orderid = exchange_rate.orderid AND exchange_rate.fieldid = 171
LEFT JOIN "order-orders_fields" canceled ON orders.orderid = canceled.orderid AND canceled.fieldid = 200
LEFT JOIN "order-orders_fields" ready_for_handling ON orders.orderid = ready_for_handling.orderid AND ready_for_handling.fieldid = 195
LEFT JOIN "order-orders_fields" billing_address_id ON billing_address_id.fieldid = 255 AND billing_address_id.orderid = orders.orderid
LEFT JOIN addresses billing_address ON billing_address.id = billing_address_id.value::int
WHERE
    confirmed.value = 'true'::text
    AND delivered.value = 'false'::text
    AND canceled.value IS NULL
    AND paid.value = 'true'::text
    AND ready_for_handling.value = 'true'::text;

GRANT SELECT ON v_analytics_orders_not_delivered TO datastudio;
