numerus/deploy/next_invoice_number.sql

39 lines
1.0 KiB
PL/PgSQL

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