numerus/deploy/next_quote_number.sql

41 lines
1015 B
PL/PgSQL

-- Deploy numerus:next_quote_number to pg
-- requires: roles
-- requires: schema_numerus
-- requires: quote_number_counter
begin;
set search_path to numerus, public;
create or replace function next_quote_number(company integer, quote_date date) returns text
as
$$
declare
num integer;
quote_number text;
begin
insert into quote_number_counter (company_id, year, currval)
values (next_quote_number.company, date_part('year', quote_date), 1)
on conflict (company_id, year) do
update
set currval = quote_number_counter.currval + 1
returning currval
into num;
select to_char(quote_date, to_char(num, 'FM' || replace(quote_number_format, '"', '\""')))
into quote_number
from company
where company_id = next_quote_number.company;
return quote_number;
end;
$$
language plpgsql
;
revoke execute on function next_quote_number(integer, date) from public;
grant execute on function next_quote_number(integer, date) to invoicer;
grant execute on function next_quote_number(integer, date) to admin;
commit;