-- P5-5403: remove ready_for_handling from 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::text = 'GB'::text THEN 'Photowall UK'::text
        WHEN billing_address.country_code::text = 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::text
        ELSE 'Photowall OTHER'::text
    END AS account,
    orders.inserted::date AS orderdate,
    orders.orderid,
    md5(billing_address.first_name::text || 'secret'::text) AS first_name,
    md5(billing_address.last_name::text || 'secret'::text) AS last_name,
    md5(billing_address.company_name::text || 'secret'::text) AS company,
    md5(billing_address.address1::text || 'secret'::text) AS address,
    billing_address.zipcode AS postal_code,
    billing_address.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" 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::integer
WHERE confirmed.value = 'true'::text AND delivered.value = 'false'::text AND canceled.value IS NULL AND paid.value = 'true'::text;


GRANT SELECT ON v_analytics_orders_not_delivered TO datastudio;
