Compare commits
14
Commits
49ecfb975f
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bda9265d70 | ||
|
|
943b19d743 | ||
|
|
9d42d52e4d | ||
|
|
1bdcc57c2f | ||
|
|
fbdeea630a | ||
|
|
0d399b77c3 | ||
|
|
5ef800e618 | ||
|
|
059a1da375 | ||
|
|
dee883472a | ||
|
|
1253f4e7fb | ||
|
|
c7298cf955 | ||
|
|
730d99d38b | ||
|
|
759b0c0d62 | ||
|
|
2371a5674f |
No files matched your search
@@ -5,6 +5,7 @@ Personal finance app. Next.js 15 (app router), Supabase (sign-in, Postgres, row-
|
||||
## Rules for any change
|
||||
|
||||
- **Bank data stays private.** Every AI path goes through `src/lib/llm/gate.ts`. A cloud model gets the summary only: rounded amounts, names replaced by tokens. Full detail goes only to a local model. Never add another path.
|
||||
- One exception, the person's own explicit choice: an MCP token made with "Full detail" on Connect your AI (`src/app/api/mcp`, migration 0034). Summary stays the default, IBANs and account numbers stay shortened, and a token only ever reaches its own user's rows (their session, plus a `user_id` filter in every tool, so a partner's shared accounts never show).
|
||||
- **No AI API keys.** AI runs on the person's own signed-in app (Claude Code, Codex, Gemini CLI, opencode), a local model, or their OpenRouter sign-in.
|
||||
- **Tools stay off for prompts from a website.** The helper (`public/broke-connect.cjs`) only runs AI apps with no tools at all. Don't add one that can read files.
|
||||
- **Every table has row-level security.** Secrets like `plaid_items.access_token` have no policies, so only the server's secret key reads them.
|
||||
|
||||
@@ -17,6 +17,7 @@ brokeless is a self-hosted copy of [broke](https://github.com/nextwork-projects/
|
||||
| ING Netherlands CSV | Spending and income all came in as income | Reads the "Af Bij" column |
|
||||
| ABN AMRO TXT/TAB | Imported nothing (no header row) and kept coded descriptions | Recognized, with the name pulled out of `/NAME/`, card and `Naam:` text |
|
||||
| Updates | Pulls from GitHub on every start | Never by itself. You review upstream commits and merge the ones you want. |
|
||||
| Charts | Month bars and a category breakdown | A Charts tab under Spending: cash flow, savings rate, categories over time, this month vs last, balance over time, top merchants, spending by weekday and biggest changes, with filters and compare |
|
||||
| Calls out | Update check on GitHub, exchange rates from frankfurter.dev | Both off (`BROKE_OFFLINE=1`) |
|
||||
| Next.js and React | 15.5.4 and 19.1.0 (critical advisory) | 15.5.29 and 19.1.10 |
|
||||
|
||||
@@ -170,6 +171,26 @@ brokeless runs in Docker, so it can't use a Claude login of its own. Instead, Cl
|
||||
|
||||
Claude only answers while that command runs. It starts Claude with every tool off, in an empty folder, so it can't touch your files. Works on Windows, macOS and Linux.
|
||||
|
||||
## Connect Claude Code (MCP)
|
||||
|
||||
brokeless is an MCP server too, so an AI app like Claude Code can read your money summary and fix things for you: find a rule that catches too much, delete it and undo what it did, make better rules, recategorize, mark transfers, merge accounts.
|
||||
|
||||
1. In brokeless: Connect your AI, **Connect an AI app (MCP)**, **Make a token**. It shows once.
|
||||
2. Run the command it shows on your computer:
|
||||
|
||||
```bash
|
||||
claude mcp add --scope user --transport http brokeless https://brokeless.mangavalk.com/api/mcp --header "Authorization: Bearer <token>"
|
||||
```
|
||||
|
||||
3. Start a new Claude Code session and ask, for example: "Which of my brokeless rules catch too much?"
|
||||
|
||||
When you make a token you choose what it sees:
|
||||
|
||||
- **Summary** (default): like broke ai. Rounded amounts, months not days, names as placeholders (⟨M1⟩, ⟨A1⟩), never single transactions.
|
||||
- **Full detail**: real names, exact amounts, dates and single transactions with their id, so Claude can fix rows one by one (`list_transactions`, `update_transactions`, `mark_transfer_pair`). IBANs and account numbers stay shortened (`NL24…5339`). Your real transactions then go to Anthropic while you use it, so brokeless asks you to confirm that.
|
||||
|
||||
A token only ever reaches its own user: every call runs in that user's session and every tool filters on that user too, so a partner's shared accounts don't show either. Changes act on your real data, and Claude says what it will change first. Revoke a token on the same page. With AI switched off in Settings the endpoint refuses.
|
||||
|
||||
## How AI stays private
|
||||
|
||||
Every AI path goes through one gate. A cloud model gets a summary: rounded amounts, names replaced by tokens. Full detail goes only to a local model, which is what Ollama is here. You can turn AI off in Settings. Each answer runs with no way to change your data.
|
||||
|
||||
@@ -3,7 +3,7 @@ import { AskButton } from "@/components/Assistant";
|
||||
import { BudgetEditor, type BudgetCat } from "@/components/BudgetEditor";
|
||||
import { EmptyBank } from "@/components/EmptyBank";
|
||||
import { budgetContext, median, monthList, suggest, type MonthSpend } from "@/lib/budget";
|
||||
import { categories, getUser, isSpend, moneyByMonth, sumOf, today, transactionsSince, typicalMonthly } from "@/lib/data";
|
||||
import { categories, getUser, isSpend, moneyByMonth, months, sumOf, today, transactionsSince, typicalMonthly } from "@/lib/data";
|
||||
import { monthStart, ymd } from "@/lib/format";
|
||||
|
||||
// Budgets: tracked against this month with a pace marker. Suggestions come from the full months of data (up to 3, the
|
||||
@@ -16,16 +16,19 @@ export default async function Budgets({ searchParams }: { searchParams: Promise<
|
||||
const from = DAY.test(sp.from ?? "") ? sp.from! : "", to = DAY.test(sp.to ?? "") ? sp.to! : "";
|
||||
const { supabase, user } = await getUser();
|
||||
const now = await today();
|
||||
const thisMonth = ymd(monthStart(now)).slice(0, 7);
|
||||
const lastMonth = ymd(monthStart(now, -1)).slice(0, 7);
|
||||
// Pay months on: this month is the pay month today is in (named after the calendar month it mostly covers).
|
||||
const mo = await months();
|
||||
const thisMonth = await mo.current();
|
||||
const cur = new Date(`${thisMonth}-01T00:00:00Z`);
|
||||
const lastMonth = ymd(monthStart(cur, -1)).slice(0, 7);
|
||||
const [txns, cats, saved, typical] = await Promise.all([
|
||||
moneyByMonth(supabase, ymd(monthStart(now, -Math.max(3, now.getUTCMonth())))), // own rows, totalled in SQL: 3 months, or back to January
|
||||
moneyByMonth(supabase, ymd(monthStart(cur, -Math.max(3, cur.getUTCMonth())))), // own rows, totalled in SQL: 3 months, or back to January
|
||||
categories(),
|
||||
supabase.from("budgets").select("category_id, amount"),
|
||||
typicalMonthly(supabase, user!.id, ymd(now)),
|
||||
]);
|
||||
|
||||
const threeMonthsAgo = ymd(monthStart(now, -3)).slice(0, 7);
|
||||
const threeMonthsAgo = ymd(monthStart(cur, -3)).slice(0, 7);
|
||||
const past = txns.filter((r) => !r.month.startsWith(thisMonth) && r.month.slice(0, 7) >= threeMonthsAgo);
|
||||
const monthsOfData = Math.max(1, new Set(past.map((r) => r.month.slice(0, 7))).size);
|
||||
const sum = (catId: string, month?: string) =>
|
||||
@@ -44,8 +47,8 @@ export default async function Budgets({ searchParams }: { searchParams: Promise<
|
||||
return { id: c.id, label: c.label, icon: c.icon, color: c.color, spent, last: sum(c.id, lastMonth), avg, suggested: suggest(avg, spent), main: c.key !== "BANK_FEES" && Math.max(avg, spent) >= 10 };
|
||||
});
|
||||
// Each month of this year, spend by category, for the year view.
|
||||
const year = String(now.getUTCFullYear());
|
||||
const yearMonths: MonthSpend[] = Array.from({ length: now.getUTCMonth() + 1 }, (_, i) => {
|
||||
const year = String(cur.getUTCFullYear());
|
||||
const yearMonths: MonthSpend[] = Array.from({ length: cur.getUTCMonth() + 1 }, (_, i) => {
|
||||
const month = `${year}-${String(i + 1).padStart(2, "0")}`;
|
||||
const cats: Record<string, number> = {};
|
||||
for (const r of txns) if (r.month.startsWith(month) && r.spend > 0) cats[r.category_id] = (cats[r.category_id] ?? 0) + r.spend;
|
||||
@@ -65,7 +68,7 @@ export default async function Budgets({ searchParams }: { searchParams: Promise<
|
||||
|
||||
return (
|
||||
// The key takes in saved changes from elsewhere (the AI's Apply) on refresh.
|
||||
<BudgetEditor key={JSON.stringify(budgets) + (range ? `${from}|${to}` : "")} basis={basis} cats={rows} initial={budgets} year={yearMonths} range={range} today={ymd(now)} income={Math.round(income)} now={now.toISOString()} tableMissing={!!saved.error} aside={
|
||||
<BudgetEditor key={JSON.stringify(budgets) + (range ? `${from}|${to}` : "")} basis={basis} cats={rows} initial={budgets} year={yearMonths} range={range} today={ymd(now)} income={Math.round(income)} now={now.toISOString()} tableMissing={!!saved.error} {...(mo.payday ? { span: mo.range(thisMonth), label: `${thisMonth}-01` } : {})} aside={
|
||||
<AskButton
|
||||
q={`Look at my budget, my income and my last 3 months of spending. Which categories should I lower, by how much, and what would that free up each month?${budgetContext(rows.filter((c) => c.id in budgets).map((c) => [c.label, budgets[c.id]]))}`}
|
||||
className="card-link w-full p-5 text-left flex items-center gap-4"
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import { ChartFilters } from "@/components/charts/ChartFilters";
|
||||
import { ChartsView, type ChartsData } from "@/components/charts/ChartsView";
|
||||
import { EmptyBank } from "@/components/EmptyBank";
|
||||
import { balances, biggestChanges, byWeekday, cashFlow, categoriesOver, merchantsOver, monthToDate, periods, previousRange, rankBySpend, savingsRate, totals, type Group, type Months, type Row } from "@/lib/charts";
|
||||
import { accountName, allTags, categories, displayName, getUser, isIncome, isSpend, months, today, transactionsSince } from "@/lib/data";
|
||||
import { ymd } from "@/lib/format";
|
||||
|
||||
// Charts: money over time with filters. Every number comes from lib/charts.ts over the same spend / income rule as
|
||||
// the rest of broke (isSpend / isIncome), so transfers between own accounts never count. Home-currency rows only.
|
||||
|
||||
type Search = { range?: string; from?: string; to?: string; g?: string; acct?: string; cat?: string; tag?: string; q?: string; dir?: string; cmp?: string };
|
||||
const DAY = /^\d{4}-\d{2}-\d{2}$/;
|
||||
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
const ids = (s?: string) => (s ?? "").split(",").filter((x) => UUID.test(x));
|
||||
const MS = 864e5;
|
||||
|
||||
export default async function Charts({ searchParams }: { searchParams: Promise<Search> }) {
|
||||
const sp = await searchParams;
|
||||
const { supabase, user } = await getUser();
|
||||
const now = ymd(await today());
|
||||
// Months that start on payday (profile.month): grouping by month, month presets and month to date follow them.
|
||||
const mo = await months();
|
||||
const pm: Months = mo.payday ? { of: mo.of, range: mo.range } : null;
|
||||
const [txns, cats, tags, { data: accts }] = await Promise.all([
|
||||
transactionsSince("1900-01-01"),
|
||||
categories(),
|
||||
allTags(),
|
||||
supabase.from("accounts").select("id, name, custom_name, type, current_balance, balance, manual, included").eq("user_id", user!.id).order("name"),
|
||||
]);
|
||||
if (!txns.length) return <EmptyBank />;
|
||||
|
||||
// Rows in the home currency, split into spend and income the way every other page does.
|
||||
const home = (user?.user_metadata?.profile?.currency as string | undefined) ?? null;
|
||||
const mine = (c: string | null) => !c || c === home;
|
||||
const otherCurrency = txns.filter((t) => !mine(t.currency)).length;
|
||||
const all: (Row & { tags: string[]; text: string })[] = txns.filter((t) => mine(t.currency)).map((t) => ({
|
||||
date: t.date, amount: Number(t.amount), spend: isSpend(t), income: isIncome(t), categoryId: t.category_id,
|
||||
merchant: displayName(t), accountId: t.account?.id ?? null, tags: t.tags ?? [],
|
||||
text: `${t.name} ${t.merchant_name ?? ""} ${t.custom_name ?? ""}`.toLowerCase(),
|
||||
}));
|
||||
const first = all.reduce((m, r) => (r.date < m ? r.date : m), now);
|
||||
|
||||
// Time range: a preset, or custom dates (either end open).
|
||||
const range = sp.range ?? "12m";
|
||||
const monthsBack = (n: number) => { const d = new Date(`${pm ? pm.of(now) : now.slice(0, 7)}-01T00:00:00Z`); d.setUTCMonth(d.getUTCMonth() - n + 1); return pm ? pm.range(ymd(d).slice(0, 7)).start : ymd(d); };
|
||||
const preset = range === "1m" ? monthsBack(1) : range === "3m" ? monthsBack(3) : range === "6m" ? monthsBack(6) : range === "ytd" ? `${now.slice(0, 4)}-01-01` : range === "all" ? first : monthsBack(12);
|
||||
const from = DAY.test(sp.from ?? "") ? sp.from! : DAY.test(sp.to ?? "") ? first : preset;
|
||||
const to = DAY.test(sp.to ?? "") ? sp.to! : now;
|
||||
const days = (Date.parse(to) - Date.parse(from)) / MS + 1;
|
||||
const group: Group = sp.g === "day" || sp.g === "week" || sp.g === "month" ? sp.g : days <= 31 ? "day" : days <= 120 ? "week" : "month";
|
||||
|
||||
// Filters. Balances follow only the account filter: a balance is the whole account, not a slice of it.
|
||||
const acct = ids(sp.acct), cat = ids(sp.cat), tag = (sp.tag ?? "").split(",").filter((t) => t && t.length <= 100);
|
||||
const q = (sp.q ?? "").trim().toLowerCase().slice(0, 100);
|
||||
const dir = sp.dir === "in" || sp.dir === "out" ? sp.dir : null;
|
||||
const filtered = all
|
||||
.filter((r) => !acct.length || (r.accountId && acct.includes(r.accountId)))
|
||||
.filter((r) => !cat.length || (r.categoryId && cat.includes(r.categoryId)))
|
||||
.filter((r) => !tag.length || tag.some((t) => r.tags.includes(t)))
|
||||
.filter((r) => !q || r.text.includes(q) || r.merchant.toLowerCase().includes(q))
|
||||
.map((r) => (dir === "out" ? { ...r, income: false } : dir === "in" ? { ...r, spend: false } : r));
|
||||
const within = (a: string, b: string) => filtered.filter((r) => r.date >= a && r.date <= b);
|
||||
const ps = periods(from, to, group, pm);
|
||||
const rows = within(from, to);
|
||||
const compare = sp.cmp === "1";
|
||||
const prev = previousRange(from, to);
|
||||
const before = within(prev.from, prev.to);
|
||||
// The period before, lined up period by period with this one (same length, same grouping).
|
||||
const psBefore = periods(prev.from, prev.to, group, pm).slice(-ps.length);
|
||||
const flowBefore = compare ? cashFlow(before, psBefore, group, pm) : null;
|
||||
const pad = <T,>(xs: T[] | null) => (xs ? [...Array(Math.max(0, ps.length - xs.length)).fill(null), ...xs] : null);
|
||||
|
||||
// Stable colors: slots follow all-time spending, so filtering never repaints a category, merchant or account.
|
||||
const catRank = rankBySpend(all, (r) => r.categoryId);
|
||||
const catSlot = new Map(catRank.slice(0, 7).map((id, i) => [id, i + 1]));
|
||||
const label = new Map(cats.map((c) => [c.id, c.label]));
|
||||
const keep = rankBySpend(rows, (r) => r.categoryId).filter((id) => catSlot.has(id)).slice(0, 7);
|
||||
const merchRank = rankBySpend(all, (r) => r.merchant);
|
||||
const topMerch = rankBySpend(rows, (r) => r.merchant).slice(0, 5);
|
||||
const merchSlot = (m: string) => { const i = merchRank.indexOf(m); return i >= 0 && i < 8 ? i + 1 : 0; };
|
||||
|
||||
const accounts = (accts ?? []).filter((a) => a.included !== false && ["depository", "credit", "loan"].includes(a.type) && (!acct.length || acct.includes(a.id)));
|
||||
const bal = balances(
|
||||
accounts.map((a) => ({ id: a.id, name: accountName(a), balance: Number((a.manual ? a.balance : a.current_balance) ?? 0), owed: a.type === "credit" || a.type === "loan" })),
|
||||
all.filter((r) => r.date > from), from, to, group, pm,
|
||||
);
|
||||
const flow = cashFlow(rows, ps, group, pm);
|
||||
const psMonth = periods(from, to, "month", pm);
|
||||
const ch = biggestChanges(rows, before, (r) => r.categoryId);
|
||||
|
||||
const data: ChartsData = {
|
||||
periods: ps,
|
||||
compare,
|
||||
totals: totals(rows),
|
||||
totalsBefore: compare ? totals(before) : null,
|
||||
flow,
|
||||
flowBefore: flowBefore ? (pad(flowBefore) as ChartsData["flow"]).map((f, i) => f ?? { key: ps[i].key, income: 0, spend: 0, net: 0 }) : null,
|
||||
// Savings rate is per month whatever the grouping: most weeks have no pay in them, and a rate of nothing isn't 0%.
|
||||
rate: { periods: psMonth, values: savingsRate(cashFlow(rows, psMonth, "month", pm)).map((r) => r.rate) },
|
||||
rateBefore: compare ? (() => { const pb = periods(prev.from, prev.to, "month", pm).slice(-psMonth.length); const v = savingsRate(cashFlow(before, pb, "month", pm)).map((r) => r.rate); return [...Array(Math.max(0, psMonth.length - v.length)).fill(null), ...v]; })() : null,
|
||||
cats: { order: keep.map((id) => ({ id, label: label.get(id) ?? "Uncategorized", slot: catSlot.get(id)! })), values: categoriesOver(rows, ps, group, keep, pm).map((c) => c.values) },
|
||||
mtd: monthToDate(filtered, now, pm),
|
||||
balance: { ...bal, series: bal.series.map((s, i) => ({ ...s, slot: (i % 8) + 1 })) },
|
||||
weekday: byWeekday(rows, from, to),
|
||||
weekdayBefore: compare ? byWeekday(before, prev.from, prev.to) : null,
|
||||
merchants: merchantsOver(rows, ps, group, topMerch, pm).map((m) => ({ ...m, slot: merchSlot(m.name) })),
|
||||
changes: {
|
||||
categories: { up: ch.up.map((c) => ({ ...c, label: label.get(c.id) ?? "Uncategorized" })), down: ch.down.map((c) => ({ ...c, label: label.get(c.id) ?? "Uncategorized" })) },
|
||||
merchants: biggestChanges(rows, before, (r) => r.merchant),
|
||||
},
|
||||
// Activity takes one account, one tag and a search: pass them on when exactly one is picked.
|
||||
otherCurrency,
|
||||
link: Object.fromEntries(Object.entries({ account: acct.length === 1 ? acct[0] : "", tag: tag.length === 1 ? tag[0] : "", q: sp.q?.trim() ?? "" }).filter(([, v]) => v)),
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<ChartFilters
|
||||
accounts={(accts ?? []).map((a) => ({ value: a.id, label: accountName(a) }))}
|
||||
categories={cats.filter((c) => c.kind !== "transfer").map((c) => ({ value: c.id, label: c.label }))}
|
||||
tags={tags.map((t) => ({ value: t, label: t }))}
|
||||
/>
|
||||
<ChartsView d={data} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ConnectAI } from "@/components/ConnectAI";
|
||||
import { McpTokens } from "@/components/McpTokens";
|
||||
import { getUser } from "@/lib/data";
|
||||
import { savedChoice } from "@/lib/llm/gate";
|
||||
import { isHosted, providersFor } from "@/lib/llm/providers";
|
||||
@@ -6,5 +7,10 @@ import { isHosted, providersFor } from "@/lib/llm/providers";
|
||||
export default async function ConnectAIPage({ searchParams }: { searchParams: Promise<{ connected?: string; error?: string }> }) {
|
||||
const { user } = await getUser();
|
||||
const [providers, q] = await Promise.all([providersFor(user!.id), searchParams]);
|
||||
return <ConnectAI initial={JSON.parse(JSON.stringify(providers))} choice={savedChoice(user)} hosted={isHosted()} connected={!!q.connected} failed={!!q.error} />;
|
||||
return (
|
||||
<div className="max-w-2xl space-y-4">
|
||||
<ConnectAI initial={JSON.parse(JSON.stringify(providers))} choice={savedChoice(user)} hosted={isHosted()} connected={!!q.connected} failed={!!q.error} />
|
||||
<McpTokens />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,11 @@
|
||||
import { ChevronRight, Sparkles } from "lucide-react";
|
||||
import { DonateLink } from "@/components/Donate";
|
||||
import Link from "next/link";
|
||||
|
||||
const PAGES = [
|
||||
{ href: "/debt", label: "Debt", what: "What you owe, what you're paying and what it costs." },
|
||||
];
|
||||
|
||||
// What isn't in the main menu: Debt, connecting your AI and supporting broke.
|
||||
// What isn't in the main menu: Debt and connecting your AI.
|
||||
export default function More() {
|
||||
return (
|
||||
<div className="max-w-2xl space-y-4">
|
||||
@@ -23,8 +22,6 @@ export default function More() {
|
||||
<span className="flex-1 font-medium">Connect your AI</span>
|
||||
<ChevronRight size={18} className="text-muted shrink-0" />
|
||||
</Link>
|
||||
{/* The sidebar has this link too; on a phone, More is the only place. */}
|
||||
<DonateLink className="card-link flex items-center gap-3 px-6 py-4 font-medium [&_svg]:text-muted" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -11,8 +11,8 @@ import { PayQuestion } from "@/components/PayQuestion";
|
||||
import { SyncButton } from "@/components/PlaidButtons";
|
||||
import { TxnList } from "@/components/TxnList";
|
||||
import { WeekCard } from "@/components/WeekCard";
|
||||
import { categories, getUser, moneyByMonth, today, TXN_SELECT, withAccountNames, type Txn } from "@/lib/data";
|
||||
import { dateLabel, money0, monthStart, ymd } from "@/lib/format";
|
||||
import { categories, getUser, moneyByMonth, months, today, TXN_SELECT, withAccountNames, type Txn } from "@/lib/data";
|
||||
import { dateLabel, money0, ymd } from "@/lib/format";
|
||||
import { deterministicMoves, ladder } from "@/lib/plan";
|
||||
import { myPlanFacts } from "@/lib/plan-facts";
|
||||
import { payGuess } from "@/lib/pay";
|
||||
@@ -66,6 +66,8 @@ export default async function Dashboard() {
|
||||
const now = await today(); // the user's date at UTC midnight: read it with getUTC* and ymd
|
||||
const day = ymd(now), soon = ymd(new Date(now.getTime() + 14 * 864e5));
|
||||
const checks = (fetchChecks(supabase, uid, day) as Promise<Checks>).catch(() => ({ rows: [], total: 0 })); // starts now, beside the queries below
|
||||
// Pay months on: "this month" is the pay month today is in, named after the calendar month it mostly covers.
|
||||
const thisMonth = await (await months()).current();
|
||||
|
||||
// Own rows only: an account a partner shares is on the Accounts page, not in your totals.
|
||||
const [{ data: recent }, { data: accounts }, { data: noRate }, { data: bills }, rows, cats] = await Promise.all([
|
||||
@@ -73,7 +75,7 @@ export default async function Dashboard() {
|
||||
supabase.from("accounts").select("type, subtype, current_balance:home_balance, included").eq("user_id", uid),
|
||||
supabase.rpc("fx_missing"),
|
||||
supabase.from("recurring").select("id, merchant_name, logo_url, average_amount:home_average, next_date").eq("user_id", uid).eq("active", true).eq("is_income", false).neq("status", "TOMBSTONED").gte("next_date", day).lte("next_date", soon).order("next_date").limit(4),
|
||||
moneyByMonth(supabase, ymd(monthStart(now))),
|
||||
moneyByMonth(supabase, `${thisMonth}-01`),
|
||||
categories(),
|
||||
]);
|
||||
|
||||
@@ -93,8 +95,8 @@ export default async function Dashboard() {
|
||||
{ label: "You owe", value: owed == null ? null : Math.abs(owed), href: "/debt" },
|
||||
].filter((t) => t.value != null);
|
||||
|
||||
const pic = moneyPicture(rows, cats, ymd(monthStart(now)).slice(0, 7), null);
|
||||
const monthName = dateLabel(day, { month: "long" });
|
||||
const pic = moneyPicture(rows, cats, thisMonth, null);
|
||||
const monthName = dateLabel(`${thisMonth}-01`, { month: "long" });
|
||||
|
||||
return (
|
||||
<div className="space-y-4 max-w-4xl">
|
||||
|
||||
@@ -181,6 +181,27 @@ function Card({ title, what, s, children }: { title: string; what?: string; s?:
|
||||
);
|
||||
}
|
||||
|
||||
// When a month starts: on the 1st, or on payday (lib/paymonths.ts). Saved as soon as it's picked.
|
||||
function MonthStart({ profile }: { profile: Profile }) {
|
||||
const router = useRouter();
|
||||
const [v, setV] = useState(profile.month === "payday" ? "payday" : "calendar");
|
||||
const [msg, setMsg] = useState("");
|
||||
async function pick(next: string) {
|
||||
setV(next);
|
||||
const { error } = await updateMeta(createClient(), { data: { profile: { ...profile, month: next === "payday" ? "payday" : undefined } } });
|
||||
setMsg(error ? "Couldn't save that. Try again." : "Saved.");
|
||||
if (!error) router.refresh();
|
||||
}
|
||||
return (
|
||||
<Card title="A month starts" what="On payday: each month runs from one salary to the day before the next, and is named after the month it mostly covers. Salary is money in under Income.">
|
||||
<div className="max-w-sm">
|
||||
<Dropdown label="A month starts" value={v} options={[{ value: "calendar", label: "On the 1st" }, { value: "payday", label: "On payday" }]} onChange={pick} placeholder="On the 1st" />
|
||||
</div>
|
||||
{msg && <span className="text-sm text-muted">{msg}</span>}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function ProfileCards({ email, profile }: { email: string; profile: Profile }) {
|
||||
const router = useRouter();
|
||||
const start = { country: profile.country ?? "US", currency: profile.currency ?? countryOf(profile.country).currency };
|
||||
@@ -210,6 +231,7 @@ function ProfileCards({ email, profile }: { email: string; profile: Profile }) {
|
||||
{msg && <span className="text-sm text-muted">{msg}</span>}
|
||||
</div>
|
||||
</Card>
|
||||
<MonthStart profile={profile} />
|
||||
<Card title="Money profile" what="Filing status, income, goals and more. Ask broke and Optimize use it to tailor advice.">
|
||||
<Link href="/optimize#profile" className="btn inline-block">Edit money profile</Link>
|
||||
</Card>
|
||||
|
||||
@@ -5,7 +5,7 @@ import { EmptyBank } from "@/components/EmptyBank";
|
||||
import { MonthBars } from "@/components/MonthBars";
|
||||
import { PageDates } from "@/components/PageDates";
|
||||
import { Merchant } from "@/components/Merchant";
|
||||
import { categories, displayName, getUser, isIncome, isSpend, loanPayments, moneyByMonth, savedByMonth, sumOf, today, transactionsSince, type MonthRow, type Txn } from "@/lib/data";
|
||||
import { categories, displayName, getUser, isIncome, isSpend, loanPayments, moneyByMonth, months as monthsOf, savedByMonth, sumOf, today, transactionsSince, type MonthRow, type Txn } from "@/lib/data";
|
||||
import { dateLabel, money, money0, monthLabel, monthStart, ymd } from "@/lib/format";
|
||||
|
||||
const DAY = /^\d{4}-\d{2}-\d{2}$/;
|
||||
@@ -108,13 +108,21 @@ export default async function Spending({ searchParams }: { searchParams: Promise
|
||||
const { m, bills, from: rawFrom, to: rawTo, span } = await searchParams;
|
||||
const from = DAY.test(rawFrom ?? "") ? rawFrom! : "", to = DAY.test(rawTo ?? "") ? rawTo! : "";
|
||||
const includeBills = bills !== "0";
|
||||
const now = await today();
|
||||
let now = await today();
|
||||
if (from || to) return <CustomRange from={from} to={to} today={ymd(now)} />;
|
||||
const { supabase, user } = await getUser();
|
||||
// Pay months on (profile.month = "payday"): "now" is the pay month today is in, so after salary on the 24th it's
|
||||
// already next month. Calendar months otherwise. Month arithmetic runs on the month's name, its dates come from mo.range.
|
||||
const mo = await monthsOf();
|
||||
const curYm = await mo.current();
|
||||
const daysIn = Math.round((now.getTime() - Date.parse(`${mo.range(curYm).start}T00:00:00Z`)) / 864e5) + 1;
|
||||
const real = now;
|
||||
now = new Date(`${curYm}-01T00:00:00Z`);
|
||||
const ymOf = (d: Date) => ymd(d).slice(0, 7);
|
||||
// m = "YYYY-MM" (the arrows or a bar), "last" or "now"; anything else = this month. Up to 5 years back.
|
||||
const ym = /^\d{4}-\d{2}$/.test(m ?? "") ? m!.split("-").map(Number) : null;
|
||||
// The first days of a month open on last month: this one is still empty. m=now asks for this month anyway.
|
||||
const offset = m === "last" || (!m && now.getUTCDate() <= 3) ? -1 : ym ? Math.max(-59, Math.min(0, (ym[0] - now.getUTCFullYear()) * 12 + ym[1] - 1 - now.getUTCMonth())) : 0;
|
||||
const offset = m === "last" || (!m && daysIn <= 3) ? -1 : ym ? Math.max(-59, Math.min(0, (ym[0] - now.getUTCFullYear()) * 12 + ym[1] - 1 - now.getUTCMonth())) : 0;
|
||||
const month = monthStart(now, offset);
|
||||
const prevMonth = monthStart(now, offset - 1);
|
||||
// The chart and table: the picked month's whole year by default, or the last 12 or 6 months (the 6 or 12 ending at the
|
||||
@@ -130,9 +138,9 @@ export default async function Spending({ searchParams }: { searchParams: Promise
|
||||
const [rows, allCats, monthTxns, loans, savedMonths] = await Promise.all([
|
||||
moneyByMonth(supabase, ymd(first)),
|
||||
categories(),
|
||||
transactionsSince(ymd(month), ymd(monthStart(now, offset + 1))),
|
||||
loanPayments(supabase, user!.id, ymd(first)),
|
||||
savedByMonth(supabase, user!.id, ymd(first)),
|
||||
transactionsSince(mo.range(ymOf(month)).start, mo.range(ymOf(month)).end),
|
||||
loanPayments(supabase, user!.id, mo.range(ymOf(first)).start, undefined, mo.of),
|
||||
savedByMonth(supabase, user!.id, mo.range(ymOf(first)).start, undefined, mo.of),
|
||||
]);
|
||||
// ponytail: "no transactions in 6 months" is treated as "no bank yet"; split the copy if linked-but-quiet accounts show up.
|
||||
if (!rows.length) return <EmptyBank title="See where your money goes" body="Link a bank to get a monthly breakdown by category." />;
|
||||
@@ -183,6 +191,8 @@ export default async function Spending({ searchParams }: { searchParams: Promise
|
||||
|
||||
const change = prevTotal ? Math.round(((total - prevTotal) / prevTotal) * 100) : null;
|
||||
const vs = (a: number, b: number) => (Math.abs(a - b) < 1 ? `Same as ${monthLabel(prevMonth)}` : `${money0(Math.abs(a - b))} ${a > b ? "more" : "less"} than ${monthLabel(prevMonth)}`);
|
||||
// The month's last day: the day before the next salary, or the day before its usual date while it's running.
|
||||
const lastDay = new Date(Date.parse(`${mo.range(ymOf(month)).end}T00:00:00Z`) - 864e5).toISOString().slice(0, 10);
|
||||
const qs = (o: Record<string, string | undefined>) => "/spending?" + new URLSearchParams(Object.entries({ m, bills, span, ...o }).filter(([, v]) => v) as [string, string][]);
|
||||
|
||||
return (
|
||||
@@ -191,14 +201,17 @@ export default async function Spending({ searchParams }: { searchParams: Promise
|
||||
{offset > -59 ? (
|
||||
<Link scroll={false} href={qs({ m: ymd(prevMonth).slice(0, 7) })} aria-label="Earlier month" className="size-9 rounded-full border border-line grid place-items-center text-muted hover:text-ink row-hover"><ChevronLeft size={18} /></Link>
|
||||
) : <span className="size-9" />}
|
||||
<span className="min-w-36 text-center font-medium tabular-nums">{dateLabel(month, { month: "long", year: "numeric" })}</span>
|
||||
<span className="min-w-36 text-center">
|
||||
<span className="block font-medium tabular-nums">{dateLabel(month, { month: "long", year: "numeric" })}</span>
|
||||
{mo.payday && <span className="block text-xs text-muted tabular-nums">{dateLabel(mo.range(ymOf(month)).start, { month: "short", day: "numeric" })} to {dateLabel(lastDay, { month: "short", day: "numeric" })}</span>}
|
||||
</span>
|
||||
{offset < 0 ? (
|
||||
<Link scroll={false} href={qs({ m: offset === -1 ? "now" : ymd(monthStart(now, offset + 1)).slice(0, 7) })} aria-label="Later month" className="size-9 rounded-full border border-line grid place-items-center text-muted hover:text-ink row-hover"><ChevronRight size={18} /></Link>
|
||||
) : <span className="size-9" />}
|
||||
{offset < -1 && <Link scroll={false} href={qs({ m: "now" })} className="text-sm text-muted hover:text-ink underline underline-offset-4 ml-1">This month</Link>}
|
||||
</div>
|
||||
|
||||
<PageDates path="/spending" from="" to="" today={ymd(now)} />
|
||||
<PageDates path="/spending" from="" to="" today={ymd(real)} />
|
||||
|
||||
<nav aria-label="How much to show" className="pill-tabs max-w-full overflow-x-auto">
|
||||
{[
|
||||
@@ -289,7 +302,7 @@ export default async function Spending({ searchParams }: { searchParams: Promise
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
<IncomeSources txns={monthTxns} range={`&from=${ymd(month)}&to=${ymd(new Date(monthStart(now, offset + 1).getTime() - 864e5))}`} />
|
||||
<IncomeSources txns={monthTxns} range={`&from=${mo.range(ymOf(month)).start}&to=${lastDay}`} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
|
||||
@@ -1,58 +1,18 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { planMerge, type MergeRow } from "@/lib/merge";
|
||||
import { mergeAccounts } from "@/lib/merge-run";
|
||||
import { sameOrigin } from "@/lib/setup";
|
||||
import { createAdminClient } from "@/utils/supabase/admin";
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
|
||||
// Merge an imported account into another of the person's accounts (usually the one their bank link made).
|
||||
// preview: true only counts. Both accounts must be theirs, and only an imported (manual) one can be merged away:
|
||||
// a linked account would come back on the next sync.
|
||||
const COLS = "id, date, amount, category_id, custom_name, note, tags, ignored, plaid_transaction_id";
|
||||
|
||||
async function rowsOf(db: ReturnType<typeof createAdminClient>, userId: string, accountId: string) {
|
||||
const out: MergeRow[] = [];
|
||||
for (let from = 0; ; from += 1000) {
|
||||
const { data, error } = await db.from("transactions").select(COLS).eq("user_id", userId).eq("account_id", accountId).order("date").range(from, from + 999);
|
||||
if (error) throw error;
|
||||
out.push(...(data ?? []).map(({ plaid_transaction_id, ...r }) => ({ ...r, fromBank: !!plaid_transaction_id }) as MergeRow));
|
||||
if ((data ?? []).length < 1000) return out;
|
||||
}
|
||||
}
|
||||
const chunks = <T,>(xs: T[], n = 200) => Array.from({ length: Math.ceil(xs.length / n) }, (_, i) => xs.slice(i * n, i * n + n));
|
||||
|
||||
// Merge an imported account into another of the person's accounts (lib/merge-run.ts). preview: true only counts.
|
||||
export async function POST(request: Request) {
|
||||
const { data: { user } } = await (await createClient()).auth.getUser();
|
||||
if (!user) return NextResponse.json({ error: "Not signed in" }, { status: 401 });
|
||||
if (!sameOrigin(request)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
const { from, into, preview } = (await request.json().catch(() => ({}))) as { from?: string; into?: string; preview?: boolean };
|
||||
if (!from || !into || from === into) return NextResponse.json({ error: "Pick the account to merge into." }, { status: 400 });
|
||||
|
||||
const db = createAdminClient();
|
||||
const { data: accts } = await db.from("accounts").select("id, manual").eq("user_id", user.id).in("id", [from, into]);
|
||||
const src = accts?.find((a) => a.id === from), dst = accts?.find((a) => a.id === into);
|
||||
if (!src || !dst) return NextResponse.json({ error: "Account not found." }, { status: 404 });
|
||||
if (!src.manual) return NextResponse.json({ error: "Only an imported account can be merged into another." }, { status: 400 });
|
||||
|
||||
try {
|
||||
const plan = planMerge(await rowsOf(db, user.id, from), await rowsOf(db, user.id, into));
|
||||
const counts = { start: plan.start, moved: plan.move.length, replaced: plan.drop.length, edits: plan.edits.length };
|
||||
if (preview) return NextResponse.json(counts);
|
||||
|
||||
for (const e of plan.edits) {
|
||||
const { error } = await db.from("transactions").update(e.patch).eq("id", e.id).eq("user_id", user.id);
|
||||
if (error) throw error;
|
||||
}
|
||||
for (const ids of chunks(plan.move)) {
|
||||
const { error } = await db.from("transactions").update({ account_id: into }).eq("user_id", user.id).in("id", ids);
|
||||
if (error) throw error;
|
||||
}
|
||||
// Rules and repeating charges that point at the imported account now point at the one it went into.
|
||||
await db.from("rules").update({ account_id: into }).eq("user_id", user.id).eq("account_id", from);
|
||||
await db.from("recurring").update({ account_id: into }).eq("user_id", user.id).eq("account_id", from);
|
||||
// What's left on the imported account is the overlap the bank already has. Deleting the account takes it along.
|
||||
const { error } = await db.from("accounts").delete().eq("id", from).eq("user_id", user.id);
|
||||
if (error) throw error;
|
||||
return NextResponse.json({ ok: true, ...counts });
|
||||
const r = await mergeAccounts(createAdminClient(), user.id, from ?? "", into ?? "", !!preview);
|
||||
return r.error ? NextResponse.json({ error: r.error }, { status: r.status ?? 400 }) : NextResponse.json(r);
|
||||
} catch (e) {
|
||||
console.error("[broke] merge accounts:", e instanceof Error ? e.message : e);
|
||||
return NextResponse.json({ error: "Couldn't finish the merge. Try again: it picks up where it stopped." }, { status: 500 });
|
||||
|
||||
@@ -40,7 +40,7 @@ export async function GET(request: Request, { params }: { params: Promise<{ id:
|
||||
}
|
||||
return back("connect=done");
|
||||
} catch (e) {
|
||||
console.error(`[broke] ${id} connect:`, e instanceof Error ? e.message : e);
|
||||
console.error(`[broke] ${id} connect:`, e instanceof Error ? e.message : JSON.stringify(e));
|
||||
return back("connect=failed");
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { changeLines, checkinFacts, sameDollars, type CheckinFacts } from "@/lib/checkins";
|
||||
import { allRows, today as todayDate, displayName, isSpend, TXN_SELECT, typicalMonthly, type Txn } from "@/lib/data";
|
||||
import { allRows, today as todayDate, displayName, isSpend, paySpan, TXN_SELECT, typicalMonthly, type Txn } from "@/lib/data";
|
||||
import { runViaHelper } from "@/lib/llm/helper";
|
||||
import { runCodex, runGemini, runOpencode } from "@/lib/llm/cli-snapshot";
|
||||
import { AGENT_DIR, runClaudeCode } from "@/lib/llm/claude-code";
|
||||
@@ -83,6 +83,7 @@ async function generate(supabase: Sb, user: User, replace: string | null) {
|
||||
supabase.from("checkins").select("facts").eq("user_id", userId).lt("created_at", new Date(Date.now() - SINCE).toISOString()).order("created_at", { ascending: false }).limit(1).maybeSingle(),
|
||||
loadPlan(supabase, userId).catch(() => null),
|
||||
]);
|
||||
const span = await paySpan(supabase, userId, today); // months that start on payday, if on
|
||||
// The plan's next move by the ladder, or one marked done in the last 7 days.
|
||||
type M = { title: string; why: string; status?: string; done_at?: string | null; deadline: string | null; ref: string | null; kind: Kind; step: number | null };
|
||||
const moves = (plan?.moves ?? []) as unknown as M[];
|
||||
@@ -108,6 +109,7 @@ async function generate(supabase: Sb, user: User, replace: string | null) {
|
||||
prev: (prev?.facts as CheckinFacts | undefined) ?? null,
|
||||
move: pick ? { title: pick.title, line: whyLine(pick.title, pick.why), done: pick === justDone, by: pick.deadline ?? addDays(today, 7) } : null,
|
||||
today,
|
||||
span,
|
||||
});
|
||||
|
||||
// Off: no model call, the card shows the plain facts. Summary: placeholders and rounded amounts, names swapped back below.
|
||||
|
||||
@@ -7,7 +7,7 @@ import { createClient } from "@/utils/supabase/server";
|
||||
// Settings, Database, "Clear my data": the signed-in user's money data, and nobody else's. Bank connections are revoked
|
||||
// at Plaid first, then deleted (accounts, transactions, bills and holdings cascade). Sign-in, profile answers, categories
|
||||
// and the AI connection stay, so they can link again or use a test bank straight away.
|
||||
const TABLES = ["accounts", "transactions", "recurring", "budgets", "rules", "plans", "checkins", "chat_threads", "bookmarks"];
|
||||
const TABLES = ["accounts", "transactions", "recurring", "budgets", "rules", "plans", "checkins", "chat_threads", "bookmarks", "pay_periods"];
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const { data: { user } } = await (await createClient()).auth.getUser();
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { createMcpToken } from "@/lib/llm/mcp-tokens";
|
||||
import { sameOrigin } from "@/lib/setup";
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
|
||||
// Connect your AI makes a token for the MCP endpoint here. It's returned once; listing and revoking go straight to
|
||||
// the table (RLS: own rows, select and delete only).
|
||||
export async function POST(request: Request) {
|
||||
const { data: { user } } = await (await createClient()).auth.getUser();
|
||||
if (!user) return NextResponse.json({ error: "Not signed in" }, { status: 401 });
|
||||
if (!sameOrigin(request)) return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
const { label, level } = (await request.json().catch(() => ({}))) as { label?: string; level?: string };
|
||||
try {
|
||||
return NextResponse.json({ token: await createMcpToken(user.id, typeof label === "string" ? label : "Claude", level === "full" ? "full" : "summary") });
|
||||
} catch (e) {
|
||||
console.error("[broke] mcp token:", e instanceof Error ? e.message : e);
|
||||
return NextResponse.json({ error: "Couldn't make a token. If this is new, restart brokeless so the database updates." }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
||||
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
||||
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { z } from "zod";
|
||||
import { agentClient, mintAgentToken } from "@/lib/llm/agent-auth";
|
||||
import { aiAllowed, SUMMARY_NOTE } from "@/lib/llm/gate";
|
||||
import { mcpUser } from "@/lib/llm/mcp-tokens";
|
||||
import { makeTools } from "@/lib/llm/shared";
|
||||
import { manageTools } from "@/lib/llm/tools/manage";
|
||||
import { maskNumbers, rowTools } from "@/lib/llm/tools/rows";
|
||||
import { createAdminClient } from "@/utils/supabase/admin";
|
||||
|
||||
// brokeless as an MCP server (Streamable HTTP, stateless) for AI apps such as Claude Code. A personal token from
|
||||
// Settings (migration 0033) signs it in as that user; their own session runs every query, so RLS applies.
|
||||
// Summary by default: an outside AI is a cloud model (lib/llm/gate.ts). Full detail only for a token the person made
|
||||
// with Full detail on Connect your AI (migration 0034): their explicit choice, per token. AI switched off: refused.
|
||||
// One user per token: every call runs in that user's own session (RLS), and every tool filters on their id too.
|
||||
const READ_ONLY = new Set(["spending_summary", "search_transactions", "list_recurring", "list_accounts", "list_holdings", "get_profile", "list_categories", "list_rules", "list_transactions"]);
|
||||
const DESTRUCTIVE = new Set(["delete_rule", "merge_accounts", "recategorize", "update_transactions"]);
|
||||
const CHANGES = "Tools that change things act on the real data: say what you will change and how many transactions it touches before you do it, and preview merges first.";
|
||||
const INSTRUCTIONS = `You are connected to the user's own brokeless, a personal finance app. ${SUMMARY_NOTE}
|
||||
${CHANGES}`;
|
||||
const FULL_INSTRUCTIONS = `You are connected to the user's own brokeless, a personal finance app, with full detail: real names, exact amounts, dates and single transactions with their id (IBANs and account numbers are shortened). Amounts: positive is money out, negative is money in. Transfers between the user's own accounts (category kind "transfer") count as neither spending nor income.
|
||||
${CHANGES}`;
|
||||
|
||||
const deny = (status: number, message: string) => Response.json({ jsonrpc: "2.0", error: { code: -32001, message }, id: null }, { status });
|
||||
|
||||
async function handle(request: Request) {
|
||||
const who = await mcpUser(request.headers.get("authorization")?.replace(/^Bearer\s+/i, "") ?? null);
|
||||
const userId = who?.userId, full = who?.level === "full";
|
||||
if (!userId) return deny(401, "Missing or revoked token. Make one in brokeless: Connect your AI, Connect an AI app (MCP).");
|
||||
const { data: { user } } = await createAdminClient().auth.admin.getUserById(userId);
|
||||
if (!user) return deny(401, "That token's account is gone.");
|
||||
if (!aiAllowed(user)) return deny(403, "AI is switched off in brokeless (Settings).");
|
||||
const session = await agentClient(await mintAgentToken(user));
|
||||
if (!session) return deny(503, "Couldn't open a session. Try again.");
|
||||
|
||||
const tools = full
|
||||
? [...makeTools(session.supabase, user.user_metadata?.profile, user.id, "full"), ...manageTools(session.supabase, user.id, true), ...rowTools(session.supabase, user.id)]
|
||||
: [...makeTools(session.supabase, user.user_metadata?.profile, user.id, "summary"), ...manageTools(session.supabase, user.id)];
|
||||
const server = new Server({ name: "brokeless", version: "1.0.0" }, { capabilities: { tools: {} }, instructions: full ? FULL_INSTRUCTIONS : INSTRUCTIONS });
|
||||
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
||||
tools: tools.map((t) => ({
|
||||
name: t.name, description: t.description, inputSchema: z.toJSONSchema(t.schema) as { type: "object" },
|
||||
annotations: { readOnlyHint: READ_ONLY.has(t.name), destructiveHint: DESTRUCTIVE.has(t.name) },
|
||||
})),
|
||||
}));
|
||||
server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
||||
const t = tools.find((x) => x.name === req.params.name);
|
||||
if (!t) return { content: [{ type: "text", text: `Unknown tool ${req.params.name}` }], isError: true };
|
||||
const parsed = t.schema.safeParse(req.params.arguments ?? {});
|
||||
if (!parsed.success) return { content: [{ type: "text", text: `Invalid arguments: ${parsed.error.message}` }], isError: true };
|
||||
try {
|
||||
const text = await t.run(parsed.data as Record<string, unknown>);
|
||||
return { content: [{ type: "text", text: full ? maskNumbers(text) : text }] };
|
||||
} catch (e) {
|
||||
console.error("[broke] mcp tool:", t.name, e instanceof Error ? e.message : e);
|
||||
return { content: [{ type: "text", text: "That didn't work. Try again." }], isError: true };
|
||||
}
|
||||
});
|
||||
const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
|
||||
await server.connect(transport);
|
||||
return transport.handleRequest(request);
|
||||
}
|
||||
|
||||
export const POST = handle;
|
||||
export const GET = handle;
|
||||
export const DELETE = handle;
|
||||
@@ -1,5 +1,5 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { allRows, getUser, moneyByMonth, today as userToday } from "@/lib/data";
|
||||
import { allRows, getUser, moneyByMonth, payMonthToday, today as userToday } from "@/lib/data";
|
||||
import { firstFact } from "@/lib/first-fact";
|
||||
import { dateLabel, FREQ_PER_MONTH, money0, monthStart, ymd } from "@/lib/format";
|
||||
import { typicalMonth } from "@/lib/insights";
|
||||
@@ -17,13 +17,15 @@ export async function GET() {
|
||||
const now = await userToday();
|
||||
const today = ymd(now);
|
||||
const since90 = ymd(new Date(now.getTime() - 90 * 864e5));
|
||||
// Month logic runs on the pay month today is in when months start on payday (lib/paymonths.ts).
|
||||
const monthNow = new Date(`${(await payMonthToday(supabase, uid, today)).slice(0, 7)}-01T00:00:00Z`);
|
||||
const [{ data: items }, { data: accts }, { data: streams }, { data: cats }, { data: first }, rows, interest] = await Promise.all([
|
||||
supabase.from("plaid_items").select("id, last_synced_at").eq("user_id", uid),
|
||||
supabase.from("accounts").select("id, type, manual").eq("user_id", uid),
|
||||
supabase.from("recurring").select("merchant_name, frequency, average_amount:home_average, is_income, next_date, category:categories(key)").eq("user_id", uid).eq("active", true).neq("status", "TOMBSTONED"),
|
||||
supabase.from("categories").select("id, label"),
|
||||
supabase.from("transactions").select("date").eq("user_id", uid).order("date").limit(1),
|
||||
moneyByMonth(supabase, ymd(monthStart(now, -3))),
|
||||
moneyByMonth(supabase, ymd(monthStart(monthNow, -3))),
|
||||
// Card or loan interest, the For you page's rule.
|
||||
allRows<{ amount: number }>((a, b) => supabase.from("transactions").select("amount").eq("user_id", uid).eq("ignored", false).gt("amount", 0).gte("date", since90)
|
||||
.or("plaid_category.eq.BANK_FEES_INTEREST_CHARGE,name.ilike.*interest charge*").order("id").range(a, b)),
|
||||
@@ -39,7 +41,7 @@ export async function GET() {
|
||||
if ((items ?? []).some((i) => !i.last_synced_at) || !oldest) return NextResponse.json({ ...base, status: "importing" });
|
||||
|
||||
// The biggest category in the last full month the history covers, against its average over the full months before it.
|
||||
const ym = (k: number) => ymd(monthStart(now, -k)).slice(0, 7);
|
||||
const ym = (k: number) => ymd(monthStart(monthNow, -k)).slice(0, 7);
|
||||
const covered = [1, 2, 3].map(ym).filter((m) => `${m}-01` >= oldest);
|
||||
const spentIn = (m: string) => {
|
||||
const by = new Map<string, number>();
|
||||
@@ -58,7 +60,7 @@ export async function GET() {
|
||||
};
|
||||
}
|
||||
}
|
||||
const typical = typicalMonth(rows, today, oldest);
|
||||
const typical = typicalMonth(rows, await payMonthToday(supabase, uid, today), oldest);
|
||||
const subs = s.filter((x) => !x.is_income && !BILL.has(x.category?.key ?? "")).map((x) => ({ monthly: x.average_amount * (FREQ_PER_MONTH[x.frequency] ?? 0) }));
|
||||
const fact = firstFact({ typical, interest90: interest.reduce((t, r) => t + Number(r.amount), 0), subs, top }, (n) => money0(n));
|
||||
return NextResponse.json({ ...base, status: fact ? "ready" : "thin", fact });
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { twinAccounts } from "@/lib/links";
|
||||
import { foldInto } from "@/lib/merge-run";
|
||||
import { revokeItem } from "@/lib/plaid";
|
||||
import { createAdminClient } from "@/utils/supabase/admin";
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
|
||||
// Removes a bank connection: revokes it at Plaid, then deletes the item (its accounts, transactions and holdings cascade).
|
||||
type Acct = { id: string; item_id: string | null; name: string | null; mask: string | null; type: string | null };
|
||||
|
||||
// Removes a bank connection: revokes it at the provider, then deletes the connection. Its accounts and their history
|
||||
// stay. An account that another connection also has (linked twice, or linked again) folds into that one: older rows
|
||||
// move over and your categories and names carry over. Any other account stays as an account added by hand, no longer
|
||||
// syncing. Only a test bank's accounts and transactions go with it, because test data never stays next to real banks.
|
||||
export async function POST(request: Request) {
|
||||
const supabase = await createClient();
|
||||
const { data: { user } } = await supabase.auth.getUser();
|
||||
@@ -15,7 +22,36 @@ export async function POST(request: Request) {
|
||||
if (!item) return NextResponse.json({ error: "Connection not found" }, { status: 404 });
|
||||
|
||||
if (!(await revokeItem(item)).ok) return NextResponse.json({ error: "Plaid couldn't remove this connection. Try again in a moment." }, { status: 502 });
|
||||
if (!item.access_token?.startsWith("access-sandbox-")) {
|
||||
try {
|
||||
await keepAccounts(db, user.id, item.id);
|
||||
} catch (e) {
|
||||
console.error("[broke] remove, keeping accounts:", e instanceof Error ? e.message : JSON.stringify(e));
|
||||
return NextResponse.json({ error: "Couldn't keep this connection's accounts, so nothing was removed. Try again." }, { status: 500 });
|
||||
}
|
||||
}
|
||||
const { error } = await db.from("plaid_items").delete().eq("id", item.id);
|
||||
if (error) return NextResponse.json({ error: "Couldn't remove this connection." }, { status: 500 });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
async function keepAccounts(db: ReturnType<typeof createAdminClient>, userId: string, itemId: string) {
|
||||
const { data, error } = await db.from("accounts").select("id, item_id, name, mask, type").eq("user_id", userId).not("item_id", "is", null);
|
||||
if (error) throw error;
|
||||
const all = (data ?? []) as Acct[];
|
||||
const leaving = all.filter((a) => a.item_id === itemId);
|
||||
const twins = twinAccounts(leaving, all.filter((a) => a.item_id !== itemId));
|
||||
for (const a of leaving) {
|
||||
const twin = twins.get(a.id);
|
||||
if (twin) {
|
||||
await foldInto(db, userId, a.id, twin);
|
||||
continue;
|
||||
}
|
||||
// No twin: unlink it. Its rows lose the bank's ids, so linking the bank again adds the bank's rows fresh and
|
||||
// Accounts can merge this one into the new account like an imported statement.
|
||||
const rows = await db.from("transactions").update({ plaid_transaction_id: null }).eq("user_id", userId).eq("account_id", a.id);
|
||||
if (rows.error) throw rows.error;
|
||||
const acct = await db.from("accounts").update({ item_id: null, plaid_account_id: null, manual: true }).eq("id", a.id).eq("user_id", userId);
|
||||
if (acct.error) throw acct.error;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { saveFoundRecurring } from "@/lib/recurring-save";
|
||||
import { NextResponse } from "next/server";
|
||||
import { plaidError } from "@/lib/plaid";
|
||||
import { ITEM_COLS, syncItem } from "@/lib/sync";
|
||||
import { fileOwnTransfers, ITEM_COLS, syncItem } from "@/lib/sync";
|
||||
import { createAdminClient } from "@/utils/supabase/admin";
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
|
||||
@@ -35,6 +35,8 @@ export async function POST() {
|
||||
results.push({ id: item.id, added: 0, modified: 0, removed: 0, error: err.code });
|
||||
}
|
||||
}
|
||||
// Transfers between own accounts nobody marked (imported statements): neither spending nor income.
|
||||
await fileOwnTransfers(user.id).catch((e) => console.error("[broke] own transfers:", e instanceof Error ? e.message : e));
|
||||
// broke's own recurring finder, over every account (Plaid's misses, feeds, imported statements).
|
||||
await saveFoundRecurring(user.id).catch((e) => console.error("[broke] recurring:", e instanceof Error ? e.message : e));
|
||||
return NextResponse.json({ ok: true, results });
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { saveFoundRecurring } from "@/lib/recurring-save";
|
||||
import { fileOwnTransfers } from "@/lib/sync";
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
|
||||
// Finds charges and pay that repeat in the signed-in user's own transactions. Called after a statement import.
|
||||
export async function POST() {
|
||||
const { data: { user } } = await (await createClient()).auth.getUser();
|
||||
if (!user) return NextResponse.json({ error: "Not signed in" }, { status: 401 });
|
||||
// A statement just came in: mark transfers between own accounts first, so they aren't found as repeating charges.
|
||||
await fileOwnTransfers(user.id).catch((e) => console.error("[broke] own transfers:", e instanceof Error ? e.message : e));
|
||||
return NextResponse.json(await saveFoundRecurring(user.id));
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { fileOwnTransfers } from "@/lib/sync";
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
|
||||
// Marks transfers between the signed-in user's own accounts (lib/transfers.ts findOwnTransfers). AutoSync calls it on
|
||||
// opening broke, apart from the bank sync, which only runs every few hours: imported statements need it too.
|
||||
export async function POST() {
|
||||
const { data: { user } } = await (await createClient()).auth.getUser();
|
||||
if (!user) return NextResponse.json({ error: "Not signed in" }, { status: 401 });
|
||||
try {
|
||||
return NextResponse.json({ marked: await fileOwnTransfers(user.id) });
|
||||
} catch (e) {
|
||||
console.error("[broke] own transfers:", e instanceof Error ? e.message : e);
|
||||
return NextResponse.json({ error: "Couldn't check for transfers." }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,10 @@
|
||||
--shadow-card: 0 1px 2px #0000000a, 0 6px 20px -8px #00000014;
|
||||
--shadow-pop: 0 1px 3px #0000000f, 0 18px 44px -14px #00000038;
|
||||
--backdrop: #0000004d; /* behind a modal */
|
||||
/* Charts page: categorical series, in this fixed order (validated for colour blindness on #fff; three sit below 3:1,
|
||||
so every chart has a legend, tooltips and a table view). "other" is the fold for everything past slot 7. */
|
||||
--series-1: #2a78d6; --series-2: #eb6834; --series-3: #1baf7a; --series-4: #eda100;
|
||||
--series-5: #e87ba4; --series-6: #008300; --series-7: #6250d6; --series-8: #e34948; --series-other: #a3a3a0;
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
@@ -37,6 +41,7 @@
|
||||
/* Dark lifts cards with a top highlight, not a shadow. */
|
||||
--shadow-card: inset 0 1px 0 #ffffff0a, 0 1px 2px #00000059; --shadow-pop: inset 0 1px 0 #ffffff0f, 0 18px 44px -14px #000000b3;
|
||||
--good: #4ade80; --bad: #f87171; --on-ink: #141414; --backdrop: #000000a6; color-scheme: dark;
|
||||
--series-1: #3987e5; --series-2: #d95926; --series-3: #199e70; --series-4: #c98500; --series-5: #d55181; --series-6: #0ca30c; --series-7: #9085e9; --series-8: #e66767; --series-other: #6b6b72;
|
||||
/* Tailwind's pale status tints, dimmed for dark surfaces. */
|
||||
--color-green-50: #4ade801a; --color-green-100: #4ade8033; --color-red-50: #f871711f; --color-amber-50: #f59e0b1f; --color-amber-600: #fbbf24;
|
||||
}
|
||||
@@ -47,6 +52,7 @@
|
||||
/* Dark lifts cards with a top highlight, not a shadow. */
|
||||
--shadow-card: inset 0 1px 0 #ffffff0a, 0 1px 2px #00000059; --shadow-pop: inset 0 1px 0 #ffffff0f, 0 18px 44px -14px #000000b3;
|
||||
--good: #4ade80; --bad: #f87171; --on-ink: #141414; --backdrop: #000000a6; color-scheme: dark;
|
||||
--series-1: #3987e5; --series-2: #d95926; --series-3: #199e70; --series-4: #c98500; --series-5: #d55181; --series-6: #0ca30c; --series-7: #9085e9; --series-8: #e66767; --series-other: #6b6b72;
|
||||
--color-green-50: #4ade801a; --color-green-100: #4ade8033; --color-red-50: #f871711f; --color-amber-50: #f59e0b1f; --color-amber-600: #fbbf24;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,17 +4,19 @@ import { useRouter } from "next/navigation";
|
||||
import { useEffect } from "react";
|
||||
|
||||
// Opening broke syncs any bank that's due (the layout decides), in the background, once per 10 minutes per tab,
|
||||
// then refreshes the page with what came in. Without a deployed webhook this is how new and older history arrives.
|
||||
// then refreshes the page with what came in. With nothing due it still checks for transfers between own accounts. Without a deployed webhook this is how new and older history arrives.
|
||||
export function AutoSync({ due }: { due: boolean }) {
|
||||
const router = useRouter();
|
||||
useEffect(() => {
|
||||
if (!due) return;
|
||||
try {
|
||||
const last = Number(sessionStorage.getItem("broke:autosync"));
|
||||
if (last && Date.now() - last < 10 * 60_000) return;
|
||||
sessionStorage.setItem("broke:autosync", String(Date.now()));
|
||||
} catch {}
|
||||
fetch("/api/plaid/sync", { method: "POST" }).then((r) => r.ok && router.refresh()).catch(() => {});
|
||||
// A due bank syncs, and the sync also marks transfers. Otherwise only the transfer check runs: imported statements
|
||||
// between own accounts would count as spending and income until the next bank sync, hours away or never.
|
||||
if (due) fetch("/api/plaid/sync", { method: "POST" }).then((r) => r.ok && router.refresh()).catch(() => {});
|
||||
else fetch("/api/transfers/find", { method: "POST" }).then((r) => (r.ok ? r.json() : null)).then((b) => b?.marked && router.refresh()).catch(() => {});
|
||||
}, [due, router]);
|
||||
return null;
|
||||
}
|
||||
@@ -23,7 +23,8 @@ export type BudgetCat = { id: string; label: string; icon: string; color: string
|
||||
// Bars use the app's chart blue, like the rest of the app; only an overspend turns red.
|
||||
const TEXT = { ok: "text-muted", near: "text-ink", over: "text-bad" };
|
||||
|
||||
export function BudgetEditor({ basis, cats: all, initial, year, range, today, income, now, tableMissing, aside }: { basis: string; cats: BudgetCat[]; initial: Record<string, number>; year: MonthSpend[]; range: BudgetRange | null; today: string; income: number; now: string; tableMissing: boolean; aside?: React.ReactNode }) {
|
||||
// span and label: with pay months on, this month's dates and the calendar month it's named after ("YYYY-MM-01").
|
||||
export function BudgetEditor({ basis, cats: all, initial, year, range, today, income, now, tableMissing, aside, span, label }: { basis: string; cats: BudgetCat[]; initial: Record<string, number>; year: MonthSpend[]; range: BudgetRange | null; today: string; income: number; now: string; tableMissing: boolean; aside?: React.ReactNode; span?: { start: string; end: string }; label?: string }) {
|
||||
const { money0, dateLabel } = useMoney();
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
const [budgets, setBudgets] = useState(initial);
|
||||
@@ -41,8 +42,8 @@ export function BudgetEditor({ basis, cats: all, initial, year, range, today, in
|
||||
try { localStorage.setItem("budget-view", v); } catch {}
|
||||
};
|
||||
|
||||
const m = month(new Date(now));
|
||||
const d = new Date(now);
|
||||
const m = month(new Date(now), span);
|
||||
const d = new Date(label ? `${label}T00:00:00Z` : now);
|
||||
const lastMonth = dateLabel(new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() - 1, 1)).toISOString().slice(0, 10), { month: "long" });
|
||||
// This month or last: the same rows with "spent" swapped, so the list, table and summary all follow.
|
||||
const [period, setPeriod] = useState<"this" | "last" | "year" | "custom">(() => range ? "custom" : startPeriod(m.day, all.filter((c) => c.id in initial).reduce((s, c) => s + c.last, 0)));
|
||||
@@ -227,7 +228,7 @@ export function BudgetEditor({ basis, cats: all, initial, year, range, today, in
|
||||
<div className="section-label px-1">Summary</div>
|
||||
<section className="card p-6 space-y-5">
|
||||
<div>
|
||||
<div className="card-title">{past ? lastMonth : dateLabel(now.slice(0, 10), { month: "long" })}</div>
|
||||
<div className="card-title">{past ? lastMonth : dateLabel(label ?? now.slice(0, 10), { month: "long" })}</div>
|
||||
<div className="figure mt-1">
|
||||
{left >= 0 ? <CountUp value={left} format="money0" /> : money0(-left)}{" "}
|
||||
<span className={`text-base font-medium tracking-normal ${left >= 0 ? "text-muted" : "text-bad"}`}>{left >= 0 ? (past ? "under" : "left") : "over"}</span>
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { Heart } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Modal } from "@/components/Modal";
|
||||
|
||||
export const DONATE_URL = "https://buy.stripe.com/5kQ6oHgXWc1T33CbNt5Vu05";
|
||||
const USED = "broke.minutesUsed", ASKED = "broke.donateAsked";
|
||||
const ASK_AFTER = 120; // minutes with broke open and on screen
|
||||
|
||||
const read = (k: string) => { try { return localStorage.getItem(k); } catch { return null; } };
|
||||
const write = (k: string, v: string) => { try { localStorage.setItem(k, v); } catch { /* private window: just don't count */ } };
|
||||
|
||||
export function DonateLink({ className = "" }: { className?: string }) {
|
||||
return (
|
||||
<a href={DONATE_URL} target="_blank" rel="noopener noreferrer" className={className}>
|
||||
<Heart size={18} strokeWidth={1.6} className="shrink-0" />
|
||||
<span className="flex-1 text-left">Support broke</span>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
// Asks once, after about two hours of use: minutes count only while a broke tab is open and visible, in this browser.
|
||||
export function DonatePrompt() {
|
||||
const [open, setOpen] = useState(false);
|
||||
useEffect(() => {
|
||||
if (read(ASKED)) return;
|
||||
const tick = setInterval(() => {
|
||||
if (document.visibilityState !== "visible") return;
|
||||
const used = Number(read(USED) ?? 0) + 1;
|
||||
write(USED, String(used));
|
||||
if (used < ASK_AFTER || read(ASKED)) return;
|
||||
write(ASKED, new Date().toISOString());
|
||||
setOpen(true);
|
||||
clearInterval(tick);
|
||||
}, 60_000);
|
||||
return () => clearInterval(tick);
|
||||
}, []);
|
||||
if (!open) return null;
|
||||
return (
|
||||
<Modal label="Support broke" onClose={() => setOpen(false)}>
|
||||
<div className="space-y-4">
|
||||
<Heart size={22} strokeWidth={1.6} className="text-muted" />
|
||||
<div className="space-y-1.5">
|
||||
<h2 className="text-lg font-semibold">Finding broke useful?</h2>
|
||||
<p className="text-sm text-muted">broke is free and open source. If it's saved you money, you can chip in to keep it going. This is the only time it asks.</p>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<a href={DONATE_URL} target="_blank" rel="noopener noreferrer" onClick={() => setOpen(false)} className="btn-primary" data-autofocus>Donate</a>
|
||||
<button className="btn" onClick={() => setOpen(false)}>Not now</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { createClient } from "@/utils/supabase/client";
|
||||
|
||||
// Connect your AI: personal tokens for brokeless's MCP endpoint (api/mcp), for AI apps such as Claude Code.
|
||||
// A new token shows once, with the command that adds it to Claude Code. Revoking deletes it: the app loses access at once.
|
||||
type Row = { id: string; label: string; created_at: string; last_used_at: string | null; level: "summary" | "full" };
|
||||
const when = (d: string | null) => (d ? new Date(d).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }) : "never");
|
||||
|
||||
export function McpTokens() {
|
||||
const [rows, setRows] = useState<Row[] | null>(null);
|
||||
const [fresh, setFresh] = useState<string | null>(null);
|
||||
const [err, setErr] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [level, setLevel] = useState<"summary" | "full">("summary");
|
||||
const [agree, setAgree] = useState(false);
|
||||
const load = () => createClient().from("mcp_tokens").select("id, label, created_at, last_used_at, level").order("created_at").then(({ data }) => setRows((data ?? []) as Row[]));
|
||||
useEffect(() => { load(); }, []);
|
||||
const url = typeof window === "undefined" ? "" : `${window.location.origin}/api/mcp`;
|
||||
const command = fresh ? `claude mcp add --scope user --transport http brokeless ${url} --header "Authorization: Bearer ${fresh}"` : "";
|
||||
|
||||
async function make() {
|
||||
setBusy(true);
|
||||
setErr("");
|
||||
const r = await fetch("/api/mcp-tokens", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ label: level === "full" ? "Claude (full detail)" : "Claude", level }) });
|
||||
const b = (await r.json().catch(() => ({}))) as { token?: string; error?: string };
|
||||
setBusy(false);
|
||||
if (!r.ok || !b.token) return setErr(b.error ?? "Couldn't make a token.");
|
||||
setFresh(b.token);
|
||||
load();
|
||||
}
|
||||
async function revoke(id: string) {
|
||||
await createClient().from("mcp_tokens").delete().eq("id", id);
|
||||
load();
|
||||
}
|
||||
function copy(text: string) {
|
||||
if (navigator.clipboard) return void navigator.clipboard.writeText(text);
|
||||
const t = Object.assign(document.createElement("textarea"), { value: text });
|
||||
document.body.append(t);
|
||||
t.select();
|
||||
document.execCommand("copy");
|
||||
t.remove();
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="card p-6 space-y-3">
|
||||
<div className="space-y-1">
|
||||
<h2 className="card-title">Connect an AI app (MCP)</h2>
|
||||
<p className="text-sm text-muted">Let an AI app like Claude Code look at your money and fix things for you: rules, categories, transfers, merging accounts. A token only ever reaches your own data.</p>
|
||||
</div>
|
||||
{fresh && (
|
||||
<div className="space-y-2 rounded-xl border border-line p-3">
|
||||
<p className="text-sm font-medium">Your token. It shows only now: copy it before you leave this page.</p>
|
||||
<p className="text-xs text-muted">Add it to Claude Code by running this on your computer. --scope user makes it work in every folder, not only the one you run it in.</p>
|
||||
<code className="block text-xs break-all rounded-lg bg-canvas p-3">{command}</code>
|
||||
<div className="flex gap-2">
|
||||
<button type="button" className="btn" onClick={() => copy(command)}>Copy command</button>
|
||||
<button type="button" className="btn" onClick={() => copy(fresh)}>Copy token only</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{!!rows?.length && (
|
||||
<ul className="text-sm">
|
||||
{rows.map((r) => (
|
||||
<li key={r.id} className="flex items-center justify-between gap-3 border-t border-line py-2">
|
||||
<span>{r.label} <span className={r.level === "full" ? "text-bad" : "text-muted"}>· {r.level === "full" ? "full detail" : "summary"}</span> <span className="text-muted">· made {when(r.created_at)} · last used {when(r.last_used_at)}</span></span>
|
||||
<button type="button" className="text-bad underline underline-offset-2" onClick={() => revoke(r.id)}>Revoke</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{err && <p className="text-sm text-bad">{err}</p>}
|
||||
<fieldset className="space-y-2 text-sm">
|
||||
<legend className="font-medium pb-1">What the AI app may see</legend>
|
||||
<label className="flex gap-2 cursor-pointer"><input type="radio" name="mcp-level" checked={level === "summary"} onChange={() => setLevel("summary")} />
|
||||
<span><span className="font-medium">Summary</span> <span className="text-muted">· like broke ai: rounded amounts, months, placeholder names (⟨M1⟩), never single transactions.</span></span></label>
|
||||
<label className="flex gap-2 cursor-pointer"><input type="radio" name="mcp-level" checked={level === "full"} onChange={() => setLevel("full")} />
|
||||
<span><span className="font-medium">Full detail</span> <span className="text-muted">· real names, exact amounts, dates and single transactions, so it can fix them one by one. IBANs and account numbers are shortened.</span></span></label>
|
||||
{level === "full" && (
|
||||
<label className="flex gap-2 cursor-pointer rounded-xl border border-line p-3">
|
||||
<input type="checkbox" checked={agree} onChange={(e) => setAgree(e.target.checked)} />
|
||||
<span>I understand the AI app sends my real transactions to its maker (for Claude: Anthropic) while I use it.</span>
|
||||
</label>
|
||||
)}
|
||||
</fieldset>
|
||||
<button type="button" className="btn" disabled={busy || (level === "full" && !agree)} onClick={make}>{busy ? "Making..." : level === "full" ? "Make a full-detail token" : "Make a token"}</button>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import { usePathname, useRouter } from "next/navigation";
|
||||
import { Suspense, useEffect, useState } from "react";
|
||||
import { useAssistant } from "@/components/Assistant";
|
||||
import { BookmarkButton, SavedList } from "@/components/Bookmarks";
|
||||
import { DonateLink, DonatePrompt } from "@/components/Donate";
|
||||
|
||||
// Spending holds Budgets and Recurring as tabs, Plan holds Optimize, Bonuses and Cards, More holds the rest. Every page keeps its own URL.
|
||||
type Icon = ComponentType<{ size?: number; strokeWidth?: number }>;
|
||||
@@ -19,7 +18,7 @@ const LINKS: { href: string; label: string; icon: Icon }[] = [
|
||||
{ href: "/accounts", label: "Accounts", icon: Landmark },
|
||||
{ href: "/more", label: "More", icon: Ellipsis },
|
||||
];
|
||||
const SPENDING = [{ href: "/spending", label: "Overview" }, { href: "/budgets", label: "Budgets" }, { href: "/recurring", label: "Recurring" }];
|
||||
const SPENDING = [{ href: "/spending", label: "Overview" }, { href: "/charts", label: "Charts" }, { href: "/budgets", label: "Budgets" }, { href: "/recurring", label: "Recurring" }];
|
||||
const PLAN = [{ href: "/plan", label: "Money plan" }, { href: "/optimize", label: "Optimize" }, { href: "/bonuses", label: "Bonuses" }, { href: "/cards", label: "Cards" }];
|
||||
const under = (path: string, href: string) => (href === "/" ? path === "/" : path === href || path.startsWith(href + "/"));
|
||||
const tabsOf = (path: string) => [SPENDING, PLAN].find((g) => g.some((t) => under(path, t.href)));
|
||||
@@ -61,10 +60,8 @@ export function Nav() {
|
||||
<MessageCircle size={18} strokeWidth={1.6} />
|
||||
<span className="flex-1 text-left">Ask broke ai</span>
|
||||
</button>
|
||||
<DonateLink className="flex items-center gap-3 px-3 py-2 rounded-xl text-[14px] whitespace-nowrap text-ink/70 hover:text-ink hover:bg-canvas/60" />
|
||||
<Suspense><SavedList /></Suspense>
|
||||
</nav>
|
||||
<DonatePrompt />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -155,7 +155,7 @@ export function ConnectionActions({ itemId, broken, name }: { itemId: string; br
|
||||
<span className="flex items-center gap-2">
|
||||
{confirm ? (
|
||||
<>
|
||||
<span className="text-xs text-muted">Remove {name} and its transactions?</span>
|
||||
<span className="text-xs text-muted">Stop syncing {name}? Its accounts and history stay.</span>
|
||||
<button className="btn text-bad" onClick={remove} disabled={removing}>{removing ? "Removing..." : "Remove"}</button>
|
||||
<button className="btn" onClick={() => setConfirm(false)} disabled={removing}>Cancel</button>
|
||||
</>
|
||||
@@ -226,7 +226,7 @@ export function RemoveCopy({ itemId, name }: { itemId: string; name: string }) {
|
||||
}
|
||||
return confirm ? (
|
||||
<span className="flex flex-wrap items-center gap-2 text-sm">
|
||||
<span className="text-muted">Remove this copy of {name}? The other one keeps all your transactions.</span>
|
||||
<span className="text-muted">Remove this copy of {name}? Its history and your changes move to the other one.</span>
|
||||
<button className="btn text-bad" onClick={remove} disabled={busy}>{busy ? "Removing..." : "Remove copy"}</button>
|
||||
<button className="text-muted hover:text-ink" onClick={() => setConfirm(false)} disabled={busy}>Cancel</button>
|
||||
{err && <span className="text-bad">{err}</span>}
|
||||
|
||||
@@ -21,6 +21,7 @@ export type Profile = {
|
||||
alsoBanksIn?: string[]; // countries besides their own: only "NZ" changes anything today (wantsAkahu)
|
||||
credit?: string; creditAsOf?: string; // a credit.ts Band and a "YYYY-MM" month
|
||||
pay?: { amount: number; every: string }; // take-home pay per check; every: a Plaid frequency (WEEKLY ... MONTHLY)
|
||||
month?: "payday"; // months start on payday (lib/paymonths.ts); absent = on the 1st
|
||||
onboarding?: string; // the first-run step to resume at (Onboarding.tsx); absent or "done" = finished
|
||||
};
|
||||
|
||||
|
||||
+32
-32
@@ -10,33 +10,20 @@ import { useMoney } from "@/components/Money";
|
||||
import { TagEditor } from "@/components/Tags";
|
||||
import type { Category } from "@/lib/data";
|
||||
import { displayName, plural } from "@/lib/format";
|
||||
import { findsSomething, matches, mergeTags, type Rule } from "@/lib/rules";
|
||||
import { findsSomething, type Rule } from "@/lib/rules";
|
||||
import { applyRulePast, pastMatchesWith, undoRuleWith, type PastRow } from "@/lib/rule-past";
|
||||
import { createClient } from "@/utils/supabase/client";
|
||||
|
||||
export type Draft = Omit<Rule, "id"> & { id?: string };
|
||||
export const emptyRule = (x: Partial<Draft> = {}): Draft => ({ match: "", amount_min: null, amount_max: null, account_id: null, day_from: null, day_to: null, category_id: null, rename: null, ignore: null, add_tags: null, ...x });
|
||||
|
||||
type Match = { id: string; date: string; name: string; merchant_name: string | null; custom_name: string | null; logo_url: string | null; amount: number; currency: string | null; account_id: string; tags: string[] | null };
|
||||
type Match = PastRow;
|
||||
const session = async () => { const db = createClient(); return { db, uid: (await db.auth.getSession()).data.session?.user.id } };
|
||||
|
||||
// Past transactions the rule matches, newest first. Name and account filter in Postgres, the rest here.
|
||||
// Past transactions the rule matches, newest first (lib/rule-past.ts).
|
||||
export async function pastMatches(d: Draft) {
|
||||
if (!findsSomething(d)) return [];
|
||||
const s = d.match.trim().replace(/[%,()]/g, " ");
|
||||
const db = createClient();
|
||||
const uid = (await db.auth.getSession()).data.session?.user.id;
|
||||
if (!uid) return [];
|
||||
// Own rows only (not a partner's shared ones), paged: Supabase returns at most 1000 rows per request.
|
||||
// ponytail: a rule with no name pages through every own row; fine for a personal ledger, an RPC if it gets slow.
|
||||
const rows: Match[] = [];
|
||||
for (let from = 0; ; from += 1000) {
|
||||
let q = db.from("transactions").select("id, date, name, merchant_name, custom_name, logo_url, amount, currency, account_id, tags").eq("user_id", uid);
|
||||
if (s) q = q.or(`name.ilike.%${s}%,merchant_name.ilike.%${s}%`);
|
||||
if (d.account_id) q = q.eq("account_id", d.account_id);
|
||||
const { data } = await q.order("date", { ascending: false }).order("id").range(from, from + 999);
|
||||
rows.push(...((data ?? []) as Match[]));
|
||||
if (!data || data.length < 1000) break;
|
||||
}
|
||||
return rows.filter((t) => matches(d, t));
|
||||
const { db, uid } = await session();
|
||||
return uid ? pastMatchesWith(db, uid, d) : [];
|
||||
}
|
||||
|
||||
/** Saves the rule and, if asked, rewrites the past transactions it matches. Returns how many changed, or an error. */
|
||||
@@ -49,16 +36,17 @@ export async function saveRule(d: Draft, applyPast: boolean): Promise<{ error?:
|
||||
const { error } = d.id ? await supabase.from("rules").update(row).eq("id", d.id) : await supabase.from("rules").insert(row);
|
||||
if (error) return { error: /rules|column/.test(error.message) ? "Rules need a database update. Open Setup to run it." : "Couldn't save the rule.", updated: 0 };
|
||||
if (!applyPast) return { updated: 0 };
|
||||
const patch = { ...(row.category_id ? { category_id: row.category_id } : {}), ...(row.rename ? { custom_name: row.rename } : {}), ...(row.ignore != null ? { ignored: row.ignore } : {}) };
|
||||
const past = await pastMatches(d);
|
||||
const ids = past.map((t) => t.id);
|
||||
if (Object.keys(patch).length) for (let i = 0; i < ids.length; i += 200) await supabase.from("transactions").update(patch).in("id", ids.slice(i, i + 200));
|
||||
// Tags merge with what each row already has, so it's one write per row that gains a tag.
|
||||
// ponytail: per-row updates, 10 at a time; a Postgres function would do it in one call if rules grow to thousands of rows.
|
||||
const tagged = row.add_tags ? past.filter((t) => mergeTags(t.tags, row.add_tags).length > (t.tags ?? []).length) : [];
|
||||
for (let i = 0; i < tagged.length; i += 10)
|
||||
await Promise.all(tagged.slice(i, i + 10).map((t) => supabase.from("transactions").update({ tags: mergeTags(t.tags, row.add_tags) }).eq("id", t.id)));
|
||||
return { updated: ids.length };
|
||||
const { db, uid } = await session();
|
||||
return { updated: uid ? await applyRulePast(db, uid, { ...d, ...row }) : 0 };
|
||||
}
|
||||
|
||||
/** Takes back what a rule did to past transactions (lib/rule-past.ts), then looks for own transfers again, since rows
|
||||
* without a category are open to that. */
|
||||
export async function undoRule(rule: Draft): Promise<number> {
|
||||
const { db, uid } = await session();
|
||||
const n = uid ? await undoRuleWith(db, uid, rule) : 0;
|
||||
await fetch("/api/transfers/find", { method: "POST" }).catch(() => null);
|
||||
return n;
|
||||
}
|
||||
|
||||
export const categoryOptions = (cats: Category[]) =>
|
||||
@@ -149,10 +137,15 @@ export function RuleDialog({ initial, cats, allTags, onClose, onDone }: { initia
|
||||
onDone(r.updated ? `Rule saved. Updated ${plural(r.updated, "past transaction")}.` : "Rule saved.");
|
||||
}
|
||||
|
||||
const [undoPast, setUndoPast] = useState(true);
|
||||
async function remove() {
|
||||
setBusy(true);
|
||||
// Undo first, while the rule still exists to say which rows it changed; the saved rule, not unsaved edits.
|
||||
const undone = undoPast ? await undoRule({ ...initial, id: d.id }) : 0;
|
||||
const { error } = await createClient().from("rules").delete().eq("id", d.id!);
|
||||
setBusy(false);
|
||||
if (error) return setErr("Couldn't delete the rule.");
|
||||
onDone("Rule deleted. Past transactions keep their changes.");
|
||||
onDone(undoPast ? `Rule deleted. Took it back on ${plural(undone, "past transaction")}.` : "Rule deleted. Past transactions keep their changes.");
|
||||
}
|
||||
|
||||
// Until the count for these settings lands, say so instead of showing 0 (or the last count).
|
||||
@@ -178,6 +171,10 @@ export function RuleDialog({ initial, cats, allTags, onClose, onDone }: { initia
|
||||
<p className="text-sm text-muted pb-1">First, set up how your rule finds transactions. Pick one or more.</p>
|
||||
<Option icon={Pencil} label="Match on name" on={on.name} set={turn("name")}>
|
||||
<input autoFocus value={d.match} onChange={(e) => setD({ ...d, match: e.target.value })} placeholder="Name contains, e.g. uber" aria-label="Name contains" className="select" />
|
||||
{/* Text matches anywhere in a name: "ing" is also in Stichting, Payments and every ING IBAN. */}
|
||||
{d.match.trim().length > 0 && d.match.trim().length <= 3 && (
|
||||
<p className="text-xs text-bad">Short text also matches inside other words: "{d.match.trim()}" is in more names than you'd think. Check the matches, or use a longer piece of the name.</p>
|
||||
)}
|
||||
</Option>
|
||||
<Option icon={DollarSign} label="Match on amount" on={on.amount} set={turn("amount")}>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
@@ -220,7 +217,10 @@ export function RuleDialog({ initial, cats, allTags, onClose, onDone }: { initia
|
||||
{d.id && (
|
||||
<div className="px-1 pt-2 text-sm">
|
||||
{confirmDelete
|
||||
? <span className="flex flex-wrap items-center gap-2"><span>Delete this rule? Past transactions keep their changes.</span><button type="button" onClick={remove} className="font-medium text-bad hover:opacity-70">Delete</button><button type="button" onClick={() => setConfirmDelete(false)} className="text-muted hover:text-ink">Cancel</button></span>
|
||||
? <span className="flex flex-col gap-2">
|
||||
<label className="flex items-center gap-2 cursor-pointer"><input type="checkbox" checked={undoPast} onChange={(e) => setUndoPast(e.target.checked)} className="size-4 accent-[var(--color-ink)]" />Also undo it on the past transactions it changed</label>
|
||||
<span className="flex flex-wrap items-center gap-2"><span>Delete this rule?</span><button type="button" onClick={remove} disabled={busy} className="font-medium text-bad hover:opacity-70">{busy ? "Deleting..." : "Delete"}</button><button type="button" onClick={() => setConfirmDelete(false)} className="text-muted hover:text-ink">Cancel</button></span>
|
||||
</span>
|
||||
: <button type="button" onClick={() => setConfirmDelete(true)} className="text-muted underline underline-offset-2 hover:text-bad">Delete rule</button>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
"use client";
|
||||
|
||||
import { Search } from "lucide-react";
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Dropdown } from "@/components/Dropdown";
|
||||
|
||||
// The Charts page's filters, in one row above the charts. Each one lives in the URL, so back, refresh and links keep it.
|
||||
// Lists (accounts, categories, tags) are comma-separated ids; empty means all.
|
||||
|
||||
type Opt = { value: string; label: string };
|
||||
const RANGES = [
|
||||
{ value: "1m", label: "This month" }, { value: "3m", label: "Last 3 months" }, { value: "6m", label: "Last 6 months" },
|
||||
{ value: "12m", label: "Last 12 months" }, { value: "ytd", label: "This year" }, { value: "all", label: "Everything" },
|
||||
];
|
||||
const GROUPS = [{ value: "", label: "Group: automatic" }, { value: "day", label: "By day" }, { value: "week", label: "By week" }, { value: "month", label: "By month" }];
|
||||
const DIRS = [{ value: "", label: "Money in and out" }, { value: "out", label: "Only money out" }, { value: "in", label: "Only money in" }];
|
||||
|
||||
function Multi({ label, all, options, value, onChange }: { label: string; all: string; options: Opt[]; value: string[]; onChange: (v: string[]) => void }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const box = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const close = (e: PointerEvent) => { if (!box.current?.contains(e.target as Node)) setOpen(false); };
|
||||
document.addEventListener("pointerdown", close);
|
||||
return () => document.removeEventListener("pointerdown", close);
|
||||
}, [open]);
|
||||
const picked = options.filter((o) => value.includes(o.value));
|
||||
const text = !picked.length ? all : picked.length === 1 ? picked[0].label : `${label}: ${picked.length}`;
|
||||
return (
|
||||
<div ref={box} className="relative">
|
||||
<button type="button" aria-haspopup="listbox" aria-expanded={open} aria-label={`${label}: ${text}`} onClick={() => setOpen(!open)}
|
||||
className={`btn !py-1.5 text-sm ${picked.length ? "!bg-ink !text-on-ink" : ""}`}>{text}</button>
|
||||
{open && (
|
||||
<div role="listbox" aria-multiselectable className="absolute z-20 mt-1 w-64 max-h-72 overflow-auto card p-2 shadow-[var(--shadow-pop)]">
|
||||
<button type="button" className="w-full text-left text-xs text-muted px-2 py-1 hover:text-ink" onClick={() => onChange([])}>{all}</button>
|
||||
{options.map((o) => (
|
||||
<label key={o.value} className="flex items-center gap-2 px-2 py-1.5 rounded-lg hover:bg-[var(--hover)] text-sm cursor-pointer">
|
||||
<input type="checkbox" checked={value.includes(o.value)} onChange={(e) => onChange(e.target.checked ? [...value, o.value] : value.filter((v) => v !== o.value))} />
|
||||
<span className="truncate">{o.label}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ChartFilters({ accounts, categories, tags }: { accounts: Opt[]; categories: Opt[]; tags: Opt[] }) {
|
||||
const router = useRouter(), path = usePathname(), params = useSearchParams();
|
||||
const set = (patch: Record<string, string | null>) => {
|
||||
const next = new URLSearchParams(params);
|
||||
for (const [k, v] of Object.entries(patch)) {
|
||||
if (v) next.set(k, v);
|
||||
else next.delete(k);
|
||||
}
|
||||
router.replace(`${path}?${next}`, { scroll: false });
|
||||
};
|
||||
const list = (k: string) => (params.get(k) ?? "").split(",").filter(Boolean);
|
||||
const [q, setQ] = useState(params.get("q") ?? "");
|
||||
useEffect(() => {
|
||||
if (q === (params.get("q") ?? "")) return;
|
||||
const t = setTimeout(() => set({ q: q.trim() || null }), 400);
|
||||
return () => clearTimeout(t);
|
||||
});
|
||||
const custom = !!(params.get("from") || params.get("to"));
|
||||
const any = ["acct", "cat", "tag", "q", "dir", "from", "to", "g"].some((k) => params.get(k));
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Dropdown label="Time range" value={custom ? "custom" : params.get("range") ?? "12m"}
|
||||
options={[...RANGES, ...(custom ? [{ value: "custom", label: "Custom dates" }] : [])]}
|
||||
onChange={(v) => set({ range: v === "12m" ? null : v, from: null, to: null })} />
|
||||
<label className="flex items-center gap-1 text-sm text-muted">
|
||||
<input type="date" aria-label="From" className="select !py-1 !w-auto" value={params.get("from") ?? ""} onChange={(e) => set({ from: e.target.value || null, range: null })} />
|
||||
–
|
||||
<input type="date" aria-label="To" className="select !py-1 !w-auto" value={params.get("to") ?? ""} onChange={(e) => set({ to: e.target.value || null, range: null })} />
|
||||
</label>
|
||||
<Dropdown label="Group" value={params.get("g") ?? ""} options={GROUPS} onChange={(v) => set({ g: v || null })} />
|
||||
<label className="flex items-center gap-2 text-sm ml-auto cursor-pointer">
|
||||
<input type="checkbox" role="switch" checked={params.get("cmp") === "1"} onChange={(e) => set({ cmp: e.target.checked ? "1" : null })} />
|
||||
Compare with previous period
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Multi label="Accounts" all="All accounts" options={accounts} value={list("acct")} onChange={(v) => set({ acct: v.join(",") || null })} />
|
||||
<Multi label="Categories" all="All categories" options={categories} value={list("cat")} onChange={(v) => set({ cat: v.join(",") || null })} />
|
||||
{!!tags.length && <Multi label="Tags" all="All tags" options={tags} value={list("tag")} onChange={(v) => set({ tag: v.join(",") || null })} />}
|
||||
<Dropdown label="Direction" value={params.get("dir") ?? ""} options={DIRS} onChange={(v) => set({ dir: v || null })} />
|
||||
<label className="flex items-center gap-2 select !py-1.5 !w-56">
|
||||
<Search size={14} className="text-muted shrink-0" aria-hidden />
|
||||
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Merchant or name" aria-label="Search merchant or name" className="bg-transparent outline-none w-full text-sm" />
|
||||
</label>
|
||||
{any && <button type="button" className="text-sm text-muted hover:text-ink underline underline-offset-2" onClick={() => { setQ(""); router.replace(`${path}${params.get("cmp") ? "?cmp=1" : ""}`, { scroll: false }); }}>Clear filters</button>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||||
|
||||
// The Charts page's pieces, drawn in SVG to match broke's own charts. One y-axis per chart, thin marks, recessive grid,
|
||||
// a legend for 2+ series, a tooltip on hover, and a table view for every chart (some light colors sit below 3:1).
|
||||
|
||||
export type Series = { name: string; color: string; values: (number | null)[]; faint?: (number | null)[]; width?: number; dashed?: boolean };
|
||||
type Fmt = (n: number) => string;
|
||||
|
||||
function useWidth() {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [w, setW] = useState(640);
|
||||
useEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
const ro = new ResizeObserver(([e]) => setW(Math.max(280, Math.round(e.contentRect.width))));
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
return { ref, w };
|
||||
}
|
||||
|
||||
/** Round-number ticks from 0 (or below, for negatives) to the top. */
|
||||
function ticks(min: number, max: number) {
|
||||
const span = Math.max(1, max - Math.min(0, min));
|
||||
const raw = span / 4, mag = 10 ** Math.floor(Math.log10(raw)), step = [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw)!;
|
||||
const lo = Math.floor(Math.min(0, min) / step) * step, hi = Math.ceil(max / step) * step || step;
|
||||
const out: number[] = [];
|
||||
for (let v = lo; v <= hi + 1e-9; v += step) out.push(Math.round(v * 100) / 100);
|
||||
return out;
|
||||
}
|
||||
|
||||
export function Card({ title, note, legend, table, children }: { title: string; note?: string; legend?: { name: string; color: string; dashed?: boolean }[]; table?: { head: string[]; rows: (string | number)[][] }; children: ReactNode }) {
|
||||
const [asTable, setAsTable] = useState(false);
|
||||
return (
|
||||
<section className="card p-5 space-y-3 min-w-0">
|
||||
<div className="flex flex-wrap items-start justify-between gap-2">
|
||||
<div>
|
||||
<div className="card-title">{title}</div>
|
||||
{note && <p className="text-xs text-muted mt-0.5">{note}</p>}
|
||||
</div>
|
||||
{table && <button type="button" className="text-xs text-muted hover:text-ink underline underline-offset-2" onClick={() => setAsTable(!asTable)}>{asTable ? "Show chart" : "Show table"}</button>}
|
||||
</div>
|
||||
{legend && legend.length > 1 && !asTable && (
|
||||
<div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted">
|
||||
{legend.map((l) => (
|
||||
<span key={l.name} className="flex items-center gap-1.5">
|
||||
<span className="w-3 h-0.5 rounded" style={l.dashed ? { borderTop: `2px dashed ${l.color}`, height: 0 } : { background: l.color, height: 3 }} />{l.name}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{asTable && table ? (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-xs tabular">
|
||||
<thead><tr>{table.head.map((h, i) => <th key={i} className={`py-1.5 pr-3 font-medium text-muted ${i ? "text-right" : "text-left"}`}>{h}</th>)}</tr></thead>
|
||||
<tbody>{table.rows.map((r, i) => <tr key={i} className="border-t border-line">{r.map((c, j) => <td key={j} className={`py-1.5 pr-3 ${j ? "text-right" : ""}`}>{c}</td>)}</tr>)}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Tip({ x, w, children }: { x: number; w: number; children: ReactNode }) {
|
||||
const left = Math.min(Math.max(x, 90), w - 90);
|
||||
return <div className="absolute top-0 -translate-x-1/2 bg-ink text-on-ink text-[11px] rounded-lg px-2.5 py-1.5 shadow-lg pointer-events-none z-10 whitespace-nowrap space-y-0.5" style={{ left }}>{children}</div>;
|
||||
}
|
||||
|
||||
const H = 200, PAD = { l: 52, r: 8, t: 12, b: 24 };
|
||||
|
||||
/** Bars per period: side by side, or stacked. `faint` draws the previous period as a pale outline behind each bar. */
|
||||
export function Bars({ labels, series, stacked = false, fmt, hrefs }: { labels: string[]; series: Series[]; stacked?: boolean; fmt: Fmt; hrefs?: (i: number, s?: number) => string | null }) {
|
||||
const { ref, w } = useWidth();
|
||||
const router = useRouter();
|
||||
const [hover, setHover] = useState<number | null>(null);
|
||||
const n = labels.length;
|
||||
const vals = (i: number) => series.map((s) => s.values[i] ?? 0);
|
||||
const top = Math.max(1, ...labels.map((_, i) => (stacked ? vals(i).reduce((a, b) => a + Math.max(0, b), 0) : Math.max(...vals(i), ...series.map((s) => s.faint?.[i] ?? 0)))));
|
||||
const low = Math.min(0, ...labels.flatMap((_, i) => vals(i)));
|
||||
const tk = ticks(low, top), y0 = tk[0], y1 = tk[tk.length - 1];
|
||||
const y = (v: number) => PAD.t + (H - PAD.t - PAD.b) * (1 - (v - y0) / (y1 - y0 || 1));
|
||||
const band = (w - PAD.l - PAD.r) / Math.max(1, n), inner = Math.min(band * 0.72, 56);
|
||||
const per = stacked ? inner : (inner - 2 * (series.length - 1)) / series.length; // 2px gap between bars in a group
|
||||
const every = Math.ceil(n / Math.max(1, Math.floor((w - PAD.l) / 54))); // label every k-th period so they don't collide
|
||||
return (
|
||||
<div ref={ref} className="relative" onPointerLeave={() => setHover(null)}>
|
||||
{hover !== null && (
|
||||
<Tip x={PAD.l + band * (hover + 0.5)} w={w}>
|
||||
<div className="font-medium">{labels[hover]}</div>
|
||||
{series.map((s) => <div key={s.name} className="flex items-center gap-1.5"><span className="size-2 rounded-sm" style={{ background: s.color }} />{s.name}: {fmt(s.values[hover] ?? 0)}{s.faint ? <span className="opacity-70"> (before: {fmt(s.faint[hover] ?? 0)})</span> : null}</div>)}
|
||||
</Tip>
|
||||
)}
|
||||
<svg width={w} height={H} role="img" aria-label={`${series.map((s) => s.name).join(", ")} per period`}>
|
||||
{tk.map((t) => (
|
||||
<g key={t}>
|
||||
<line x1={PAD.l} x2={w - PAD.r} y1={y(t)} y2={y(t)} stroke="var(--line)" strokeWidth={t === 0 ? 1.5 : 1} />
|
||||
<text x={PAD.l - 6} y={y(t) + 3} textAnchor="end" fontSize="10" fill="var(--muted)">{fmt(t)}</text>
|
||||
</g>
|
||||
))}
|
||||
{labels.map((l, i) => {
|
||||
const x0 = PAD.l + band * i + (band - inner) / 2;
|
||||
let stack = 0;
|
||||
const dim = hover !== null && hover !== i;
|
||||
const go = (s?: number) => { const h = hrefs?.(i, s); if (h) router.push(h); };
|
||||
return (
|
||||
<g key={i} opacity={dim ? 0.45 : 1} style={{ cursor: hrefs ? "pointer" : undefined }} onPointerEnter={() => setHover(i)} onClick={() => go()}>
|
||||
<rect x={PAD.l + band * i} y={PAD.t} width={band} height={H - PAD.t - PAD.b} fill="transparent" />
|
||||
{series.map((s, j) => {
|
||||
const v = s.values[i] ?? 0;
|
||||
if (stacked) {
|
||||
if (v <= 0) return null;
|
||||
const yTop = y(stack + v), yBot = y(stack);
|
||||
stack += v;
|
||||
return <rect key={j} x={x0} y={yTop} width={inner} height={Math.max(0, yBot - yTop - 2)} rx={2} fill={s.color} onClick={(e) => { e.stopPropagation(); go(j); }} />;
|
||||
}
|
||||
const bx = x0 + j * (per + 2);
|
||||
const f = s.faint?.[i];
|
||||
return (
|
||||
<g key={j}>
|
||||
{f ? <rect x={bx} y={y(Math.max(0, f))} width={per} height={Math.abs(y(f) - y(0))} rx={4} fill="none" stroke={s.color} strokeOpacity={0.45} strokeDasharray="3 2" /> : null}
|
||||
<rect x={bx} y={y(Math.max(0, v))} width={per} height={Math.max(v ? 2 : 0, Math.abs(y(v) - y(0)))} rx={4} fill={s.color} onClick={(e) => { e.stopPropagation(); go(j); }} />
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{i % every === 0 && <text x={PAD.l + band * (i + 0.5)} y={H - 6} textAnchor="middle" fontSize="10" fill="var(--muted)">{l}</text>}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
</svg>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Lines over the same periods, with a crosshair and one tooltip for every series at that point. */
|
||||
export function Lines({ labels, series, fmt, hrefs, zero = true }: { labels: string[]; series: Series[]; fmt: Fmt; hrefs?: (i: number) => string | null; zero?: boolean }) {
|
||||
const { ref, w } = useWidth();
|
||||
const router = useRouter();
|
||||
const [hover, setHover] = useState<number | null>(null);
|
||||
const n = labels.length;
|
||||
const all = series.flatMap((s) => [...s.values, ...(s.faint ?? [])]).filter((v): v is number => v !== null);
|
||||
const hi = Math.max(zero ? 1 : -Infinity, ...all), lo = Math.min(zero ? 0 : Infinity, ...all);
|
||||
const tk = zero ? ticks(lo, hi) : ticks(lo - (hi - lo) * 0.1, hi).filter((t) => t >= lo - (hi - lo) * 0.25);
|
||||
const y0 = tk[0], y1 = tk[tk.length - 1];
|
||||
const x = (i: number) => PAD.l + (n <= 1 ? 0 : ((w - PAD.l - PAD.r) * i) / (n - 1));
|
||||
const y = (v: number) => PAD.t + (H - PAD.t - PAD.b) * (1 - (v - y0) / (y1 - y0 || 1));
|
||||
const path = (vs: (number | null)[]) => vs.map((v, i) => (v === null ? "" : `${i && vs[i - 1] !== null ? "L" : "M"}${x(i).toFixed(1)},${y(v).toFixed(1)}`)).join("");
|
||||
const every = Math.ceil(n / Math.max(1, Math.floor((w - PAD.l) / 54)));
|
||||
const pick = (cx: number) => Math.max(0, Math.min(n - 1, Math.round(((cx - PAD.l) / Math.max(1, w - PAD.l - PAD.r)) * (n - 1))));
|
||||
return (
|
||||
<div ref={ref} className="relative" onPointerLeave={() => setHover(null)}>
|
||||
{hover !== null && (
|
||||
<Tip x={x(hover)} w={w}>
|
||||
<div className="font-medium">{labels[hover]}</div>
|
||||
{series.filter((s) => s.values[hover] !== null).map((s) => <div key={s.name} className="flex items-center gap-1.5"><span className="size-2 rounded-full" style={{ background: s.color }} />{s.name}: {fmt(s.values[hover]!)}{s.faint?.[hover] != null ? <span className="opacity-70"> (before: {fmt(s.faint[hover]!)})</span> : null}</div>)}
|
||||
</Tip>
|
||||
)}
|
||||
<svg width={w} height={H} role="img" aria-label={`${series.map((s) => s.name).join(", ")} over time`}
|
||||
style={{ cursor: hrefs ? "pointer" : undefined }}
|
||||
onPointerMove={(e) => setHover(pick(e.clientX - e.currentTarget.getBoundingClientRect().left))}
|
||||
onClick={() => { if (hover !== null) { const h = hrefs?.(hover); if (h) router.push(h); } }}>
|
||||
{tk.map((t) => (
|
||||
<g key={t}>
|
||||
<line x1={PAD.l} x2={w - PAD.r} y1={y(t)} y2={y(t)} stroke="var(--line)" strokeWidth={t === 0 && zero ? 1.5 : 1} />
|
||||
<text x={PAD.l - 6} y={y(t) + 3} textAnchor="end" fontSize="10" fill="var(--muted)">{fmt(t)}</text>
|
||||
</g>
|
||||
))}
|
||||
{labels.map((l, i) => (i % every === 0 ? <text key={i} x={x(i)} y={H - 6} textAnchor={i === 0 ? "start" : "middle"} fontSize="10" fill="var(--muted)">{l}</text> : null))}
|
||||
{series.map((s) => s.faint && <path key={`f${s.name}`} d={path(s.faint)} fill="none" stroke={s.color} strokeOpacity={0.35} strokeWidth={1.5} strokeDasharray="4 3" />)}
|
||||
{series.map((s) => <path key={s.name} d={path(s.values)} fill="none" stroke={s.color} strokeWidth={s.width ?? 2} strokeLinejoin="round" strokeLinecap="round" strokeDasharray={s.dashed ? "5 4" : undefined} />)}
|
||||
{/* A point with no neighbor draws no line: give it a dot so it doesn't vanish. */}
|
||||
{series.map((s) => s.values.map((v, i) => v !== null && (s.values[i - 1] ?? null) === null && (s.values[i + 1] ?? null) === null
|
||||
? <circle key={`${s.name}${i}`} cx={x(i)} cy={y(v)} r={4} fill={s.color} stroke="var(--surface)" strokeWidth={2} /> : null))}
|
||||
{hover !== null && (
|
||||
<g pointerEvents="none">
|
||||
<line x1={x(hover)} x2={x(hover)} y1={PAD.t} y2={H - PAD.b} stroke="var(--muted)" strokeOpacity={0.5} />
|
||||
{series.map((s) => s.values[hover] !== null && <circle key={s.name} cx={x(hover)} cy={y(s.values[hover]!)} r={4} fill={s.color} stroke="var(--surface)" strokeWidth={2} />)}
|
||||
</g>
|
||||
)}
|
||||
</svg>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
import { useMoney } from "@/components/Money";
|
||||
import { Bars, Card, Lines, type Series } from "@/components/charts/ChartKit";
|
||||
import type { Change, Flow, Period } from "@/lib/charts";
|
||||
|
||||
// Everything here is worked out on the server (app/(app)/charts/page.tsx, lib/charts.ts). This only draws it.
|
||||
// Colors: income and spending keep broke's own (--good, --chart); categories, merchants and accounts take the series
|
||||
// slots in a fixed order set by all-time spending, so a filter never repaints one.
|
||||
|
||||
export type ChartsData = {
|
||||
periods: Period[];
|
||||
compare: boolean;
|
||||
totals: { spend: number; income: number; net: number };
|
||||
totalsBefore: { spend: number; income: number; net: number } | null;
|
||||
flow: Flow[];
|
||||
flowBefore: Flow[] | null;
|
||||
rate: { periods: Period[]; values: (number | null)[] };
|
||||
rateBefore: (number | null)[] | null;
|
||||
cats: { order: { id: string; label: string; slot: number }[]; values: Record<string, number>[] };
|
||||
mtd: { thisMonth: string; lastMonth: string; start: string; current: number[]; last: number[]; average: number[] }; // start: day 1 (payday with pay months)
|
||||
balance: { days: string[]; series: { id: string; name: string; owed: boolean; slot: number; values: number[] }[]; total: number[] };
|
||||
weekday: number[];
|
||||
weekdayBefore: number[] | null;
|
||||
merchants: { name: string; slot: number; values: number[] }[];
|
||||
changes: { categories: { up: (Change & { label: string })[]; down: (Change & { label: string })[] }; merchants: { up: Change[]; down: Change[] } } | null;
|
||||
otherCurrency: number; // transactions in another currency, left out of every chart
|
||||
link: Record<string, string>; // filters Activity understands: account, tag, q (only when exactly one is picked)
|
||||
};
|
||||
|
||||
const slot = (n: number) => (n >= 1 && n <= 8 ? `var(--series-${n})` : "var(--series-other)");
|
||||
const WEEKDAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
|
||||
const monthName = (k: string) => new Date(`${k}-15T12:00:00Z`).toLocaleDateString("en-US", { month: "long", timeZone: "UTC" });
|
||||
const day = (d: string) => new Date(`${d}T12:00:00Z`).toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" });
|
||||
|
||||
export function ChartsView({ d }: { d: ChartsData }) {
|
||||
const { money0 } = useMoney();
|
||||
const pct = (n: number) => `${Math.round(n)}%`;
|
||||
const labels = d.periods.map((p) => p.label);
|
||||
const activity = (extra: Record<string, string | undefined>) => {
|
||||
const q = new URLSearchParams(Object.entries({ ...d.link, ...extra }).filter((e): e is [string, string] => !!e[1]));
|
||||
return `/transactions?${q}`;
|
||||
};
|
||||
const inPeriod = (i: number, extra: Record<string, string | undefined> = {}) => activity({ from: d.periods[i].from, to: d.periods[i].to, ...extra });
|
||||
const tableOf = (head: string[], cols: (string | number)[][]) => ({ head, rows: labels.map((l, i) => [l, ...cols.map((c) => c[i])]) });
|
||||
|
||||
const change = (now: number, before?: number) => {
|
||||
if (before === undefined) return null;
|
||||
if (!before) return null;
|
||||
const p = ((now - before) / Math.abs(before)) * 100;
|
||||
return <span className="text-xs text-muted"> {p >= 0 ? "+" : ""}{Math.round(p)}% vs before</span>;
|
||||
};
|
||||
const [hidden, setHidden] = useState<Set<string>>(new Set());
|
||||
const toggle = (id: string) => setHidden((h) => { const n = new Set(h); if (n.has(id)) n.delete(id); else n.add(id); return n; });
|
||||
|
||||
const flowSeries: Series[] = [
|
||||
{ name: "Money in", color: "var(--good)", values: d.flow.map((f) => f.income), faint: d.flowBefore?.map((f) => f.income) },
|
||||
{ name: "Money out", color: "var(--chart)", values: d.flow.map((f) => f.spend), faint: d.flowBefore?.map((f) => f.spend) },
|
||||
];
|
||||
// Stacked from the biggest up; each block knows its category, so a click opens that category (Other: all of them).
|
||||
const catDefs = [...d.cats.order.map((c) => ({ id: c.id as string | undefined, name: c.label, color: slot(c.slot), values: d.cats.values.map((v) => v[c.id] ?? 0) })), { id: undefined, name: "Other", color: slot(0), values: d.cats.values.map((v) => v.other ?? 0) }].filter((s) => s.values.some((v) => v));
|
||||
const catSeries: Series[] = catDefs;
|
||||
const mtdDays = d.mtd.average.map((_, i) => String(i + 1));
|
||||
const bal = d.balance;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{d.otherCurrency > 0 && <p className="text-xs text-muted px-1">{d.otherCurrency} transactions in another currency are left out of these charts.</p>}
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
{([["Money in", d.totals.income, d.totalsBefore?.income], ["Money out", d.totals.spend, d.totalsBefore?.spend], ["Kept", d.totals.net, d.totalsBefore?.net]] as const).map(([k, v, b]) => (
|
||||
<div key={k} className="card px-5 py-4">
|
||||
<div className="text-xs text-muted">{k}</div>
|
||||
<div className={`text-xl font-semibold tabular ${k === "Kept" && v < 0 ? "text-bad" : ""}`}>{money0(v)}</div>
|
||||
{d.compare && change(v, b)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 @4xl:grid-cols-2">
|
||||
<Card title="Cash flow" note={d.compare ? "Dashed outlines: the period before." : "Money in and out per period. Click a bar to see the transactions."} legend={flowSeries}
|
||||
table={tableOf(["Period", "In", "Out", "Kept"], [d.flow.map((f) => money0(f.income)), d.flow.map((f) => money0(f.spend)), d.flow.map((f) => money0(f.net))])}>
|
||||
<Bars labels={labels} series={flowSeries} fmt={money0} hrefs={(i) => inPeriod(i)} />
|
||||
</Card>
|
||||
|
||||
<Card title="Savings rate" note="Share of what came in that you kept, per month. Empty where nothing came in." legend={d.compare ? [{ name: "This period", color: "var(--good)" }, { name: "Before", color: "var(--good)", dashed: true }] : undefined}
|
||||
table={{ head: ["Month", "Kept", ...(d.rateBefore ? ["Before"] : [])], rows: d.rate.periods.map((p, i) => [p.label, d.rate.values[i] === null ? "–" : pct(d.rate.values[i]!), ...(d.rateBefore ? [d.rateBefore[i] === null ? "–" : pct(d.rateBefore[i]!)] : [])]) }}>
|
||||
<Lines labels={d.rate.periods.map((p) => p.label)} series={[{ name: "Kept", color: "var(--good)", values: d.rate.values, faint: d.rateBefore ?? undefined }]} fmt={pct}
|
||||
hrefs={(i) => activity({ from: d.rate.periods[i].from, to: d.rate.periods[i].to })} />
|
||||
</Card>
|
||||
|
||||
<Card title="Spending by category" note="Your biggest categories; the rest is Other. Click a block to see it." legend={catSeries}
|
||||
table={tableOf(["Period", ...catSeries.map((s) => s.name)], catSeries.map((s) => s.values.map((v) => money0(v ?? 0))))}>
|
||||
<Bars labels={labels} series={catSeries} stacked fmt={money0}
|
||||
hrefs={(i, s) => inPeriod(i, s !== undefined ? { category: catDefs[s]?.id } : {})} />
|
||||
</Card>
|
||||
|
||||
<Card title="This month so far" note={`Spending added up day by day: ${monthName(d.mtd.thisMonth)} against ${monthName(d.mtd.lastMonth)} and the average of the 3 months before.`}
|
||||
legend={[{ name: "This month", color: "var(--chart)" }, { name: "Last month", color: "var(--muted)", dashed: true }, { name: "3-month average", color: "var(--series-other)" }]}
|
||||
table={{ head: ["Day", "This month", "Last month", "Average"], rows: mtdDays.map((l, i) => [l, d.mtd.current[i] !== undefined ? money0(d.mtd.current[i]) : "–", d.mtd.last[i] !== undefined ? money0(d.mtd.last[i]) : "–", money0(d.mtd.average[i])]) }}>
|
||||
<Lines labels={mtdDays} fmt={money0} hrefs={(i) => activity({ from: d.mtd.start, to: new Date(Date.parse(`${d.mtd.start}T00:00:00Z`) + i * 864e5).toISOString().slice(0, 10) })} series={[
|
||||
{ name: "3-month average", color: "var(--series-other)", values: d.mtd.average, width: 1.5 },
|
||||
{ name: "Last month", color: "var(--muted)", values: mtdDays.map((_, i) => d.mtd.last[i] ?? null), dashed: true, width: 1.5 },
|
||||
{ name: "This month", color: "var(--chart)", values: mtdDays.map((_, i) => d.mtd.current[i] ?? null), width: 2.5 },
|
||||
]} />
|
||||
</Card>
|
||||
|
||||
<Card title="Balance over time" note="Worked back from today's balances. Cards and loans count as owed. Click a name to show or hide it."
|
||||
table={{ head: ["Day", "Total", ...bal.series.map((s) => s.name)], rows: bal.days.map((dd, i) => [day(dd), money0(bal.total[i]), ...bal.series.map((s) => money0(s.values[i]))]) }}>
|
||||
<div className="flex flex-wrap gap-x-3 gap-y-1 text-xs">
|
||||
<span className="flex items-center gap-1.5 font-medium"><span className="w-3 rounded" style={{ background: "var(--ink)", height: 3 }} />Total</span>
|
||||
{bal.series.map((s) => (
|
||||
<button key={s.id} type="button" onClick={() => toggle(s.id)} aria-pressed={!hidden.has(s.id)} className={`flex items-center gap-1.5 ${hidden.has(s.id) ? "text-muted line-through" : "text-muted hover:text-ink"}`}>
|
||||
<span className="w-3 rounded" style={{ background: slot(s.slot), height: 3 }} />{s.name}{s.owed ? " (owed)" : ""}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<Lines labels={bal.days.map(day)} fmt={money0} zero={false} series={[
|
||||
...bal.series.filter((s) => !hidden.has(s.id)).map((s) => ({ name: s.name, color: slot(s.slot), values: s.values, width: 1.25 })),
|
||||
{ name: "Total", color: "var(--ink)", values: bal.total, width: 2.5 },
|
||||
]} />
|
||||
</Card>
|
||||
|
||||
<Card title="Top merchants" note="Your biggest merchants in this period, spending per period." legend={d.merchants.map((m) => ({ name: m.name, color: slot(m.slot) }))}
|
||||
table={tableOf(["Period", ...d.merchants.map((m) => m.name)], d.merchants.map((m) => m.values.map((v) => money0(v))))}>
|
||||
{d.merchants.length ? <Lines labels={labels} fmt={money0} hrefs={(i) => inPeriod(i)} series={d.merchants.map((m) => ({ name: m.name, color: slot(m.slot), values: m.values }))} /> : <p className="text-sm text-muted">No spending in this period.</p>}
|
||||
</Card>
|
||||
|
||||
<Card title="Spending by weekday" note={d.compare ? "Average per weekday. Dashed outlines: the period before." : "Average spent on each day of the week in this period."}
|
||||
table={{ head: ["Day", "Average", ...(d.weekdayBefore ? ["Before"] : [])], rows: WEEKDAYS.map((w, i) => [w, money0(d.weekday[i]), ...(d.weekdayBefore ? [money0(d.weekdayBefore[i])] : [])]) }}>
|
||||
<Bars labels={WEEKDAYS} series={[{ name: "Average spent", color: "var(--chart)", values: d.weekday, faint: d.weekdayBefore ?? undefined }]} fmt={money0} />
|
||||
</Card>
|
||||
|
||||
<Card title="Biggest changes" note="Compared with the same length of time just before.">
|
||||
{d.changes ? (
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
{([["Categories", d.changes.categories, (c: Change & { label?: string }) => c.label ?? c.id, (c: Change) => activity({ category: c.id, from: d.periods[0]?.from, to: d.periods.at(-1)?.to })],
|
||||
["Merchants", d.changes.merchants, (c: Change) => c.id, (c: Change) => activity({ q: c.id, from: d.periods[0]?.from, to: d.periods.at(-1)?.to })]] as const).map(([title, ch, name, href]) => (
|
||||
<div key={title} className="space-y-1 min-w-0">
|
||||
<div className="text-xs font-medium text-muted">{title}</div>
|
||||
{!ch.up.length && !ch.down.length && <p className="text-xs text-muted">No real changes.</p>}
|
||||
{[...ch.up, ...ch.down].map((c) => (
|
||||
<Link key={c.id} href={href(c)} className="row-hover flex justify-between gap-2 rounded-lg px-2 py-1 -mx-2">
|
||||
<span className="truncate">{name(c)}</span>
|
||||
<span className={`tabular shrink-0 ${c.delta > 0 ? "text-bad" : "text-good"}`}>{c.delta > 0 ? "+" : "−"}{money0(Math.abs(c.delta))}</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : <p className="text-sm text-muted">Pick a time range to compare.</p>}
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+5
-3
@@ -34,9 +34,11 @@ export function retune<C extends { id: string; suggested: number; main: boolean
|
||||
}
|
||||
|
||||
// Where the month is: today counts as a day left.
|
||||
export function month(now: Date) {
|
||||
const day = now.getUTCDate();
|
||||
const days = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 0)).getUTCDate();
|
||||
// span: a pay month's first day and the day after its last (lib/paymonths.ts), else the calendar month.
|
||||
export function month(now: Date, span?: { start: string; end: string }) {
|
||||
const at = (d: string) => Date.parse(`${d}T00:00:00Z`);
|
||||
const day = span ? Math.round((now.getTime() - at(span.start)) / 864e5) + 1 : now.getUTCDate();
|
||||
const days = span ? Math.round((at(span.end) - at(span.start)) / 864e5) : new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 0)).getUTCDate();
|
||||
return { day, days, left: days - day + 1, pace: day / days };
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
// node src/lib/charts.test.ts
|
||||
import assert from "node:assert/strict";
|
||||
import { monthOf, rangeOf } from "./paymonths.ts";
|
||||
import { balances, biggestChanges, byWeekday, cashFlow, categoriesOver, merchantsOver, monthToDate, periodKey, periods, previousRange, rankBySpend, savingsRate, totals, type Row } from "./charts.ts";
|
||||
|
||||
const r = (date: string, amount: number, extra: Partial<Row> = {}): Row => ({
|
||||
date, amount, spend: amount > 0, income: amount < 0, categoryId: "food", merchant: "AH", accountId: "chk", ...extra,
|
||||
});
|
||||
|
||||
// Periods: weeks start on Monday, months cover the whole month, empty periods still listed.
|
||||
assert.equal(periodKey("2026-11-19", "week"), "2026-11-16"); // a Thursday -> Monday 16 Nov
|
||||
assert.equal(periodKey("2026-11-16", "week"), "2026-11-16");
|
||||
assert.equal(periodKey("2026-11-22", "week"), "2026-11-16"); // Sunday belongs to the week before
|
||||
assert.deepEqual(periods("2026-10-15", "2026-12-02", "month").map((p) => [p.key, p.from, p.to]), [["2026-10", "2026-10-01", "2026-10-31"], ["2026-11", "2026-11-01", "2026-11-30"], ["2026-12", "2026-12-01", "2026-12-31"]]);
|
||||
assert.equal(periods("2026-12-20", "2027-01-05", "month")[1].label, "Jan '27");
|
||||
assert.equal(periods("2026-11-01", "2026-11-03", "day").length, 3);
|
||||
assert.deepEqual(previousRange("2026-11-01", "2026-11-30"), { from: "2026-10-02", to: "2026-10-31" });
|
||||
|
||||
// Cash flow and savings rate.
|
||||
const rows = [r("2026-10-01", -2500, { categoryId: "pay", merchant: "Werkgever" }), r("2026-10-03", 40), r("2026-10-20", 60, { categoryId: "fun", merchant: "Cinema" }), r("2026-11-02", 30)];
|
||||
const ps = periods("2026-10-01", "2026-11-30", "month");
|
||||
const flow = cashFlow(rows, ps, "month");
|
||||
assert.deepEqual(flow, [{ key: "2026-10", income: 2500, spend: 100, net: 2400 }, { key: "2026-11", income: 0, spend: 30, net: -30 }]);
|
||||
assert.deepEqual(savingsRate(flow), [{ key: "2026-10", rate: 96 }, { key: "2026-11", rate: null }]);
|
||||
// A transfer (neither spend nor income) counts nowhere.
|
||||
assert.deepEqual(cashFlow([r("2026-10-05", 1000, { spend: false, income: false })], ps, "month")[0], { key: "2026-10", income: 0, spend: 0, net: 0 });
|
||||
assert.deepEqual(totals(rows), { spend: 130, income: 2500, net: 2370 });
|
||||
|
||||
// Categories over time with "other", and the stable spend ranking.
|
||||
assert.deepEqual(categoriesOver(rows, ps, "month", ["food"]).map((x) => x.values), [{ food: 40, other: 60 }, { food: 30, other: 0 }]);
|
||||
assert.deepEqual(rankBySpend(rows, (x) => x.categoryId), ["food", "fun"]);
|
||||
assert.deepEqual(merchantsOver(rows, ps, "month", ["AH"]), [{ name: "AH", values: [40, 30] }]);
|
||||
|
||||
// Month to date: running totals, cut at today for this month.
|
||||
const mtd = monthToDate([r("2026-11-01", 10), r("2026-11-03", 5), r("2026-10-02", 20), r("2026-11-25", 99)], "2026-11-03");
|
||||
assert.deepEqual(mtd.current, [10, 10, 15]);
|
||||
assert.equal(mtd.last.length, 31);
|
||||
assert.equal(mtd.last[1], 20);
|
||||
assert.equal(mtd.average.length, 30);
|
||||
assert.equal(mtd.average[30 - 1], round(20 / 3));
|
||||
function round(n: number) { return Math.round(n * 100) / 100; }
|
||||
|
||||
// Balances worked back from today: spending lowers a bank balance and raises what's owed on a card.
|
||||
const b = balances(
|
||||
[{ id: "chk", name: "Checking", balance: 1000, owed: false }, { id: "card", name: "Card", balance: 50, owed: true }],
|
||||
[r("2026-11-02", 100), r("2026-11-03", -40), r("2026-11-02", 50, { accountId: "card" })],
|
||||
"2026-11-01", "2026-11-03", "day",
|
||||
);
|
||||
assert.deepEqual(b.days, ["2026-11-01", "2026-11-02", "2026-11-03"]);
|
||||
assert.deepEqual(b.series[0].values, [1060, 960, 1000]); // before the €100 out and the €40 in
|
||||
assert.deepEqual(b.series[1].values, [0, 50, 50]);
|
||||
assert.deepEqual(b.total, [1060, 910, 950]);
|
||||
assert.deepEqual(balances([{ id: "chk", name: "C", balance: 1, owed: false }], [], "2026-11-01", "2026-11-30", "week").days, ["2026-11-01", "2026-11-08", "2026-11-15", "2026-11-22", "2026-11-29", "2026-11-30"]);
|
||||
|
||||
// Weekday averages: Mon 2 Nov and Mon 9 Nov in range, €30 spent on one of them -> €15 a Monday.
|
||||
assert.equal(byWeekday([r("2026-11-02", 30)], "2026-11-02", "2026-11-15")[0], 15);
|
||||
|
||||
// Biggest changes.
|
||||
const ch = biggestChanges([r("2026-11-02", 300, { categoryId: "fun" }), r("2026-11-03", 20)], [r("2026-10-02", 100, { categoryId: "fun" }), r("2026-10-03", 90)], (x) => x.categoryId);
|
||||
assert.deepEqual(ch.up, [{ id: "fun", now: 300, before: 100, delta: 200 }]);
|
||||
assert.deepEqual(ch.down, [{ id: "food", now: 20, before: 90, delta: -70 }]);
|
||||
|
||||
// Months that start on payday: salary on 24 Sep and 23 Oct, so "October" is 24 Sep to 22 Oct.
|
||||
const pays = [{ month: "2026-10-01", start: "2026-09-24" }, { month: "2026-11-01", start: "2026-10-23" }];
|
||||
const pm = { of: (d: string) => monthOf(pays, d), range: (ym: string) => rangeOf(pays, ym) };
|
||||
assert.equal(periodKey("2026-10-23", "month", pm), "2026-11");
|
||||
assert.deepEqual(periods("2026-09-24", "2026-11-03", "month", pm).map((p) => [p.key, p.from, p.to]), [["2026-10", "2026-09-24", "2026-10-22"], ["2026-11", "2026-10-23", "2026-11-22"]]);
|
||||
const flowPm = cashFlow([r("2026-10-22", 10), r("2026-10-23", 7)], periods("2026-09-24", "2026-11-03", "month", pm), "month", pm);
|
||||
assert.deepEqual(flowPm.map((f) => f.spend), [10, 7], "the 23rd is already November");
|
||||
const mtdPm = monthToDate([r("2026-10-23", 5), r("2026-10-25", 2), r("2026-09-24", 4)], "2026-10-25", pm);
|
||||
assert.equal(mtdPm.thisMonth, "2026-11");
|
||||
assert.equal(mtdPm.start, "2026-10-23");
|
||||
assert.deepEqual(mtdPm.current, [5, 5, 7], "day 1 is payday");
|
||||
assert.equal(mtdPm.last[0], 4);
|
||||
console.log("charts ok");
|
||||
@@ -0,0 +1,205 @@
|
||||
// Numbers for the Charts page (app/(app)/charts). Pure: `node src/lib/charts.test.ts` runs it.
|
||||
// Amounts use the app's sign: positive = money out. Rows arrive already filtered and already split into spend and
|
||||
// income by the same rule as everywhere else (isSpend / isIncome in lib/data.ts), so transfers never count.
|
||||
|
||||
export type Group = "day" | "week" | "month";
|
||||
export type Row = {
|
||||
date: string; // YYYY-MM-DD
|
||||
amount: number;
|
||||
spend: boolean;
|
||||
income: boolean;
|
||||
categoryId: string | null;
|
||||
merchant: string;
|
||||
accountId: string | null;
|
||||
};
|
||||
export type Period = { key: string; label: string; from: string; to: string };
|
||||
/** Months that start on payday (lib/paymonths.ts): the month ("YYYY-MM") a day is in, and a month's first day and the
|
||||
* day after its last. Null: calendar months. Only grouping by month changes. */
|
||||
export type Months = { of: (d: string) => string; range: (ym: string) => { start: string; end: string } } | null;
|
||||
|
||||
const DAY = 864e5;
|
||||
const iso = (t: number) => new Date(t).toISOString().slice(0, 10);
|
||||
const at = (d: string) => Date.parse(`${d}T00:00:00Z`);
|
||||
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
||||
const round2 = (n: number) => Math.round(n * 100) / 100;
|
||||
|
||||
/** The period a day falls in: the day itself, the Monday of its week, or its month. */
|
||||
export function periodKey(d: string, g: Group, pm: Months = null) {
|
||||
if (g === "day") return d;
|
||||
if (g === "month") return pm ? pm.of(d) : d.slice(0, 7);
|
||||
const t = at(d), wd = (new Date(t).getUTCDay() + 6) % 7; // Monday = 0
|
||||
return iso(t - wd * DAY);
|
||||
}
|
||||
|
||||
/** Every period from `from` to `to` (inclusive), so empty ones still show as zero. */
|
||||
export function periods(from: string, to: string, g: Group, pm: Months = null): Period[] {
|
||||
const out: Period[] = [];
|
||||
let key = periodKey(from, g, pm);
|
||||
const last = periodKey(to, g, pm);
|
||||
for (let guard = 0; key <= last && guard < 4000; guard++) {
|
||||
if (g === "month") {
|
||||
const [y, m] = key.split("-").map(Number);
|
||||
const next = m === 12 ? `${y + 1}-01` : `${y}-${String(m + 1).padStart(2, "0")}`;
|
||||
const r = pm ? pm.range(key) : { start: `${key}-01`, end: `${next}-01` };
|
||||
out.push({ key, label: `${MONTHS[m - 1]}${m === 1 || !out.length ? ` '${String(y).slice(2)}` : ""}`, from: r.start, to: iso(at(r.end) - DAY) });
|
||||
key = next;
|
||||
} else {
|
||||
const span = g === "day" ? 1 : 7, d = new Date(at(key));
|
||||
out.push({ key, label: `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]}`, from: key, to: iso(at(key) + (span - 1) * DAY) });
|
||||
key = iso(at(key) + span * DAY);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The same length of time just before [from, to]: what "compare with previous period" compares with. */
|
||||
export function previousRange(from: string, to: string) {
|
||||
const len = at(to) - at(from) + DAY;
|
||||
return { from: iso(at(from) - len), to: iso(at(from) - DAY) };
|
||||
}
|
||||
|
||||
export type Flow = { key: string; income: number; spend: number; net: number };
|
||||
export function cashFlow(rows: Row[], ps: Period[], g: Group, pm: Months = null): Flow[] {
|
||||
const by = new Map(ps.map((p) => [p.key, { key: p.key, income: 0, spend: 0, net: 0 }]));
|
||||
for (const r of rows) {
|
||||
const f = by.get(periodKey(r.date, g, pm));
|
||||
if (!f) continue;
|
||||
if (r.spend) f.spend += r.amount;
|
||||
else if (r.income) f.income -= r.amount; // money in is negative in the app's sign
|
||||
}
|
||||
return [...by.values()].map((f) => ({ key: f.key, income: round2(f.income), spend: round2(f.spend), net: round2(f.income - f.spend) }));
|
||||
}
|
||||
|
||||
/** Share of income kept, per period. null where nothing came in (a rate of nothing isn't 0%). */
|
||||
export const savingsRate = (flows: Flow[]) => flows.map((f) => ({ key: f.key, rate: f.income > 0 ? Math.round(((f.income - f.spend) / f.income) * 1000) / 10 : null }));
|
||||
|
||||
/** Spending per period per category: the `keep` categories by name, everything else summed as "other". */
|
||||
export function categoriesOver(rows: Row[], ps: Period[], g: Group, keep: string[], pm: Months = null) {
|
||||
const by = new Map(ps.map((p) => [p.key, Object.fromEntries([...keep, "other"].map((k) => [k, 0])) as Record<string, number>]));
|
||||
for (const r of rows) {
|
||||
if (!r.spend) continue;
|
||||
const b = by.get(periodKey(r.date, g, pm));
|
||||
if (!b) continue;
|
||||
const k = r.categoryId && keep.includes(r.categoryId) ? r.categoryId : "other";
|
||||
b[k] = round2(b[k] + r.amount);
|
||||
}
|
||||
return ps.map((p) => ({ key: p.key, values: by.get(p.key)! }));
|
||||
}
|
||||
|
||||
/** Biggest first, by money spent: the stable order categories and merchants take their colors from. */
|
||||
export function rankBySpend(rows: Row[], of: (r: Row) => string | null) {
|
||||
const sum = new Map<string, number>();
|
||||
for (const r of rows) {
|
||||
const k = of(r);
|
||||
if (r.spend && k) sum.set(k, (sum.get(k) ?? 0) + r.amount);
|
||||
}
|
||||
return [...sum.entries()].sort((a, b) => b[1] - a[1]).map(([k]) => k);
|
||||
}
|
||||
|
||||
/** Running total of spending day by day through a month, for this month, last month and the average of the three before.
|
||||
* With pay months, day 1 is payday and a month is as long as its pay month. */
|
||||
export function monthToDate(rows: Row[], today: string, pm: Months = null) {
|
||||
const cur = pm ? pm.of(today) : today.slice(0, 7);
|
||||
const month = (offset: number) => {
|
||||
const [y, m] = cur.split("-").map(Number);
|
||||
return iso(Date.UTC(y, m - 1 + offset, 1)).slice(0, 7);
|
||||
};
|
||||
const span = (key: string) => pm!.range(key); // only with pay months
|
||||
const days = (key: string) => {
|
||||
if (!pm) return new Date(Date.UTC(Number(key.slice(0, 4)), Number(key.slice(5, 7)), 0)).getUTCDate();
|
||||
const r = span(key);
|
||||
return Math.round((at(r.end) - at(r.start)) / DAY);
|
||||
};
|
||||
const daily = (key: string) => {
|
||||
const out = new Array(days(key)).fill(0) as number[];
|
||||
const start = pm ? at(span(key).start) : 0;
|
||||
for (const r of rows) {
|
||||
if (!r.spend) continue;
|
||||
const i = pm ? Math.round((at(r.date) - start) / DAY) : r.date.startsWith(key) ? Number(r.date.slice(8, 10)) - 1 : -1;
|
||||
if (i >= 0 && i < out.length) out[i] += r.amount;
|
||||
}
|
||||
let run = 0;
|
||||
return out.map((v) => (run = round2(run + v)));
|
||||
};
|
||||
const thisKey = month(0), lastKey = month(-1);
|
||||
const upTo = pm ? Math.round((at(today) - at(span(thisKey).start)) / DAY) + 1 : Number(today.slice(8, 10));
|
||||
const avgOf = [month(-1), month(-2), month(-3)].map(daily);
|
||||
const avg = Array.from({ length: 40 }, (_, i) => round2(avgOf.reduce((s, m) => s + (m[Math.min(i, m.length - 1)] ?? 0), 0) / avgOf.length));
|
||||
return {
|
||||
thisMonth: thisKey, lastMonth: lastKey, start: pm ? span(thisKey).start : `${thisKey}-01`,
|
||||
current: daily(thisKey).slice(0, upTo),
|
||||
last: daily(lastKey),
|
||||
average: avg.slice(0, days(thisKey)),
|
||||
};
|
||||
}
|
||||
|
||||
export type Balance = { id: string; name: string; balance: number; owed: boolean };
|
||||
/** Each account's balance at the end of every day in [from, to], worked back from today's balance: a day's balance is
|
||||
* today's plus what went out since (minus what came in). A card or loan counts what's owed; the total subtracts it. */
|
||||
export function balances(accounts: Balance[], rows: Row[], from: string, to: string, step: Group, pm: Months = null) {
|
||||
const ds: string[] = [];
|
||||
for (let t = at(from); t <= at(to); t += DAY) ds.push(iso(t));
|
||||
const marks = step === "day" ? ds : ds.filter((d, i) => i === ds.length - 1 || periodKey(ds[i + 1], step, pm) !== periodKey(d, step, pm)); // last day of each period
|
||||
const series = accounts.map((a) => {
|
||||
const mine = rows.filter((r) => r.accountId === a.id).sort((x, y) => y.date.localeCompare(x.date));
|
||||
let i = 0, after = 0; // sum of amounts dated after the mark
|
||||
const values = [...marks].reverse().map((d) => {
|
||||
while (i < mine.length && mine[i].date > d) after += mine[i++].amount;
|
||||
return round2(a.owed ? a.balance - after : a.balance + after);
|
||||
}).reverse();
|
||||
return { id: a.id, name: a.name, owed: a.owed, values };
|
||||
});
|
||||
const total = marks.map((_, j) => round2(series.reduce((s, x) => s + (x.owed ? -x.values[j] : x.values[j]), 0)));
|
||||
return { days: marks, series, total };
|
||||
}
|
||||
|
||||
/** Average spent on each weekday (Monday first): total spent on those days over how many of them the range holds. */
|
||||
export function byWeekday(rows: Row[], from: string, to: string) {
|
||||
const sum = new Array(7).fill(0) as number[], count = new Array(7).fill(0) as number[];
|
||||
for (let t = at(from); t <= at(to); t += DAY) count[(new Date(t).getUTCDay() + 6) % 7]++;
|
||||
for (const r of rows) if (r.spend && r.date >= from && r.date <= to) sum[(new Date(at(r.date)).getUTCDay() + 6) % 7] += r.amount;
|
||||
return sum.map((s, i) => round2(count[i] ? s / count[i] : 0));
|
||||
}
|
||||
|
||||
/** Spending per period for each of the given merchants. */
|
||||
export function merchantsOver(rows: Row[], ps: Period[], g: Group, names: string[], pm: Months = null) {
|
||||
const by = new Map(names.map((n) => [n, new Map(ps.map((p) => [p.key, 0]))]));
|
||||
for (const r of rows) {
|
||||
const m = r.spend ? by.get(r.merchant) : undefined;
|
||||
const k = periodKey(r.date, g, pm);
|
||||
if (m?.has(k)) m.set(k, round2(m.get(k)! + r.amount));
|
||||
}
|
||||
return names.map((n) => ({ name: n, values: ps.map((p) => by.get(n)!.get(p.key)!) }));
|
||||
}
|
||||
|
||||
export type Change = { id: string; now: number; before: number; delta: number };
|
||||
/** What went up and down most between two periods, by category and by merchant. Spending only. */
|
||||
export function biggestChanges(now: Row[], before: Row[], of: (r: Row) => string | null, n = 5) {
|
||||
const sum = (rows: Row[]) => {
|
||||
const m = new Map<string, number>();
|
||||
for (const r of rows) {
|
||||
const k = of(r);
|
||||
if (r.spend && k) m.set(k, (m.get(k) ?? 0) + r.amount);
|
||||
}
|
||||
return m;
|
||||
};
|
||||
const a = sum(now), b = sum(before);
|
||||
const all = [...new Set([...a.keys(), ...b.keys()])].map((id) => {
|
||||
const x = round2(a.get(id) ?? 0), y = round2(b.get(id) ?? 0);
|
||||
return { id, now: x, before: y, delta: round2(x - y) };
|
||||
}).filter((c) => Math.abs(c.delta) >= 1);
|
||||
return {
|
||||
up: all.filter((c) => c.delta > 0).sort((p, q) => q.delta - p.delta).slice(0, n),
|
||||
down: all.filter((c) => c.delta < 0).sort((p, q) => p.delta - q.delta).slice(0, n),
|
||||
};
|
||||
}
|
||||
|
||||
/** Totals for the header: spent, earned and kept. */
|
||||
export function totals(rows: Row[]) {
|
||||
let spend = 0, income = 0;
|
||||
for (const r of rows) {
|
||||
if (r.spend) spend += r.amount;
|
||||
else if (r.income) income -= r.amount;
|
||||
}
|
||||
return { spend: round2(spend), income: round2(income), net: round2(income - spend) };
|
||||
}
|
||||
+5
-4
@@ -53,6 +53,7 @@ const same = (a: string, b: string) => a.toLowerCase().includes(b.toLowerCase())
|
||||
export function checkinFacts(o: {
|
||||
txns: CheckinTxn[]; streams: CheckinStream[]; cash: number | null; available?: number | null; spendable?: number | null; spendableIn?: string; income?: number | null; today: string;
|
||||
usualSpend?: number | null; budgets?: { category: string; amount: number }[]; prev?: CheckinFacts | null; move?: CheckinFacts["move"];
|
||||
span?: { start: string; end: string }; // with pay months on: this month's first day and the day after its last (lib/paymonths.ts)
|
||||
}): CheckinFacts {
|
||||
const weekAgo = shift(o.today, -7);
|
||||
const unusual: CheckinFacts["unusual"] = [];
|
||||
@@ -91,7 +92,7 @@ export function checkinFacts(o: {
|
||||
|
||||
const upcomingTotal = r2(upcoming.reduce((s, u) => s + u.amount, 0));
|
||||
const sum = (xs: CheckinTxn[]) => r2(xs.reduce((s, t) => s + t.amount, 0));
|
||||
const month = o.txns.filter((t) => t.date >= o.today.slice(0, 8) + "01");
|
||||
const month = o.txns.filter((t) => t.date >= (o.span?.start ?? o.today.slice(0, 8) + "01"));
|
||||
const monthSpend = sum(month);
|
||||
const byCat = new Map<string, number>();
|
||||
for (const t of month) byCat.set(t.category ?? "Other", (byCat.get(t.category ?? "Other") ?? 0) + t.amount);
|
||||
@@ -119,10 +120,10 @@ const monthEnd = (today: string) => today.slice(0, 8) + String(new Date(Date.UTC
|
||||
function reviewOf(o: Parameters<typeof checkinFacts>[0] & {
|
||||
weekSpend: number; monthSpend: number; month: CheckinTxn[]; bills: CheckinStream[]; newSubs: CheckinFacts["newSubs"]; priceUps: CheckinFacts["priceUps"];
|
||||
}) {
|
||||
const end = monthEnd(o.today), daysLeft = Number(end.slice(8)) - Number(o.today.slice(8));
|
||||
const end = o.span ? shift(o.span.end, -1) : monthEnd(o.today), daysLeft = Math.round((Date.parse(end) - Date.parse(o.today)) / DAY);
|
||||
const subs = [...new Set(o.bills.map((s) => s.merchant_name))].sort();
|
||||
const prev = o.prev?.subs ? o.prev : null;
|
||||
const left = leftThisMonth({ income: o.income ?? null, spend: o.usualSpend ?? null, streams: o.streams, spent: o.monthSpend, today: o.today });
|
||||
const left = leftThisMonth({ income: o.income ?? null, spend: o.usualSpend ?? null, streams: o.streams, spent: o.monthSpend, today: o.today, span: o.span });
|
||||
const byCat = (c: string) => r2(o.month.filter((t) => (t.category ?? "Other") === c).reduce((s, t) => s + t.amount, 0));
|
||||
const budgets = (o.budgets ?? []).filter((b) => b.amount > 0).map((b) => ({ category: b.category, budget: b.amount, spent: byCat(b.category) }));
|
||||
|
||||
@@ -144,7 +145,7 @@ function reviewOf(o: Parameters<typeof checkinFacts>[0] & {
|
||||
// A budget tip from last month has nothing to check against in a new month.
|
||||
const checks: Check[] = (prev?.tips ?? []).flatMap((t): Check[] => {
|
||||
if (t.kind === "pace") return [{ tip: t, now: o.weekSpend, ok: o.weekSpend <= t.amount }];
|
||||
if (t.kind === "budget") return t.by.slice(0, 7) === o.today.slice(0, 7) ? [{ tip: t, now: byCat(t.key), ok: byCat(t.key) <= t.amount }] : [];
|
||||
if (t.kind === "budget") return (o.span ? t.by >= o.span.start : t.by.slice(0, 7) === o.today.slice(0, 7)) ? [{ tip: t, now: byCat(t.key), ok: byCat(t.key) <= t.amount }] : [];
|
||||
if (t.kind === "hike") { const now = o.streams.find((s) => s.merchant_name === t.key)?.last_amount ?? t.last ?? 0; return [{ tip: t, now, ok: now <= t.amount * 1.05 }]; }
|
||||
const charged = o.txns.filter((x) => x.date > t.on && same(x.merchant, t.key)).reduce((s, x) => s + x.amount, 0);
|
||||
return [{ tip: t, now: r2(charged), ok: charged === 0 }];
|
||||
|
||||
+70
-4
@@ -5,6 +5,7 @@ import { cache } from "react";
|
||||
import { dayIn, fmtFor, setFmtScope, US_FMT, type Fmt } from "@/lib/format";
|
||||
import { ensureRates } from "@/lib/fx";
|
||||
import { typicalMonth } from "@/lib/insights";
|
||||
import { detectPeriods, monthOf, rangeOf, type Pay, type Period } from "@/lib/paymonths";
|
||||
import { createAdminClient } from "@/utils/supabase/admin";
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
|
||||
@@ -94,7 +95,12 @@ export async function transactionsSince(gte: string, lt?: string) {
|
||||
// Totals from SQL (migration 0014), own rows only, same rules as isSpend / isIncome. income is money in, positive.
|
||||
// Take the client so the AI tools can call them with theirs.
|
||||
export type MonthRow = { month: string; category_id: string; spend: number; income: number; n: number };
|
||||
// With pay months on, a month's first day is its payday, so a start on the 1st moves back to that day.
|
||||
export async function moneyByMonth(supabase: SupabaseClient, start: string, end?: string) {
|
||||
if (start.endsWith("-01")) {
|
||||
const { data: p } = await supabase.from("pay_periods").select("start_date").eq("month", start).maybeSingle();
|
||||
if (p?.start_date && p.start_date < start) start = p.start_date as string;
|
||||
}
|
||||
const { data, error } = await supabase.rpc("money_by_month", { start_date: start, end_date: end ?? null });
|
||||
if (error) throw new Error(error.message);
|
||||
return ((data ?? []) as MonthRow[]).map((r) => ({ ...r, spend: Number(r.spend), income: Number(r.income), n: Number(r.n) }));
|
||||
@@ -107,6 +113,7 @@ export async function spendByDay(supabase: SupabaseClient, start: string, end?:
|
||||
// The user's typical month: income and spend averaged over the last 3 full months (typicalMonth in insights.ts has
|
||||
// the rule). The one source for "about $X a month" income on every page. Null until there is a full month.
|
||||
export async function typicalMonthly(supabase: SupabaseClient, userId: string, today: string) {
|
||||
today = await payMonthToday(supabase, userId, today);
|
||||
const [y, m] = today.split("-").map(Number);
|
||||
const [rows, { data }] = await Promise.all([
|
||||
moneyByMonth(supabase, new Date(Date.UTC(y, m - 4, 1)).toISOString().slice(0, 10)),
|
||||
@@ -114,25 +121,41 @@ export async function typicalMonthly(supabase: SupabaseClient, userId: string, t
|
||||
]);
|
||||
return typicalMonth(rows, today, (data?.[0]?.date as string | undefined) ?? null);
|
||||
}
|
||||
/** With pay months on, today as seen by month logic: the first day of the pay month it's in (after salary on the
|
||||
* 24th it's already next month). Else today itself. */
|
||||
export async function payMonthToday(supabase: SupabaseClient, userId: string, today: string) {
|
||||
const { data } = await supabase.from("pay_periods").select("month").eq("user_id", userId).lte("start_date", today).order("start_date", { ascending: false }).limit(1);
|
||||
const m = data?.[0]?.month as string | undefined;
|
||||
return m && m.slice(0, 7) !== today.slice(0, 7) ? m : today;
|
||||
}
|
||||
/** With pay months on, the pay month today is in: its first day and the day after its last (a guess while it runs).
|
||||
* Undefined with calendar months. Reads the stored months, so it works outside a page request too. */
|
||||
export async function paySpan(supabase: SupabaseClient, userId: string, today: string) {
|
||||
const { data } = await supabase.from("pay_periods").select("month, start_date").eq("user_id", userId).order("start_date");
|
||||
const ps = ((data ?? []) as { month: string; start_date: string }[]).map((p): Period => ({ month: p.month, start: p.start_date }));
|
||||
if (!ps.length || ps[0].start > today) return undefined;
|
||||
return rangeOf(ps, monthOf(ps, today));
|
||||
}
|
||||
// Loan payments per "YYYY-MM": car, student, mortgage and so on. They're transfers in the spending totals (migration 0022),
|
||||
// but the money still leaves, so anything saying what's left over must count them. Only the row leaving a bank account:
|
||||
// the same payment arriving on a linked loan is negative, and a loan account's own rows don't count. Card payments have their own category.
|
||||
export async function loanPayments(supabase: SupabaseClient, userId: string, start: string, end = "9999-12-31") {
|
||||
// key: the month a date is in (months().of with pay months on), calendar by default. Same for savedByMonth.
|
||||
export async function loanPayments(supabase: SupabaseClient, userId: string, start: string, end = "9999-12-31", key = (d: string) => d.slice(0, 7)) {
|
||||
const rows = await allRows<{ date: string; amount: number }>((a, b) =>
|
||||
supabase.from("transactions").select("date, amount, category:categories!inner(key), account:accounts!inner(type)")
|
||||
.eq("user_id", userId).eq("ignored", false).gt("amount", 0).gte("date", start).lte("date", end)
|
||||
.eq("category.key", "LOAN_PAYMENTS").neq("account.type", "loan").order("id").range(a, b));
|
||||
const by = new Map<string, number>();
|
||||
for (const r of rows) by.set(r.date.slice(0, 7), (by.get(r.date.slice(0, 7)) ?? 0) + Number(r.amount));
|
||||
for (const r of rows) by.set(key(r.date), (by.get(key(r.date)) ?? 0) + Number(r.amount));
|
||||
return by;
|
||||
}
|
||||
// Money going into savings and investment accounts per "YYYY-MM": what arrives on a savings account (net of what leaves it)
|
||||
// and contributions to investment accounts. Only accounts broke can see.
|
||||
export async function savedByMonth(supabase: SupabaseClient, userId: string, start: string, end = "9999-12-31") {
|
||||
export async function savedByMonth(supabase: SupabaseClient, userId: string, start: string, end = "9999-12-31", key = (d: string) => d.slice(0, 7)) {
|
||||
const { data: accts } = await supabase.from("accounts").select("id, type, subtype").eq("user_id", userId).or("type.eq.investment,subtype.eq.savings");
|
||||
const by = new Map<string, number>();
|
||||
const savings = (accts ?? []).filter((a) => a.type !== "investment").map((a) => a.id), invest = (accts ?? []).filter((a) => a.type === "investment").map((a) => a.id);
|
||||
const add = (date: string, n: number) => by.set(date.slice(0, 7), (by.get(date.slice(0, 7)) ?? 0) + n);
|
||||
const add = (date: string, n: number) => by.set(key(date), (by.get(key(date)) ?? 0) + n);
|
||||
if (savings.length)
|
||||
for (const t of await allRows<{ date: string; amount: number }>((a, b) => supabase.from("transactions").select("date, amount").eq("ignored", false).gte("date", start).lte("date", end).in("account_id", savings).order("id").range(a, b))) add(t.date, -Number(t.amount));
|
||||
if (invest.length) {
|
||||
@@ -161,3 +184,46 @@ export async function allTags() {
|
||||
if (!seen.has(tag.toLowerCase())) seen.set(tag.toLowerCase(), tag);
|
||||
return [...seen.values()].sort((a, b) => a.localeCompare(b));
|
||||
}
|
||||
|
||||
// Months that start on payday (profile.month = "payday", lib/paymonths.ts), worked out from the salary in the
|
||||
// transactions on every request, so a new paycheck or a category change shows at once. money_by_month (migration 0035)
|
||||
// reads the same months from pay_periods, which is rewritten here only when they change. Null: calendar months.
|
||||
export const payPeriods = cache(async (): Promise<Period[] | null> => {
|
||||
const { supabase, user } = await getUser();
|
||||
if (!user) return null;
|
||||
const on = (user.user_metadata?.profile as { month?: string } | undefined)?.month === "payday";
|
||||
const [{ data: stored }, periods] = await Promise.all([
|
||||
supabase.from("pay_periods").select("month, start_date").order("month"),
|
||||
on ? findPeriods(supabase, user.id) : Promise.resolve(null),
|
||||
]);
|
||||
const want = periods ?? [];
|
||||
const same = (stored ?? []).length === want.length && want.every((p, i) => stored![i].month === p.month && stored![i].start_date === p.start);
|
||||
if (!same) {
|
||||
const db = createAdminClient();
|
||||
await db.from("pay_periods").delete().eq("user_id", user.id);
|
||||
if (want.length) await db.from("pay_periods").insert(want.map((p) => ({ user_id: user.id, month: p.month, start_date: p.start })));
|
||||
}
|
||||
return periods;
|
||||
});
|
||||
|
||||
async function findPeriods(supabase: SupabaseClient, userId: string) {
|
||||
const [pays, { data: first }, now] = await Promise.all([
|
||||
allRows<{ date: string; amount: number }>((a, b) => supabase.from("transactions").select("date, amount, category:categories!inner(key), account:accounts!inner(included)")
|
||||
.eq("user_id", userId).eq("ignored", false).lt("amount", 0).eq("category.key", "INCOME").eq("account.included", true).order("id").range(a, b)),
|
||||
supabase.from("transactions").select("date").eq("user_id", userId).order("date").limit(1),
|
||||
today(),
|
||||
]);
|
||||
if (!first?.length) return null;
|
||||
return detectPeriods(pays.map((p): Pay => ({ date: p.date, amount: -Number(p.amount) })), first[0].date as string, now.toISOString().slice(0, 10));
|
||||
}
|
||||
|
||||
/** This request's months: what month a date is in, a month's dates, and the month today is in. */
|
||||
export async function months() {
|
||||
const periods = await payPeriods();
|
||||
return {
|
||||
payday: !!periods,
|
||||
of: (date: string) => monthOf(periods, date),
|
||||
range: (ym: string) => rangeOf(periods, ym),
|
||||
current: async () => monthOf(periods, (await today()).toISOString().slice(0, 10)),
|
||||
};
|
||||
}
|
||||
@@ -113,6 +113,12 @@ assert.equal(Math.round(left.left), Math.round(5200 - 1820 - 2100 - pace * 8));
|
||||
assert.equal(leftThisMonth({ income: null, spend: 4000, streams: lm, spent: 2100, today: "2026-10-23" }), null, "no income: no guess");
|
||||
assert.equal(leftThisMonth({ income: 3000, spend: 4000, streams: [], spent: 2900, today: "2026-10-31" })!.left, 100, "last day: nothing more at the usual pace");
|
||||
assert.ok(leftThisMonth({ income: 2000, spend: 4000, streams: lm, spent: 2100, today: "2026-10-23" })!.left < 0, "negative when spending runs past income");
|
||||
// Pay months: Oct 23 is payday, the month runs to Nov 22 (31 days, 30 left after today). Gym lands Oct 24, 31, Nov 7, 14, 21.
|
||||
const span = { start: "2026-10-23", end: "2026-11-23" };
|
||||
assert.deepEqual(billsDueThisMonth(lm, "2026-10-23", span).map((b) => b.date), ["2026-10-24", "2026-10-25", "2026-10-31", "2026-11-07", "2026-11-14", "2026-11-21"]);
|
||||
const leftPm = leftThisMonth({ income: 5200, spend: 4000, streams: lm, spent: 0, today: "2026-10-23", span })!;
|
||||
assert.equal(leftPm.due, 1850);
|
||||
assert.equal(Math.round(leftPm.rest), Math.round(pace * 30));
|
||||
|
||||
console.log("insights ok");
|
||||
|
||||
|
||||
+12
-6
@@ -75,9 +75,13 @@ export function safeToSpend(accts: Acct[], streams: Stream[], today: string) {
|
||||
}
|
||||
|
||||
// Bills still due from today to the last day of the month. A weekly or every-two-weeks bill counts each time it lands.
|
||||
// span: a pay month's first day and the day after its last (lib/paymonths.ts), else the calendar month.
|
||||
const STEP_DAYS: Record<string, number> = { WEEKLY: 7, BIWEEKLY: 14, SEMI_MONTHLY: 15 };
|
||||
export function billsDueThisMonth(streams: Stream[], today: string) {
|
||||
const end = today.slice(0, 8) + String(new Date(Date.UTC(+today.slice(0, 4), +today.slice(5, 7), 0)).getUTCDate()).padStart(2, "0");
|
||||
export type Span = { start: string; end: string };
|
||||
const lastDayOf = (today: string, span?: Span) =>
|
||||
span ? addDays(span.end, -1) : today.slice(0, 8) + String(new Date(Date.UTC(+today.slice(0, 4), +today.slice(5, 7), 0)).getUTCDate()).padStart(2, "0");
|
||||
export function billsDueThisMonth(streams: Stream[], today: string, span?: Span) {
|
||||
const end = lastDayOf(today, span);
|
||||
const out: { name: string; date: string; amount: number }[] = [];
|
||||
for (const s of streams.filter((s) => !s.is_income && s.next_date && s.next_date >= today))
|
||||
for (let d = s.next_date!; d <= end; d = addDays(d, STEP_DAYS[s.frequency] ?? 99)) out.push({ name: s.merchant_name, date: d, amount: Number(s.average_amount) });
|
||||
@@ -88,12 +92,14 @@ export function billsDueThisMonth(streams: Stream[], today: string) {
|
||||
// minus the rest of the month at the usual pace. The usual pace is a typical month's spending without its recurring
|
||||
// bills (they are counted on their own dates), spread over the days left after today.
|
||||
// Null with no typical income: broke doesn't guess one.
|
||||
export function leftThisMonth(o: { income: number | null; spend: number | null; streams: Stream[]; spent: number; today: string }) {
|
||||
export function leftThisMonth(o: { income: number | null; spend: number | null; streams: Stream[]; spent: number; today: string; span?: Span }) {
|
||||
if (!o.income || o.income <= 0) return null;
|
||||
const days = new Date(Date.UTC(+o.today.slice(0, 4), +o.today.slice(5, 7), 0)).getUTCDate();
|
||||
const due = sum(billsDueThisMonth(o.streams, o.today).map((b) => b.amount));
|
||||
const at = (d: string) => Date.parse(`${d}T00:00:00Z`);
|
||||
const days = o.span ? Math.round((at(o.span.end) - at(o.span.start)) / 864e5) : new Date(Date.UTC(+o.today.slice(0, 4), +o.today.slice(5, 7), 0)).getUTCDate();
|
||||
const day = o.span ? Math.round((at(o.today) - at(o.span.start)) / 864e5) + 1 : +o.today.slice(8, 10);
|
||||
const due = sum(billsDueThisMonth(o.streams, o.today, o.span).map((b) => b.amount));
|
||||
const monthlyBills = sum(o.streams.filter((s) => !s.is_income).map((s) => (Number(s.average_amount) * (PER_YEAR[s.frequency] ?? 12)) / 12));
|
||||
const rest = (Math.max(0, (o.spend ?? 0) - monthlyBills) / days) * (days - +o.today.slice(8, 10));
|
||||
const rest = (Math.max(0, (o.spend ?? 0) - monthlyBills) / days) * Math.max(0, days - day);
|
||||
return { income: o.income, due, spent: o.spent, rest, left: o.income - due - o.spent - rest };
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Run: node src/lib/links.test.ts
|
||||
import assert from "node:assert/strict";
|
||||
import { duplicateItems, sameAccounts } from "./links.ts";
|
||||
import { duplicateItems, sameAccounts, twinAccounts } from "./links.ts";
|
||||
|
||||
const wf = [{ mask: "8640", type: "depository" }, { mask: "4381", type: "credit" }];
|
||||
assert.equal(sameAccounts(wf, wf), true);
|
||||
@@ -17,4 +17,11 @@ const items = [
|
||||
{ id: "co3", institution_id: "ins_128026", created_at: "2026-10-29T15:40", accounts: [{ mask: "7777", type: "credit" }] },
|
||||
];
|
||||
assert.deepEqual([...duplicateItems(items)], [["wf2", "wf1"], ["co2", "co1"]]);
|
||||
|
||||
// Removing a connection: its accounts find their twins on the connection that stays.
|
||||
const leaving = [{ id: "a1", mask: "5339", type: "depository" }, { id: "a2", mask: null, type: "depository", name: "Savings" }, { id: "a3", mask: "1111", type: "credit" }];
|
||||
const staying = [{ id: "b1", mask: "5339", type: "depository" }, { id: "b2", mask: null, type: "depository", name: "Savings" }, { id: "b3", mask: "1111", type: "depository" }];
|
||||
assert.deepEqual([...twinAccounts(leaving, staying)], [["a1", "b1"], ["a2", "b2"]], "a3 has no twin: another type");
|
||||
assert.deepEqual([...twinAccounts([leaving[0], { ...leaving[0], id: "a4" }], staying)], [["a1", "b1"]], "each twin used once");
|
||||
assert.deepEqual([...twinAccounts([{ id: "a5", mask: null, type: "depository", name: null }], [{ id: "b5", mask: null, type: "depository", name: null }])], [], "no digits and no name: can't tell");
|
||||
console.log("links ok");
|
||||
@@ -13,6 +13,18 @@ export function sameAccounts(next: Acct[], existing: Acct[]) {
|
||||
return masked.every((a) => have.has(a.mask));
|
||||
}
|
||||
|
||||
/** The same account on another connection, for a connection that is being removed: same type and last four digits,
|
||||
* or, without digits, the same type and name. Each other account is used once. */
|
||||
export function twinAccounts<T extends Acct & { id: string; name?: string | null }>(leaving: T[], others: T[]) {
|
||||
const pool = [...others], twins = new Map<string, string>();
|
||||
const same = (a: T, b: T) => (a.type ?? "") === (b.type ?? "") && (a.mask ? a.mask === b.mask : !b.mask && !!a.name && a.name === b.name);
|
||||
for (const a of leaving) {
|
||||
const i = pool.findIndex((b) => same(a, b));
|
||||
if (i >= 0) twins.set(a.id, pool.splice(i, 1)[0].id);
|
||||
}
|
||||
return twins;
|
||||
}
|
||||
|
||||
/** Connections that copy an earlier one at the same bank: id -> the earlier connection's id. */
|
||||
export function duplicateItems(items: { id: string; institution_id: string | null; created_at: string; accounts: Acct[] }[]) {
|
||||
const copies = new Map<string, string>();
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import "server-only";
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { createAdminClient } from "@/utils/supabase/admin";
|
||||
|
||||
// Personal tokens for /api/mcp (migration 0033). Shown once, stored as a SHA-256 hash, revocable in Settings.
|
||||
// "bk_" in front so it's recognizable in a config file.
|
||||
const hash = (t: string) => createHash("sha256").update(t).digest("hex");
|
||||
|
||||
export type McpLevel = "summary" | "full";
|
||||
export async function createMcpToken(userId: string, label = "Claude", level: McpLevel = "summary") {
|
||||
const token = `bk_${randomBytes(32).toString("base64url")}`;
|
||||
const { error } = await createAdminClient().from("mcp_tokens").insert({ user_id: userId, token_hash: hash(token), label: label.slice(0, 60) || "Claude", level });
|
||||
if (error) throw error;
|
||||
return token;
|
||||
}
|
||||
|
||||
/** The user a token belongs to and what it may see, or null. Notes when it was last used (at most once a minute). */
|
||||
export async function mcpUser(token: string | null): Promise<{ userId: string; level: McpLevel } | null> {
|
||||
if (!token || !/^bk_[\w-]{20,}$/.test(token)) return null;
|
||||
const db = createAdminClient();
|
||||
const { data } = await db.from("mcp_tokens").select("id, user_id, last_used_at, level").eq("token_hash", hash(token)).maybeSingle();
|
||||
if (!data) return null;
|
||||
if (!data.last_used_at || Date.now() - Date.parse(data.last_used_at) > 60_000) await db.from("mcp_tokens").update({ last_used_at: new Date().toISOString() }).eq("id", data.id);
|
||||
return { userId: data.user_id as string, level: data.level === "full" ? "full" : "summary" };
|
||||
}
|
||||
@@ -128,7 +128,8 @@ export function fullTools(supabase: SupabaseClient, profile: Record<string, unkn
|
||||
const byCat: Record<string, number> = {};
|
||||
const byMerchant: Record<string, number> = {};
|
||||
for (const t of spend) {
|
||||
byCat[t.category!.label] = (byCat[t.category!.label] ?? 0) + t.amount;
|
||||
const cat = t.category?.label ?? "Other"; // money out with no category counts as spend (isSpend), so it has none
|
||||
byCat[cat] = (byCat[cat] ?? 0) + t.amount;
|
||||
byMerchant[displayName(t)] = (byMerchant[displayName(t)] ?? 0) + t.amount;
|
||||
}
|
||||
const round = (o: Record<string, number>) => Object.entries(o).sort((a, b) => b[1] - a[1]).map(([k, v]) => [k, Math.round(v * 100) / 100]);
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import "server-only";
|
||||
import type { SupabaseClient } from "@supabase/supabase-js";
|
||||
import { z } from "zod";
|
||||
import { namesFor } from "@/lib/llm/gate";
|
||||
import type { Tool } from "@/lib/llm/shared";
|
||||
import { mergeAccounts } from "@/lib/merge-run";
|
||||
import { mask, unmask } from "@/lib/privacy";
|
||||
import { applyRulePast, pastMatchesWith, undoRuleWith, type RuleDraft } from "@/lib/rule-past";
|
||||
import { RULE_COLS, type Rule } from "@/lib/rules";
|
||||
import { fileOwnTransfers } from "@/lib/sync";
|
||||
import { createAdminClient } from "@/utils/supabase/admin";
|
||||
|
||||
// Tools that change things, for the MCP endpoint (api/mcp). Summary only, like every cloud path: they take real names or
|
||||
// placeholders (⟨M1⟩, ⟨A1⟩), turn placeholders back into names here, and answer with counts and placeholders, never a
|
||||
// single transaction. Writes run as the user (RLS); the few columns the user's own session can't write (moving rows
|
||||
// between accounts, marking transfers) go through the same server code the app uses, filtered to this user.
|
||||
|
||||
const tool = <S extends z.ZodObject>(t: { name: string; description: string; schema: S; run: (input: z.infer<S>) => Promise<string> }) => t as unknown as Tool;
|
||||
const ok = (x: unknown) => JSON.stringify(x);
|
||||
|
||||
/** full: a token the person set to Full detail. Rule text then shows as written instead of with placeholders. */
|
||||
export function manageTools(supabase: SupabaseClient, userId: string, full = false): Tool[] {
|
||||
const names = () => namesFor(supabase, userId);
|
||||
const categories = async () => {
|
||||
const { data } = await supabase.from("categories").select("id, key, label, kind");
|
||||
return (data ?? []) as { id: string; key: string; label: string; kind: string }[];
|
||||
};
|
||||
const categoryId = async (k: string) => {
|
||||
const t = k.trim().toLowerCase();
|
||||
return (await categories()).find((c) => c.key.toLowerCase() === t || c.label.toLowerCase() === t)?.id ?? null;
|
||||
};
|
||||
const accountId = async (ref: string) => {
|
||||
const real = unmask(ref, await names()).trim().toLowerCase();
|
||||
const { data } = await supabase.from("accounts").select("id, name, custom_name").eq("user_id", userId);
|
||||
return (data ?? []).find((a) => (a.custom_name || a.name).toLowerCase() === real)?.id ?? null;
|
||||
};
|
||||
const dir = z.enum(["in", "out"]).optional().describe("Only money coming in, or only money going out");
|
||||
|
||||
return [
|
||||
tool({
|
||||
name: "list_categories",
|
||||
description: "Every category a transaction can have: key, label and kind (spend, income or transfer: transfers never count as spending or income). Use a key or label wherever a tool asks for a category.",
|
||||
schema: z.object({}),
|
||||
run: async () => ok((await categories()).map(({ key, label, kind }) => ({ key, label, kind }))),
|
||||
}),
|
||||
tool({
|
||||
name: "list_rules",
|
||||
description: "The user's rules: what text they match (merchant names as placeholders), direction, the category they set, and how many past transactions each matches now. A rule's text matches anywhere in a name, so very short text can catch far too much.",
|
||||
schema: z.object({}),
|
||||
run: async () => {
|
||||
const n = await names();
|
||||
const [{ data }, cats] = await Promise.all([supabase.from("rules").select(`${RULE_COLS}, created_at`).eq("user_id", userId).order("created_at"), categories()]);
|
||||
const key = new Map(cats.map((c) => [c.id, c.key]));
|
||||
const out = [];
|
||||
for (const r of (data ?? []) as (Rule & { created_at: string })[])
|
||||
out.push({ id: r.id, match: r.match ? (full ? r.match : mask(r.match, n)) : null, direction: r.direction ?? "both", category: r.category_id ? key.get(r.category_id) ?? null : null,
|
||||
renames: !!r.rename, hides: !!r.ignore, matches_now: (await pastMatchesWith(supabase, userId, r)).length });
|
||||
return ok(out);
|
||||
},
|
||||
}),
|
||||
tool({
|
||||
name: "create_rule",
|
||||
description: "Make a rule that sets a category on matching transactions, new ones from now on and (by default) past ones too. match: text that appears in the name (a real name or a placeholder like ⟨M1⟩). Returns how many past transactions it changed.",
|
||||
schema: z.object({
|
||||
match: z.string().min(2).describe("Text in the transaction name, or a placeholder such as ⟨M1⟩"),
|
||||
category: z.string().describe("Category key or label, see list_categories"),
|
||||
direction: dir,
|
||||
apply_past: z.boolean().optional().describe("Also change matching past transactions (default true)"),
|
||||
}),
|
||||
run: async ({ match, category, direction, apply_past }) => {
|
||||
const cat = await categoryId(category);
|
||||
if (!cat) return ok({ error: `No category "${category}". See list_categories.` });
|
||||
const real = unmask(match, await names()).trim();
|
||||
const draft: RuleDraft = { match: real, amount_min: null, amount_max: null, account_id: null, day_from: null, day_to: null, direction: direction ?? null, category_id: cat, rename: null, ignore: null, add_tags: null };
|
||||
const { data, error } = await supabase.from("rules").insert(draft).select("id").single();
|
||||
if (error) return ok({ error: "Couldn't save the rule." });
|
||||
const updated = apply_past === false ? 0 : await applyRulePast(supabase, userId, draft);
|
||||
return ok({ rule_id: data.id, updated_past: updated, warning: real.length <= 3 ? "Very short text matches inside other words. Check list_rules matches_now." : undefined });
|
||||
},
|
||||
}),
|
||||
tool({
|
||||
name: "delete_rule",
|
||||
description: "Delete a rule by id (from list_rules). By default it also takes back what the rule did to past transactions: they get what the other rules say, or no category, and transfers between own accounts are looked for again.",
|
||||
schema: z.object({ id: z.string().uuid(), undo_past: z.boolean().optional().describe("Take back its changes on past transactions (default true)") }),
|
||||
run: async ({ id, undo_past }) => {
|
||||
const { data: rule } = await supabase.from("rules").select(RULE_COLS).eq("user_id", userId).eq("id", id).maybeSingle();
|
||||
if (!rule) return ok({ error: "No such rule." });
|
||||
const undone = undo_past === false ? 0 : await undoRuleWith(supabase, userId, rule as Rule);
|
||||
const { error } = await supabase.from("rules").delete().eq("id", id).eq("user_id", userId);
|
||||
if (error) return ok({ error: "Couldn't delete the rule." });
|
||||
const transfers = undo_past === false ? 0 : await fileOwnTransfers(userId);
|
||||
return ok({ deleted: true, undone_past: undone, marked_as_transfers: transfers });
|
||||
},
|
||||
}),
|
||||
tool({
|
||||
name: "recategorize",
|
||||
description: "Set a category on past transactions that match a name (real text or placeholder), optionally only money in or out and only between two dates. No rule is made, so new transactions aren't affected: use create_rule for that. Returns how many changed.",
|
||||
schema: z.object({
|
||||
match: z.string().min(2).describe("Text in the transaction name, or a placeholder such as ⟨M1⟩"),
|
||||
category: z.string().describe("Category key or label"),
|
||||
direction: dir,
|
||||
from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
|
||||
to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
|
||||
}),
|
||||
run: async ({ match, category, direction, from, to }) => {
|
||||
const cat = await categoryId(category);
|
||||
if (!cat) return ok({ error: `No category "${category}". See list_categories.` });
|
||||
const draft: RuleDraft = { match: unmask(match, await names()).trim(), amount_min: null, amount_max: null, account_id: null, day_from: null, day_to: null, direction: direction ?? null, category_id: cat, rename: null, ignore: null, add_tags: null };
|
||||
const ids = (await pastMatchesWith(supabase, userId, draft)).filter((t) => (!from || t.date >= from) && (!to || t.date <= to)).map((t) => t.id);
|
||||
for (let i = 0; i < ids.length; i += 200) await supabase.from("transactions").update({ category_id: cat }).in("id", ids.slice(i, i + 200));
|
||||
return ok({ updated: ids.length });
|
||||
},
|
||||
}),
|
||||
tool({
|
||||
name: "find_transfers",
|
||||
description: "Look for money moved between the user's own accounts that still counts as spending and income (same amount out and in within 4 days, or a savings or investment account by name) and mark it as transfers. Only rows without a category, or Other.",
|
||||
schema: z.object({}),
|
||||
run: async () => ok({ marked_as_transfers: await fileOwnTransfers(userId) }),
|
||||
}),
|
||||
tool({
|
||||
name: "merge_accounts",
|
||||
description: "Merge an imported (CSV) account into a linked one, by placeholder (⟨A1⟩, see list_accounts). Older imported transactions move over; from the day the bank's history starts its own are kept and edits carry over; then the imported account is removed. preview (default true) only counts.",
|
||||
schema: z.object({ from: z.string().describe("The imported account, e.g. ⟨A2⟩"), into: z.string().describe("The linked account, e.g. ⟨A1⟩"), preview: z.boolean().optional() }),
|
||||
run: async ({ from, into, preview }) => {
|
||||
const [a, b] = await Promise.all([accountId(from), accountId(into)]);
|
||||
if (!a || !b) return ok({ error: "Account not found. Use placeholders from list_accounts." });
|
||||
return ok(await mergeAccounts(createAdminClient(), userId, a, b, preview !== false));
|
||||
},
|
||||
}),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import "server-only";
|
||||
import type { SupabaseClient } from "@supabase/supabase-js";
|
||||
import { z } from "zod";
|
||||
import { displayName, TXN_SELECT, type Txn } from "@/lib/data";
|
||||
import type { Tool } from "@/lib/llm/shared";
|
||||
|
||||
// Single-transaction tools for an MCP token the person set to "Full detail" (Connect your AI, migration 0034).
|
||||
// Never for a summary token. Rows come with their id so an AI can fix them one by one; writes run as the user (RLS),
|
||||
// only on the columns the app itself lets them change (category, name, hidden).
|
||||
|
||||
const tool = <S extends z.ZodObject>(t: { name: string; description: string; schema: S; run: (input: z.infer<S>) => Promise<string> }) => t as unknown as Tool;
|
||||
|
||||
/** IBANs and long account numbers keep only their first and last characters, in everything a full-detail token sees. */
|
||||
// Ids (UUIDs) stay exactly as they are: a tool needs them back.
|
||||
const UUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;
|
||||
const maskPart = (text: string) =>
|
||||
text
|
||||
.replace(/\b([A-Z]{2}\d{2})[A-Z0-9]{4,}(\d{4})\b/g, "$1…$2") // NL24INGB0008165339 -> NL24…5339
|
||||
.replace(/\b\d{5,}(\d{4})\b/g, "…$1"); // 210026951876 -> …1876
|
||||
export const maskNumbers = (text: string) => {
|
||||
const ids = text.match(UUID_RE) ?? [];
|
||||
return text.split(UUID_RE).map(maskPart).reduce((out, part, i) => out + part + (ids[i] ?? ""), "");
|
||||
};
|
||||
|
||||
const UUID = z.string().uuid();
|
||||
|
||||
export function rowTools(supabase: SupabaseClient, userId: string): Tool[] {
|
||||
const cats = async () => ((await supabase.from("categories").select("id, key, label, kind")).data ?? []) as { id: string; key: string; label: string; kind: string }[];
|
||||
const catId = async (k: string) => { const t = k.trim().toLowerCase(); return (await cats()).find((c) => c.key.toLowerCase() === t || c.label.toLowerCase() === t)?.id ?? null; };
|
||||
|
||||
return [
|
||||
tool({
|
||||
name: "list_transactions",
|
||||
description: "Single transactions with their id, newest first: date, amount (positive = money out, negative = money in), name, merchant, your own name for it, category key and kind, account, hidden, tags. Filters combine. IBANs and account numbers are shortened.",
|
||||
schema: z.object({
|
||||
query: z.string().optional().describe("Text in the name, merchant or your own name for it"),
|
||||
from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
|
||||
to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
|
||||
account: z.string().optional().describe("Account name (see list_accounts)"),
|
||||
category: z.string().optional().describe('Category key or label, or "none" for rows without one'),
|
||||
direction: z.enum(["in", "out"]).optional(),
|
||||
min_amount: z.number().optional().describe("At least this much (either direction)"),
|
||||
limit: z.number().int().min(1).max(500).default(100),
|
||||
offset: z.number().int().min(0).default(0),
|
||||
}),
|
||||
run: async ({ query, from, to, account, category, direction, min_amount, limit, offset }) => {
|
||||
let q = supabase.from("transactions").select(TXN_SELECT).eq("user_id", userId);
|
||||
if (query) { const s = query.replace(/[%,()]/g, " "); q = q.or(`name.ilike.%${s}%,merchant_name.ilike.%${s}%,custom_name.ilike.%${s}%`); }
|
||||
if (from) q = q.gte("date", from);
|
||||
if (to) q = q.lte("date", to);
|
||||
if (direction === "out") q = q.gt("amount", 0);
|
||||
if (direction === "in") q = q.lt("amount", 0);
|
||||
if (account) {
|
||||
const { data } = await supabase.from("accounts").select("id, name, custom_name").eq("user_id", userId);
|
||||
const a = (data ?? []).find((x) => (x.custom_name || x.name).toLowerCase() === account.trim().toLowerCase());
|
||||
if (!a) return JSON.stringify({ error: `No account "${account}".` });
|
||||
q = q.eq("account_id", a.id);
|
||||
}
|
||||
if (category) {
|
||||
if (category.trim().toLowerCase() === "none") q = q.is("category_id", null);
|
||||
else { const id = await catId(category); if (!id) return JSON.stringify({ error: `No category "${category}". See list_categories.` }); q = q.eq("category_id", id); }
|
||||
}
|
||||
if (min_amount) q = q.or(`amount.gte.${Math.abs(min_amount)},amount.lte.${-Math.abs(min_amount)}`);
|
||||
const { data, error } = await q.order("date", { ascending: false }).order("id").range(offset, offset + limit - 1);
|
||||
if (error) return JSON.stringify({ error: error.message });
|
||||
return JSON.stringify(((data ?? []) as unknown as Txn[]).map((t) => ({
|
||||
id: t.id, date: t.date, amount: Number(t.amount), name: t.name, merchant: t.merchant_name, your_name: t.custom_name, shown_as: displayName(t),
|
||||
category: t.category?.key ?? null, kind: t.category?.kind ?? null, account: t.account ? t.account.custom_name || t.account.name : null, hidden: t.ignored || undefined, tags: t.tags?.length ? t.tags : undefined,
|
||||
})));
|
||||
},
|
||||
}),
|
||||
tool({
|
||||
name: "update_transactions",
|
||||
description: "Change specific transactions by id (from list_transactions): category, your own name for them, or hidden (left out of every total). Returns how many changed.",
|
||||
schema: z.object({
|
||||
ids: z.array(UUID).min(1).max(500),
|
||||
category: z.string().optional().describe('Category key or label, or "none" to clear it'),
|
||||
name: z.string().max(120).nullable().optional().describe("Your own name for them; null clears it"),
|
||||
hidden: z.boolean().optional(),
|
||||
}),
|
||||
run: async ({ ids, category, name, hidden }) => {
|
||||
const patch: Record<string, unknown> = {};
|
||||
if (category !== undefined) {
|
||||
if (category.trim().toLowerCase() === "none") patch.category_id = null;
|
||||
else { const id = await catId(category); if (!id) return JSON.stringify({ error: `No category "${category}".` }); patch.category_id = id; }
|
||||
}
|
||||
if (name !== undefined) patch.custom_name = name?.trim() || null;
|
||||
if (hidden !== undefined) patch.ignored = hidden;
|
||||
if (!Object.keys(patch).length) return JSON.stringify({ error: "Nothing to change." });
|
||||
const { data, error } = await supabase.from("transactions").update(patch).eq("user_id", userId).in("id", ids).select("id");
|
||||
return JSON.stringify(error ? { error: "Couldn't update them." } : { updated: data?.length ?? 0 });
|
||||
},
|
||||
}),
|
||||
tool({
|
||||
name: "mark_transfer_pair",
|
||||
description: "Mark two transactions as one transfer between your own accounts: the money-out row becomes Transfers out, the money-in row Transfers in, so neither counts as spending or income. They must be the same amount, in different accounts.",
|
||||
schema: z.object({ out_id: UUID, in_id: UUID }),
|
||||
run: async ({ out_id, in_id }) => {
|
||||
const { data } = await supabase.from("transactions").select("id, amount, account_id").eq("user_id", userId).in("id", [out_id, in_id]);
|
||||
const o = data?.find((t) => t.id === out_id), i = data?.find((t) => t.id === in_id);
|
||||
if (!o || !i) return JSON.stringify({ error: "Transaction not found." });
|
||||
if (!(Number(o.amount) > 0 && Number(i.amount) < 0) || Math.abs(Number(o.amount) + Number(i.amount)) >= 0.005) return JSON.stringify({ error: "out_id must be money out and in_id the same amount coming in." });
|
||||
if (o.account_id === i.account_id) return JSON.stringify({ error: "They're in the same account." });
|
||||
const ids = Object.fromEntries((await cats()).filter((c) => c.key === "TRANSFER_OUT" || c.key === "TRANSFER_IN").map((c) => [c.key, c.id]));
|
||||
await supabase.from("transactions").update({ category_id: ids.TRANSFER_OUT }).eq("id", out_id).eq("user_id", userId);
|
||||
await supabase.from("transactions").update({ category_id: ids.TRANSFER_IN }).eq("id", in_id).eq("user_id", userId);
|
||||
return JSON.stringify({ marked: true });
|
||||
},
|
||||
}),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import "server-only";
|
||||
import type { SupabaseClient } from "@supabase/supabase-js";
|
||||
import { planMerge, type MergeRow } from "@/lib/merge";
|
||||
|
||||
// Merge an imported account into another of the person's accounts (lib/merge.ts decides what moves). Used by the
|
||||
// Accounts page (api/accounts/merge) and the MCP tools. db: a client that can write the user's rows.
|
||||
const COLS = "id, date, amount, category_id, custom_name, note, tags, ignored, plaid_transaction_id";
|
||||
|
||||
async function rowsOf(db: SupabaseClient, userId: string, accountId: string) {
|
||||
const out: MergeRow[] = [];
|
||||
for (let from = 0; ; from += 1000) {
|
||||
const { data, error } = await db.from("transactions").select(COLS).eq("user_id", userId).eq("account_id", accountId).order("date").range(from, from + 999);
|
||||
if (error) throw error;
|
||||
out.push(...(data ?? []).map(({ plaid_transaction_id, ...r }) => ({ ...r, fromBank: !!plaid_transaction_id }) as MergeRow));
|
||||
if ((data ?? []).length < 1000) return out;
|
||||
}
|
||||
}
|
||||
const chunks = <T,>(xs: T[], n = 200) => Array.from({ length: Math.ceil(xs.length / n) }, (_, i) => xs.slice(i * n, i * n + n));
|
||||
|
||||
export type MergeResult = { error?: string; status?: number; start?: string | null; moved?: number; replaced?: number; edits?: number; ok?: boolean };
|
||||
export async function mergeAccounts(db: SupabaseClient, userId: string, from: string, into: string, preview: boolean): Promise<MergeResult> {
|
||||
if (!from || !into || from === into) return { error: "Pick the account to merge into.", status: 400 };
|
||||
const { data: accts } = await db.from("accounts").select("id, manual").eq("user_id", userId).in("id", [from, into]);
|
||||
const src = accts?.find((a) => a.id === from), dst = accts?.find((a) => a.id === into);
|
||||
if (!src || !dst) return { error: "Account not found.", status: 404 };
|
||||
if (!src.manual) return { error: "Only an imported account can be merged into another.", status: 400 };
|
||||
return foldInto(db, userId, from, into, preview);
|
||||
}
|
||||
|
||||
/** Moves one account's history into another: older rows move, the overlap the target already has goes, edits carry
|
||||
* over. Then the source account is deleted. Also used when a connection is removed and the same account stays on
|
||||
* another connection (api/plaid/remove), so nothing typed or chosen there is lost. */
|
||||
export async function foldInto(db: SupabaseClient, userId: string, from: string, into: string, preview = false): Promise<MergeResult> {
|
||||
const plan = planMerge(await rowsOf(db, userId, from), await rowsOf(db, userId, into));
|
||||
const counts = { start: plan.start, moved: plan.move.length, replaced: plan.drop.length, edits: plan.edits.length };
|
||||
if (preview) return counts;
|
||||
for (const e of plan.edits) {
|
||||
const { error } = await db.from("transactions").update(e.patch).eq("id", e.id).eq("user_id", userId);
|
||||
if (error) throw error;
|
||||
}
|
||||
for (const ids of chunks(plan.move)) {
|
||||
const { error } = await db.from("transactions").update({ account_id: into }).eq("user_id", userId).in("id", ids);
|
||||
if (error) throw error;
|
||||
}
|
||||
// Rules and repeating charges that point at the imported account now point at the one it went into.
|
||||
await db.from("rules").update({ account_id: into }).eq("user_id", userId).eq("account_id", from);
|
||||
await db.from("recurring").update({ account_id: into }).eq("user_id", userId).eq("account_id", from);
|
||||
// What's left on the imported account is the overlap the bank already has. Deleting the account takes it along.
|
||||
const { error } = await db.from("accounts").delete().eq("id", from).eq("user_id", userId);
|
||||
if (error) throw error;
|
||||
return { ok: true, ...counts };
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// Run: node src/lib/paymonths.test.ts
|
||||
import assert from "node:assert/strict";
|
||||
import { detectPeriods, monthOf, paychecks, rangeOf } from "./paymonths.ts";
|
||||
|
||||
// Salary around the 24th or 25th, early when that's a weekend. A tax refund and student finance are no paychecks.
|
||||
const pays = [
|
||||
{ date: "2026-07-24", amount: 2700 }, { date: "2026-08-25", amount: 2700 }, { date: "2026-09-04", amount: 310 },
|
||||
{ date: "2026-09-24", amount: 2750 }, { date: "2026-10-23", amount: 2760 }, { date: "2026-10-30", amount: 64 },
|
||||
];
|
||||
assert.deepEqual(paychecks(pays).map((p) => p.date), ["2026-07-24", "2026-08-25", "2026-09-24", "2026-10-23"]);
|
||||
|
||||
let ps = detectPeriods(pays, "2026-07-02", "2026-11-22")!;
|
||||
assert.deepEqual(ps, [
|
||||
{ month: "2026-08-01", start: "2026-07-24" },
|
||||
{ month: "2026-09-01", start: "2026-08-25" },
|
||||
{ month: "2026-10-01", start: "2026-09-24" },
|
||||
{ month: "2026-11-01", start: "2026-10-23" },
|
||||
], "December has not started: no salary yet and it isn't the 24th");
|
||||
assert.equal(monthOf(ps, "2026-10-22"), "2026-10");
|
||||
assert.equal(monthOf(ps, "2026-10-23"), "2026-11", "salary day opens the month");
|
||||
assert.equal(monthOf(ps, "2026-07-10"), "2026-07", "before the first salary: calendar");
|
||||
assert.deepEqual(rangeOf(ps, "2026-10"), { start: "2026-09-24", end: "2026-10-23" });
|
||||
assert.deepEqual(rangeOf(ps, "2026-11"), { start: "2026-10-23", end: "2026-11-23" }, "running month: a month on");
|
||||
assert.deepEqual(rangeOf(ps, "2026-07"), { start: "2026-07-01", end: "2026-07-24" }, "the month before the first salary");
|
||||
assert.deepEqual(rangeOf(null, "2026-02"), { start: "2026-02-01", end: "2026-03-01" });
|
||||
|
||||
// Salary late: past the usual day the month waits for it, a day at a time.
|
||||
ps = detectPeriods(pays, "2026-07-02", "2026-11-26")!;
|
||||
assert.equal(ps.at(-1)!.month, "2026-11-01", "the 26th, still no salary: November runs on");
|
||||
// It comes on the 27th.
|
||||
ps = detectPeriods([...pays, { date: "2026-11-27", amount: 2780 }], "2026-07-02", "2026-11-27")!;
|
||||
assert.deepEqual(ps.at(-1), { month: "2026-12-01", start: "2026-11-27" });
|
||||
// No salary at all for 12 days after the usual day (the 25th here): the usual day stands in.
|
||||
ps = detectPeriods(pays.slice(0, 2), "2026-07-02", "2026-10-30")!;
|
||||
assert.deepEqual(ps.map((p) => p.start), ["2026-07-24", "2026-08-25", "2026-09-25"]);
|
||||
|
||||
// Paid on the 1st: each month starts on its own payday.
|
||||
ps = detectPeriods([{ date: "2026-09-01", amount: 2000 }, { date: "2026-09-30", amount: 2000 }, { date: "2026-11-02", amount: 2000 }], "2026-09-01", "2026-11-05")!;
|
||||
assert.deepEqual(ps, [{ month: "2026-09-01", start: "2026-09-01" }, { month: "2026-10-01", start: "2026-09-30" }, { month: "2026-11-01", start: "2026-11-02" }]);
|
||||
|
||||
assert.equal(detectPeriods([], "2026-01-01", "2026-11-22"), null);
|
||||
console.log("paymonths ok");
|
||||
@@ -0,0 +1,67 @@
|
||||
// Months that start on payday (profile.month = "payday"): each month runs from one salary to the day before the next.
|
||||
// A month is named after the calendar month it mostly covers, so salary on 24 October starts "November".
|
||||
// Salary: money in under the Income category, at least half a usual paycheck, so a small refund never starts a month.
|
||||
// Before the first salary, or for a month whose salary hasn't come yet, the usual pay day stands in.
|
||||
// Pure: `node src/lib/paymonths.test.ts` runs it.
|
||||
|
||||
export type Pay = { date: string; amount: number }; // amount: money in, positive
|
||||
export type Period = { month: string; start: string }; // month: "YYYY-MM-01", start: "YYYY-MM-DD"
|
||||
|
||||
const DAY = 864e5;
|
||||
const at = (iso: string) => Date.parse(`${iso}T00:00:00Z`);
|
||||
const iso = (t: number) => new Date(t).toISOString().slice(0, 10);
|
||||
const addMonths = (ym: string, n: number) => iso(Date.UTC(+ym.slice(0, 4), +ym.slice(5, 7) - 1 + n, 1)).slice(0, 7);
|
||||
const median = (xs: number[]) => { const s = [...xs].sort((a, b) => a - b); return s.length ? s[Math.floor(s.length / 2)] : 0; };
|
||||
const dayIn = (ym: string, d: number) => {
|
||||
const last = new Date(Date.UTC(+ym.slice(0, 4), +ym.slice(5, 7), 0)).getUTCDate();
|
||||
return `${ym}-${String(Math.min(d, last)).padStart(2, "0")}`;
|
||||
};
|
||||
|
||||
/** The paychecks among money in: per calendar month the biggest one sets a usual size, and anything at least half
|
||||
* of that counts. */
|
||||
export function paychecks(pays: Pay[]) {
|
||||
const top = new Map<string, number>();
|
||||
for (const p of pays) top.set(p.date.slice(0, 7), Math.max(top.get(p.date.slice(0, 7)) ?? 0, p.amount));
|
||||
const usual = median([...top.values()]);
|
||||
return usual > 0 ? pays.filter((p) => p.amount >= usual / 2).sort((a, b) => a.date.localeCompare(b.date)) : [];
|
||||
}
|
||||
|
||||
/** Every month from the one holding `first` up to the one today is in. Null with no salary to go by. */
|
||||
export function detectPeriods(pays: Pay[], first: string, today: string): Period[] | null {
|
||||
const checks = paychecks(pays);
|
||||
if (!checks.length) return null;
|
||||
const usualDay = median(checks.map((p) => +p.date.slice(8, 10)));
|
||||
// Pay late in the month starts the next month's period; pay early in the month starts its own.
|
||||
const lead = usualDay >= 15 ? 1 : 0;
|
||||
const out: Period[] = [];
|
||||
for (let ym = addMonths(first.slice(0, 7), lead); ; ym = addMonths(ym, 1)) {
|
||||
const expected = dayIn(addMonths(ym, -lead), usualDay);
|
||||
const prev = out.at(-1)?.start;
|
||||
// Salary up to 12 days either side of the usual day (weekends, holidays, a late employer), at least 20 days after
|
||||
// the last start, so one paycheck never starts two months.
|
||||
const found = checks.find((p) => Math.abs(at(p.date) - at(expected)) <= 12 * DAY && (!prev || at(p.date) - at(prev) >= 20 * DAY));
|
||||
const waiting = !found && at(expected) + 12 * DAY > at(today);
|
||||
// Not paid yet: the month can't start before tomorrow, so today stays in the month that's running.
|
||||
const start = found ? found.date : waiting ? iso(Math.max(at(expected), at(today) + DAY)) : expected;
|
||||
if (start > today) break;
|
||||
out.push({ month: `${ym}-01`, start });
|
||||
}
|
||||
return out.length ? out : null;
|
||||
}
|
||||
|
||||
/** "YYYY-MM" of the month a date is in. Without pay months (or before the first one): its calendar month. */
|
||||
export function monthOf(periods: Period[] | null, date: string) {
|
||||
if (periods) for (let i = periods.length - 1; i >= 0; i--) if (periods[i].start <= date) return periods[i].month.slice(0, 7);
|
||||
return date.slice(0, 7);
|
||||
}
|
||||
|
||||
/** First day and the day after the last day of a month ("YYYY-MM"). */
|
||||
export function rangeOf(periods: Period[] | null, ym: string) {
|
||||
const cal = { start: `${ym}-01`, end: `${addMonths(ym, 1)}-01` };
|
||||
if (!periods?.length) return cal;
|
||||
const i = periods.findIndex((p) => p.month.startsWith(ym));
|
||||
if (i < 0) return ym < periods[0].month ? { start: cal.start, end: ym === addMonths(periods[0].month, -1) ? periods[0].start : cal.end } : cal;
|
||||
// The running month: its end is a guess, the same day a month on (the next salary decides).
|
||||
const s = periods[i].start;
|
||||
return { start: s, end: periods[i + 1]?.start ?? dayIn(addMonths(s.slice(0, 7), 1), +s.slice(8, 10)) };
|
||||
}
|
||||
+3
-1
@@ -42,7 +42,9 @@ export function plaidError(e: unknown): { code: string; message: string } {
|
||||
if (d?.error_code) return { code: d.error_code, message: d.display_message || d.error_message || d.error_code };
|
||||
const code = (e as { code?: unknown })?.code; // other providers (src/lib/providers) throw { code: "AKAHU_401", message }
|
||||
if (typeof code === "string" && /^(AKAHU_|CONSENT_EXPIRED$|FEED_CONSENT$)/.test(code) && e instanceof Error) return { code, message: e.message };
|
||||
return { code: "ERROR", message: e instanceof Error ? e.message : "Plaid request failed" };
|
||||
// A database error is a plain object with a message, not an Error: keep its message so the log and Accounts say what broke.
|
||||
const message = e instanceof Error ? e.message : typeof (e as { message?: unknown })?.message === "string" ? (e as { message: string }).message : "Plaid request failed";
|
||||
return { code: "ERROR", message };
|
||||
}
|
||||
|
||||
/** Revokes a bank connection at Plaid. Akahu tokens belong to the server owner, and a test connection can't be revoked
|
||||
|
||||
@@ -6,7 +6,7 @@ import { cardMatches } from "@/lib/cards-data";
|
||||
import { cashInsights, myCashInsights } from "@/lib/cash";
|
||||
import { countryOf } from "@/lib/countries";
|
||||
import { cache } from "react";
|
||||
import { allRows, displayName, getUser, isIncome, isSpend, moneyByMonth, today as userToday, TXN_SELECT, type Txn, loanPayments } from "@/lib/data";
|
||||
import { allRows, displayName, getUser, isIncome, isSpend, moneyByMonth, payMonthToday, today as userToday, TXN_SELECT, type Txn, loanPayments } from "@/lib/data";
|
||||
import { dateLabel, fmtFor, money0, ymd } from "@/lib/format";
|
||||
import { addDays, toldMonthly } from "@/lib/insights";
|
||||
import { contributionRoom } from "@/lib/invest";
|
||||
@@ -52,6 +52,8 @@ export async function planFacts(supabase: SupabaseClient, userId: string, profil
|
||||
const country = countryOf(profile.country);
|
||||
const since = addDays(today, -90);
|
||||
const usTax = country.code === "US" && Number(today.slice(0, 4)) === TAX_YEAR;
|
||||
// Month logic runs on the pay month today is in when months start on payday (lib/paymonths.ts).
|
||||
const monthToday = await payMonthToday(supabase, userId, today);
|
||||
// US tax rows load in the same batch: they only depend on usTax.
|
||||
const [cash, { streams, txns: charges }, { data: rec }, months, txns, { data: cats }, room, cards, byMonth, { data: accts }, [taxTxns, { data: held }]] = await Promise.all([
|
||||
cash0 ?? cashInsights(supabase, profile, { userId, today }),
|
||||
@@ -62,7 +64,7 @@ export async function planFacts(supabase: SupabaseClient, userId: string, profil
|
||||
supabase.from("categories").select("id, label, key"),
|
||||
contributionRoom(supabase, profile, { tax: country.tax, today, locale: country.locale, mine: profile.contributed as Record<string, number> | undefined }).catch(() => []),
|
||||
country.cards ? cardMatches(supabase, userId, creditOf(profile)?.band) : Promise.resolve(null),
|
||||
moneyByMonth(supabase, monthStart(today, -3)),
|
||||
moneyByMonth(supabase, monthStart(monthToday, -3)),
|
||||
supabase.from("accounts").select("type, subtype, current_balance:home_balance, included").eq("user_id", userId),
|
||||
usTax
|
||||
? Promise.all([
|
||||
@@ -160,7 +162,7 @@ export async function planFacts(supabase: SupabaseClient, userId: string, profil
|
||||
// The affordability gate's numbers: monthly income and spending over the last full months with data (up to 3),
|
||||
// essentials from the same months, and cash available now (the same figure as safe to spend).
|
||||
const key = new Map((cats ?? []).map((c) => [c.id as string, c.key as string]));
|
||||
const thisMonth = today.slice(0, 7);
|
||||
const thisMonth = monthToday.slice(0, 7);
|
||||
const perMonth = new Map<string, { income: number; spend: number; essentials: number; cats: Map<string, number> }>();
|
||||
for (const row of byMonth) {
|
||||
const m = row.month.slice(0, 7);
|
||||
@@ -178,11 +180,11 @@ export async function planFacts(supabase: SupabaseClient, userId: string, profil
|
||||
// No paycheck found (typicalMonth has no income): the take-home pay they told us in onboarding, flagged. Never mixed in.
|
||||
const told = cash.typical && cash.typical.income > 0 ? null : toldMonthly(profile.pay as { amount?: number; every?: string } | undefined);
|
||||
// Loan payments aren't spending in the totals, but the money is gone and they can't be skipped: count them as essentials.
|
||||
const paid = await loanPayments(supabase, userId, monthStart(today, -3));
|
||||
const paid = await loanPayments(supabase, userId, monthStart(monthToday, -3));
|
||||
const baseMonths = [...perMonth].filter(([, x]) => base.includes(x)).map(([m]) => m);
|
||||
const loanAvg = baseMonths.length ? baseMonths.reduce((s, m) => s + (paid.get(m) ?? 0), 0) / baseMonths.length : 0;
|
||||
const budget = { income: r2(told ?? avg((x) => x.income)), ...(told ? { incomeTold: true } : {}), spend: r2(spendAvg + loanAvg), cash: r2(cash.safe.cash), essentials: r2((essentials > 0 ? essentials : spendAvg) + loanAvg), essentialsAll: !(essentials > 0) };
|
||||
const last = monthStart(today, -1).slice(0, 7);
|
||||
const last = monthStart(monthToday, -1).slice(0, 7);
|
||||
const monthRows = [last, thisMonth].flatMap((m) => { const x = perMonth.get(m); return x && (x.spend || x.income) ? [{ month: m, income: r2(x.income), spend: r2(x.spend) }] : []; });
|
||||
const now = perMonth.get(thisMonth);
|
||||
const spikes = earlier.length && now
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Run: node src/lib/providers/feeds.test.ts
|
||||
import assert from "node:assert/strict";
|
||||
import { createVerify, generateKeyPairSync } from "node:crypto";
|
||||
import { basiqAccount, basiqStart, basiqTxn, belvoAccount, belvoStart, belvoTxn, ebAccount, ebJwt, ebStart, ebTxn, feedData, pemFrom, validCpf } from "./feeds.ts";
|
||||
import { basiqAccount, basiqStart, basiqTxn, belvoAccount, belvoStart, belvoTxn, ebAccount, ebJwt, ebStart, ebTxn, feedData, matchRenamed, pemFrom, validCpf } from "./feeds.ts";
|
||||
|
||||
const { privateKey, publicKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
|
||||
const pem = privateKey.export({ type: "pkcs8", format: "pem" }).toString();
|
||||
@@ -99,6 +99,26 @@ console.log("feeds: ok");
|
||||
const b = ebTxn({ transaction_id: "x2", entry_reference: "ref-9", booking_date: "2026-11-02", transaction_amount: { amount: "3.50" }, credit_debit_indicator: "DBIT", status: "BOOK" }, "u1")!;
|
||||
assert.equal(a.plaid_transaction_id, b.plaid_transaction_id);
|
||||
}
|
||||
// Linking again gave every row a new transaction_id: each new row takes over its saved twin instead of doubling.
|
||||
{
|
||||
const t = (id: string, date: string, amount: number, name: string) => ({ ...ebTxn({ transaction_id: id, booking_date: date, transaction_amount: { amount: String(amount) }, credit_debit_indicator: "DBIT", status: "BOOK", note: name }, "h")!, account_id: "acc" });
|
||||
const saved = [
|
||||
{ id: "s1", account_id: "acc", date: "2026-11-17", amount: "3.49", name: "Action" },
|
||||
{ id: "s2", account_id: "acc", date: "2026-11-17", amount: "3.49", name: "Action" }, // two identical buys
|
||||
{ id: "s3", account_id: "acc", date: "2026-11-17", amount: 14, name: "Pizza" },
|
||||
{ id: "s4", account_id: "other", date: "2026-11-17", amount: 14, name: "Pizza" }, // other account: never matched
|
||||
];
|
||||
const fresh = [t("n1", "2026-11-17", 3.49, "Action"), t("n2", "2026-11-17", 3.49, "Action"), t("n3", "2026-11-17", 3.49, "Action"), t("n4", "2026-11-17", 14, "Pizza"), t("n5", "2026-11-18", 14, "Pizza")];
|
||||
const m = matchRenamed(fresh, saved);
|
||||
assert.equal(m.size, 3); // two Actions and the pizza; the third Action and the next day's pizza are really new
|
||||
assert.deepEqual(new Set([m.get(fresh[0].plaid_transaction_id), m.get(fresh[1].plaid_transaction_id)]), new Set(["s1", "s2"]));
|
||||
assert.equal(m.get(fresh[2].plaid_transaction_id), undefined);
|
||||
assert.equal(m.get(fresh[3].plaid_transaction_id), "s3");
|
||||
assert.equal(m.get(fresh[4].plaid_transaction_id), undefined);
|
||||
// A hidden copy is only used when the visible one is taken.
|
||||
const h = matchRenamed([fresh[3]], [{ id: "hidden", account_id: "acc", date: "2026-11-17", amount: 14, name: "Pizza", ignored: true }, { id: "shown", account_id: "acc", date: "2026-11-17", amount: 14, name: "Pizza", ignored: false }]);
|
||||
assert.equal(h.get(fresh[3].plaid_transaction_id), "shown");
|
||||
}
|
||||
// A key pasted on one line keeps its own label, PKCS#1 included, and still signs.
|
||||
{
|
||||
const { generateKeyPairSync, createPrivateKey: load } = await import("node:crypto");
|
||||
|
||||
@@ -97,6 +97,25 @@ export function ebTxn(t: EbTxn, uid: string): FeedTxn | null {
|
||||
const id = t.entry_reference || t.transaction_id || `${date}|${n}|${text}`;
|
||||
return { plaid_transaction_id: `enablebanking:${uid}:${id}`, account_ref: `enablebanking:${uid}`, date: date.slice(0, 10), amount: out ? Math.abs(n) : -Math.abs(n), name: text || other || "Transaction", merchant_name: other, logo_url: null, pending: false, plaid_category: t.bank_transaction_code?.code ?? null };
|
||||
}
|
||||
/** A bank can give a row a new id on a later fetch (ING through Enable Banking does after linking again), so a row
|
||||
* already saved under its old id looks new. Pairs each such "new" row with a saved row of the same account, day, amount
|
||||
* and name whose id didn't come back in this fetch. One saved row per new row, so two identical coffees stay two rows.
|
||||
* Returns new id -> saved row's id. Saved rows that aren't hidden are used first. */
|
||||
export type SavedRow = { id: string; account_id: string; date: string; amount: number | string; name: string | null; ignored?: boolean | null };
|
||||
export function matchRenamed(fresh: (FeedTxn & { account_id: string })[], unmatchedSaved: SavedRow[]) {
|
||||
const key = (r: { account_id: string; date: string; amount: number | string; name: string | null }) => `${r.account_id}|${r.date.slice(0, 10)}|${Number(r.amount).toFixed(2)}|${r.name ?? ""}`;
|
||||
const pool = new Map<string, SavedRow[]>();
|
||||
for (const s of [...unmatchedSaved].sort((a, b) => Number(!!b.ignored) - Number(!!a.ignored))) {
|
||||
const k = key(s);
|
||||
pool.set(k, [...(pool.get(k) ?? []), s]); // hidden first, popped last
|
||||
}
|
||||
const out = new Map<string, string>();
|
||||
for (const t of fresh) {
|
||||
const s = pool.get(key(t))?.pop();
|
||||
if (s) out.set(t.plaid_transaction_id, s.id);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
async function ebFeed(env: Env, token: string, since: string, f?: Fetch, now = Date.now()) {
|
||||
const s = JSON.parse(token) as { accounts: EbAccount[]; institution?: string; valid_until?: string | null };
|
||||
if (s.valid_until && Date.parse(s.valid_until) <= now) throw consentExpired();
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
// A rule's effect on past transactions: find them, apply the rule, or take it back. Shared by the rule form (browser
|
||||
// client) and the MCP tools (server, the user's own session): same code, same RLS.
|
||||
import type { SupabaseClient } from "@supabase/supabase-js";
|
||||
import { applyRules, findsSomething, matches, mergeTags, RULE_COLS, type Rule } from "@/lib/rules";
|
||||
|
||||
export type RuleDraft = Omit<Rule, "id"> & { id?: string };
|
||||
export type PastRow = { id: string; date: string; name: string; merchant_name: string | null; custom_name: string | null; logo_url: string | null; amount: number; currency: string | null; account_id: string; tags: string[] | null; category_id?: string | null; ignored?: boolean };
|
||||
|
||||
// Past transactions the rule matches, newest first. Name and account filter in Postgres, the rest here.
|
||||
// Own rows only (not a partner's shared ones), paged: Supabase returns at most 1000 rows per request.
|
||||
export async function pastMatchesWith(db: SupabaseClient, uid: string, d: RuleDraft) {
|
||||
if (!findsSomething(d)) return [];
|
||||
const s = d.match.trim().replace(/[%,()]/g, " ");
|
||||
const rows: PastRow[] = [];
|
||||
for (let from = 0; ; from += 1000) {
|
||||
let q = db.from("transactions").select("id, date, name, merchant_name, custom_name, logo_url, amount, currency, account_id, tags, category_id, ignored").eq("user_id", uid);
|
||||
if (s) q = q.or(`name.ilike.%${s}%,merchant_name.ilike.%${s}%`);
|
||||
if (d.account_id) q = q.eq("account_id", d.account_id);
|
||||
const { data } = await q.order("date", { ascending: false }).order("id").range(from, from + 999);
|
||||
rows.push(...((data ?? []) as PastRow[]));
|
||||
if (!data || data.length < 1000) break;
|
||||
}
|
||||
return rows.filter((t) => matches(d, t));
|
||||
}
|
||||
|
||||
/** Applies a rule's category, name, hiding and tags to the past transactions it matches. Returns how many it matched. */
|
||||
export async function applyRulePast(db: SupabaseClient, uid: string, d: RuleDraft) {
|
||||
const patch = { ...(d.category_id ? { category_id: d.category_id } : {}), ...(d.rename ? { custom_name: d.rename } : {}), ...(d.ignore != null ? { ignored: d.ignore } : {}) };
|
||||
const past = await pastMatchesWith(db, uid, d);
|
||||
const ids = past.map((t) => t.id);
|
||||
if (Object.keys(patch).length) for (let i = 0; i < ids.length; i += 200) await db.from("transactions").update(patch).in("id", ids.slice(i, i + 200));
|
||||
// Tags merge with what each row already has, so it's one write per row that gains a tag.
|
||||
const tagged = d.add_tags ? past.filter((t) => mergeTags(t.tags, d.add_tags).length > (t.tags ?? []).length) : [];
|
||||
for (let i = 0; i < tagged.length; i += 10)
|
||||
await Promise.all(tagged.slice(i, i + 10).map((t) => db.from("transactions").update({ tags: mergeTags(t.tags, d.add_tags) }).eq("id", t.id)));
|
||||
return ids.length;
|
||||
}
|
||||
|
||||
/** Takes back what a rule did to past transactions, before it's deleted: rows it still matches and that still carry its
|
||||
* category, name or hiding get what the other rules say instead (or nothing: Other for money out). Tags stay. */
|
||||
export async function undoRuleWith(db: SupabaseClient, uid: string, rule: RuleDraft) {
|
||||
const past = await pastMatchesWith(db, uid, rule);
|
||||
const { data: rest } = await db.from("rules").select(RULE_COLS).neq("id", rule.id ?? "").order("created_at", { ascending: false });
|
||||
const { data: other } = await db.from("categories").select("id").is("user_id", null).eq("key", "OTHER").maybeSingle();
|
||||
const by = new Map<string, string[]>(); // patch as JSON -> row ids
|
||||
for (const t of past) {
|
||||
const p = applyRules((rest ?? []) as Rule[], t);
|
||||
const patch: Record<string, unknown> = {};
|
||||
if (rule.category_id && t.category_id === rule.category_id) patch.category_id = p.category_id ?? (t.amount > 0 ? other?.id ?? null : null);
|
||||
if (rule.rename && t.custom_name === rule.rename) patch.custom_name = p.custom_name ?? null;
|
||||
if (rule.ignore != null && t.ignored === rule.ignore) patch.ignored = p.ignored ?? false;
|
||||
if (!Object.keys(patch).length) continue;
|
||||
const k = JSON.stringify(patch);
|
||||
by.set(k, [...(by.get(k) ?? []), t.id]);
|
||||
}
|
||||
let n = 0;
|
||||
for (const [k, ids] of by)
|
||||
for (let i = 0; i < ids.length; i += 200) {
|
||||
const { error } = await db.from("transactions").update(JSON.parse(k)).in("id", ids.slice(i, i + 200));
|
||||
if (!error) n += Math.min(200, ids.length - i);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
+79
-12
@@ -3,9 +3,9 @@ import type { CountryCode, InvestmentTransaction, RemovedTransaction, Transactio
|
||||
import { categoryKey, plaid, PLAID_COUNTRIES } from "@/lib/plaid";
|
||||
import { akahuTokens } from "@/lib/providers";
|
||||
import { akahuAccounts, akahuTransactions, toAccount, toTxn } from "@/lib/providers/akahu";
|
||||
import { feedData, isFeed, type FeedAccount, type FeedId, type FeedTxn } from "@/lib/providers/feeds";
|
||||
import { feedData, isFeed, matchRenamed, type FeedAccount, type FeedId, type FeedTxn, type SavedRow } from "@/lib/providers/feeds";
|
||||
import { applyRules, RULE_COLS, type Rule } from "@/lib/rules";
|
||||
import { pairTransfers } from "@/lib/transfers";
|
||||
import { pairTransfers, findOwnTransfers, type OwnRow } from "@/lib/transfers";
|
||||
import { createAdminClient } from "@/utils/supabase/admin";
|
||||
|
||||
type Item = { id: string; user_id: string; access_token: string | null; cursor: string | null; provider?: string | null };
|
||||
@@ -160,6 +160,32 @@ export async function fileTransferPairs(userId: string) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Transfers between the person's own accounts that came in uncategorized (statement imports above all): both sides
|
||||
* become Transfers out / in, so they count as neither spending nor income. All history, read in pages. */
|
||||
export async function fileOwnTransfers(userId: string) {
|
||||
const db = createAdminClient();
|
||||
const rows: OwnRow[] = [];
|
||||
for (let from = 0; ; from += 1000) {
|
||||
const { data, error } = await db.from("transactions").select("id, date, amount, account_id, name, category:categories(key)").eq("user_id", userId).order("id").range(from, from + 999);
|
||||
if (error) throw error;
|
||||
for (const r of (data ?? []) as unknown as { id: string; date: string; amount: number; account_id: string; name: string | null; category: { key: string } | null }[])
|
||||
rows.push({ id: r.id, date: r.date, amount: Number(r.amount), account_id: r.account_id, name: r.name ?? "", categoryKey: r.category?.key ?? null });
|
||||
if ((data ?? []).length < 1000) break;
|
||||
}
|
||||
const found = findOwnTransfers(rows);
|
||||
if (!found.length) return 0;
|
||||
const { data: cats } = await db.from("categories").select("id, key").is("user_id", null).in("key", ["TRANSFER_OUT", "TRANSFER_IN"]);
|
||||
const idOf = Object.fromEntries((cats ?? []).map((c) => [c.key, c.id]));
|
||||
for (const key of ["TRANSFER_OUT", "TRANSFER_IN"] as const) {
|
||||
const ids = found.filter((f) => f.key === key).map((f) => f.id);
|
||||
for (let i = 0; i < ids.length; i += 200) {
|
||||
const { error } = await db.from("transactions").update({ category_id: idOf[key] }).eq("user_id", userId).in("id", ids.slice(i, i + 200));
|
||||
if (error) throw error;
|
||||
}
|
||||
}
|
||||
return found.length;
|
||||
}
|
||||
|
||||
// Plaid sends a new bank's recent weeks first and fetches up to 2 years of history in the background, which takes
|
||||
// minutes to hours. Until it says the history is in, sync the item again every 10 minutes, for up to 4 hours.
|
||||
// ponytail: in-process timers, lost on restart (the next Sync now picks it up); swap for Plaid's webhook once deployed.
|
||||
@@ -394,6 +420,43 @@ export async function linkFeed(userId: string, id: FeedId, ref: string, institut
|
||||
return result;
|
||||
}
|
||||
|
||||
/** This provider's saved rows on these accounts between the first and last day of the fetch, read in pages. Read by
|
||||
* account and date, not by a list of ids: bank ids can be 150 characters, and hundreds of them make a URL the database
|
||||
* gateway turns away. */
|
||||
async function savedInWindow(item: Item, txns: FeedTxn[], accountId: Map<string, string>) {
|
||||
const rows: (SavedRow & { plaid_transaction_id: string })[] = [];
|
||||
if (!txns.length) return rows;
|
||||
const db = createAdminClient();
|
||||
const dates = txns.map((t) => t.date).sort();
|
||||
const accounts = [...new Set(txns.map((t) => accountId.get(t.account_ref)!))];
|
||||
for (let from = 0; ; from += 1000) {
|
||||
let q = db.from("transactions").select("id, plaid_transaction_id, account_id, date, amount, name, ignored")
|
||||
.eq("user_id", item.user_id).in("account_id", accounts).gte("date", dates[0]).lte("date", dates[dates.length - 1]);
|
||||
if (item.provider) q = q.like("plaid_transaction_id", `${item.provider}:%`);
|
||||
const { data, error } = await q.order("id").range(from, from + 999);
|
||||
if (error) throw error;
|
||||
rows.push(...((data ?? []) as typeof rows));
|
||||
if ((data ?? []).length < 1000) break;
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** New-looking rows that match a saved row (same account, day, amount, name) whose id this fetch didn't return: the
|
||||
* saved row moves to the new id, keeping its edits. Returns the new ids that now exist. */
|
||||
async function adoptRenamed(unknown: FeedTxn[], unmatched: SavedRow[], accountId: Map<string, string>) {
|
||||
if (!unknown.length || !unmatched.length) return [];
|
||||
const db = createAdminClient();
|
||||
const moves = [...matchRenamed(unknown.map((t) => ({ ...t, account_id: accountId.get(t.account_ref)! })), unmatched)];
|
||||
const moved: string[] = [];
|
||||
for (let i = 0; i < moves.length; i += 50)
|
||||
await Promise.all(moves.slice(i, i + 50).map(async ([to, id]) => {
|
||||
const { error } = await db.from("transactions").update({ plaid_transaction_id: to }).eq("id", id);
|
||||
if (!error) moved.push(to);
|
||||
else if (error.code !== "23505") throw error; // the new id is already saved elsewhere: leave this row be
|
||||
}));
|
||||
return moved;
|
||||
}
|
||||
|
||||
// Writes any provider's accounts and rows the same way: new rows get the user's rules, seen rows keep their edits.
|
||||
async function saveFeed(item: Item, accounts: FeedAccount[] | ReturnType<typeof toAccount>[], feed: FeedTxn[]) {
|
||||
const db = createAdminClient();
|
||||
@@ -407,28 +470,32 @@ async function saveFeed(item: Item, accounts: FeedAccount[] | ReturnType<typeof
|
||||
const row = ({ account_ref, ...t }: FeedTxn) => ({ ...t, user_id: item.user_id, account_id: accountId.get(account_ref)! });
|
||||
|
||||
const chunks = <T,>(xs: T[]) => Array.from({ length: Math.ceil(xs.length / 500) }, (_, i) => xs.slice(i * 500, i * 500 + 500));
|
||||
const known = new Set<string>();
|
||||
for (const c of chunks(txns.map((t) => t.plaid_transaction_id))) {
|
||||
const { data } = await db.from("transactions").select("plaid_transaction_id").eq("user_id", item.user_id).in("plaid_transaction_id", c);
|
||||
for (const r of data ?? []) known.add(r.plaid_transaction_id);
|
||||
}
|
||||
const fetched = new Set(txns.map((t) => t.plaid_transaction_id));
|
||||
const stored = await savedInWindow(item, txns, accountId);
|
||||
const known = new Set(stored.map((r) => r.plaid_transaction_id).filter((id) => fetched.has(id)));
|
||||
// Rows the bank sent again under a new id: the saved row takes the new id, so it updates instead of doubling.
|
||||
const unmatched = stored.filter((r) => !fetched.has(r.plaid_transaction_id));
|
||||
for (const id of await adoptRenamed(txns.filter((t) => !known.has(t.plaid_transaction_id)), unmatched, accountId)) known.add(id);
|
||||
const fresh = txns.filter((t) => !known.has(t.plaid_transaction_id));
|
||||
const seen = txns.filter((t) => known.has(t.plaid_transaction_id));
|
||||
const { data: rules } = await db.from("rules").select(RULE_COLS).eq("user_id", item.user_id).order("created_at", { ascending: false });
|
||||
const { data: other } = await db.from("categories").select("id").is("user_id", null).eq("key", "OTHER").maybeSingle();
|
||||
for (const c of chunks(fresh)) {
|
||||
const { error } = await db.from("transactions").insert(c.map((t) => {
|
||||
// A new row whose id is saved after all (outside the date window, say) is skipped, never a failed sync: the saved
|
||||
// one keeps its edits. The same id twice in one fetch is one row.
|
||||
const unique = [...new Map(fresh.map((t) => [t.plaid_transaction_id, t])).values()];
|
||||
for (const c of chunks(unique)) {
|
||||
const { error } = await db.from("transactions").upsert(c.map((t) => {
|
||||
const r = applyRules((rules ?? []) as Rule[], row(t));
|
||||
// No category we can map with confidence: money out is Other, money in stays blank (counts as income).
|
||||
return { ...row(t), category_id: r.category_id ?? (t.amount > 0 ? other?.id ?? null : null), custom_name: r.custom_name ?? null, ignored: r.ignored ?? false, tags: r.tags ?? [] };
|
||||
}));
|
||||
}), { onConflict: "plaid_transaction_id", ignoreDuplicates: true });
|
||||
if (error) throw error;
|
||||
}
|
||||
// Seen rows: refresh what the provider owns; the user's category, name, note and tags stay.
|
||||
for (const c of chunks(seen)) {
|
||||
for (const c of chunks([...new Map(seen.map((t) => [t.plaid_transaction_id, t])).values()])) {
|
||||
const { error } = await db.from("transactions").upsert(c.map(row), { onConflict: "plaid_transaction_id" });
|
||||
if (error) throw error;
|
||||
}
|
||||
await db.from("plaid_items").update({ cursor: new Date().toISOString(), last_synced_at: new Date().toISOString(), status: "ok", error: null }).eq("id", item.id);
|
||||
return { added: fresh.length, modified: seen.length, removed: 0 };
|
||||
return { added: unique.length, modified: seen.length, removed: 0 };
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
// Run: node src/lib/transfers.test.ts
|
||||
import assert from "node:assert/strict";
|
||||
import { pairTransfers } from "./transfers.ts";
|
||||
import { findOwnTransfers, pairTransfers } from "./transfers.ts";
|
||||
|
||||
const chk = { id: "chk", name: "Everyday Checking", mask: "1234" }, card = { id: "card", name: "Capital One", mask: "9876" };
|
||||
const t = (id: string, date: string, amount: number, account: typeof chk, kind: string | null = "transfer") => ({ id, date, amount, account, category: { kind } });
|
||||
@@ -19,3 +19,34 @@ p = pairTransfers([t("o1", "2026-10-01", 500, chk), t("o2", "2026-10-15", 500, c
|
||||
assert.deepEqual([...p.hidden].sort(), ["i1", "i2"], "each money-in pairs once");
|
||||
assert.equal(pairTransfers([t("in", "2026-10-03", -500, card)]).hidden.size, 0, "partner not in the list: shown");
|
||||
console.log("transfers ok");
|
||||
|
||||
// Own transfers nobody marked: pairs across own accounts, then savings names on their own.
|
||||
{
|
||||
const r = (id: string, date: string, amount: number, account_id: string, name = "x", categoryKey: string | null = null) => ({ id, date, amount, account_id, name, categoryKey });
|
||||
const found = findOwnTransfers([
|
||||
r("to-sav", "2026-10-01", 1000, "chk", "Naar spaar"), r("at-sav", "2026-10-02", -1000, "sav", "Van betaal"), // pair
|
||||
r("same-acct-a", "2026-10-03", 50, "chk"), r("same-acct-b", "2026-10-03", -50, "chk"), // same account: no
|
||||
r("far-a", "2026-10-01", 70, "chk"), r("far-b", "2026-10-20", -70, "sav"), // 19 days apart: no
|
||||
r("mine", "2026-10-05", 200, "chk", "x", "GROCERIES"), r("mine-b", "2026-10-05", -200, "sav"), // a chosen category stays
|
||||
r("oranje", "2026-10-07", 300, "chk", "Oranje Spaarrekening V123456"), // savings name, other side not imported
|
||||
r("ah", "2026-10-08", 42.17, "chk", "Albert Heijn 1234"),
|
||||
]);
|
||||
assert.deepEqual(found, [{ id: "to-sav", key: "TRANSFER_OUT" }, { id: "at-sav", key: "TRANSFER_IN" }, { id: "oranje", key: "TRANSFER_OUT" }]);
|
||||
// Two transfers of the same amount: each pairs with its nearest partner, once.
|
||||
const two = findOwnTransfers([r("o1", "2026-10-01", 500, "chk"), r("o2", "2026-10-15", 500, "chk"), r("i2", "2026-10-16", -500, "sav"), r("i1", "2026-10-02", -500, "sav")]);
|
||||
assert.deepEqual(two.map((t) => t.id).sort(), ["i1", "i2", "o1", "o2"]);
|
||||
assert.deepEqual(two.slice(0, 2), [{ id: "o1", key: "TRANSFER_OUT" }, { id: "i1", key: "TRANSFER_IN" }]);
|
||||
}
|
||||
console.log("own transfers ok");
|
||||
|
||||
// ING's own wording for its accounts, Dutch and English.
|
||||
{
|
||||
const r = (id: string, amount: number, name: string) => ({ id, date: "2026-10-01", amount, account_id: id, name, categoryKey: null });
|
||||
const f = findOwnTransfers([
|
||||
r("a", 100, "Transfer to current account NL24INGB0001234567"), r("b", -50, "Transfer from current account NL24INGB0001234567"),
|
||||
r("c", 5000, "Naar Beleggingsrek. 15671748 Valutadatum: 26-08-2026"), r("d", 87.24, "Incasso ING creditcard Accountnr 210026951876 Periode juli"),
|
||||
r("e", 36.93, "Naam: Alternate Nederland Omschrijving: 51312519073X"),
|
||||
]);
|
||||
assert.deepEqual(f.map((x) => x.id), ["a", "b", "c", "d"]);
|
||||
}
|
||||
console.log("ing phrases ok");
|
||||
@@ -24,3 +24,40 @@ export function pairTransfers(txns: Row[]) {
|
||||
}
|
||||
return { hidden, to, pairs };
|
||||
}
|
||||
|
||||
// ---- Spotting transfers nobody marked yet ----
|
||||
// Money moved between the person's own accounts that came in uncategorized (statement imports have no category):
|
||||
// without this, moving €1,000 to savings counts as €1,000 spent on one side and €1,000 earned on the other.
|
||||
export type OwnRow = { id: string; date: string; amount: number; account_id: string; name: string; categoryKey: string | null };
|
||||
export type OwnTransfer = { id: string; key: "TRANSFER_OUT" | "TRANSFER_IN" };
|
||||
|
||||
// Savings accounts at Dutch banks, by the name the other side carries: ING (Oranje) Spaarrekening, Doelspaarrekening,
|
||||
// ABN AMRO Direct Sparen, Rabobank/ASN/SNS bonusrente and deposito accounts.
|
||||
// Also ING's English savings export ("Transfer to current account NL..."), ING's investment account ("Naar
|
||||
// Beleggingsrek."), and ING's monthly credit card collection ("Incasso ING creditcard Accountnr ...").
|
||||
const SAVINGS = /spaarrekening|doelspaar|direct sparen|bonusrente|spaardeposito|vermogensspaar|spaarpot|beleggingsrek|transfer (to|from) (current|savings) account|incasso ing creditcard/i;
|
||||
const open = (r: OwnRow) => r.categoryKey === null || r.categoryKey === "OTHER"; // a category the person chose stays
|
||||
|
||||
/** Pairs first (same amount out of one own account and into another within DAYS days, nearest date wins, each row used
|
||||
* once), then single rows whose name is a savings account. Only rows without a category, or "Other". */
|
||||
export function findOwnTransfers(rows: OwnRow[]): OwnTransfer[] {
|
||||
const out: OwnTransfer[] = [];
|
||||
const done = new Set<string>();
|
||||
const ins = rows.filter((r) => r.amount < 0 && open(r));
|
||||
for (const o of [...rows].filter((r) => r.amount > 0 && open(r)).sort((a, b) => a.date.localeCompare(b.date))) {
|
||||
let best: OwnRow | null = null, gap = Infinity;
|
||||
for (const i of ins) {
|
||||
if (done.has(i.id) || i.account_id === o.account_id || Math.abs(i.amount + o.amount) >= 0.005) continue;
|
||||
const d = Math.abs(Date.parse(i.date) - Date.parse(o.date));
|
||||
if (d <= DAYS * 864e5 && d < gap) { best = i; gap = d; }
|
||||
}
|
||||
if (!best) continue;
|
||||
done.add(o.id).add(best.id);
|
||||
out.push({ id: o.id, key: "TRANSFER_OUT" }, { id: best.id, key: "TRANSFER_IN" });
|
||||
}
|
||||
for (const r of rows) {
|
||||
if (done.has(r.id) || !open(r) || !SAVINGS.test(r.name)) continue;
|
||||
out.push({ id: r.id, key: r.amount > 0 ? "TRANSFER_OUT" : "TRANSFER_IN" });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
+1
-1
@@ -5,5 +5,5 @@ export const middleware = (request: NextRequest) => updateSession(request);
|
||||
|
||||
// auth/callback runs without the session refresh: clearing an old sign-in there would wipe the one the email link just made.
|
||||
export const config = {
|
||||
matcher: ["/((?!_next/static|_next/image|favicon.ico|api/plaid/webhook|auth/callback|api/agent|api/ai/helper|broke-connect|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)"],
|
||||
matcher: ["/((?!_next/static|_next/image|favicon.ico|api/plaid/webhook|auth/callback|api/agent|api/mcp|api/ai/helper|broke-connect|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)"],
|
||||
};
|
||||
@@ -0,0 +1,17 @@
|
||||
-- Personal tokens for the MCP endpoint (/api/mcp): an AI app such as Claude Code connects with one and acts as you,
|
||||
-- summary only. Only a hash is stored; the token itself is shown once. You see and revoke your own; the server checks them.
|
||||
create table if not exists public.mcp_tokens (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
user_id uuid not null references auth.users on delete cascade,
|
||||
token_hash text not null unique,
|
||||
label text not null default 'Claude',
|
||||
created_at timestamptz not null default now(),
|
||||
last_used_at timestamptz
|
||||
);
|
||||
create index if not exists mcp_tokens_user on public.mcp_tokens (user_id);
|
||||
alter table public.mcp_tokens enable row level security;
|
||||
drop policy if exists "own" on public.mcp_tokens;
|
||||
create policy "own" on public.mcp_tokens for select to authenticated using (user_id = (select auth.uid()));
|
||||
drop policy if exists "own delete" on public.mcp_tokens;
|
||||
create policy "own delete" on public.mcp_tokens for delete to authenticated using (user_id = (select auth.uid()));
|
||||
grant select (id, user_id, label, created_at, last_used_at), delete on public.mcp_tokens to authenticated;
|
||||
@@ -0,0 +1,4 @@
|
||||
-- What an MCP token may see: the summary (like every cloud AI), or full detail, which the person turns on for that
|
||||
-- token themselves on Connect your AI. Tokens made before this stay summary.
|
||||
alter table public.mcp_tokens add column if not exists level text not null default 'summary' check (level in ('summary', 'full'));
|
||||
grant select (level) on public.mcp_tokens to authenticated;
|
||||
@@ -0,0 +1,28 @@
|
||||
-- Months that start on payday (profile.month = "payday", src/lib/paymonths.ts): one row per month with the day it starts.
|
||||
-- The server writes them (lib/data.ts payPeriods) whenever they change; with no rows, months are calendar months.
|
||||
create table if not exists public.pay_periods (
|
||||
user_id uuid not null references auth.users on delete cascade,
|
||||
month date not null, -- the calendar month it's named after, first day
|
||||
start_date date not null,
|
||||
primary key (user_id, month)
|
||||
);
|
||||
create index if not exists pay_periods_start on public.pay_periods (user_id, start_date);
|
||||
alter table public.pay_periods enable row level security;
|
||||
drop policy if exists "own" on public.pay_periods;
|
||||
create policy "own" on public.pay_periods for select to authenticated using (user_id = (select auth.uid()));
|
||||
grant select on public.pay_periods to authenticated;
|
||||
|
||||
-- By month and category, the month being the pay month a day falls in (the latest start on or before it), else the
|
||||
-- calendar month. 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 $$
|
||||
with x as (
|
||||
select coalesce(
|
||||
(select p.month from public.pay_periods p where p.user_id = (select auth.uid()) and p.start_date <= r.date order by p.start_date desc limit 1),
|
||||
date_trunc('month', r.date)::date) as month,
|
||||
r.category_id, r.spend, r.income
|
||||
from public.money_rows(start_date, end_date) r
|
||||
)
|
||||
select x.month, x.category_id, sum(x.spend), sum(x.income), count(*) from x group by 1, 2
|
||||
$$;
|
||||
Reference in new issue
Block a user