-- Deploy camper:invoice_product_amount to pg
-- requires: schema_camper
-- requires: invoice_product
-- requires: invoice_product_tax

begin;

set search_path to camper, public;

create or replace view invoice_product_amount as
select invoice_product_id
     , round(price * quantity * (1 - discount_rate))::integer as subtotal
     , max(round(price * quantity * (1 - discount_rate))::integer) + coalesce(sum(round(round(price * quantity * (1 - discount_rate))::integer * tax_rate)::integer)::integer, 0) as total
from invoice_product
left join invoice_product_tax using (invoice_product_id)
group by invoice_product_id, price, quantity, discount_rate
;

grant select on table invoice_product_amount to employee;
grant select on table invoice_product_amount to admin;

commit;
