-- Deploy camper:invoice_number_counter to pg
-- requires: schema_camper
-- requires: company

begin;

set search_path to camper, public;

create table invoice_number_counter (
	company_id integer not null references company,
	year integer not null constraint year_always_positive check(year > 0),
	currval integer not null constraint counter_zero_or_positive check(currval >= 0),
	primary key (company_id, year)
);

grant select, insert, update on table invoice_number_counter to employee;
grant select, insert, update on table invoice_number_counter to admin;

alter table invoice_number_counter enable row level security;

create policy company_policy
on invoice_number_counter
using (
	exists(
		select 1
		from company_user
		join user_profile using (user_id)
		where company_user.company_id = invoice_number_counter.company_id
	)
);

commit;
