DROP VIEW IF EXISTS v_analytics_order_rows;

CREATE VIEW v_analytics_order_rows AS
  SELECT
    CASE
       WHEN orders.market IS NULL THEN 'Unknown'
       WHEN orders.market = 'GB' THEN 'Photowall UK'
       WHEN orders.market = 'GLOBAL' THEN 'Photowall OTHER'
       ELSE 'Photowall ' || orders.market
    END AS account,
    order_rows.order_id as orderid,
    order_rows.id as rowid,
    orders.inserted::date AS orderdate,
    order_rows.data->>'artNo' AS artno,
    order_rows.data->>'productId' AS productid,
	order_rows.data->>'name' AS name,
	order_rows.data->>'inquiryid' AS inquiryid,
    CASE
        WHEN order_rows.type = 'sample' THEN 'Sample'
        ELSE COALESCE(order_rows.data->>'group', order_rows.type::text)
    END AS type,
    order_rows.data->>'material' as material,
    COALESCE((order_rows.data->>'width_mm')::float / 10::float, (order_rows.data->>'width')::float) AS width,
    COALESCE((order_rows.data->>'height_mm')::float / 10::float, (order_rows.data->>'height')::float) AS height,
    CASE
        WHEN order_rows.status = 'process' THEN 'Ready for processing'
        WHEN  order_rows.status = 'print' THEN 'Ready for packing'
        WHEN  order_rows.status = 'packed' THEN 'Ready for sending'
        WHEN  order_rows.status = 'sent' THEN 'Sent'
        ELSE 'Unknown'
    END AS status,
    order_rows.data->>'commission' AS commission_percent,
    round((order_rows.data->>'height')::float) AS commission_amount,
    order_rows.data->>'discountType' AS discount_type,
    order_rows.data->>'discountValue' AS discount_value,
    CASE
        WHEN order_rows.data->>'discountType' <> '%' THEN (order_rows.data->>'discountValue')::float / orders.exchange_rate
        ELSE NULL::float
    END AS discount_amount_sek,
    orders.currency::TEXT AS order_currency,
    order_rows.data->>'designer' AS designer,
    (order_rows.price / orders.exchange_rate)::float AS item_value_sek,
    order_rows.data->>'framed' AS canvas_frame,
    order_rows.data->>'posterHanger' as poster_hanger,
    order_rows.data->>'frame_color' as framed_print_frame,
    order_rows.price::float AS price,
    orders.delivery_vat AS vat
   FROM order_rows
     LEFT JOIN orders ON orders.id = order_rows.order_id
     WHERE order_rows.type in ('print', 'stock', 'sample');


GRANT SELECT ON v_analytics_order_rows to datastudio;
