-- Deploy numerus:expense to pg
-- requires: schema_numerus
-- requires: contact
-- requires: company
-- requires: currency_code
-- requires: currency
-- requires: tag_name

begin;

set search_path to numerus, public;

create table expense (
	expense_id serial primary key,
	company_id integer not null references company,
	slug uuid not null unique default gen_random_uuid(),
	contact_id integer not null references contact,
	invoice_number text not null,
	invoice_date date not null,
	amount integer not null,
	currency_code currency_code not null references currency,
	tags tag_name[] not null default '{}',
	created_at timestamptz not null default current_timestamp
);

create index on expense using gin (tags);

grant select, insert, update, delete on table expense to invoicer;
grant select, insert, update, delete on table expense to admin;

grant usage on sequence expense_expense_id_seq to invoicer;
grant usage on sequence expense_expense_id_seq to admin;

alter table expense enable row level security;

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

commit;
