-- Execute em um projeto Supabase novo. Contém apenas o esquema. begin; -- 20261127031625_finance_spaces.sql -- Financial records inherit access from their space. Personal spaces never -- consult the membership table. Provision spaces and members administratively. create table public.finance_spaces ( id uuid primary key default gen_random_uuid(), personal_owner_id uuid unique references auth.users(id), name text not null check (char_length(name) between 1 and 100) ); create table public.finance_space_members ( workspace_id uuid not null references public.finance_spaces(id) on delete cascade, user_id uuid not null references auth.users(id) on delete cascade, primary key (workspace_id, user_id) ); create index on public.finance_space_members (user_id, workspace_id); alter table public.finance_spaces enable row level security; alter table public.finance_space_members enable row level security; revoke all on public.finance_spaces, public.finance_space_members from public, anon, authenticated; grant select on public.finance_spaces, public.finance_space_members to authenticated; create policy own_memberships on public.finance_space_members for select to authenticated using (user_id = (select auth.uid())); create policy accessible_spaces on public.finance_spaces for select to authenticated using (personal_owner_id = (select auth.uid()) or ( personal_owner_id is null and id in ( select workspace_id from public.finance_space_members where user_id = (select auth.uid()) ) )); -- Keep legacy identifiers as text for import. The workspace scopes primary -- keys and foreign keys, including identifiers from bank providers. create domain public.financial_cents as bigint check (value between -9007199254740991 and 9007199254740991); create table public.connections ( id text not null, workspace_id uuid not null references public.finance_spaces(id), name TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'PENDING', last_sync timestamptz, error TEXT, consent_expires_at timestamptz, primary key (workspace_id, id) ); create table public.accounts ( id text not null, workspace_id uuid not null references public.finance_spaces(id), name TEXT NOT NULL, institution TEXT NOT NULL, type TEXT NOT NULL, balance public.financial_cents NOT NULL DEFAULT 0, color TEXT NOT NULL DEFAULT '#2563eb', currency TEXT NOT NULL DEFAULT 'BRL', item_id text, available_credit_limit public.financial_cents, credit_limit public.financial_cents, primary key (workspace_id, id), foreign key (workspace_id, item_id) references public.connections(workspace_id, id) ); create table public.categories ( id text not null, workspace_id uuid not null references public.finance_spaces(id), name TEXT NOT NULL, color TEXT NOT NULL, image_slug TEXT, sort_order INTEGER NOT NULL DEFAULT 0, taxonomy_key TEXT, UNIQUE(workspace_id, name), primary key (workspace_id, id) ); create table public.category_rules ( id text not null, workspace_id uuid not null references public.finance_spaces(id), category_id text NOT NULL, match_text TEXT NOT NULL, match_key TEXT NOT NULL, operator TEXT NOT NULL DEFAULT 'contains' CHECK(operator IN ('contains','equals')), priority INTEGER NOT NULL DEFAULT 100 CHECK(priority BETWEEN 0 AND 9999), active INTEGER NOT NULL DEFAULT 1 CHECK(active IN (0,1)), UNIQUE(workspace_id, operator, match_key), primary key (workspace_id, id), foreign key (workspace_id, category_id) references public.categories(workspace_id, id) ON DELETE CASCADE ); create table public.goals ( id text not null, workspace_id uuid not null references public.finance_spaces(id), name TEXT NOT NULL, target public.financial_cents NOT NULL CHECK(target > 0), current public.financial_cents NOT NULL DEFAULT 0 CHECK(current >= 0), deadline date NOT NULL, icon TEXT NOT NULL, color TEXT NOT NULL, image_slug TEXT, completed INTEGER NOT NULL DEFAULT 0 CHECK(completed IN (0,1)), description TEXT NOT NULL DEFAULT '', category TEXT NOT NULL DEFAULT 'Sem categoria', created_at timestamptz, completed_at timestamptz, primary key (workspace_id, id) ); create table public.investments ( id text not null, workspace_id uuid not null references public.finance_spaces(id), name TEXT NOT NULL, institution TEXT NOT NULL, type TEXT NOT NULL, balance public.financial_cents NOT NULL CHECK(balance >= 0), invested public.financial_cents CHECK(invested >= 0), currency TEXT NOT NULL DEFAULT 'BRL', source TEXT NOT NULL DEFAULT 'manual', item_id text, primary key (workspace_id, id), foreign key (workspace_id, item_id) references public.connections(workspace_id, id) ); create table public.merchant_assets ( workspace_id uuid not null references public.finance_spaces(id), match_text TEXT NOT NULL, image_data TEXT NOT NULL, PRIMARY KEY(workspace_id, match_text) ); create table public.plan_months ( workspace_id uuid not null references public.finance_spaces(id), month date NOT NULL, monthly_limit public.financial_cents NOT NULL DEFAULT 0, fixed_cost public.financial_cents NOT NULL DEFAULT 0, monthly_savings public.financial_cents NOT NULL DEFAULT 0, expected_salary public.financial_cents NOT NULL DEFAULT 0, expected_freelance public.financial_cents NOT NULL DEFAULT 0, PRIMARY KEY (workspace_id, month), check (extract(day from month) = 1), check (least(monthly_limit, fixed_cost, monthly_savings, expected_salary, expected_freelance) >= 0) ); create table public.plan_settings ( workspace_id uuid not null references public.finance_spaces(id), monthly_limit public.financial_cents NOT NULL DEFAULT 0 CHECK(monthly_limit >= 0), fixed_cost public.financial_cents NOT NULL DEFAULT 0 CHECK(fixed_cost >= 0), monthly_savings public.financial_cents NOT NULL DEFAULT 0 CHECK(monthly_savings >= 0) , expected_salary public.financial_cents NOT NULL DEFAULT 0, expected_freelance public.financial_cents NOT NULL DEFAULT 0, primary key (workspace_id), check (least(monthly_limit, fixed_cost, monthly_savings, expected_salary, expected_freelance) >= 0) ); create table public.pluggy_webhook_events ( workspace_id uuid not null references public.finance_spaces(id), event_id uuid not null, event TEXT NOT NULL, item_id TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','processed','failed')), received_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, processed_at timestamptz, error TEXT, primary key (workspace_id, event_id), foreign key (workspace_id, item_id) references public.connections(workspace_id, id) ); create table public.recurrings ( id text not null, workspace_id uuid not null references public.finance_spaces(id), kind TEXT NOT NULL CHECK(kind IN ('income','expense')), type TEXT NOT NULL CHECK(type IN ('fixed','installment')), description TEXT NOT NULL, amount public.financial_cents NOT NULL CHECK(amount > 0), day_of_month INTEGER NOT NULL CHECK(day_of_month BETWEEN 1 AND 31), frequency TEXT NOT NULL DEFAULT 'monthly' CHECK(frequency='monthly'), category TEXT NOT NULL, account_id text, installment_current INTEGER CHECK(installment_current IS NULL OR installment_current >= 1), installment_total INTEGER CHECK(installment_total IS NULL OR installment_total >= 2), start_date date, end_date date, source TEXT NOT NULL CHECK(source IN ('detected','manual')), match_key TEXT NOT NULL, ignored INTEGER NOT NULL DEFAULT 0 CHECK(ignored IN (0,1)), active INTEGER NOT NULL DEFAULT 1 CHECK(active IN (0,1)), user_edited INTEGER NOT NULL DEFAULT 0 CHECK(user_edited IN (0,1)), currency TEXT NOT NULL DEFAULT 'BRL', primary key (workspace_id, id), foreign key (workspace_id, account_id) references public.accounts(workspace_id, id) ); create table public.transactions ( id text not null, workspace_id uuid not null references public.finance_spaces(id), description TEXT NOT NULL, amount public.financial_cents NOT NULL CHECK(amount > 0), kind TEXT NOT NULL CHECK(kind IN ('income','expense','transfer')), date date NOT NULL, status TEXT NOT NULL CHECK(status IN ('paid','pending')), category TEXT NOT NULL, account_id text, source TEXT NOT NULL DEFAULT 'manual', currency TEXT NOT NULL DEFAULT 'BRL', user_categorized INTEGER NOT NULL DEFAULT 0, installment_number INTEGER, installment_total INTEGER, primary key (workspace_id, id), foreign key (workspace_id, account_id) references public.accounts(workspace_id, id) ); create index on public.accounts (workspace_id, item_id); create index on public.investments (workspace_id, item_id); create index on public.transactions (workspace_id, date desc); create index on public.transactions (workspace_id, account_id); create index on public.category_rules (workspace_id, category_id); create index on public.category_rules (workspace_id, active, priority); create index on public.categories (workspace_id, sort_order, name); create index on public.recurrings (workspace_id, active, ignored); create index on public.recurrings (workspace_id, account_id); create unique index recurring_identity on public.recurrings (workspace_id, kind, type, match_key, coalesce(installment_total, 0)); create index on public.pluggy_webhook_events (workspace_id, item_id); create index on public.pluggy_webhook_events (received_at) where status = 'pending'; -- The schema is staged before application authorization. Expose read access -- scoped by RLS. Mutations remain server-only until the API port is tested. do $policies$ declare resource text; begin foreach resource in array array[ 'accounts', 'categories', 'category_rules', 'connections', 'goals', 'investments', 'merchant_assets', 'plan_months', 'plan_settings', 'pluggy_webhook_events', 'recurrings', 'transactions' ] loop execute format('alter table public.%I enable row level security', resource); execute format('revoke all on public.%I from public, anon, authenticated', resource); if resource not in ('connections', 'pluggy_webhook_events') then execute format('grant select on public.%I to authenticated', resource); execute format( 'create policy accessible_records on public.%I for select to authenticated using (workspace_id in (select id from public.finance_spaces))', resource ); end if; end loop; end; $policies$; -- 20261127035135_private_ledger.sql -- The authenticated pilot uses only the user's JWT. No elevated key is needed. do $mfa$ declare resource text; begin foreach resource in array array[ 'finance_spaces', 'finance_space_members', 'accounts', 'categories', 'category_rules', 'goals', 'investments', 'merchant_assets', 'plan_months', 'plan_settings', 'recurrings', 'transactions' ] loop execute format( 'create policy require_totp on public.%I as restrictive for all to authenticated using ((select auth.jwt()->>''aal'') = ''aal2'') with check ((select auth.jwt()->>''aal'') = ''aal2'')', resource ); end loop; end; $mfa$; alter table public.transactions alter column id set default gen_random_uuid()::text; alter table public.categories alter column id set default gen_random_uuid()::text; -- Neither IDs nor ownership can be changed after insertion. Imported fields -- are intentionally excluded from write grants. grant insert (workspace_id, description, amount, kind, date, status, category), update (description, amount, kind, date, status, category), delete on public.transactions to authenticated; grant insert (workspace_id, name, color) on public.categories to authenticated; create policy create_personal_categories on public.categories for insert to authenticated with check ( workspace_id in ( select id from public.finance_spaces where personal_owner_id = (select auth.uid()) ) and char_length(trim(name)) between 1 and 80 and name = trim(name) and name <> 'Sem categoria' and color ~ '^#[0-9a-fA-F]{6}$' ); create policy create_personal_transactions on public.transactions for insert to authenticated with check ( workspace_id in ( select id from public.finance_spaces where personal_owner_id = (select auth.uid()) ) and char_length(trim(description)) between 1 and 160 and amount between 1 and 100000000000 and ( category = 'Sem categoria' or exists ( select from public.categories c where c.workspace_id = transactions.workspace_id and c.name = transactions.category ) ) ); create policy update_personal_transactions on public.transactions for update to authenticated using ( source = 'manual' and account_id is null and currency = 'BRL' and workspace_id in ( select id from public.finance_spaces where personal_owner_id = (select auth.uid()) ) ) with check ( source = 'manual' and account_id is null and currency = 'BRL' and workspace_id in ( select id from public.finance_spaces where personal_owner_id = (select auth.uid()) ) and char_length(trim(description)) between 1 and 160 and amount between 1 and 100000000000 and ( category = 'Sem categoria' or exists ( select from public.categories c where c.workspace_id = transactions.workspace_id and c.name = transactions.category ) ) ); create policy delete_personal_transactions on public.transactions for delete to authenticated using ( source = 'manual' and account_id is null and currency = 'BRL' and workspace_id in ( select id from public.finance_spaces where personal_owner_id = (select auth.uid()) ) ); -- 20261127060000_private_finance.sql -- All writes remain scoped to the personal workspace and require the AAL2 -- restrictive policies installed by private_ledger. do $finance$ declare resource text; personal_scope text := 'workspace_id in (select id from public.finance_spaces where personal_owner_id = (select auth.uid()))'; begin foreach resource in array array['goals', 'investments', 'recurrings', 'category_rules', 'plan_months'] loop if resource <> 'plan_months' then execute format('alter table public.%I alter column id set default gen_random_uuid()::text', resource); end if; if resource = 'investments' then execute format('create policy personal_finance_write on public.%I for all to authenticated using (%s and source = ''manual'' and item_id is null) with check (%s and source = ''manual'' and item_id is null)', resource, personal_scope, personal_scope); else execute format('create policy personal_finance_write on public.%I for all to authenticated using (%s) with check (%s)', resource, personal_scope, personal_scope); end if; end loop; end; $finance$; grant insert (workspace_id, name, target, current, deadline, icon, color, image_slug, completed, description, category, created_at, completed_at), update (name, target, current, deadline, icon, color, image_slug, completed, description, category, completed_at), delete on public.goals to authenticated; grant insert (workspace_id, name, institution, type, balance, invested), update (name, institution, type, balance, invested), delete on public.investments to authenticated; grant insert (workspace_id, kind, type, description, amount, day_of_month, category, account_id, installment_current, installment_total, start_date, end_date, source, match_key, ignored, active, user_edited), update (kind, type, description, amount, day_of_month, category, account_id, installment_current, installment_total, start_date, end_date, match_key, ignored, active, user_edited), delete on public.recurrings to authenticated; grant insert (workspace_id, category_id, match_text, match_key, operator, priority, active), update (category_id, match_text, match_key, operator, priority, active), delete on public.category_rules to authenticated; grant insert (workspace_id, month, monthly_limit, fixed_cost, monthly_savings, expected_salary, expected_freelance), update (monthly_limit, fixed_cost, monthly_savings, expected_salary, expected_freelance) on public.plan_months to authenticated; create function public.contribute_to_goal(goal_id text, contribution bigint) returns text language sql security invoker set search_path = '' as $$ update public.goals set current = current + contribution where id = goal_id and contribution between 1 and 100000000000 and workspace_id in (select id from public.finance_spaces where personal_owner_id = (select auth.uid())) returning id; $$; revoke all on function public.contribute_to_goal(text, bigint) from public, anon; grant execute on function public.contribute_to_goal(text, bigint) to authenticated; grant insert (image_slug), update (name, color, image_slug), delete on public.categories to authenticated; create policy update_personal_categories on public.categories for update to authenticated using (workspace_id in (select id from public.finance_spaces where personal_owner_id = (select auth.uid()))) with check ( workspace_id in (select id from public.finance_spaces where personal_owner_id = (select auth.uid())) and char_length(trim(name)) between 1 and 80 and name = trim(name) and color ~ '^#[0-9a-fA-F]{6}$' ); create policy delete_personal_categories on public.categories for delete to authenticated using (workspace_id in (select id from public.finance_spaces where personal_owner_id = (select auth.uid()))); create function public.keep_category_references() returns trigger language plpgsql security definer set search_path = '' as $$ begin if tg_op = 'UPDATE' and old.name = new.name then return new; end if; if old.name = 'Sem categoria' then raise exception 'A categoria padrão precisa ser mantida.' using errcode = '23514'; end if; if tg_op = 'DELETE' then if exists (select from public.transactions where workspace_id = old.workspace_id and category = old.name) or exists (select from public.goals where workspace_id = old.workspace_id and category = old.name) or exists (select from public.recurrings where workspace_id = old.workspace_id and category = old.name) then raise exception 'A categoria está em uso.' using errcode = '23503'; end if; return old; end if; update public.transactions set category = new.name where workspace_id = old.workspace_id and category = old.name; update public.goals set category = new.name where workspace_id = old.workspace_id and category = old.name; update public.recurrings set category = new.name where workspace_id = old.workspace_id and category = old.name; return new; end; $$; revoke all on function public.keep_category_references() from public, anon, authenticated; create trigger keep_category_references before update of name or delete on public.categories for each row execute function public.keep_category_references(); grant insert (account_id), update (account_id) on public.transactions to authenticated; drop policy update_personal_transactions on public.transactions; create policy update_personal_transactions on public.transactions for update to authenticated using ( source = 'manual' and currency = 'BRL' and workspace_id in (select id from public.finance_spaces where personal_owner_id = (select auth.uid())) ) with check ( source = 'manual' and currency = 'BRL' and workspace_id in (select id from public.finance_spaces where personal_owner_id = (select auth.uid())) and char_length(trim(description)) between 1 and 160 and amount between 1 and 100000000000 and (category = 'Sem categoria' or exists ( select from public.categories c where c.workspace_id = transactions.workspace_id and c.name = transactions.category )) ); drop policy delete_personal_transactions on public.transactions; create policy delete_personal_transactions on public.transactions for delete to authenticated using ( source = 'manual' and currency = 'BRL' and workspace_id in (select id from public.finance_spaces where personal_owner_id = (select auth.uid())) ); create function public.save_finance_plan( plan_month date, plan_limit bigint, plan_fixed bigint, plan_savings bigint, plan_salary bigint, plan_freelance bigint ) returns uuid language sql security invoker set search_path = '' as $$ insert into public.plan_months (workspace_id, month, monthly_limit, fixed_cost, monthly_savings, expected_salary, expected_freelance) select id, plan_month, plan_limit, plan_fixed, plan_savings, plan_salary, plan_freelance from public.finance_spaces where personal_owner_id = (select auth.uid()) on conflict (workspace_id, month) do update set monthly_limit = excluded.monthly_limit, fixed_cost = excluded.fixed_cost, monthly_savings = excluded.monthly_savings, expected_salary = excluded.expected_salary, expected_freelance = excluded.expected_freelance returning workspace_id; $$; revoke all on function public.save_finance_plan(date, bigint, bigint, bigint, bigint, bigint) from public, anon; grant execute on function public.save_finance_plan(date, bigint, bigint, bigint, bigint, bigint) to authenticated; grant select (id, workspace_id, name, status, last_sync, error, consent_expires_at) on public.connections to authenticated; create policy personal_connections on public.connections for select to authenticated using (workspace_id in (select id from public.finance_spaces where personal_owner_id = (select auth.uid()))); create unique index pluggy_single_owner on public.connections (id); create function public.apply_pluggy_snapshot( owner_id uuid, space_id uuid, item_id text, item_name text, item_status text, consent_expires timestamptz, account_rows jsonb, transaction_rows jsonb, investment_rows jsonb ) returns void language plpgsql security definer set search_path = '' as $$ begin if not exists (select from public.finance_spaces where id = space_id and personal_owner_id = owner_id) then raise exception 'Espaço indisponível.' using errcode = '42501'; end if; insert into public.connections (workspace_id,id,name,status,last_sync,consent_expires_at) values (space_id,item_id,item_name,item_status,now(),consent_expires) on conflict (workspace_id,id) do update set status = excluded.status, last_sync = excluded.last_sync, error = null, consent_expires_at = excluded.consent_expires_at; insert into public.accounts (workspace_id,id,name,institution,type,balance,currency,item_id,available_credit_limit,credit_limit) select space_id, row.id, row.name, row.institution, row.type, row.balance, row.currency, apply_pluggy_snapshot.item_id, row.available_credit_limit, row.credit_limit from jsonb_to_recordset(account_rows) as row(id text, name text, institution text, type text, balance bigint, currency text, available_credit_limit bigint, credit_limit bigint) on conflict (workspace_id,id) do update set name = excluded.name, institution = excluded.institution, type = excluded.type, balance = excluded.balance, currency = excluded.currency, available_credit_limit = excluded.available_credit_limit, credit_limit = excluded.credit_limit where accounts.item_id = excluded.item_id; insert into public.transactions (workspace_id,id,description,amount,kind,date,status,category,account_id,source,currency,installment_number,installment_total) select space_id,row.id,row.description,row.amount,row.kind,row.date,row.status,'Sem categoria', row.account_id,'pluggy',row.currency,row.installment_number,row.installment_total from jsonb_to_recordset(transaction_rows) as row(id text, description text, amount bigint, kind text, date date, status text, account_id text, currency text, installment_number integer, installment_total integer) join public.accounts a on a.workspace_id = space_id and a.id = row.account_id and a.item_id = apply_pluggy_snapshot.item_id on conflict (workspace_id,id) do update set description = excluded.description, amount = excluded.amount, kind = case when transactions.user_categorized = 1 then transactions.kind else excluded.kind end, date = excluded.date, status = excluded.status, currency = excluded.currency, installment_number = excluded.installment_number, installment_total = excluded.installment_total where transactions.source = 'pluggy' and transactions.account_id = excluded.account_id; insert into public.investments (workspace_id,id,name,institution,type,balance,invested,currency,source,item_id) select space_id,row.id,row.name,row.institution,row.type,row.balance,row.invested,row.currency,'pluggy',apply_pluggy_snapshot.item_id from jsonb_to_recordset(coalesce(nullif(investment_rows, 'null'::jsonb), '[]'::jsonb)) as row(id text, name text, institution text, type text, balance bigint, invested bigint, currency text) on conflict (workspace_id,id) do update set name = excluded.name, institution = excluded.institution, type = excluded.type, balance = excluded.balance, invested = coalesce(excluded.invested, investments.invested), currency = excluded.currency where investments.source = 'pluggy' and investments.item_id = excluded.item_id; end; $$; revoke all on function public.apply_pluggy_snapshot(uuid, uuid, text, text, text, timestamptz, jsonb, jsonb, jsonb) from public, anon, authenticated; grant execute on function public.apply_pluggy_snapshot(uuid, uuid, text, text, text, timestamptz, jsonb, jsonb, jsonb) to service_role; -- 20261127070000_personal_category_defaults.sql alter table public.finance_spaces add column categories_initialized boolean not null default false; create function public.initialize_personal_categories() returns void language plpgsql security definer set search_path = '' as $$ declare space_id uuid; begin if (auth.jwt()->>'aal') is distinct from 'aal2' then raise exception 'Verificação em duas etapas necessária'; end if; update public.finance_spaces set categories_initialized = true where personal_owner_id = auth.uid() and not categories_initialized returning id into space_id; if space_id is null then return; end if; insert into public.categories (workspace_id, name, color, image_slug, sort_order) select space_id, name, color, image_slug, sort_order from (values ('Alimentação', '#EF4444', 'compras-mercado', 0), ('Restaurantes', '#F97316', 'alimentacao', 1), ('Transporte', '#0891B2', 'transporte', 2), ('Saúde', '#FB7185', 'saude', 3), ('Barbeiro', '#C084FC', 'barbeiro', 4), ('Pets', '#F59E0B', 'pets', 5), ('Contas da casa', '#3B82F6', 'contas-da-casa', 6), ('Assinaturas', '#8B5CF6', 'assinaturas', 7), ('Software', '#DB2777', 'software', 8), ('Compras', '#22C55E', 'compras', 9), ('Jogos', '#A855F7', 'jogos', 10), ('Educação', '#6366F1', 'educacao', 11), ('Taxas', '#64748B', 'taxas', 12), ('Investimentos', '#10B981', 'investimentos', 13), ('Transferências', '#94A3B8', 'transferencias', 14), ('Sem categoria', '#94A3B8', 'sem-categoria', 15) ) as defaults(name, color, image_slug, sort_order) on conflict (workspace_id, name) do nothing; end; $$; revoke all on function public.initialize_personal_categories() from public, anon; grant execute on function public.initialize_personal_categories() to authenticated; commit;