-- Test next_quote_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_quote_number', array ['integer', 'date']);
select function_lang_is('numerus', 'next_quote_number', array ['integer', 'date'], 'plpgsql');
select function_returns('numerus', 'next_quote_number', array ['integer', 'date'], 'text');
select isnt_definer('numerus', 'next_quote_number', array ['integer', 'date']);
select volatility_is('numerus', 'next_quote_number', array ['integer', 'date'], 'volatile');
select function_privs_are('numerus', 'next_quote_number', array ['integer', 'date'], 'guest', array []::text[]);
select function_privs_are('numerus', 'next_quote_number', array ['integer', 'date'], 'invoicer', array ['EXECUTE']);
select function_privs_are('numerus', 'next_quote_number', array ['integer', 'date'], 'admin', array ['EXECUTE']);
select function_privs_are('numerus', 'next_quote_number', array ['integer', 'date'], 'authenticator', array []::text[]);


set client_min_messages to warning;
truncate quote_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, quote_number_format, default_payment_method_id)
values (1, 'Company 2', 'XX123', '', '555-555-555', 'a@a', '', '', '', '', '', 'ES', 'EUR', '"Q"YYYY0000', 111)
     , (2, 'Company 4', 'XX234', '', '666-666-666', 'b@b', '', '', '', '', '', 'FR', 'USD', '"QUO"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 quote_number_counter (company_id, year, currval)
values (1, 2010, 5)
     , (2, 2010, 6)
;

select is( next_quote_number(1, '2010-12-25'), 'Q20100006' );
select is( next_quote_number(2, '2010-12-25'), 'QUO007-10' );
select is( next_quote_number(1, '2010-10-17'), 'Q20100007' );
select is( next_quote_number(2, '2010-10-17'), 'QUO008-10' );
select is( next_quote_number(1, '2011-12-25'), 'Q20110001' );
select is( next_quote_number(2, '2012-12-25'), 'QUO001-12' );
select is( next_quote_number(1, '2011-12-25'), 'Q20110002' );
select is( next_quote_number(2, '2012-12-25'), 'QUO002-12' );

select *
from finish();

rollback;
