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

begin;

select plan(14);

set search_path to numerus, auth, public;

select has_function('numerus', 'compute_new_invoice_amount', array ['integer', 'new_invoice_product[]']);
select function_lang_is('numerus', 'compute_new_invoice_amount', array ['integer', 'new_invoice_product[]'], 'plpgsql');
select function_returns('numerus', 'compute_new_invoice_amount', array ['integer', 'new_invoice_product[]'], 'new_invoice_amount');
select isnt_definer('numerus', 'compute_new_invoice_amount', array ['integer', 'new_invoice_product[]']);
select volatility_is('numerus', 'compute_new_invoice_amount', array ['integer', 'new_invoice_product[]'], 'stable');
select function_privs_are('numerus', 'compute_new_invoice_amount', array ['integer', 'new_invoice_product[]'], 'guest', array []::text[]);
select function_privs_are('numerus', 'compute_new_invoice_amount', array ['integer', 'new_invoice_product[]'], 'invoicer', array ['EXECUTE']);
select function_privs_are('numerus', 'compute_new_invoice_amount', array ['integer', 'new_invoice_product[]'], 'admin', array ['EXECUTE']);
select function_privs_are('numerus', 'compute_new_invoice_amount', array ['integer', 'new_invoice_product[]'], 'authenticator', array []::text[]);

set client_min_messages to warning;
truncate tax cascade;
truncate tax_class cascade;
truncate company cascade;
reset client_min_messages;

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

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)
;

select is(
	compute_new_invoice_amount(1, '{}'),
	'(0.00,"{}",0.00)'::new_invoice_amount
);

select is(
	compute_new_invoice_amount(1, '{"(6,P,D,1.00,1,0.0,\"{2,5}\")","(6,P,D,2.00,2,0.1,{3})"}'),
	'(4.60,"{{IRPF -15 %,-0.15},{IVA 4 %,0.14},{IVA 21 %,0.21}}",4.80)'::new_invoice_amount
);

select is(
	compute_new_invoice_amount(1, '{"(6,P,D,2.22,3,0.0,\"{2,4,5}\")","(6,P,D,3.33,4,0.2,{4})"}'),
	'(17.32,"{{IRPF -15 %,-1.00},{IVA 10 %,1.74},{IVA 21 %,1.40}}",19.46)'::new_invoice_amount
);

select is(
	compute_new_invoice_amount(1, '{"(6,P,D,4.44,5,0.0,\"{4,5}\")","(6,P,D,5.55,6,0.1,\"{5,3}\")"}'),
	'(52.17,"{{IVA 4 %,1.20},{IVA 10 %,2.22},{IVA 21 %,10.95}}",66.54)'::new_invoice_amount
);

select is(
	compute_new_invoice_amount(1, '{"(6,P,D,7.77,8,0.0,\"{}\")"}'),
	'(62.16,"{}",62.16)'::new_invoice_amount
);

select *
from finish();

rollback;
