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

begin;

select plan(17);

set search_path to numerus, public;

select has_function('numerus', 'next_invoice_number', array ['integer', 'date']);
select function_lang_is('numerus', 'next_invoice_number', array ['integer', 'date'], 'plpgsql');
select function_returns('numerus', 'next_invoice_number', array ['integer', 'date'], 'text');
select isnt_definer('numerus', 'next_invoice_number', array ['integer', 'date']);
select volatility_is('numerus', 'next_invoice_number', array ['integer', 'date'], 'volatile');
select function_privs_are('numerus', 'next_invoice_number', array ['integer', 'date'], 'guest', array []::text[]);
select function_privs_are('numerus', 'next_invoice_number', array ['integer', 'date'], 'invoicer', array ['EXECUTE']);
select function_privs_are('numerus', 'next_invoice_number', array ['integer', 'date'], 'admin', array ['EXECUTE']);
select function_privs_are('numerus', 'next_invoice_number', array ['integer', 'date'], 'authenticator', array []::text[]);


set client_min_messages to warning;
truncate invoice_number_counter 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, invoice_number_format, default_payment_method_id)
values (1, 'Company 2', 'XX123', '', '555-555-555', 'a@a', '', '', '', '', '', 'ES', 'EUR', '"F"YYYY0000', 111)
     , (2, 'Company 4', 'XX234', '', '666-666-666', 'b@b', '', '', '', '', '', 'FR', 'USD', '"INV"000-YY', 222)
;

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

set constraints "company_default_payment_method_id_fkey" immediate;

insert into invoice_number_counter (company_id, year, currval)
values (1, 2010, 5)
     , (2, 2010, 6)
;

select is( next_invoice_number(1, '2010-12-25'), 'F20100006' );
select is( next_invoice_number(2, '2010-12-25'), 'INV007-10' );
select is( next_invoice_number(1, '2010-10-17'), 'F20100007' );
select is( next_invoice_number(2, '2010-10-17'), 'INV008-10' );
select is( next_invoice_number(1, '2011-12-25'), 'F20110001' );
select is( next_invoice_number(2, '2012-12-25'), 'INV001-12' );
select is( next_invoice_number(1, '2011-12-25'), 'F20110002' );
select is( next_invoice_number(2, '2012-12-25'), 'INV002-12' );

select *
from finish();

rollback;
