-- P5-6180: create datastudio view for contract customer discounts
DROP VIEW IF EXISTS v_analytics_contract_customer_discounts;

CREATE VIEW v_analytics_contract_customer_discounts AS

 SELECT rows.orderid,
    rows.rowid,
    vat.value AS vat,
    price.value::numeric AS price,
    round(percent.value::numeric / 100, 2) AS percent
   FROM "order-rows" rows
     JOIN "order-rows_details" modifier ON rows.rowid = modifier.rowid AND modifier.fieldid = 113 AND modifier.value = 'contractCustomerDiscount'::text
     LEFT JOIN "order-rows_details" price ON rows.rowid = price.rowid AND price.fieldid = 98
     LEFT JOIN "order-rows_details" vat ON rows.rowid = vat.rowid AND vat.fieldid = 110
     LEFT JOIN "order-rows_details" percent ON rows.rowid = percent.rowid AND percent.fieldid = 147;

GRANT SELECT ON v_analytics_contract_customer_discounts TO datastudio;
