-- Add date fields for Funnel on v_analytics_products and v_analytics_contract_customer_discounts

DROP VIEW IF EXISTS v_analytics_products;
create view v_analytics_products as
    select
        products.productid as product_id,
        products.path as product_path,
        visible,
        browsable,
        products.inserted as product_inserted,
        products.updated as product_updated,
        designers.designerid as designer_id,
        designers.name as designer_name,
        ref1,
        ref2,
        ref3,
        artno.value as artno,
        name.value as product_name,
        width.value::int as width,
        height.value::int as height,
        copyright.value as copyright,
        batch.value as batch,
        coalesce(products.updated, products.inserted) last_updated
    from "product-products" products
    left join designers on products.designerid = designers.designerid
    left join "product-products_fields" artno on artno.fieldid = 1 and artno.productid = products.productid
    left join "product-products_fields" name on name.fieldid = 2 and name.productid = products.productid
    left join "product-products_fields" width on width.fieldid = 5 and width.productid = products.productid
    left join "product-products_fields" height on height.fieldid = 3 and height.productid = products.productid
    left join "product-products_fields" copyright on copyright.fieldid = 25 and copyright.productid = products.productid
    left join "product-products_fields" batch on batch.fieldid = 36 and batch.productid = products.productid;

grant select on v_analytics_products to datastudio;
grant select on v_analytics_products to funnel;


drop view if exists v_analytics_contract_customer_discounts;
create view v_analytics_contract_customer_discounts as
SELECT order_rows.order_id AS orderid,
       order_rows.id AS rowid,
       orders.delivery_vat AS vat,
       order_rows.price,
       round(((order_rows.data ->> 'percent'::text)::numeric) / 100::numeric, 2) AS percent,
       orders.inserted AS orderdate
FROM order_rows
         JOIN orders ON orders.id = order_rows.order_id
WHERE order_rows.sub_type = 'contract_customer_discount'::order_row_sub_type;

grant select on v_analytics_contract_customer_discounts to datastudio;
grant select on v_analytics_contract_customer_discounts to funnel;
