-- P5-5125: fix name and address in v_analytics_orders

DROP VIEW IF EXISTS v_analytics_orders;

CREATE VIEW v_analytics_orders 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,
    COALESCE(confirmed.value::boolean, false) AS confirmed,
    COALESCE(paid.value::boolean, false) AS paid,
    COALESCE(delivered.value::boolean, false) AS delivered,
    orders.orderid,
    billing_address.first_name,
    billing_address.last_name,
    md5(billing_address.company_name || 'vX9Px6g6yOBRTKRyH6Kt'::text) AS company,
    md5(billing_address.address1 || 'gK8fM79jomiQK4joWc3t'::text) AS address,
    billing_address.zipcode AS postal_code,
    billing_address.city,
    billing_address.country_code AS country,
    email.value 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" 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;

GRANT SELECT ON v_analytics_orders TO datastudio;
