-- Test expense_tax_amount
set client_min_messages to warning;
create extension if not exists pgtap;
reset client_min_messages;

begin;

select plan(12);

set search_path to numerus, auth, public;

select has_view('expense_tax_amount');
select table_privs_are('expense_tax_amount', 'guest', array[]::text[]);
select table_privs_are('expense_tax_amount', 'invoicer', array['SELECT']);
select table_privs_are('expense_tax_amount', 'admin', array['SELECT']);
select table_privs_are('expense_tax_amount', 'authenticator', array[]::text[]);

select has_column('expense_tax_amount', 'expense_id');
select col_type_is('expense_tax_amount', 'expense_id', 'integer');

select has_column('expense_tax_amount', 'tax_id');
select col_type_is('expense_tax_amount', 'tax_id', 'integer');

select has_column('expense_tax_amount', 'amount');
select col_type_is('expense_tax_amount', 'amount', 'integer');


set client_min_messages to warning;
truncate expense_tax cascade;
truncate expense cascade;
truncate contact cascade;
truncate tax cascade;
truncate tax_class cascade;
truncate payment_method cascade;
truncate company cascade;
reset client_min_messages;

set constraints "company_default_payment_method_id_fkey" deferred;

insert into company (company_id, business_name, vatin, trade_name, phone, email, web, address, city, province, postal_code, country_code, currency_code, default_payment_method_id)
values (1, 'Company 1', 'XX123', '', '555-555-555', 'a@a', '', '', '', '', '', 'ES', 'EUR', 111)
;

insert into payment_method (payment_method_id, company_id, name, instructions)
values (111, 1, 'cash', 'cash')
;

set constraints "company_default_payment_method_id_fkey" immediate;

insert into tax_class (tax_class_id, company_id, name)
values (11, 1, 'tax')
;

insert into tax (tax_id, company_id, tax_class_id, name, rate)
values (2, 1, 11, 'IRPF -15 %', -0.15)
     , (3, 1, 11, 'IVA 4 %', 0.04)
     , (4, 1, 11, 'IVA 10 %', 0.10)
     , (5, 1, 11, 'IVA 21 %', 0.21)
;

insert into contact (contact_id, company_id, name)
values (7, 1, 'Contact')
;

insert into expense (expense_id, company_id, invoice_number, invoice_date, contact_id, amount, currency_code)
values ( 8, 1, 'I1', current_date, 7,    123, 'EUR')
     , ( 9, 1, 'I2', current_date, 7,  44444, 'EUR')
     , (10, 1, 'I3', current_date, 7,   9999, 'EUR')
     , (11, 1, 'I4', current_date, 7, 100000, 'EUR')
;

insert into expense_tax (expense_id, tax_id, tax_rate)
values ( 8, 2, -0.15)
     , ( 8, 5,  0.21)
     , ( 9, 3,  0.04)
     , (10, 4,  0.10)
     , (10, 5,  0.21)
     , (10, 2, -0.07)
;   

select bag_eq(
	$$ select expense_id, tax_id, amount from expense_tax_amount $$,
	$$ values ( 8, 2,  -18)
	        , ( 8, 5,   26)
	        , ( 9, 3, 1778)
	        , (10, 2, -700)
	        , (10, 4, 1000)
	        , (10, 5, 2100)
	$$,
	'Should compute the amount for all taxes in the expenses.'
);

select *
from finish();

rollback;