broke: a private money app that runs on your own accounts and your own AI
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
f550865e93
359 files changed
+34290
No files matched your search
@@ -0,0 +1,131 @@
|
||||
-- broke: core schema. Every row belongs to auth.uid(); Plaid access tokens are never readable by the browser.
|
||||
|
||||
create table public.categories (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
user_id uuid references auth.users on delete cascade, -- null = built-in
|
||||
key text not null,
|
||||
label text not null,
|
||||
icon text not null,
|
||||
color text not null,
|
||||
kind text not null check (kind in ('spend', 'income', 'transfer')),
|
||||
unique (user_id, key)
|
||||
);
|
||||
|
||||
create table public.plaid_items (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
user_id uuid not null references auth.users on delete cascade,
|
||||
plaid_item_id text not null unique,
|
||||
access_token text not null,
|
||||
institution_id text,
|
||||
institution_name text,
|
||||
institution_logo text,
|
||||
institution_color text,
|
||||
cursor text,
|
||||
status text not null default 'ok',
|
||||
last_synced_at timestamptz,
|
||||
created_at timestamptz not null default now()
|
||||
);
|
||||
|
||||
create table public.accounts (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
user_id uuid not null references auth.users on delete cascade,
|
||||
item_id uuid not null references public.plaid_items on delete cascade,
|
||||
plaid_account_id text not null unique,
|
||||
name text not null,
|
||||
official_name text,
|
||||
mask text,
|
||||
type text not null,
|
||||
subtype text,
|
||||
current_balance numeric,
|
||||
available_balance numeric,
|
||||
credit_limit numeric,
|
||||
currency text default 'USD',
|
||||
included boolean not null default true
|
||||
);
|
||||
|
||||
create table public.transactions (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
user_id uuid not null references auth.users on delete cascade,
|
||||
account_id uuid not null references public.accounts on delete cascade,
|
||||
plaid_transaction_id text not null unique,
|
||||
date date not null,
|
||||
amount numeric not null, -- Plaid sign: positive = money out
|
||||
name text not null,
|
||||
merchant_name text,
|
||||
logo_url text,
|
||||
pending boolean not null default false,
|
||||
plaid_category text,
|
||||
category_id uuid references public.categories on delete set null,
|
||||
custom_name text,
|
||||
note text,
|
||||
ignored boolean not null default false,
|
||||
tax_deductible boolean not null default false
|
||||
);
|
||||
create index on public.transactions (user_id, date desc);
|
||||
|
||||
create table public.recurring (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
user_id uuid not null references auth.users on delete cascade,
|
||||
plaid_stream_id text not null unique,
|
||||
account_id uuid references public.accounts on delete cascade,
|
||||
merchant_name text not null,
|
||||
logo_url text,
|
||||
frequency text not null,
|
||||
average_amount numeric not null,
|
||||
last_amount numeric,
|
||||
last_date date,
|
||||
next_date date,
|
||||
is_income boolean not null default false,
|
||||
active boolean not null default true,
|
||||
status text,
|
||||
category_id uuid references public.categories on delete set null
|
||||
);
|
||||
|
||||
alter table public.categories enable row level security;
|
||||
alter table public.plaid_items enable row level security;
|
||||
alter table public.accounts enable row level security;
|
||||
alter table public.transactions enable row level security;
|
||||
alter table public.recurring enable row level security;
|
||||
|
||||
create policy "read built-in and own" on public.categories for select to authenticated
|
||||
using (user_id is null or user_id = (select auth.uid()));
|
||||
create policy "write own" on public.categories for all to authenticated
|
||||
using (user_id = (select auth.uid())) with check (user_id = (select auth.uid()));
|
||||
create policy "own" on public.plaid_items for select to authenticated using (user_id = (select auth.uid()));
|
||||
create policy "own" on public.accounts for all to authenticated
|
||||
using (user_id = (select auth.uid())) with check (user_id = (select auth.uid()));
|
||||
create policy "own" on public.transactions for all to authenticated
|
||||
using (user_id = (select auth.uid())) with check (user_id = (select auth.uid()));
|
||||
create policy "own" on public.recurring for all to authenticated
|
||||
using (user_id = (select auth.uid())) with check (user_id = (select auth.uid()));
|
||||
|
||||
-- "Expose new tables" is off, so grant exactly what the browser may touch.
|
||||
grant select, insert, update, delete on public.categories to authenticated;
|
||||
grant select (id, user_id, institution_name, institution_logo, institution_color, status, last_synced_at, created_at)
|
||||
on public.plaid_items to authenticated; -- no access_token, no cursor
|
||||
grant select, update (included, name) on public.accounts to authenticated;
|
||||
grant select, update (category_id, custom_name, note, ignored, tax_deductible) on public.transactions to authenticated;
|
||||
grant select, update (active, category_id) on public.recurring to authenticated;
|
||||
grant all on all tables in schema public to service_role;
|
||||
|
||||
-- Built-in categories keyed on Plaid personal_finance_category.primary (groceries split out of food).
|
||||
insert into public.categories (key, label, icon, color, kind) values
|
||||
('INCOME', 'Income', 'income', '#16a34a', 'income'),
|
||||
('TRANSFER_IN', 'Transfers in', 'transfer', '#64748b', 'transfer'),
|
||||
('TRANSFER_OUT', 'Transfers out', 'transfer', '#64748b', 'transfer'),
|
||||
('CREDIT_CARD_PAYMENT', 'Credit card payment', 'credit_card', '#64748b', 'transfer'),
|
||||
('LOAN_PAYMENTS', 'Loan payments', 'loan', '#7c3aed', 'spend'),
|
||||
('BANK_FEES', 'Fees', 'fees', '#dc2626', 'spend'),
|
||||
('ENTERTAINMENT', 'Entertainment', 'entertainment', '#db2777', 'spend'),
|
||||
('FOOD_AND_DRINK', 'Dining & drinks', 'dining', '#ea580c', 'spend'),
|
||||
('GROCERIES', 'Groceries', 'groceries', '#65a30d', 'spend'),
|
||||
('GENERAL_MERCHANDISE', 'Shopping', 'shopping', '#2563eb', 'spend'),
|
||||
('HOME_IMPROVEMENT', 'Home', 'home', '#a16207', 'spend'),
|
||||
('MEDICAL', 'Health', 'health', '#e11d48', 'spend'),
|
||||
('PERSONAL_CARE', 'Personal care', 'personal_care', '#c026d3', 'spend'),
|
||||
('GENERAL_SERVICES', 'Services', 'services', '#0891b2', 'spend'),
|
||||
('GOVERNMENT_AND_NON_PROFIT', 'Taxes & giving', 'taxes', '#4f46e5', 'spend'),
|
||||
('TRANSPORTATION', 'Auto & transport', 'transport', '#0284c7', 'spend'),
|
||||
('TRAVEL', 'Travel', 'travel', '#0d9488', 'spend'),
|
||||
('RENT_AND_UTILITIES', 'Bills & utilities', 'bills', '#9333ea', 'spend'),
|
||||
('OTHER', 'Other', 'other', '#78716c', 'spend');
|
||||
@@ -0,0 +1,10 @@
|
||||
-- Supabase default privileges gave anon/authenticated full table access, which made the column grants in 0001 moot.
|
||||
revoke all on all tables in schema public from anon, authenticated;
|
||||
alter default privileges in schema public revoke all on tables from anon, authenticated;
|
||||
|
||||
grant select, insert, update, delete on public.categories to authenticated;
|
||||
grant select (id, user_id, institution_name, institution_logo, institution_color, status, last_synced_at, created_at)
|
||||
on public.plaid_items to authenticated;
|
||||
grant select, update (included, name) on public.accounts to authenticated;
|
||||
grant select, update (category_id, custom_name, note, ignored, tax_deductible) on public.transactions to authenticated;
|
||||
grant select, update (active, category_id) on public.recurring to authenticated;
|
||||
@@ -0,0 +1,51 @@
|
||||
-- broke: saved AI chats and bookmarks. Same rules as 0001/0002: owner-only RLS, explicit grants.
|
||||
|
||||
create table public.chat_threads (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
user_id uuid not null references auth.users on delete cascade,
|
||||
title text not null,
|
||||
provider text,
|
||||
model text,
|
||||
created_at timestamptz not null default now(),
|
||||
updated_at timestamptz not null default now()
|
||||
);
|
||||
create index on public.chat_threads (user_id, updated_at desc);
|
||||
|
||||
create table public.chat_messages (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
thread_id uuid not null references public.chat_threads on delete cascade,
|
||||
user_id uuid not null references auth.users on delete cascade,
|
||||
role text not null check (role in ('user', 'assistant')),
|
||||
content text not null,
|
||||
created_at timestamptz not null default now()
|
||||
);
|
||||
create index on public.chat_messages (thread_id, created_at);
|
||||
|
||||
create table public.bookmarks (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
user_id uuid not null references auth.users on delete cascade,
|
||||
kind text not null default 'page' check (kind in ('page', 'transaction')),
|
||||
href text not null check (href like '/%'), -- in-app paths only, never external URLs
|
||||
label text not null,
|
||||
created_at timestamptz not null default now(),
|
||||
unique (user_id, href)
|
||||
);
|
||||
create index on public.bookmarks (user_id, created_at desc);
|
||||
|
||||
alter table public.chat_threads enable row level security;
|
||||
alter table public.chat_messages enable row level security;
|
||||
alter table public.bookmarks enable row level security;
|
||||
|
||||
create policy "own" on public.chat_threads for all to authenticated
|
||||
using (user_id = (select auth.uid())) with check (user_id = (select auth.uid()));
|
||||
-- A message must belong to the user AND sit in one of their own threads.
|
||||
create policy "own" on public.chat_messages for all to authenticated
|
||||
using (user_id = (select auth.uid()))
|
||||
with check (user_id = (select auth.uid()) and exists (select 1 from public.chat_threads t where t.id = thread_id and t.user_id = (select auth.uid())));
|
||||
create policy "own" on public.bookmarks for all to authenticated
|
||||
using (user_id = (select auth.uid())) with check (user_id = (select auth.uid()));
|
||||
|
||||
grant select, insert, update (title, updated_at), delete on public.chat_threads to authenticated;
|
||||
grant select, insert, delete on public.chat_messages to authenticated;
|
||||
grant select, insert, update (label), delete on public.bookmarks to authenticated;
|
||||
grant all on public.chat_threads, public.chat_messages, public.bookmarks to service_role;
|
||||
@@ -0,0 +1,13 @@
|
||||
-- Budgets: one monthly amount per category per user.
|
||||
create table public.budgets (
|
||||
user_id uuid not null references auth.users on delete cascade,
|
||||
category_id uuid not null references public.categories on delete cascade,
|
||||
amount numeric not null check (amount >= 0),
|
||||
updated_at timestamptz not null default now(),
|
||||
primary key (user_id, category_id)
|
||||
);
|
||||
alter table public.budgets enable row level security;
|
||||
create policy "own" on public.budgets for all to authenticated
|
||||
using (user_id = (select auth.uid())) with check (user_id = (select auth.uid()));
|
||||
grant select, insert, update, delete on public.budgets to authenticated;
|
||||
grant all on public.budgets to service_role;
|
||||
@@ -0,0 +1,3 @@
|
||||
-- The Claude Code session behind a chat, so the next message (and "Open in Terminal") resumes it.
|
||||
alter table public.chat_threads add column if not exists cli_session_id text;
|
||||
grant update (cli_session_id) on public.chat_threads to authenticated;
|
||||
@@ -0,0 +1,21 @@
|
||||
-- Investment holdings (brokerage, IRA, 401(k), HSA) from Plaid Investments. Replaced on every sync.
|
||||
create table if not exists public.holdings (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
user_id uuid not null references auth.users on delete cascade,
|
||||
account_id uuid not null references public.accounts on delete cascade,
|
||||
security_id text not null,
|
||||
name text,
|
||||
ticker text,
|
||||
type text,
|
||||
quantity numeric,
|
||||
price numeric,
|
||||
value numeric,
|
||||
cost_basis numeric,
|
||||
updated_at timestamptz not null default now(),
|
||||
unique (account_id, security_id)
|
||||
);
|
||||
alter table public.holdings enable row level security;
|
||||
create policy "own" on public.holdings for all to authenticated
|
||||
using (user_id = (select auth.uid())) with check (user_id = (select auth.uid()));
|
||||
grant select on public.holdings to authenticated;
|
||||
grant all on public.holdings to service_role;
|
||||
@@ -0,0 +1,18 @@
|
||||
-- Investment transactions (buys, sells, contributions) from Plaid Investments. Feeds contribution tracking.
|
||||
create table if not exists public.investment_transactions (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
user_id uuid not null references auth.users on delete cascade,
|
||||
account_id uuid not null references public.accounts on delete cascade,
|
||||
plaid_investment_transaction_id text not null unique,
|
||||
date date not null,
|
||||
name text,
|
||||
type text,
|
||||
subtype text,
|
||||
amount numeric,
|
||||
ticker text
|
||||
);
|
||||
alter table public.investment_transactions enable row level security;
|
||||
create policy "own" on public.investment_transactions for all to authenticated
|
||||
using (user_id = (select auth.uid())) with check (user_id = (select auth.uid()));
|
||||
grant select on public.investment_transactions to authenticated;
|
||||
grant all on public.investment_transactions to service_role;
|
||||
@@ -0,0 +1,15 @@
|
||||
-- Weekly check-ins broke AI writes on its own: the facts found in code, plus the AI's short summary of them.
|
||||
create table if not exists public.checkins (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
user_id uuid not null references auth.users on delete cascade,
|
||||
created_at timestamptz not null default now(),
|
||||
facts jsonb not null,
|
||||
summary text,
|
||||
provider text
|
||||
);
|
||||
create index if not exists checkins_user_created on public.checkins (user_id, created_at desc);
|
||||
alter table public.checkins enable row level security;
|
||||
create policy "own" on public.checkins for all to authenticated
|
||||
using (user_id = (select auth.uid())) with check (user_id = (select auth.uid()));
|
||||
grant select, insert on public.checkins to authenticated;
|
||||
grant all on public.checkins to service_role;
|
||||
@@ -0,0 +1,78 @@
|
||||
-- broke: partner sharing. An owner marks accounts as shared and invites a partner by link.
|
||||
-- The partner reads shared accounts and their transactions, recurring charges and holdings. Never writes, never plaid_items.
|
||||
|
||||
alter table public.accounts add column if not exists shared boolean not null default false;
|
||||
grant update (shared) on public.accounts to authenticated;
|
||||
|
||||
create table public.shares (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
owner_id uuid not null default auth.uid() references auth.users on delete cascade,
|
||||
owner_email text default (auth.jwt() ->> 'email'), -- the label the partner sees
|
||||
partner_email text not null check (partner_email like '%_@_%'),
|
||||
partner_id uuid references auth.users on delete cascade, -- set on accept
|
||||
token text not null unique default replace(gen_random_uuid()::text || gen_random_uuid()::text, '-', ''),
|
||||
expires_at timestamptz not null default now() + interval '7 days',
|
||||
accepted_at timestamptz,
|
||||
created_at timestamptz not null default now()
|
||||
);
|
||||
create index on public.shares (owner_id);
|
||||
create index on public.shares (partner_id);
|
||||
alter table public.shares enable row level security;
|
||||
|
||||
create policy "owner or partner reads" on public.shares for select to authenticated
|
||||
using (owner_id = (select auth.uid()) or partner_id = (select auth.uid()));
|
||||
create policy "owner invites" on public.shares for insert to authenticated
|
||||
with check (owner_id = (select auth.uid()));
|
||||
create policy "either side ends" on public.shares for delete to authenticated
|
||||
using (owner_id = (select auth.uid()) or partner_id = (select auth.uid()));
|
||||
-- Only the email is client-set; owner, label, token and acceptance come from defaults and accept_share.
|
||||
grant select, delete on public.shares to authenticated;
|
||||
grant insert (partner_email) on public.shares to authenticated;
|
||||
grant all on public.shares to service_role;
|
||||
|
||||
-- Account ids the caller may read as a partner. Definer so the policies below don't recurse through accounts RLS.
|
||||
create function public.shared_account_ids() returns setof uuid
|
||||
language sql stable security definer set search_path = '' as $$
|
||||
select a.id from public.accounts a join public.shares s on s.owner_id = a.user_id
|
||||
where a.shared and s.accepted_at is not null and s.partner_id = (select auth.uid())
|
||||
$$;
|
||||
|
||||
-- Read-only: SELECT policies only. The "own" policies still gate every write.
|
||||
create policy "partner reads shared" on public.accounts for select to authenticated
|
||||
using (id in (select public.shared_account_ids()));
|
||||
create policy "partner reads shared" on public.transactions for select to authenticated
|
||||
using (account_id in (select public.shared_account_ids()));
|
||||
create policy "partner reads shared" on public.recurring for select to authenticated
|
||||
using (account_id in (select public.shared_account_ids()));
|
||||
create policy "partner reads shared" on public.holdings for select to authenticated
|
||||
using (account_id in (select public.shared_account_ids()));
|
||||
|
||||
-- Accepts an invite as the signed-in user. The invite must be unused, unexpired, someone else's, and for this email.
|
||||
create function public.accept_share(invite text) returns text
|
||||
language plpgsql security definer set search_path = '' as $$
|
||||
declare who text;
|
||||
begin
|
||||
update public.shares set partner_id = auth.uid(), accepted_at = now()
|
||||
where token = invite and accepted_at is null and expires_at > now()
|
||||
and owner_id <> auth.uid() and lower(partner_email) = lower(auth.jwt() ->> 'email')
|
||||
returning coalesce(owner_email, '') into who;
|
||||
if not found then raise exception 'invite not valid' using errcode = 'P0002'; end if;
|
||||
return who;
|
||||
end $$;
|
||||
|
||||
-- Computed columns (select "owner_label" / "institution_name" on accounts).
|
||||
-- owner_label: the owner's email on accounts shared with the caller, null on the caller's own.
|
||||
create function public.owner_label(public.accounts) returns text
|
||||
language sql stable set search_path = '' as $$
|
||||
select s.owner_email from public.shares s
|
||||
where s.owner_id = $1.user_id and s.partner_id = (select auth.uid()) and s.accepted_at is not null limit 1
|
||||
$$;
|
||||
-- institution_name: plaid_items stays unreadable to partners, so only this one field crosses over.
|
||||
create function public.institution_name(public.accounts) returns text
|
||||
language sql stable security definer set search_path = '' as $$
|
||||
select i.institution_name from public.accounts a join public.plaid_items i on i.id = a.item_id
|
||||
where a.id = $1.id and (a.user_id = (select auth.uid()) or a.id in (select public.shared_account_ids()))
|
||||
$$;
|
||||
|
||||
revoke execute on function public.shared_account_ids(), public.accept_share(text), public.owner_label(public.accounts), public.institution_name(public.accounts) from public, anon;
|
||||
grant execute on function public.shared_account_ids(), public.accept_share(text), public.owner_label(public.accounts), public.institution_name(public.accounts) to authenticated;
|
||||
@@ -0,0 +1,20 @@
|
||||
-- Rules: when a transaction's merchant or name contains `match` (and its amount is in range), set its category,
|
||||
-- rename it, hide it from totals, or add tags (transactions.tags, 0011). Applied to new transactions on sync, and to past ones when a rule is saved.
|
||||
create table if not exists public.rules (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
user_id uuid not null default auth.uid() references auth.users on delete cascade,
|
||||
match text not null check (length(trim(match)) > 0),
|
||||
amount_min numeric check (amount_min >= 0),
|
||||
amount_max numeric check (amount_max >= 0),
|
||||
category_id uuid references public.categories on delete cascade,
|
||||
rename text,
|
||||
ignore boolean,
|
||||
add_tags text[],
|
||||
created_at timestamptz not null default now(),
|
||||
check (category_id is not null or rename is not null or ignore is not null or cardinality(add_tags) > 0)
|
||||
);
|
||||
alter table public.rules enable row level security;
|
||||
create policy "own" on public.rules for all to authenticated
|
||||
using (user_id = (select auth.uid())) with check (user_id = (select auth.uid()));
|
||||
grant select, insert, update, delete on public.rules to authenticated;
|
||||
grant all on public.rules to service_role;
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Tags: free-form labels on transactions ("vacation", "work trip"), set by hand or by a rule.
|
||||
alter table public.transactions add column if not exists tags text[] not null default '{}';
|
||||
create index if not exists transactions_tags_idx on public.transactions using gin (tags);
|
||||
grant update (tags) on public.transactions to authenticated;
|
||||
@@ -0,0 +1,22 @@
|
||||
-- Manual accounts and transactions: cash, a bank Plaid can't reach, anything typed in by hand.
|
||||
-- Manual rows have no Plaid ids. Users can add and delete only manual rows, and only on their own accounts.
|
||||
alter table public.accounts alter column item_id drop not null;
|
||||
alter table public.accounts alter column plaid_account_id drop not null;
|
||||
alter table public.accounts alter column user_id set default auth.uid();
|
||||
alter table public.accounts add column if not exists manual boolean not null default false;
|
||||
|
||||
alter table public.transactions alter column plaid_transaction_id drop not null;
|
||||
alter table public.transactions alter column user_id set default auth.uid();
|
||||
alter table public.transactions add column if not exists manual boolean not null default false;
|
||||
|
||||
grant insert (name, type, subtype, current_balance, manual) on public.accounts to authenticated;
|
||||
grant delete on public.accounts to authenticated;
|
||||
grant insert (account_id, date, amount, name, merchant_name, category_id, note, tags, ignored, manual) on public.transactions to authenticated;
|
||||
grant delete on public.transactions to authenticated;
|
||||
|
||||
-- Restrictive: on top of the "own" policies. Plaid-synced rows can't be created or deleted from the app.
|
||||
create policy "manual accounts only" on public.accounts as restrictive for insert to authenticated with check (manual);
|
||||
create policy "delete manual accounts only" on public.accounts as restrictive for delete to authenticated using (manual);
|
||||
create policy "manual on own account" on public.transactions as restrictive for insert to authenticated
|
||||
with check (manual and account_id in (select id from public.accounts where user_id = (select auth.uid())));
|
||||
create policy "delete manual only" on public.transactions as restrictive for delete to authenticated using (manual);
|
||||
@@ -0,0 +1,40 @@
|
||||
-- broke: hardening from the 2026-10-22 audit. Safe on existing data.
|
||||
|
||||
-- Renames survive sync: Plaid owns accounts.name, the user owns custom_name. Show coalesce(custom_name, name).
|
||||
alter table public.accounts add column if not exists custom_name text;
|
||||
revoke update (name) on public.accounts from authenticated;
|
||||
grant update (custom_name) on public.accounts to authenticated;
|
||||
|
||||
-- Broken connections: status holds Plaid's error_code (ITEM_LOGIN_REQUIRED...), error its message.
|
||||
alter table public.plaid_items add column if not exists error text;
|
||||
grant select (error) on public.plaid_items to authenticated;
|
||||
|
||||
-- A row may only point at a built-in category or one owned by the row's user.
|
||||
create or replace function public.check_category_owner() returns trigger
|
||||
language plpgsql security definer set search_path = '' as $$
|
||||
begin
|
||||
if new.category_id is not null and not exists (
|
||||
select 1 from public.categories c where c.id = new.category_id and (c.user_id is null or c.user_id = new.user_id)
|
||||
) then
|
||||
raise exception 'category not found' using errcode = '23503';
|
||||
end if;
|
||||
return new;
|
||||
end $$;
|
||||
revoke execute on function public.check_category_owner() from public, anon, authenticated;
|
||||
|
||||
drop trigger if exists category_owner on public.budgets;
|
||||
create trigger category_owner before insert or update of category_id, user_id on public.budgets for each row execute function public.check_category_owner();
|
||||
drop trigger if exists category_owner on public.rules;
|
||||
create trigger category_owner before insert or update of category_id, user_id on public.rules for each row execute function public.check_category_owner();
|
||||
drop trigger if exists category_owner on public.transactions;
|
||||
create trigger category_owner before insert or update of category_id, user_id on public.transactions for each row execute function public.check_category_owner();
|
||||
drop trigger if exists category_owner on public.recurring;
|
||||
create trigger category_owner before insert or update of category_id, user_id on public.recurring for each row execute function public.check_category_owner();
|
||||
|
||||
-- Check-ins are written by the server (admin client) only.
|
||||
revoke insert on public.checkins from authenticated;
|
||||
|
||||
-- Bookmarks: in-app paths only. "//host" and "/\host" are protocol-relative URLs to the browser.
|
||||
delete from public.bookmarks where href !~ '^/([^/\\]|$)';
|
||||
alter table public.bookmarks drop constraint if exists bookmarks_href_local;
|
||||
alter table public.bookmarks add constraint bookmarks_href_local check (href ~ '^/([^/\\]|$)');
|
||||
@@ -0,0 +1,98 @@
|
||||
-- broke: money totals in SQL (PostgREST returns at most 1000 rows, so totals over fetched rows undercount), manual balances, indexes.
|
||||
-- Every function is security invoker (RLS still applies) and counts only the caller's own rows: partner-shared rows
|
||||
-- are readable, but never the viewer's money.
|
||||
|
||||
-- One row per own transaction with its spend and income share. Same rules as isSpend / isIncome in src/lib/data.ts:
|
||||
-- not ignored, on an included account; spend = money out on a spend category, income = minus the amount on an income
|
||||
-- category (so income is positive). No category: money out counts as spend under Other, money in as income under Income.
|
||||
create or replace function public.money_rows(start_date date, end_date date default null)
|
||||
returns table (date date, category_id uuid, spend numeric, income numeric)
|
||||
language sql stable set search_path = '' as $$
|
||||
with b as (
|
||||
select (select id from public.categories where user_id is null and key = 'OTHER') as other,
|
||||
(select id from public.categories where user_id is null and key = 'INCOME') as income
|
||||
), r as (
|
||||
select t.date, t.amount,
|
||||
coalesce(t.category_id, case when t.amount > 0 then b.other else b.income end) as category_id,
|
||||
not t.ignored and a.included as counted,
|
||||
coalesce(c.kind, case when t.amount > 0 then 'spend' else 'income' end) as kind
|
||||
from public.transactions t
|
||||
join public.accounts a on a.id = t.account_id
|
||||
left join public.categories c on c.id = t.category_id
|
||||
cross join b
|
||||
where t.user_id = (select auth.uid()) and t.date >= start_date and (end_date is null or t.date <= end_date)
|
||||
)
|
||||
select date, category_id,
|
||||
case when counted and kind = 'spend' and amount > 0 then amount else 0 end,
|
||||
case when counted and kind = 'income' then -amount else 0 end
|
||||
from r
|
||||
$$;
|
||||
|
||||
-- By month and category. n counts every own row in the group, counted or not (pages use it for "months of data").
|
||||
create or replace function public.money_by_month(start_date date, end_date date default null)
|
||||
returns table (month date, category_id uuid, spend numeric, income numeric, n bigint)
|
||||
language sql stable set search_path = '' as $$
|
||||
select date_trunc('month', date)::date, category_id, sum(spend), sum(income), count(*)
|
||||
from public.money_rows(start_date, end_date) group by 1, 2
|
||||
$$;
|
||||
|
||||
-- Spend per day (dashboard chart).
|
||||
create or replace function public.spend_by_day(start_date date, end_date date default null)
|
||||
returns table (day date, spend numeric)
|
||||
language sql stable set search_path = '' as $$
|
||||
select date, sum(spend) from public.money_rows(start_date, end_date) group by 1
|
||||
$$;
|
||||
|
||||
-- Transactions page: money out and in over the whole filter, own rows, without ignored rows and transfers.
|
||||
-- q is matched like the page's search (name, merchant or custom name contains it).
|
||||
create or replace function public.txn_totals(q text default null, cat uuid default null, acct uuid default null, tag text default null, start_date date default null)
|
||||
returns table (money_out numeric, money_in numeric)
|
||||
language sql stable set search_path = '' as $$
|
||||
select coalesce(sum(t.amount) filter (where t.amount > 0), 0), coalesce(-sum(t.amount) filter (where t.amount < 0), 0)
|
||||
from public.transactions t left join public.categories c on c.id = t.category_id
|
||||
where t.user_id = (select auth.uid()) and not t.ignored and c.kind is distinct from 'transfer'
|
||||
and (q is null or t.name ilike '%' || q || '%' or t.merchant_name ilike '%' || q || '%' or t.custom_name ilike '%' || q || '%')
|
||||
and (cat is null or t.category_id = cat)
|
||||
and (acct is null or t.account_id = acct)
|
||||
and (tag is null or t.tags @> array[tag])
|
||||
and (start_date is null or t.date >= start_date)
|
||||
$$;
|
||||
|
||||
-- Every tag on the caller's own transactions.
|
||||
create or replace function public.my_tags() returns setof text
|
||||
language sql stable set search_path = '' as $$
|
||||
select distinct unnest(tags) from public.transactions where user_id = (select auth.uid()) and tags <> '{}'
|
||||
$$;
|
||||
|
||||
-- Computed column (select "balance" on accounts): a manual account is its starting balance less its transactions,
|
||||
-- a linked one is what the bank says. One rule for every page.
|
||||
create or replace function public.balance(public.accounts) returns numeric
|
||||
language sql stable set search_path = '' as $$
|
||||
select case when $1.manual
|
||||
then coalesce($1.current_balance, 0) - coalesce((select sum(t.amount) from public.transactions t where t.account_id = $1.id), 0)
|
||||
else $1.current_balance end
|
||||
$$;
|
||||
|
||||
revoke execute on function public.money_rows(date, date), public.money_by_month(date, date), public.spend_by_day(date, date),
|
||||
public.txn_totals(text, uuid, uuid, text, date), public.my_tags(), public.balance(public.accounts) from public, anon;
|
||||
grant execute on function public.money_rows(date, date), public.money_by_month(date, date), public.spend_by_day(date, date),
|
||||
public.txn_totals(text, uuid, uuid, text, date), public.my_tags(), public.balance(public.accounts) to authenticated;
|
||||
|
||||
-- Indexes: the partner policy (account_id in shared ids), the totals above, and every unindexed foreign key.
|
||||
-- holdings(account_id) is already covered by unique (account_id, security_id); categories(user_id) by unique (user_id, key).
|
||||
create index if not exists transactions_account_date on public.transactions (account_id, date desc);
|
||||
create index if not exists transactions_user_category_date on public.transactions (user_id, category_id, date);
|
||||
create index if not exists transactions_category on public.transactions (category_id);
|
||||
create index if not exists recurring_account on public.recurring (account_id);
|
||||
create index if not exists recurring_user on public.recurring (user_id);
|
||||
create index if not exists recurring_category on public.recurring (category_id);
|
||||
create index if not exists accounts_user on public.accounts (user_id);
|
||||
create index if not exists accounts_item on public.accounts (item_id);
|
||||
create index if not exists plaid_items_user on public.plaid_items (user_id);
|
||||
create index if not exists holdings_user on public.holdings (user_id);
|
||||
create index if not exists investment_transactions_account_date on public.investment_transactions (account_id, date);
|
||||
create index if not exists investment_transactions_user on public.investment_transactions (user_id);
|
||||
create index if not exists chat_messages_user on public.chat_messages (user_id);
|
||||
create index if not exists budgets_category on public.budgets (category_id);
|
||||
create index if not exists rules_user on public.rules (user_id);
|
||||
create index if not exists rules_category on public.rules (category_id);
|
||||
@@ -0,0 +1,129 @@
|
||||
-- broke: money in more than one currency. Every account and transaction keeps its own currency; totals are in the
|
||||
-- user's home currency, converted at the ECB rate for that day (exchange_rates, filled by src/lib/fx.ts).
|
||||
-- A null currency means the home currency: manual accounts, and anything a bank sends without a code.
|
||||
|
||||
-- The home currency: profile.currency in the caller's auth metadata (the app writes it with profile.country), else USD.
|
||||
create or replace function public.home_currency() returns text
|
||||
language sql stable security definer set search_path = '' as $$
|
||||
select coalesce((select upper(u.raw_user_meta_data #>> '{profile,currency}') from auth.users u
|
||||
where u.id = (select auth.uid()) and u.raw_user_meta_data #>> '{profile,currency}' ~* '^[a-z]{3}$'), 'USD')
|
||||
$$;
|
||||
|
||||
-- Manual accounts are in the home currency, whatever it is now. They were 'USD' by default, which was home for everyone.
|
||||
alter table public.accounts alter column currency drop default;
|
||||
update public.accounts set currency = null where manual;
|
||||
|
||||
-- Transactions: the account's currency unless the row says otherwise.
|
||||
alter table public.transactions add column if not exists currency text;
|
||||
update public.transactions t set currency = a.currency from public.accounts a where a.id = t.account_id and t.currency is null;
|
||||
create or replace function public.txn_currency() returns trigger
|
||||
language plpgsql set search_path = '' as $$
|
||||
begin
|
||||
if new.currency is null then select a.currency into new.currency from public.accounts a where a.id = new.account_id; end if;
|
||||
return new;
|
||||
end $$;
|
||||
drop trigger if exists transactions_currency on public.transactions;
|
||||
create trigger transactions_currency before insert on public.transactions for each row execute function public.txn_currency();
|
||||
|
||||
-- ECB reference rates, one row per day and currency, all against EUR. Public data: anyone signed in reads, only the server writes.
|
||||
create table if not exists public.exchange_rates (
|
||||
date date not null,
|
||||
base text not null,
|
||||
quote text not null,
|
||||
rate numeric not null check (rate > 0),
|
||||
primary key (base, quote, date)
|
||||
);
|
||||
alter table public.exchange_rates enable row level security;
|
||||
drop policy if exists "read" on public.exchange_rates;
|
||||
create policy "read" on public.exchange_rates for select to authenticated using (true);
|
||||
grant select on public.exchange_rates to authenticated;
|
||||
grant all on public.exchange_rates to service_role;
|
||||
|
||||
-- Units of cur per euro on day d: the latest rate on or before d, else the first after (older than the stored history).
|
||||
create or replace function public.eur_rate(cur text, d date) returns numeric
|
||||
language sql stable set search_path = '' as $$
|
||||
select case when cur = 'EUR' then 1 else coalesce(
|
||||
(select r.rate from public.exchange_rates r where r.base = 'EUR' and r.quote = cur and r.date <= d order by r.date desc limit 1),
|
||||
(select r.rate from public.exchange_rates r where r.base = 'EUR' and r.quote = cur and r.date > d order by r.date limit 1)) end
|
||||
$$;
|
||||
|
||||
-- One src in dst on day d. Null when either has no rate: callers leave that money out, never add it unconverted.
|
||||
create or replace function public.fx(src text, dst text, d date) returns numeric
|
||||
language sql stable set search_path = '' as $$
|
||||
select case when src is null or src = dst then 1 else public.eur_rate(dst, d) / public.eur_rate(src, d) end
|
||||
$$;
|
||||
|
||||
-- money_rows (0014) in the home currency. Same rules otherwise; change both together with src/lib/data.ts.
|
||||
create or replace function public.money_rows(start_date date, end_date date default null)
|
||||
returns table (date date, category_id uuid, spend numeric, income numeric)
|
||||
language sql stable set search_path = '' as $$
|
||||
with b as (
|
||||
select (select id from public.categories where user_id is null and key = 'OTHER') as other,
|
||||
(select id from public.categories where user_id is null and key = 'INCOME') as income,
|
||||
public.home_currency() as home
|
||||
), r as (
|
||||
select t.date, t.amount * public.fx(coalesce(t.currency, a.currency, b.home), b.home, t.date) as amount,
|
||||
coalesce(t.category_id, case when t.amount > 0 then b.other else b.income end) as category_id,
|
||||
not t.ignored and a.included as counted,
|
||||
coalesce(c.kind, case when t.amount > 0 then 'spend' else 'income' end) as kind
|
||||
from public.transactions t
|
||||
join public.accounts a on a.id = t.account_id
|
||||
left join public.categories c on c.id = t.category_id
|
||||
cross join b
|
||||
where t.user_id = (select auth.uid()) and t.date >= start_date and (end_date is null or t.date <= end_date)
|
||||
)
|
||||
select date, category_id,
|
||||
case when counted and kind = 'spend' and amount > 0 then amount else 0 end,
|
||||
case when counted and kind = 'income' and amount is not null then -amount else 0 end
|
||||
from r
|
||||
$$;
|
||||
|
||||
-- txn_totals (0014) in the home currency.
|
||||
create or replace function public.txn_totals(q text default null, cat uuid default null, acct uuid default null, tag text default null, start_date date default null)
|
||||
returns table (money_out numeric, money_in numeric)
|
||||
language sql stable set search_path = '' as $$
|
||||
with h as (select public.home_currency() as home), r as (
|
||||
select t.amount * public.fx(coalesce(t.currency, a.currency, h.home), h.home, t.date) as amount
|
||||
from public.transactions t
|
||||
join public.accounts a on a.id = t.account_id
|
||||
left join public.categories c on c.id = t.category_id
|
||||
cross join h
|
||||
where t.user_id = (select auth.uid()) and not t.ignored and c.kind is distinct from 'transfer'
|
||||
and (q is null or t.name ilike '%' || q || '%' or t.merchant_name ilike '%' || q || '%' or t.custom_name ilike '%' || q || '%')
|
||||
and (cat is null or t.category_id = cat)
|
||||
and (acct is null or t.account_id = acct)
|
||||
and (tag is null or t.tags @> array[tag])
|
||||
and (start_date is null or t.date >= start_date)
|
||||
)
|
||||
select coalesce(sum(amount) filter (where amount > 0), 0), coalesce(-sum(amount) filter (where amount < 0), 0) from r
|
||||
$$;
|
||||
|
||||
-- Computed columns for totals: an account's balance and a recurring stream's average in the home currency, at today's rate.
|
||||
-- Null when there is no rate; fx_missing() says which currency.
|
||||
create or replace function public.home_balance(public.accounts) returns numeric
|
||||
language sql stable set search_path = '' as $$
|
||||
select public.balance($1) * public.fx(coalesce($1.currency, public.home_currency()), public.home_currency(), current_date)
|
||||
$$;
|
||||
create or replace function public.home_average(public.recurring) returns numeric
|
||||
language sql stable set search_path = '' as $$
|
||||
select $1.average_amount * public.fx(coalesce((select a.currency from public.accounts a where a.id = $1.account_id), public.home_currency()), public.home_currency(), current_date)
|
||||
$$;
|
||||
|
||||
-- The caller's currencies that totals leave out because there is no rate for them (or for the home currency).
|
||||
create or replace function public.fx_missing() returns setof text
|
||||
language sql stable set search_path = '' as $$
|
||||
with h as (select public.home_currency() as home), c as (
|
||||
select a.currency as cur from public.accounts a where a.user_id = (select auth.uid()) and a.currency is not null
|
||||
union
|
||||
select distinct t.currency from public.transactions t where t.user_id = (select auth.uid()) and t.currency is not null
|
||||
)
|
||||
select c.cur from c cross join h where c.cur <> h.home and public.fx(c.cur, h.home, current_date) is null
|
||||
$$;
|
||||
|
||||
revoke execute on function public.home_currency(), public.eur_rate(text, date), public.fx(text, text, date), public.home_balance(public.accounts),
|
||||
public.home_average(public.recurring), public.fx_missing() from public, anon;
|
||||
grant execute on function public.home_currency(), public.eur_rate(text, date), public.fx(text, text, date), public.home_balance(public.accounts),
|
||||
public.home_average(public.recurring), public.fx_missing() to authenticated;
|
||||
revoke execute on function public.txn_currency() from public, anon, authenticated;
|
||||
|
||||
create index if not exists transactions_user_currency on public.transactions (user_id, currency);
|
||||
@@ -0,0 +1,17 @@
|
||||
-- broke: bank connections beyond Plaid, and statement imports. Safe on existing data.
|
||||
|
||||
-- Which service a connection comes through. Every existing row is Plaid. Akahu connections read their tokens from
|
||||
-- the server's settings, so access_token may be empty for them.
|
||||
alter table public.plaid_items add column if not exists provider text not null default 'plaid';
|
||||
alter table public.plaid_items drop constraint if exists plaid_items_provider;
|
||||
alter table public.plaid_items add constraint plaid_items_provider check (provider in ('plaid', 'akahu'));
|
||||
alter table public.plaid_items alter column access_token drop not null;
|
||||
grant select (provider) on public.plaid_items to authenticated;
|
||||
|
||||
-- Statement imports: one key per row (date, amount, name, occurrence; or the bank's own id), unique per account,
|
||||
-- so importing the same file twice adds nothing. Rows stay manual = true, so 0012's insert and delete policies apply.
|
||||
alter table public.transactions add column if not exists import_key text;
|
||||
alter table public.transactions drop constraint if exists transactions_import_key;
|
||||
alter table public.transactions add constraint transactions_import_key unique (account_id, import_key);
|
||||
-- custom_name: a rule's rename applies to imported rows too.
|
||||
grant insert (import_key, custom_name) on public.transactions to authenticated;
|
||||
@@ -0,0 +1,25 @@
|
||||
-- Built-in category colours: one muted, distinct hue each, replacing stock Tailwind 600s.
|
||||
-- The UI draws a pale disc from the colour and the glyph in the colour itself.
|
||||
update public.categories c set color = v.color
|
||||
from (values
|
||||
('FOOD_AND_DRINK', '#c0662f'), -- terracotta
|
||||
('GROCERIES', '#b84a5e'), -- raspberry
|
||||
('GENERAL_MERCHANDISE', '#a87b2a'), -- mustard
|
||||
('TRANSPORTATION', '#2e7a8c'), -- petrol
|
||||
('TRAVEL', '#3d8a6e'), -- sea green
|
||||
('RENT_AND_UTILITIES', '#b08a1c'), -- ochre
|
||||
('ENTERTAINMENT', '#a24f7c'), -- plum
|
||||
('PERSONAL_CARE', '#b8708f'), -- dusty rose
|
||||
('MEDICAL', '#c0503f'), -- brick
|
||||
('HOME_IMPROVEMENT', '#8a6a45'), -- walnut
|
||||
('GENERAL_SERVICES', '#5a7392'), -- steel blue
|
||||
('LOAN_PAYMENTS', '#6d5d8f'), -- muted violet
|
||||
('GOVERNMENT_AND_NON_PROFIT', '#6b7340'), -- olive
|
||||
('BANK_FEES', '#9c4a3a'), -- rust
|
||||
('INCOME', '#3f8a52'), -- leaf
|
||||
('CREDIT_CARD_PAYMENT', '#6b7280'), -- graphite
|
||||
('TRANSFER_IN', '#7c8088'),
|
||||
('TRANSFER_OUT', '#7c8088'),
|
||||
('OTHER', '#8a8580')
|
||||
) as v(key, color)
|
||||
where c.key = v.key and c.user_id is null;
|
||||
@@ -0,0 +1,44 @@
|
||||
-- Money plan: each audit run, and the moves it found. The server writes both (admin client, after checking the user);
|
||||
-- the browser reads its own and may only change a move's status.
|
||||
create table if not exists public.plans (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
user_id uuid not null references auth.users on delete cascade,
|
||||
created_at timestamptz not null default now(),
|
||||
provider text,
|
||||
summary text,
|
||||
total_impact numeric not null default 0
|
||||
);
|
||||
create index if not exists plans_user_created on public.plans (user_id, created_at desc);
|
||||
|
||||
create table if not exists public.plan_moves (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
plan_id uuid not null references public.plans on delete cascade,
|
||||
user_id uuid not null references auth.users on delete cascade,
|
||||
ref text, -- what the move is about ("negotiate:Comcast"), so a new run keeps done and dismissed moves out
|
||||
kind text not null check (kind in ('cancel', 'negotiate', 'insurance', 'card', 'signup', 'message', 'earn')),
|
||||
title text not null,
|
||||
why text not null,
|
||||
yearly_impact numeric not null default 0,
|
||||
effort text not null check (effort in ('5 min', '30 min', '1 hour+')),
|
||||
steps jsonb not null default '[]',
|
||||
message jsonb,
|
||||
links jsonb not null default '[]',
|
||||
confidence text not null check (confidence in ('high', 'medium', 'low')),
|
||||
status text not null default 'todo' check (status in ('todo', 'doing', 'done', 'dismissed')),
|
||||
done_at timestamptz,
|
||||
sort int not null default 0
|
||||
);
|
||||
create index if not exists plan_moves_plan on public.plan_moves (plan_id, sort);
|
||||
create index if not exists plan_moves_user on public.plan_moves (user_id, status);
|
||||
|
||||
alter table public.plans enable row level security;
|
||||
alter table public.plan_moves enable row level security;
|
||||
create policy "own read" on public.plans for select to authenticated using (user_id = (select auth.uid()));
|
||||
create policy "own read" on public.plan_moves for select to authenticated using (user_id = (select auth.uid()));
|
||||
create policy "own status" on public.plan_moves for update to authenticated
|
||||
using (user_id = (select auth.uid())) with check (user_id = (select auth.uid()));
|
||||
|
||||
revoke all on public.plans, public.plan_moves from anon, authenticated;
|
||||
grant select on public.plans, public.plan_moves to authenticated;
|
||||
grant update (status, done_at) on public.plan_moves to authenticated;
|
||||
grant all on public.plans, public.plan_moves to service_role;
|
||||
@@ -0,0 +1,10 @@
|
||||
-- Money plan, part 2: tax moves and the plan's sections and deadlines. Additive: old rows keep null section and
|
||||
-- deadline and the page works them out from the move's ref. The browser still updates only status and done_at
|
||||
-- (0018's column grants; new columns get no update grant).
|
||||
alter table public.plan_moves add column if not exists section text
|
||||
check (section is null or section in ('tax', 'debt', 'bills', 'cards', 'saving'));
|
||||
alter table public.plan_moves add column if not exists deadline date;
|
||||
|
||||
alter table public.plan_moves drop constraint if exists plan_moves_kind_check;
|
||||
alter table public.plan_moves add constraint plan_moves_kind_check
|
||||
check (kind in ('cancel', 'negotiate', 'insurance', 'card', 'signup', 'message', 'earn', 'tax'));
|
||||
@@ -0,0 +1,13 @@
|
||||
-- Rules can also find transactions by account and by day of the month, and the name match becomes optional.
|
||||
-- day_from/day_to: days of the month, both inclusive. day_from > day_to wraps past the month end (28 to 3).
|
||||
alter table public.rules
|
||||
add column if not exists account_id uuid references public.accounts on delete cascade,
|
||||
add column if not exists day_from smallint check (day_from between 1 and 31),
|
||||
add column if not exists day_to smallint check (day_to between 1 and 31);
|
||||
alter table public.rules alter column match set default '';
|
||||
alter table public.rules drop constraint if exists rules_match_check;
|
||||
alter table public.rules drop constraint if exists rules_finds_something;
|
||||
alter table public.rules add constraint rules_finds_something check (
|
||||
length(trim(match)) > 0 or amount_min is not null or amount_max is not null
|
||||
or account_id is not null or day_from is not null or day_to is not null
|
||||
);
|
||||
@@ -0,0 +1,20 @@
|
||||
-- Money plan, part 3: the priority ladder, one-time moves, saved step ticks and a data warning. Additive: old rows keep
|
||||
-- null step and false once, and the page works the step out from the move's ref.
|
||||
-- step: the ladder rung (1 stop the bleeding ... 7 smaller wins). once: the value comes once, not every year.
|
||||
-- gate: why a move isn't counted yet ("Needs about $X a month; you have about $Y spare").
|
||||
alter table public.plan_moves add column if not exists step smallint check (step is null or step between 1 and 7);
|
||||
alter table public.plan_moves add column if not exists once boolean not null default false;
|
||||
alter table public.plan_moves add column if not exists gate text;
|
||||
alter table public.plan_moves add column if not exists steps_done int[] not null default '{}';
|
||||
alter table public.plans add column if not exists note text;
|
||||
|
||||
alter table public.plan_moves drop constraint if exists plan_moves_kind_check;
|
||||
alter table public.plan_moves add constraint plan_moves_kind_check
|
||||
check (kind in ('cancel', 'negotiate', 'insurance', 'card', 'signup', 'message', 'earn', 'tax', 'budget', 'save'));
|
||||
|
||||
alter table public.plan_moves drop constraint if exists plan_moves_section_check;
|
||||
alter table public.plan_moves add constraint plan_moves_section_check
|
||||
check (section is null or section in ('tax', 'debt', 'bills', 'cards', 'saving', 'spending'));
|
||||
|
||||
-- The browser may change status, done_at and the ticked steps, nothing else (RLS "own status" still limits rows).
|
||||
grant update (status, done_at, steps_done) on public.plan_moves to authenticated;
|
||||
@@ -0,0 +1,5 @@
|
||||
-- Loan payments are neither income nor spend: paying a loan moves money between your own debts and accounts, like a
|
||||
-- card payment. The built-in category becomes a transfer, so isSpend / isIncome (src/lib/data.ts), money_rows and
|
||||
-- txn_totals (0014, 0015) all leave it out by the one rule they share: kind = 'transfer'. "Monthly payment +$522" on a
|
||||
-- loan account no longer counts as money in. Interest and fees on a loan stay spend (BANK_FEES).
|
||||
update public.categories set kind = 'transfer' where user_id is null and key = 'LOAN_PAYMENTS';
|
||||
@@ -0,0 +1,6 @@
|
||||
-- "Is this right?" category checks. checked_at: the user answered the check for this row (Yes, or a new category),
|
||||
-- so it never comes back. plaid_confidence: Plaid's confidence_level for its category (VERY_HIGH ... LOW, UNKNOWN),
|
||||
-- written on sync; LOW and UNKNOWN rows are unsure. Older rows have null and are judged by the other checks.
|
||||
alter table public.transactions add column if not exists checked_at timestamptz;
|
||||
alter table public.transactions add column if not exists plaid_confidence text;
|
||||
grant update (checked_at) on public.transactions to authenticated;
|
||||
@@ -0,0 +1,10 @@
|
||||
-- The OpenRouter key each user connects (Connect your AI). Like plaid_items.access_token, signed-in users can't read it:
|
||||
-- no policies and no grants, so only the server's secret key can.
|
||||
create table public.ai_keys (
|
||||
user_id uuid primary key references auth.users on delete cascade,
|
||||
openrouter_key text not null,
|
||||
updated_at timestamptz not null default now()
|
||||
);
|
||||
alter table public.ai_keys enable row level security;
|
||||
revoke all on public.ai_keys from anon, authenticated;
|
||||
grant all on public.ai_keys to service_role;
|
||||
@@ -0,0 +1,25 @@
|
||||
-- Built-in categories move to Apple's system colours (Max, 2026-11-01: the muted set "looks so AI").
|
||||
-- Things people don't budget get neutral greys. Custom categories keep the colour they have.
|
||||
update public.categories c set color = v.color
|
||||
from (values
|
||||
('RENT_AND_UTILITIES', '#5856D6'),
|
||||
('FOOD_AND_DRINK', '#FF9500'),
|
||||
('GROCERIES', '#34C759'),
|
||||
('GENERAL_MERCHANDISE', '#FF2D55'),
|
||||
('TRANSPORTATION', '#007AFF'),
|
||||
('TRAVEL', '#32ADE6'),
|
||||
('ENTERTAINMENT', '#AF52DE'),
|
||||
('MEDICAL', '#FF3B30'),
|
||||
('HOME_IMPROVEMENT', '#A2845E'),
|
||||
('PERSONAL_CARE', '#00C7BE'),
|
||||
('INCOME', '#34C759'),
|
||||
('LOAN_PAYMENTS', '#5856D6'),
|
||||
('GENERAL_SERVICES', '#8E8E93'),
|
||||
('GOVERNMENT_AND_NON_PROFIT', '#8E8E93'),
|
||||
('BANK_FEES', '#8E8E93'),
|
||||
('OTHER', '#8E8E93'),
|
||||
('CREDIT_CARD_PAYMENT', '#8E8E93'),
|
||||
('TRANSFER_IN', '#8E8E93'),
|
||||
('TRANSFER_OUT', '#8E8E93')
|
||||
) as v(key, color)
|
||||
where c.user_id is null and c.key = v.key;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Rules can also find by direction: money in or money out. "Moved" can then be Transfers in one way and Transfers out the other.
|
||||
alter table public.rules add column if not exists direction text check (direction in ('in', 'out'));
|
||||
@@ -0,0 +1,5 @@
|
||||
-- What the bank feed doesn't say about a debt. The user can type these on the Debt page, so broke can work out the payoff.
|
||||
-- apr: the yearly interest rate in percent. debt_payment: what they pay a month.
|
||||
alter table public.accounts add column if not exists apr numeric check (apr >= 0 and apr <= 100);
|
||||
alter table public.accounts add column if not exists debt_payment numeric check (debt_payment >= 0);
|
||||
grant update (apr, debt_payment) on public.accounts to authenticated;
|
||||
@@ -0,0 +1,17 @@
|
||||
-- Activity's custom date range: totals can stop at an end date too.
|
||||
drop function if exists public.txn_totals(text, uuid, uuid, text, date);
|
||||
create or replace function public.txn_totals(q text default null, cat uuid default null, acct uuid default null, tag text default null, start_date date default null, end_date date default null)
|
||||
returns table (money_out numeric, money_in numeric)
|
||||
language sql stable set search_path = '' as $$
|
||||
select coalesce(sum(t.amount) filter (where t.amount > 0), 0), coalesce(-sum(t.amount) filter (where t.amount < 0), 0)
|
||||
from public.transactions t left join public.categories c on c.id = t.category_id
|
||||
where t.user_id = (select auth.uid()) and not t.ignored and c.kind is distinct from 'transfer'
|
||||
and (q is null or t.name ilike '%' || q || '%' or t.merchant_name ilike '%' || q || '%' or t.custom_name ilike '%' || q || '%')
|
||||
and (cat is null or t.category_id = cat)
|
||||
and (acct is null or t.account_id = acct)
|
||||
and (tag is null or t.tags @> array[tag])
|
||||
and (start_date is null or t.date >= start_date)
|
||||
and (end_date is null or t.date <= end_date)
|
||||
$$;
|
||||
revoke execute on function public.txn_totals(text, uuid, uuid, text, date, date) from public, anon;
|
||||
grant execute on function public.txn_totals(text, uuid, uuid, text, date, date) to authenticated;
|
||||
@@ -0,0 +1,4 @@
|
||||
-- More bank connections, each through its vendor's hosted consent page: Enable Banking (UK, Europe), Basiq (Australia),
|
||||
-- Belvo (Brazil). access_token holds the vendor's reference for this user, unreadable by signed-in users like Plaid's.
|
||||
alter table public.plaid_items drop constraint if exists plaid_items_provider;
|
||||
alter table public.plaid_items add constraint plaid_items_provider check (provider in ('plaid', 'akahu', 'enablebanking', 'basiq', 'belvo'));
|
||||
@@ -0,0 +1,29 @@
|
||||
-- The helper that runs a person's own AI app on their computer for a hosted copy of broke (Connect your AI).
|
||||
-- Like ai_keys: no policies and no grants, so only the server's secret key can read these.
|
||||
create table public.ai_helpers (
|
||||
user_id uuid primary key references auth.users on delete cascade,
|
||||
code_hash text,
|
||||
code_expires timestamptz,
|
||||
token_hash text unique,
|
||||
clis jsonb not null default '[]',
|
||||
last_seen timestamptz
|
||||
);
|
||||
alter table public.ai_helpers enable row level security;
|
||||
revoke all on public.ai_helpers from anon, authenticated;
|
||||
grant all on public.ai_helpers to service_role;
|
||||
|
||||
-- One question on its way to the helper and back. Deleted as soon as it's answered: nothing is kept.
|
||||
create table public.ai_jobs (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
user_id uuid not null references auth.users on delete cascade,
|
||||
provider text not null,
|
||||
model text,
|
||||
prompt text not null,
|
||||
status text not null default 'pending',
|
||||
answer text not null default '',
|
||||
created_at timestamptz not null default now()
|
||||
);
|
||||
create index ai_jobs_user_pending on public.ai_jobs (user_id, created_at) where status = 'pending';
|
||||
alter table public.ai_jobs enable row level security;
|
||||
revoke all on public.ai_jobs from anon, authenticated;
|
||||
grant all on public.ai_jobs to service_role;
|
||||
Reference in new issue
Block a user