Sign in with a code, made-up data without Plaid, and easier everyday use

- Sign in with a code from your email (the link still works); setup item for the code email
- Use made-up data: a pretend bank with three months of spending, no Plaid account needed
- Is this your pay? when regular money in is filed as something else, with a one-press fix
- They look right: keep every bank-given category in one press
- Your week on Home, Plan in the main menu, history start per bank on Accounts
- A new version of broke is ready, in the sidebar and Settings
- Start skips the rebuild when nothing changed; country screen says it was guessed
- Fix: skipping banks no longer sends you back to setup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
minimus7andClaude Opus 5.5 committed 2026-11-09 10:54:31 -06:00
1 parent 37a97fe20a
commit 73208b79df
30 files changed
+496 -39

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
// Run: node src/lib/demo.test.ts
import assert from "node:assert/strict";
import { demoBank } from "./demo.ts";
const a = demoBank("2026-11-09"), b = demoBank("2026-11-09");
assert.deepEqual(a, b, "the same every time");
assert.ok(a.txns.length > 150 && a.txns.length < 400, `${a.txns.length} transactions`);
assert.ok(a.txns.every((t) => t.date >= "2026-08-06" && t.date <= "2026-11-09"), "inside the last 95 days");
const pay = a.txns.filter((t) => t.category === "INCOME");
assert.ok(pay.length >= 6 && pay.every((t) => t.amount === -1850), "pay every other week, as money in");
assert.ok(a.txns.some((t) => t.name === "Delta Air Lines"), "one unusual month");
for (const m of ["2026-09", "2026-10"]) {
const out = a.txns.filter((t) => t.date.startsWith(m) && t.category === "CREDIT_CARD_PAYMENT").reduce((s, t) => s + t.amount, 0);
assert.equal(Math.round(out * 100), 0, `${m}: the card payment leaves checking and lands on the card`);
}
assert.ok(a.streams.every((s) => s.next > s.last), "each bill's next date comes after its last");
console.log("demo: ok");
+71
View File
@@ -0,0 +1,71 @@
// A made-up bank for trying broke without a Plaid account: three accounts and about three months of everyday money,
// with pay, rent, bills, subscriptions, one unusual month and card payments. The same every time (seeded), dated back
// from today. Pure, no "@/" imports: `node src/lib/demo.test.ts` runs it. Amounts use broke's sign: positive = money out.
export type DemoAccount = { key: string; name: string; type: string; subtype: string; mask: string; balance: number };
export type DemoTxn = { key: string; account: string; date: string; amount: number; name: string; category: string };
export type DemoStream = { merchant: string; account: string; frequency: "WEEKLY" | "BIWEEKLY" | "MONTHLY"; amount: number; category: string; income: boolean; last: string; next: string };
export const DEMO_ACCOUNTS: DemoAccount[] = [
{ key: "checking", name: "Everyday Checking", type: "depository", subtype: "checking", mask: "4021", balance: 2340 },
{ key: "savings", name: "Savings", type: "depository", subtype: "savings", mask: "7730", balance: 3200 },
{ key: "card", name: "Rewards Card", type: "credit", subtype: "credit card", mask: "1188", balance: 612 },
];
const day = (d: Date) => d.toISOString().slice(0, 10);
const addDays = (d: string, n: number) => day(new Date(Date.parse(`${d}T00:00:00Z`) + n * 864e5));
export function demoBank(today: string) {
let seed = 7;
const rand = () => ((seed = (seed * 16807) % 2147483647) - 1) / 2147483646;
const between = (lo: number, hi: number) => Math.round((lo + rand() * (hi - lo)) * 100) / 100;
const start = addDays(today, -95);
const txns: DemoTxn[] = [];
const add = (account: string, date: string, amount: number, name: string, category: string) => {
if (date >= start && date <= today) txns.push({ key: `${txns.length}`, account, date, amount, name, category });
};
const days = Array.from({ length: 96 }, (_, i) => addDays(start, i));
const monthsIn = [...new Set(days.map((d) => d.slice(0, 7)))];
// Pay every other Friday.
const firstFriday = days.find((d) => new Date(`${d}T00:00:00Z`).getUTCDay() === 5)!;
for (let d = firstFriday; d <= today; d = addDays(d, 14)) add("checking", d, -1850, "Acme Corp Payroll", "INCOME");
for (const m of monthsIn) {
add("checking", `${m}-01`, 1450, "Parkside Apartments Rent", "RENT_AND_UTILITIES");
add("checking", `${m}-02`, 200, "Transfer to Savings", "TRANSFER_OUT");
add("savings", `${m}-02`, -200, "Transfer from Checking", "TRANSFER_IN");
add("checking", `${m}-12`, between(72, 96), "PG&E", "RENT_AND_UTILITIES");
add("card", `${m}-05`, 15.49, "Netflix", "ENTERTAINMENT");
add("card", `${m}-09`, 11.99, "Spotify", "ENTERTAINMENT");
add("card", `${m}-15`, 24.99, "Planet Fitness", "PERSONAL_CARE");
add("card", `${m}-18`, 70, "Verizon", "RENT_AND_UTILITIES");
add("card", `${m}-${String(3 + Math.floor(rand() * 20)).padStart(2, "0")}`, between(40, 120), "Target", "GENERAL_MERCHANDISE");
}
for (const d of days) {
const dow = new Date(`${d}T00:00:00Z`).getUTCDay();
if (dow === 0 || dow === 3) add("card", d, between(38, 110), rand() < 0.6 ? "Trader Joe's" : "Safeway", "GROCERIES");
if (dow === 1 || dow === 4 || dow === 6) add("card", d, between(6, 38), ["Chipotle", "Starbucks", "Sweetgreen"][Math.floor(rand() * 3)], "FOOD_AND_DRINK");
if (dow === 2 || dow === 5) add("card", d, between(12, 30), "Uber", "TRANSPORTATION");
if (dow === 6) add("card", d, between(38, 55), "Shell", "TRANSPORTATION");
if (d.endsWith("-07") || d.endsWith("-21")) add("card", d, between(18, 90), "Amazon", "GENERAL_MERCHANDISE");
}
// One unusual month: a flight, so a budget built from the usual month isn't set by it.
if (monthsIn.length >= 2) add("card", `${monthsIn[1]}-14`, 420, "Delta Air Lines", "TRAVEL");
// Each month the card is paid off from checking: money out of checking, money in on the card.
for (const m of monthsIn.slice(1)) {
const prev = monthsIn[monthsIn.indexOf(m) - 1];
const owed = Math.round(txns.filter((t) => t.account === "card" && t.date.startsWith(prev)).reduce((s, t) => s + t.amount, 0) * 100) / 100;
add("checking", `${m}-25`, owed, "Rewards Card Payment", "CREDIT_CARD_PAYMENT");
add("card", `${m}-25`, -owed, "Payment Thank You", "CREDIT_CARD_PAYMENT");
}
txns.sort((a, b) => a.date.localeCompare(b.date));
const last = (name: string) => txns.filter((t) => t.name === name).at(-1)?.date ?? today;
const nextMonthly = (d: string) => day(new Date(Date.UTC(Number(d.slice(0, 4)), Number(d.slice(5, 7)), Number(d.slice(8, 10)))));
const streams: DemoStream[] = [
{ merchant: "Acme Corp Payroll", account: "checking", frequency: "BIWEEKLY", amount: 1850, category: "INCOME", income: true, last: last("Acme Corp Payroll"), next: addDays(last("Acme Corp Payroll"), 14) },
...([["Parkside Apartments Rent", "checking", 1450, "RENT_AND_UTILITIES"], ["PG&E", "checking", 85, "RENT_AND_UTILITIES"], ["Netflix", "card", 15.49, "ENTERTAINMENT"], ["Spotify", "card", 11.99, "ENTERTAINMENT"], ["Planet Fitness", "card", 24.99, "PERSONAL_CARE"], ["Verizon", "card", 70, "RENT_AND_UTILITIES"]] as const)
.map(([merchant, account, amount, category]) => ({ merchant, account, frequency: "MONTHLY" as const, amount, category, income: false, last: last(merchant), next: nextMonthly(last(merchant)) })),
];
return { accounts: DEMO_ACCOUNTS, txns, streams };
}
+15
View File
@@ -0,0 +1,15 @@
// Run: node src/lib/pay.test.ts
import assert from "node:assert/strict";
import { payGuess } from "./pay.ts";
const weekly = ["2026-10-03", "2026-10-10", "2026-10-17", "2026-10-24"].map((date) => ({ name: "Sweetgreen", date, amount: -810.5, kind: "spend" }));
assert.deepEqual(payGuess(weekly), { name: "Sweetgreen", typical: 811, every: "week", count: 4 });
assert.equal(payGuess(weekly.map((r) => ({ ...r, kind: "income" }))), null, "already income");
assert.equal(payGuess(weekly, ["Sweetgreen"]), null, "they said it isn't pay");
assert.equal(payGuess(weekly.slice(0, 1)), null, "one deposit isn't a pattern");
assert.equal(payGuess([{ name: "Refund", date: "2026-10-01", amount: -900, kind: "spend" }, { name: "Refund", date: "2026-10-20", amount: -40, kind: "spend" }]), null, "amounts too different");
assert.equal(payGuess(weekly.map((r) => ({ ...r, amount: -50 }))), null, "small amounts aren't pay");
const monthly = ["2026-08-01", "2026-09-01", "2026-10-01"].map((date) => ({ name: "Acme Payroll", date, amount: -4000, kind: "transfer" }));
assert.equal(payGuess(monthly), null, "transfers between own accounts aren't pay");
assert.equal(payGuess([...weekly, ...monthly.map((r) => ({ ...r, kind: "spend" }))])!.name, "Acme Payroll", "the bigger pay by month wins: $4,000 a month beats $811 a week");
console.log("pay: ok");
+28
View File
@@ -0,0 +1,28 @@
// Pay that landed in the wrong category: money coming in from the same name, regularly, at about the same amount,
// filed as anything but income. Pure, no "@/" imports: `node src/lib/pay.test.ts` runs it.
export type PayRow = { name: string; date: string; amount: number; kind: string | null }; // amount < 0 is money in
export type PayGuess = { name: string; typical: number; every: "week" | "2 weeks" | "month"; count: number };
const mid = (ns: number[]) => [...ns].sort((a, b) => a - b)[Math.floor(ns.length / 2)];
export function payGuess(rows: PayRow[], skip: string[] = []): PayGuess | null {
const by = new Map<string, PayRow[]>();
for (const r of rows) {
if (r.amount >= -200 || r.kind === "income" || r.kind === "transfer" || skip.includes(r.name)) continue;
by.set(r.name, [...(by.get(r.name) ?? []), r]);
}
const found: PayGuess[] = [];
for (const [name, rs] of by) {
if (rs.length < 2) continue;
const amounts = rs.map((r) => -r.amount), typical = mid(amounts);
if (amounts.some((a) => Math.abs(a - typical) > typical * 0.25)) continue; // pay is about the same each time
const days = [...rs].sort((a, b) => a.date.localeCompare(b.date)).map((r) => Date.parse(r.date) / 864e5);
const gap = mid(days.slice(1).map((d, i) => d - days[i]));
const every = gap >= 5 && gap <= 9 ? "week" : gap >= 12 && gap <= 17 ? "2 weeks" : gap >= 26 && gap <= 35 ? "month" : null;
if (every) found.push({ name, typical: Math.round(typical), every, count: rs.length });
}
// The biggest by month: that's the main pay.
const monthly = (p: PayGuess) => p.typical * (p.every === "week" ? 52 : p.every === "2 weeks" ? 26 : 12);
return found.sort((a, b) => monthly(b) - monthly(a))[0] ?? null;
}
+2 -1
View File
@@ -49,7 +49,8 @@ export function plaidError(e: unknown): { code: string; message: string } {
* from live mode (Plaid's sandbox forgets it anyway), so those are only forgotten. Already gone at Plaid counts as done. */
export async function revokeItem(item: { access_token: string | null; provider: string | null }) {
const testInLive = item.access_token?.startsWith("access-sandbox-") && process.env.PLAID_ENV !== "sandbox";
if (item.provider !== "plaid" || testInLive || !item.access_token) return { ok: true as const };
const demo = item.access_token?.startsWith("access-sandbox-demo-"); // the made-up bank: nothing at Plaid
if (item.provider !== "plaid" || testInLive || demo || !item.access_token) return { ok: true as const };
try {
await plaid.itemRemove({ access_token: item.access_token });
return { ok: true as const };
+2
View File
@@ -36,6 +36,8 @@ export function addChoices(country?: string | null, alsoNz = false) {
feeds: options.filter((p): p is FeedId => isFeed(p)),
investments: plaid && code === "US",
sandbox: plaid && process.env.PLAID_ENV === "sandbox",
// No Plaid keys at all: a made-up bank instead (api/demo-bank), so broke can be tried with only a database.
demo: !configured("plaid"),
// NZ without Akahu keys: say where to add them.
akahuMissing: (countryOf(code).providers.includes("akahu") || alsoNz) && !configured("akahu"),
// Lives elsewhere but also banks in NZ (Settings, money profile): the NZ option beside their own.
+18
View File
@@ -88,6 +88,8 @@ async function aiRows(): Promise<AiRow[]> {
return (await providers()).map((p) => ({ id: p.id, label: p.label, ready: p.ready, reason: p.ready ? undefined : p.reason }));
}
export const SIGN_IN_EMAIL = `<h2>Your broke code</h2><p>Type this code in broke: <strong>{{ .Token }}</strong></p><p>Or <a href="{{ .ConfirmationURL }}">sign in with this link</a>.</p>`;
export async function setupStatus(signedIn: boolean): Promise<SetupStatus> {
const env = currentEnv();
const ref = env.NEXT_PUBLIC_SUPABASE_URL?.match(/https:\/\/([a-z0-9]+)\.supabase\.co/)?.[1];
@@ -162,7 +164,23 @@ export async function setupStatus(signedIn: boolean): Promise<SetupStatus> {
};
const localRow = ai.find((p) => p.id === "local");
// Supabase's emails only hold a code when their text asks for one ({{ .Token }}). Both emails: a new person gets
// "Confirm signup" the first time, everyone else "Magic link". Without this the email's link still signs them in.
const codes: Section = {
id: "codes", kind: "more",
title: "Sign in with a code",
what: "Puts a code in broke's sign-in emails, so you can type it instead of clicking a link. The link keeps working either way.",
status: "optional",
steps: [
["Open ", { href: dash("/auth/templates"), label: "Authentication → Emails" }, " in Supabase."],
["Open Confirm signup. Set the subject to Your broke code, and replace the message with the text below. Save."],
["Do the same for Magic link."],
],
command: SIGN_IN_EMAIL,
};
const more: Section[] = [
codes,
{
id: "local", kind: "more",
title: "Local model (private, free)",
+3 -1
View File
@@ -13,7 +13,9 @@ type PlaidItem = Item & { access_token: string };
export const ITEM_COLS = "id, user_id, access_token, cursor, provider";
// One connection, whichever service it comes through. Each writes the same accounts and transactions tables.
export const syncItem = (item: Item) => (item.provider === "akahu" ? syncAkahu(item) : isFeed(item.provider) ? syncFeed(item, item.provider) : syncPlaid(item as PlaidItem));
// The made-up bank (api/demo-bank) has nothing to fetch.
export const DEMO_TOKEN = "access-sandbox-demo-";
export const syncItem = (item: Item) => item.access_token?.startsWith(DEMO_TOKEN) ? Promise.resolve({ added: 0, modified: 0, removed: 0 }) : (item.provider === "akahu" ? syncAkahu(item) : isFeed(item.provider) ? syncFeed(item, item.provider) : syncPlaid(item as PlaidItem));
// Pulls accounts, transactions (cursor-based), recurring streams and investment holdings for one Plaid item.
async function syncPlaid(item: PlaidItem) {
+22
View File
@@ -0,0 +1,22 @@
import "server-only";
// Is there a newer broke on GitHub than the code this copy was built from? Compares commit dates, so a copy with its
// own changes (newer commits of its own) isn't told to update. Asks GitHub at most every 6 hours; any failure means no.
const REPO = "nextwork-projects/broke";
const g = globalThis as unknown as { __brokeUpdate?: { at: number; newer: boolean } };
export async function updateReady() {
const built = process.env.BROKE_BUILT_FROM;
if (!built) return false;
if (g.__brokeUpdate && Date.now() - g.__brokeUpdate.at < 6 * 3600_000) return g.__brokeUpdate.newer;
let newer = false;
try {
const res = await fetch(`https://api.github.com/repos/${REPO}/commits/main`, { headers: { accept: "application/vnd.github+json" }, signal: AbortSignal.timeout(3000) });
const date = res.ok ? ((await res.json()) as { commit?: { committer?: { date?: string } } }).commit?.committer?.date : null;
newer = !!date && Date.parse(date) > Date.parse(built) + 60_000;
} catch {
/* offline: say nothing */
}
g.__brokeUpdate = { at: Date.now(), newer };
return newer;
}