-- 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 camper, public;

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


set client_min_messages to warning;
truncate invoice_number_counter 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, rtc_number, tourist_tax, tourist_tax_max_days, country_code, currency_code, default_lang_tag, invoice_number_format)
values (1, 'Company 2', 'XX123', '', '555-555-555', 'a@a', '', '', '', '', '', '', 60, 7, 'ES', 'EUR', 'ca', '"F"YYYY0000')
     , (2, 'Company 4', 'XX234', '', '666-666-666', 'b@b', '', '', '', '', '', '', 60, 7, 'FR', 'USD', 'ca', '"INV"000-YY')
;

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;
