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:
1 parent
37a97fe20a
commit
73208b79df
30 files changed
+496
-39
No files matched your search
@@ -60,6 +60,12 @@ export default async function Accounts() {
|
||||
supabase.from("accounts").select("id, name, custom_name, mask, type, subtype, current_balance:balance, currency, home:home_balance, included").eq("manual", true).eq("user_id", user!.id),
|
||||
]);
|
||||
const items = (data ?? []) as unknown as Item[];
|
||||
// How far back each bank's transactions go, so a short history doesn't read as a strange month.
|
||||
const since = new Map(await Promise.all(items.map(async (i) => {
|
||||
const ids = i.accounts.map((a) => a.id);
|
||||
const { data: first } = ids.length ? await supabase.from("transactions").select("date").in("account_id", ids).order("date").limit(1) : { data: [] };
|
||||
return [i.id, (first?.[0]?.date as string | undefined) ?? null] as const;
|
||||
})));
|
||||
const manualItem = { id: "manual", institution_name: "Added by you", institution_logo: null, institution_color: null, last_synced_at: null, accounts: [] };
|
||||
const all = [
|
||||
...items.flatMap((i) => i.accounts.map((a) => ({ ...a, item: i }))),
|
||||
@@ -164,7 +170,7 @@ export default async function Accounts() {
|
||||
<div className="text-xs text-muted">
|
||||
{item.status && item.status !== "ok"
|
||||
? item.status === "ITEM_LOGIN_REQUIRED" ? "Sign in to your bank again to keep syncing." : (item.error ?? "This connection stopped syncing.")
|
||||
: `${holds(item.accounts) ? `${holds(item.accounts)} · ` : ""}${plural(item.accounts.length, "account")} · synced ${item.last_synced_at ? ago(item.last_synced_at) : "never"}`}
|
||||
: `${holds(item.accounts) ? `${holds(item.accounts)} · ` : ""}${plural(item.accounts.length, "account")}${since.get(item.id) ? ` · history from ${new Date(`${since.get(item.id)}T12:00:00Z`).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric", timeZone: "UTC" })}` : ""} · synced ${item.last_synced_at ? ago(item.last_synced_at) : "never"}`}
|
||||
</div>
|
||||
</div>
|
||||
<ConnectionActions itemId={item.id} broken={item.provider === "plaid" && !!item.status && item.status !== "ok"} name={item.institution_name ?? "this bank"} />
|
||||
|
||||
@@ -11,12 +11,14 @@ import { countryOf } from "@/lib/countries";
|
||||
import { getUser, userTz } from "@/lib/data";
|
||||
import { fmtFor, todayIn } from "@/lib/format";
|
||||
import { modeOf } from "@/lib/privacy";
|
||||
import { updateReady } from "@/lib/updates";
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
|
||||
// Accounts made before country support are treated as US (countryOf default) and get a dashboard nudge instead.
|
||||
const FIRST_RUN_SINCE = "2026-10-22";
|
||||
|
||||
export default async function AppLayout({ children }: { children: React.ReactNode }) {
|
||||
const update = await updateReady();
|
||||
const [{ user }, tz] = await Promise.all([getUser(), userTz()]);
|
||||
const profile = user?.user_metadata?.profile;
|
||||
// created_at isn't in the token, so only users with no country pay for the full user record.
|
||||
@@ -47,6 +49,7 @@ export default async function AppLayout({ children }: { children: React.ReactNod
|
||||
</div>
|
||||
<Nav />
|
||||
<div className="hidden md:block mt-auto px-3 space-y-3">
|
||||
{update && <Link href="/settings#improve" className="block text-sm underline underline-offset-4">A new version of broke is ready</Link>}
|
||||
<ThemeToggle />
|
||||
<p className="text-[11px] text-muted leading-relaxed">broke is a personal project. Bank data comes from Plaid.</p>
|
||||
</div>
|
||||
|
||||
@@ -1,25 +1,17 @@
|
||||
import { ChevronRight, Sparkles } from "lucide-react";
|
||||
import { DonateLink } from "@/components/Donate";
|
||||
import Link from "next/link";
|
||||
import { countryOf } from "@/lib/countries";
|
||||
import { getUser } from "@/lib/data";
|
||||
|
||||
const PAGES = [
|
||||
{ href: "/debt", label: "Debt", what: "What you owe, what you're paying and what it costs." },
|
||||
{ href: "/plan", label: "Money plan", what: "Every move broke found for you, in order." },
|
||||
{ href: "/optimize", label: "Optimize", what: "Tax and savings ideas for your country." },
|
||||
{ href: "/bonuses", label: "Bonuses", what: "Sign-up bonuses from banks and cards." },
|
||||
{ href: "/cards", label: "Cards", what: "Your cards and which one to use." },
|
||||
];
|
||||
|
||||
// Everything that isn't part of the three steps on Home.
|
||||
export default async function More() {
|
||||
const { user } = await getUser();
|
||||
const cards = countryOf(user?.user_metadata?.profile?.country).cards;
|
||||
// What isn't in the main menu: Debt, connecting your AI and supporting broke.
|
||||
export default function More() {
|
||||
return (
|
||||
<div className="max-w-2xl space-y-4">
|
||||
<section className="card overflow-hidden">
|
||||
{PAGES.filter((p) => cards || p.href !== "/cards").map((p) => (
|
||||
{PAGES.map((p) => (
|
||||
<Link key={p.href} href={p.href} prefetch className="row-hover flex items-center gap-3 px-6 py-4 border-b border-line last:border-0">
|
||||
<span className="flex-1 min-w-0"><span className="block font-medium">{p.label}</span><span className="block text-sm text-muted">{p.what}</span></span>
|
||||
<ChevronRight size={18} className="text-muted shrink-0" />
|
||||
|
||||
@@ -6,13 +6,16 @@ import { CountryBanner } from "@/components/CountryPicker";
|
||||
import { EmptyBank } from "@/components/EmptyBank";
|
||||
import { GoLiveCard } from "@/components/GoLiveCard";
|
||||
import { Merchant } from "@/components/Merchant";
|
||||
import { PayFound } from "@/components/PayFound";
|
||||
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 { deterministicMoves, ladder } from "@/lib/plan";
|
||||
import { myPlanFacts } from "@/lib/plan-facts";
|
||||
import { payGuess } from "@/lib/pay";
|
||||
import { moneyPicture } from "@/lib/steps";
|
||||
import { fetchChecks } from "@/lib/unsure";
|
||||
|
||||
@@ -22,6 +25,23 @@ async function HomeCheck({ checks }: { checks: Promise<Checks> }) {
|
||||
return c.total > 0 ? <CategoryCheck initial={c} closed /> : null;
|
||||
}
|
||||
|
||||
// Pay the bank filed as something else (lib/pay.ts). Streams in beside the rest.
|
||||
async function PayCheck({ uid, today, notPay }: { uid: string; today: string; notPay: string[] }) {
|
||||
const { supabase } = await getUser();
|
||||
const since = ymd(new Date(Date.parse(today) - 90 * 864e5));
|
||||
const { data } = await supabase.from("transactions").select("date, amount, name, merchant_name, custom_name, category:categories(id, key, label, kind)")
|
||||
.eq("user_id", uid).eq("ignored", false).lt("amount", -200).gte("date", since).limit(500);
|
||||
type R = { date: string; amount: number; name: string; merchant_name: string | null; custom_name: string | null; category: { key: string; label: string; kind: string } | null };
|
||||
const rows = (data ?? []) as unknown as R[];
|
||||
const name = (r: R) => r.merchant_name ?? r.name;
|
||||
const pay = payGuess(rows.map((r) => ({ name: name(r), date: r.date, amount: Number(r.amount), kind: r.category?.kind ?? null })), notPay);
|
||||
if (!pay) return null;
|
||||
const { data: income } = await supabase.from("categories").select("id").eq("key", "INCOME").is("user_id", null).maybeSingle();
|
||||
if (!income) return null;
|
||||
const filedAs = rows.find((r) => name(r) === pay.name)?.category?.label ?? "something else";
|
||||
return <PayFound pay={pay} filedAs={filedAs} incomeId={income.id as string} notPay={notPay} />;
|
||||
}
|
||||
|
||||
// One line pointing at the plan, or the one question broke needs answered. Streams in: the plan facts are the slow part.
|
||||
async function NextStep({ profile }: { profile: Record<string, unknown> }) {
|
||||
const facts = await myPlanFacts();
|
||||
@@ -91,8 +111,10 @@ export default async function Dashboard() {
|
||||
))}
|
||||
</section>
|
||||
|
||||
<Suspense fallback={null}><PayCheck uid={uid} today={day} notPay={(user?.user_metadata?.not_pay as string[] | undefined) ?? []} /></Suspense>
|
||||
<Suspense fallback={null}><NextStep profile={profile ?? {}} /></Suspense>
|
||||
<Suspense fallback={null}><HomeCheck checks={checks} /></Suspense>
|
||||
<WeekCard />
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 @3xl:grid-cols-2 items-start">
|
||||
<section className="card p-5 space-y-3">
|
||||
|
||||
@@ -36,13 +36,13 @@ const NAV: { id: Group; label: string; icon: LucideIcon; what: string }[] = [
|
||||
];
|
||||
|
||||
// Which settings page each /setup section belongs on. Sections added later land by what they're about.
|
||||
const PLACE: Record<string, Group> = { supabase: "database", database: "database", plaid: "banks", akahu: "banks", enablebanking: "banks", basiq: "banks", belvo: "banks", ai: "ai", referrals: "referrals", local: "advanced", mcp: "advanced", devlogin: "advanced" };
|
||||
const PLACE: Record<string, Group> = { supabase: "database", database: "database", codes: "database", plaid: "banks", akahu: "banks", enablebanking: "banks", basiq: "banks", belvo: "banks", ai: "ai", referrals: "referrals", local: "advanced", mcp: "advanced", devlogin: "advanced" };
|
||||
const groupOf = (s: Section): Group => PLACE[s.id] ?? (/bank/i.test(`${s.title} ${s.what}`) ? "banks" : "advanced");
|
||||
// Server setup (keys, database, model, testing shortcuts). Only shown on the machine that runs broke.
|
||||
const SERVER: Group[] = ["banks", "database", "referrals", "advanced"];
|
||||
const attention = (s: Section) => s.status === "error" || (s.status === "todo" && s.kind !== "more");
|
||||
|
||||
export function Settings({ signedIn, local, folder, repo, email, profile, mode, testItems, message, aiMode }: { signedIn: boolean; local: boolean; folder: string; repo: string | null; email: string; profile: Profile; mode: Mode; testItems: { id: string; name: string }[]; message?: string; aiMode: AiMode }) {
|
||||
export function Settings({ signedIn, local, folder, repo, update, email, profile, mode, testItems, message, aiMode }: { signedIn: boolean; local: boolean; folder: string; repo: string | null; update: boolean; email: string; profile: Profile; mode: Mode; testItems: { id: string; name: string }[]; message?: string; aiMode: AiMode }) {
|
||||
const [group, setGroup] = useState<Group>("profile");
|
||||
const [data, setData] = useState<SetupStatus | null>(null);
|
||||
const [failed, setFailed] = useState(false);
|
||||
@@ -124,6 +124,7 @@ export function Settings({ signedIn, local, folder, repo, email, profile, mode,
|
||||
<ThemeToggle />
|
||||
</Card>
|
||||
)}
|
||||
{group === "improve" && update && <Card title="A new version of broke is ready" what={folder ? "Your changes stay. Stop broke first, then run this in your broke folder, and start broke again." : "Use Get the latest broke below. Your changes stay."}>{folder && <code className="block font-mono text-[13px] rounded-lg border border-line px-3 py-2">npm run update</code>}</Card>}
|
||||
{group === "improve" && <ImproveCard folder={folder} repo={repo} />}
|
||||
{group === "database" && (
|
||||
<Card title="Clear my data" what="Disconnects every bank and deletes your accounts, transactions, bills, budgets, rules, plans and chats. Your sign-in, profile answers and AI connection stay. Only your own data is touched.">
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { getUser } from "@/lib/data";
|
||||
import { isHosted } from "@/lib/llm/providers";
|
||||
import { updateReady } from "@/lib/updates";
|
||||
import { modeOf } from "@/lib/privacy";
|
||||
import { currentEnv, fromLocalhost, setupAccess, supabaseReady } from "@/lib/setup";
|
||||
import { createAdminClient } from "@/utils/supabase/admin";
|
||||
@@ -21,6 +22,7 @@ export default async function SettingsPage({ searchParams }: { searchParams: Pro
|
||||
signedIn={access.signedIn}
|
||||
local={local}
|
||||
folder={isHosted() ? "" : process.cwd()}
|
||||
update={await updateReady()}
|
||||
repo={process.env.VERCEL_GIT_REPO_OWNER && process.env.VERCEL_GIT_REPO_SLUG ? `${process.env.VERCEL_GIT_REPO_OWNER}/${process.env.VERCEL_GIT_REPO_SLUG}` : null}
|
||||
email={user?.email ?? ""}
|
||||
profile={user?.user_metadata?.profile ?? {}}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { demoBank } from "@/lib/demo";
|
||||
import { today as userToday } from "@/lib/data";
|
||||
import { ymd } from "@/lib/format";
|
||||
import { sameOrigin } from "@/lib/setup";
|
||||
import { createAdminClient } from "@/utils/supabase/admin";
|
||||
import { createClient } from "@/utils/supabase/server";
|
||||
|
||||
// "Use made-up data": a demo bank for the signed-in user, for trying broke without a Plaid account. Its token starts
|
||||
// with access-sandbox-, so it counts as test data everywhere (Settings, Banks; switching to real banks clears it), and
|
||||
// sync and removal skip it (DEMO_TOKEN in lib/sync.ts and lib/plaid.ts). Written by the server: plaid_items is server-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 db = createAdminClient();
|
||||
const ref = `demo:${user.id}`;
|
||||
const { data: had } = await db.from("plaid_items").select("id").eq("plaid_item_id", ref).maybeSingle();
|
||||
if (had) return NextResponse.json({ error: "You already have the made-up bank." }, { status: 409 });
|
||||
|
||||
const { accounts, txns, streams } = demoBank(ymd(await userToday()));
|
||||
const { data: cats } = await db.from("categories").select("id, key").is("user_id", null);
|
||||
const cat = new Map((cats ?? []).map((c) => [c.key as string, c.id as string]));
|
||||
const { data: item, error } = await db.from("plaid_items").insert({
|
||||
user_id: user.id, provider: "plaid", plaid_item_id: ref, access_token: `access-sandbox-demo-${user.id}`,
|
||||
institution_name: "Demo Bank (made-up)", status: "ok", last_synced_at: new Date().toISOString(), cursor: "demo",
|
||||
}).select("id").single();
|
||||
if (error) return NextResponse.json({ error: "Couldn't add the made-up bank." }, { status: 500 });
|
||||
const fail = async (what: string, e: { message: string }) => {
|
||||
console.error(`[broke] demo bank ${what}:`, e.message);
|
||||
await db.from("plaid_items").delete().eq("id", item.id); // accounts and transactions go with it
|
||||
return NextResponse.json({ error: "Couldn't add the made-up bank." }, { status: 500 });
|
||||
};
|
||||
const { data: saved, error: e1 } = await db.from("accounts").insert(accounts.map((a) => ({
|
||||
user_id: user.id, item_id: item.id, plaid_account_id: `${ref}:${a.key}`, name: a.name, official_name: null, mask: a.mask,
|
||||
type: a.type, subtype: a.subtype, current_balance: a.balance, available_balance: a.type === "credit" ? null : a.balance, credit_limit: a.type === "credit" ? 5000 : null, currency: "USD",
|
||||
}))).select("id, plaid_account_id");
|
||||
if (e1) return fail("accounts", e1);
|
||||
const acct = new Map((saved ?? []).map((a) => [String(a.plaid_account_id).split(":").pop()!, a.id as string]));
|
||||
const { error: e2 } = await db.from("transactions").insert(txns.map((t) => ({
|
||||
user_id: user.id, account_id: acct.get(t.account)!, plaid_transaction_id: `${ref}:${t.key}`, date: t.date, amount: t.amount,
|
||||
name: t.name, merchant_name: t.name, pending: false, plaid_category: t.category, category_id: cat.get(t.category) ?? null,
|
||||
})));
|
||||
if (e2) return fail("transactions", e2);
|
||||
const { error: e3 } = await db.from("recurring").insert(streams.map((s) => ({
|
||||
user_id: user.id, plaid_stream_id: `${ref}:${s.merchant}`, account_id: acct.get(s.account) ?? null, merchant_name: s.merchant,
|
||||
frequency: s.frequency, average_amount: s.amount, last_amount: s.amount, last_date: s.last, next_date: s.next, is_income: s.income,
|
||||
active: true, status: "MATURE", category_id: cat.get(s.category) ?? null,
|
||||
})));
|
||||
if (e3) return fail("bills", e3);
|
||||
return NextResponse.json({ ok: true, institution: "Demo Bank (made-up)", accounts: accounts.length, added: txns.length });
|
||||
}
|
||||
+50
-10
@@ -4,9 +4,13 @@ import { useEffect, useState } from "react";
|
||||
import { Logo } from "@/components/Logo";
|
||||
import { createClient } from "@/utils/supabase/client";
|
||||
|
||||
// Sign in with a code from your email. The same email also has a link, which still works (/auth/callback).
|
||||
// Rate limits and wrong-browser links were the common trouble with links alone; a code works in any tab.
|
||||
export default function LoginPage() {
|
||||
const [email, setEmail] = useState("");
|
||||
const [state, setState] = useState<"idle" | "sending" | "sent" | "error">("idle");
|
||||
const [code, setCode] = useState("");
|
||||
const [state, setState] = useState<"idle" | "sending" | "sent" | "checking" | "error">("idle");
|
||||
const [sent, setSent] = useState(false);
|
||||
const [message, setMessage] = useState("");
|
||||
const [firstRun, setFirstRun] = useState<string | null>(null);
|
||||
const [devLogin, setDevLogin] = useState(false);
|
||||
@@ -21,8 +25,8 @@ export default function LoginPage() {
|
||||
}).catch(() => {});
|
||||
}, []);
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
async function send(e?: React.FormEvent) {
|
||||
e?.preventDefault();
|
||||
setState("sending");
|
||||
const { error } = await createClient().auth.signInWithOtp({
|
||||
email,
|
||||
@@ -30,8 +34,23 @@ export default function LoginPage() {
|
||||
});
|
||||
if (error) {
|
||||
setState("error");
|
||||
setMessage(error.message);
|
||||
} else setState("sent");
|
||||
setMessage(/rate limit|too many/i.test(error.message) ? "Too many sign-in emails for now. Supabase's free email sends a few an hour. Wait a bit, or use the code or link from the last email." : error.message);
|
||||
} else {
|
||||
setSent(true);
|
||||
setCode("");
|
||||
setState("sent");
|
||||
}
|
||||
}
|
||||
|
||||
async function verify(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setState("checking");
|
||||
const { error } = await createClient().auth.verifyOtp({ email, token: code.replace(/\s/g, ""), type: "email" });
|
||||
if (error) {
|
||||
setState("error");
|
||||
setCode(""); // ready for the right one, not mixed in with the wrong one
|
||||
setMessage(/expired|invalid/i.test(error.message) ? "That code didn't work. Codes work once, for about an hour. Check you typed the newest one, or send a new one." : error.message);
|
||||
} else window.location.assign("/"); // a full load: the page cache may still hold "/" from before sign-in (a redirect back here)
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -47,13 +66,34 @@ export default function LoginPage() {
|
||||
</ol>
|
||||
</section>
|
||||
)}
|
||||
<form onSubmit={submit} className="card p-8 space-y-5">
|
||||
<form onSubmit={sent ? verify : send} className="card p-8 space-y-5">
|
||||
<div>
|
||||
<Logo />
|
||||
<p className="text-sm text-muted mt-1">Sign in with a link sent to your email.</p>
|
||||
<p className="text-sm text-muted mt-1">{sent ? `We sent a code to ${email}.` : "Sign in with a code sent to your email."}</p>
|
||||
</div>
|
||||
{state === "sent" ? (
|
||||
<p className="text-sm">Check {email} for the sign-in link.</p>
|
||||
{sent ? (
|
||||
<>
|
||||
<input
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
required
|
||||
autoFocus
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value.replace(/[^\d\s]/g, ""))}
|
||||
placeholder="Code from the email"
|
||||
aria-label="Code from the email"
|
||||
className="input w-full tabular tracking-[0.2em] text-center text-lg"
|
||||
/>
|
||||
<button disabled={state === "checking" || code.replace(/\s/g, "").length < 6} className="btn-primary w-full">
|
||||
{state === "checking" ? "Checking..." : "Sign in"}
|
||||
</button>
|
||||
{state === "error" && <p className="text-sm text-red-600">{message}</p>}
|
||||
<p className="text-xs text-muted">No code in the email? Click its sign-in link instead, in this browser.</p>
|
||||
<div className="flex justify-between text-sm">
|
||||
<button type="button" onClick={() => send()} disabled={state === "sending"} className="text-muted underline underline-offset-4">{state === "sending" ? "Sending..." : "Send a new code"}</button>
|
||||
<button type="button" onClick={() => { setSent(false); setState("idle"); }} className="text-muted underline underline-offset-4">Use another email</button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<input
|
||||
@@ -66,7 +106,7 @@ export default function LoginPage() {
|
||||
className="input w-full"
|
||||
/>
|
||||
<button disabled={state === "sending"} className="btn-primary w-full">
|
||||
{state === "sending" ? "Sending..." : "Send link"}
|
||||
{state === "sending" ? "Sending..." : "Send code"}
|
||||
</button>
|
||||
{state === "error" && <p className="text-sm text-red-600">{message}</p>}
|
||||
{devLogin && (
|
||||
|
||||
@@ -108,7 +108,7 @@ export function SetupChecklist({ signedIn }: { signedIn: boolean }) {
|
||||
) : (
|
||||
data && <Link href="/" className="btn-primary">Open broke</Link>
|
||||
)}
|
||||
{canSkipBank && <Link href="/" className="btn">Skip banks for now</Link>}
|
||||
{canSkipBank && <Link href="/" className="btn">Skip: use made-up data</Link>}
|
||||
<button className="text-sm text-muted hover:text-ink inline-flex items-center gap-1.5" disabled={checking} onClick={() => load()}>
|
||||
<RefreshCw size={14} className={checking ? "animate-spin" : ""} /> {checking ? "Checking" : "Check again"}
|
||||
</button>
|
||||
@@ -127,7 +127,7 @@ export function SetupChecklist({ signedIn }: { signedIn: boolean }) {
|
||||
<button className="w-full flex items-center gap-4 px-6 py-4 text-left row-hover" aria-expanded={moreOpen} onClick={() => setMoreOpen(!moreOpen)}>
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className="block font-medium">More options</span>
|
||||
<span className="block text-sm text-muted truncate">Local AI model, Claude Code, skip sign-in while testing</span>
|
||||
<span className="block text-sm text-muted truncate">Sign-in codes, local AI model, Claude Code</span>
|
||||
</span>
|
||||
<ChevronDown size={18} className={`text-muted shrink-0 transition-transform duration-300 ${moreOpen ? "rotate-180" : ""}`} />
|
||||
</button>
|
||||
|
||||
@@ -130,6 +130,40 @@ export function CategoryCheck({ initial, cats: catsIn, onEmpty, title, closed =
|
||||
ask(`Help me sort these categories. Suggest rules for what you're confident about, and ask me about anything you're not sure of.\n\nThese need checking: ${lines.join("; ")}.`);
|
||||
}
|
||||
|
||||
// One press for the backlog: every row that has a category is kept as it is, so only rows with no category are left for
|
||||
// the user. Money coming in stays where the bank put it (usually a refund); pay is the "Is this your pay?" question on Home.
|
||||
// Shows what it will do before it does it.
|
||||
const [plan, setPlan] = useState<{ keep: string[]; left: number } | null>(null);
|
||||
async function planAll() {
|
||||
const id = await uid();
|
||||
if (!id) return;
|
||||
const all = ((await fetchChecks(db(), id, undefined, 1000)) as Checks).rows;
|
||||
const keep = all.filter((t) => t.category && t.category.key !== "OTHER");
|
||||
setPlan({ keep: keep.flatMap((t) => t.same), left: all.length - keep.length });
|
||||
}
|
||||
async function doAll() {
|
||||
if (!plan) return;
|
||||
const now = new Date().toISOString();
|
||||
for (let i = 0; i < plan.keep.length; i += 200) await db().from("transactions").update({ checked_at: now }).in("id", plan.keep.slice(i, i + 200));
|
||||
toast(plan.left ? `Done. ${plural(plan.left, "transaction")} with no category still need you.` : "Done. Every category is checked.");
|
||||
setPlan(null);
|
||||
const id = await uid();
|
||||
setChecks(id ? ((await fetchChecks(db(), id, undefined, limit)) as Checks) : { rows: [], total: 0 });
|
||||
router.refresh();
|
||||
}
|
||||
const fixAll = plan ? (
|
||||
<div className="w-full flex flex-wrap items-center gap-2 text-sm">
|
||||
<span className="text-muted">
|
||||
{plan.keep.length ? `Keep ${plural(plan.keep.length, "transaction")} in the category your bank gave them.` : "Nothing to keep: these have no category yet."}
|
||||
{plan.left ? ` ${plural(plan.left, "transaction")} with no category will still need you.` : ""}
|
||||
</span>
|
||||
{!!plan.keep.length && <button type="button" className="btn-primary" onClick={doAll}>Do it</button>}
|
||||
<button type="button" className="text-muted hover:text-ink" onClick={() => setPlan(null)}>Cancel</button>
|
||||
</div>
|
||||
) : (
|
||||
<button type="button" onClick={planAll} className="btn">They look right</button>
|
||||
);
|
||||
|
||||
// More of the same list, biggest first. Anything already answered is gone from it.
|
||||
async function showMore() {
|
||||
const id = await uid();
|
||||
@@ -158,14 +192,18 @@ export function CategoryCheck({ initial, cats: catsIn, onEmpty, title, closed =
|
||||
<div id="check-title" className="card-title">{head}</div>
|
||||
<p className="text-sm text-muted">Is this right? Tips are only as good as your categories.</p>
|
||||
</div>
|
||||
<button type="button" onClick={() => setOpen(true)} className="btn">Check them</button>
|
||||
{!plan && <button type="button" onClick={() => setOpen(true)} className="btn">Check them</button>}
|
||||
{fixAll}
|
||||
</section>
|
||||
);
|
||||
return (
|
||||
<section className="card px-5 md:px-6 pt-5 pb-1" aria-labelledby="check-title">
|
||||
<div id="check-title" className="card-title">{head}</div>
|
||||
<p className="text-sm text-muted mt-1">Is this right? Tips are only as good as your categories.</p>
|
||||
<button type="button" onClick={sortWithAI} className="btn inline-flex items-center gap-1.5 mt-3"><Sparkles size={15} /> Ask AI to sort these</button>
|
||||
<div className="flex flex-wrap items-center gap-2 mt-3">
|
||||
{fixAll}
|
||||
{!plan && <button type="button" onClick={sortWithAI} className="btn inline-flex items-center gap-1.5"><Sparkles size={15} /> Ask AI to sort these</button>}
|
||||
</div>
|
||||
<ul className="mt-2">{checks.rows.map((t) => <CheckItem key={t.id} t={t} cats={cats} onAnswer={onAnswer} />)}</ul>
|
||||
{checks.rows.length < checks.total && (
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 py-4 border-t border-line">
|
||||
|
||||
@@ -38,10 +38,12 @@ async function saveCountry(profile: Profile, country: string, currency: string)
|
||||
export function Welcome({ profile, onDone }: { profile: Profile; onDone?: (p: Profile) => void }) {
|
||||
const router = useRouter();
|
||||
const [c, setC] = useState({ country: "", currency: "" });
|
||||
const [guessed, setGuessed] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [err, setErr] = useState("");
|
||||
useEffect(() => {
|
||||
const country = guessCountry(navigator.languages ?? [navigator.language], Intl.DateTimeFormat().resolvedOptions().timeZone);
|
||||
setGuessed(country);
|
||||
setC((x) => (x.country ? x : { country, currency: countryOf(country).currency }));
|
||||
}, []);
|
||||
|
||||
@@ -64,6 +66,7 @@ export function Welcome({ profile, onDone }: { profile: Profile; onDone?: (p: Pr
|
||||
<p className="text-sm text-muted mt-1">broke uses it for your currency, which banks you can link and which tax tips apply. You can change it later.</p>
|
||||
</div>
|
||||
<CountryField country={c.country} currency={c.currency} onChange={(country, currency) => setC({ country, currency })} />
|
||||
{c.country && c.country === guessed && <p className="text-sm text-muted">Guessed from your computer's time zone and language. Change it if that's wrong.</p>}
|
||||
<button onClick={go} disabled={busy || !c.country || !c.currency} className="btn-primary w-full">{busy ? "Saving..." : "Continue"}</button>
|
||||
{err && <p className="text-sm text-bad">{err}</p>}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
// "Use made-up data": adds the demo bank (api/demo-bank) when there's no Plaid account to link a test bank with.
|
||||
export function DemoBankButton({ onDone, primary = false }: { onDone?: () => void; primary?: boolean }) {
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [err, setErr] = useState("");
|
||||
async function add() {
|
||||
setBusy(true);
|
||||
setErr("");
|
||||
const res = await fetch("/api/demo-bank", { method: "POST" }).catch(() => null);
|
||||
setBusy(false);
|
||||
if (!res?.ok && res?.status !== 409) return setErr(((await res?.json().catch(() => null)) as { error?: string } | null)?.error ?? "Couldn't add the made-up bank. Try again.");
|
||||
onDone?.();
|
||||
router.refresh();
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<button onClick={add} disabled={busy} className={primary ? "btn-primary" : "btn"}>{busy ? "Adding made-up data..." : "Use made-up data"}</button>
|
||||
<p className="text-xs text-muted">A pretend bank with three months of everyday spending. No Plaid account needed. Clear it any time in Settings, Database.</p>
|
||||
{err && <p className="text-sm text-bad">{err}</p>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import Link from "next/link";
|
||||
import { DemoBankButton } from "@/components/DemoBank";
|
||||
import { FeedConnect } from "@/components/FeedConnect";
|
||||
import { ImportStatement } from "@/components/ImportStatement";
|
||||
import { AkahuButton, LinkBankButton, TestModeNote } from "@/components/PlaidButtons";
|
||||
@@ -27,6 +28,7 @@ export async function EmptyBank({ title = "Link an account to get started", body
|
||||
{choices.bank === "plaid" && <LinkBankButton label={investOnly ? "Link a bank or card" : "Link a bank"} primary />}
|
||||
{choices.sandbox && <LinkBankButton sandbox label="Use a test bank (sandbox)" />}
|
||||
{choices.sandbox && <TestModeNote />}
|
||||
{choices.demo && <DemoBankButton primary={!choices.bank && !choices.feeds.length} />}
|
||||
<ImportStatement accounts={[]} locale={country.locale} currency={country.currency} />
|
||||
{children ?? (investOnly && <Link href="/transactions" className="text-sm underline underline-offset-2">Add a transaction by hand</Link>)}
|
||||
<Link href="/accounts/add" className="text-sm text-muted underline underline-offset-2 hover:text-ink">More ways to add an account</Link>
|
||||
|
||||
@@ -183,7 +183,7 @@ export function MoneyPlan({ initial, today, name }: { initial: PlanState; today:
|
||||
{state.error && <p className="text-sm text-bad" role="alert">{state.error}</p>}
|
||||
{state.stale && !state.running && <p className="text-sm text-bad">{state.stale} Redo it to use your current accounts.</p>}
|
||||
{!state.ready && <p className="text-sm text-muted">The money plan needs a database update. Open Setup to apply it.</p>}
|
||||
{p?.note && !state.running && <p className="text-sm text-muted">{p.note} Steps built on those numbers aren't counted.</p>}
|
||||
{p?.note && !state.running && <p className="text-sm text-muted">{p.note} Steps built on those numbers aren't counted. <a href="/accounts" className="underline underline-offset-2">See how far back each bank goes</a>.</p>}
|
||||
</div>
|
||||
|
||||
{p && live.length > 0 && (
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { ArrowLeftRight, ChartPie, Ellipsis, House, Landmark, MessageCircle, Monitor, Moon, Sun } from "lucide-react";
|
||||
import { ArrowLeftRight, ChartPie, ClipboardList, Ellipsis, House, Landmark, MessageCircle, Monitor, Moon, Sun } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import type { ComponentType } from "react";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
@@ -9,12 +9,13 @@ import { useAssistant } from "@/components/Assistant";
|
||||
import { BookmarkButton, SavedList } from "@/components/Bookmarks";
|
||||
import { DonateLink, DonatePrompt } from "@/components/Donate";
|
||||
|
||||
// Home is the three steps. Spending holds Budgets and Recurring as tabs, More holds the rest; every page keeps its own URL.
|
||||
// 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 }>;
|
||||
const LINKS: { href: string; label: string; icon: Icon }[] = [
|
||||
{ href: "/", label: "Home", icon: House },
|
||||
{ href: "/spending", label: "Spending", icon: ChartPie },
|
||||
{ href: "/transactions", label: "Activity", icon: ArrowLeftRight },
|
||||
{ href: "/plan", label: "Plan", icon: ClipboardList },
|
||||
{ href: "/accounts", label: "Accounts", icon: Landmark },
|
||||
{ href: "/more", label: "More", icon: Ellipsis },
|
||||
];
|
||||
@@ -22,7 +23,7 @@ const SPENDING = [{ href: "/spending", label: "Overview" }, { href: "/budgets",
|
||||
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)));
|
||||
const sectionOf = (path: string) => (SPENDING.some((t) => under(path, t.href)) ? "/spending" : LINKS.find((l) => under(path, l.href))?.href ?? (tabsOf(path) || under(path, "/connect-ai") || under(path, "/debt") ? "/more" : undefined));
|
||||
const sectionOf = (path: string) => (SPENDING.some((t) => under(path, t.href)) ? "/spending" : PLAN.some((t) => under(path, t.href)) ? "/plan" : LINKS.find((l) => under(path, l.href))?.href ?? (under(path, "/connect-ai") || under(path, "/debt") ? "/more" : undefined));
|
||||
|
||||
const TITLES: Record<string, string> = {
|
||||
"/": "Home", "/transactions": "Activity", "/spending": "Spending", "/budgets": "Budgets", "/recurring": "Recurring", "/plan": "Money plan",
|
||||
@@ -89,7 +90,7 @@ function PhoneBar({ section }: { section?: string }) {
|
||||
const assistant = useAssistant();
|
||||
const cell = "flex flex-col items-center gap-0.5 text-[11px] py-1.5 rounded-xl";
|
||||
return (
|
||||
<nav aria-label="Main" className="fixed bottom-0 inset-x-0 z-30 md:hidden bg-surface border-t border-line grid grid-cols-6 px-1 pt-1 pb-[max(6px,env(safe-area-inset-bottom))]">
|
||||
<nav aria-label="Main" className="fixed bottom-0 inset-x-0 z-30 md:hidden bg-surface border-t border-line grid grid-cols-7 px-1 pt-1 pb-[max(6px,env(safe-area-inset-bottom))]">
|
||||
{LINKS.map(({ href, label, icon: Icon }) => (
|
||||
<Link key={href} href={href} prefetch aria-current={href === section ? "page" : undefined} className={`${cell} ${href === section ? "text-ink font-medium" : "text-muted"}`}>
|
||||
<Icon size={21} strokeWidth={href === section ? 2 : 1.6} />
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useRouter } from "next/navigation";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Welcome } from "@/components/CountryPicker";
|
||||
import { GoalPicker, type DraftPlan } from "@/components/GoalPicker";
|
||||
import { DemoBankButton } from "@/components/DemoBank";
|
||||
import { FeedConnect } from "@/components/FeedConnect";
|
||||
import { Logo } from "@/components/Logo";
|
||||
import { linkedText, useAkahu, useLinkBank } from "@/components/PlaidButtons";
|
||||
@@ -83,6 +84,7 @@ function BankStep({ choices, country, info, next, reload }: { choices: AddChoice
|
||||
{choices.bank === "plaid" && <button onClick={() => link.start()} className={linked ? "btn" : "btn-primary"}>{linked ? "Link another bank" : "Link a bank or card"}</button>}
|
||||
{choices.bank === "akahu" && <button onClick={akahu.start} className={linked ? "btn" : "btn-primary"}>Link your NZ banks</button>}
|
||||
{choices.sandbox && <button onClick={() => link.start(true)} className="btn">Use a test bank</button>}
|
||||
{choices.demo && !linked && <DemoBankButton primary={!choices.bank} onDone={reload} />}
|
||||
{linked > 0 && <button onClick={next} className="btn-primary">Continue</button>}
|
||||
</div>
|
||||
{(link.error || akahu.error) && <p className="text-sm text-bad">{link.error || akahu.error}</p>}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
import { useMoney } from "@/components/Money";
|
||||
import { emptyRule, saveRule } from "@/components/RuleForm";
|
||||
import type { PayGuess } from "@/lib/pay";
|
||||
import { createClient, updateMeta } from "@/utils/supabase/client";
|
||||
|
||||
// "Is this your pay?": regular money coming in that the bank filed as something else. Yes saves a rule that files it
|
||||
// (and every past one) as Income, so the plan, budgets and leftover money count it. No never asks about that name again.
|
||||
export function PayFound({ pay, filedAs, incomeId, notPay }: { pay: PayGuess; filedAs: string; incomeId: string; notPay: string[] }) {
|
||||
const router = useRouter();
|
||||
const { money0 } = useMoney();
|
||||
const [state, setState] = useState<"idle" | "busy" | "gone">("idle");
|
||||
const [err, setErr] = useState("");
|
||||
if (state === "gone") return null;
|
||||
async function yes() {
|
||||
setState("busy");
|
||||
const r = await saveRule(emptyRule({ match: pay.name, direction: "in", category_id: incomeId }), true);
|
||||
if (r.error) return setErr(r.error), setState("idle");
|
||||
setState("gone");
|
||||
router.refresh();
|
||||
}
|
||||
async function no() {
|
||||
setState("busy");
|
||||
const sb = createClient();
|
||||
await updateMeta(sb, { data: { not_pay: [...notPay, pay.name] } });
|
||||
setState("gone");
|
||||
}
|
||||
return (
|
||||
<section className="card p-5 space-y-3">
|
||||
<div className="space-y-1">
|
||||
<p className="font-medium">Is {money0(pay.typical)} every {pay.every} from {pay.name} your pay?</p>
|
||||
<p className="text-sm text-muted">Your bank filed it as {filedAs}, so broke can't count it as money coming in. That changes your plan, budgets and what's left over.</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<button className="btn-primary" disabled={state === "busy"} onClick={yes}>Yes, it's my pay</button>
|
||||
<button className="btn" disabled={state === "busy"} onClick={no}>No</button>
|
||||
</div>
|
||||
{err && <p className="text-sm text-bad">{err}</p>}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { AskButton } from "@/components/Assistant";
|
||||
import { useMoney } from "@/components/Money";
|
||||
import { changeLines, trackLines, type CheckinFacts } from "@/lib/checkins";
|
||||
|
||||
type Checkin = { id: string; created_at: string; facts: CheckinFacts; summary: string | null };
|
||||
|
||||
// "Your week" on Home: the weekly review, written once a week (POST /api/checkins makes a new one when the last is 7+
|
||||
// days old, else returns it). Your AI's words when one is connected, else the plain facts. A few lines, no more.
|
||||
export function WeekCard() {
|
||||
const { money0, dateLabel } = useMoney();
|
||||
const [c, setC] = useState<Checkin | null>(null);
|
||||
useEffect(() => {
|
||||
fetch("/api/checkins", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" })
|
||||
.then((r) => (r.ok ? r.json() : null)).then((x: Checkin | null) => x?.facts && setC(x)).catch(() => {});
|
||||
}, []);
|
||||
if (!c) return null;
|
||||
const lines = (c.summary ? c.summary.split("\n").map((l) => l.replace(/^- /, "").trim()) : [...changeLines(c.facts, { $: money0 }), ...trackLines(c.facts, money0)]).filter(Boolean).slice(0, 4);
|
||||
if (!lines.length) return null;
|
||||
return (
|
||||
<section className="card p-5 space-y-2.5">
|
||||
<div className="flex items-baseline justify-between gap-3">
|
||||
<span className="text-sm text-muted">Your week · {dateLabel(c.created_at.slice(0, 10), { month: "short", day: "numeric" })}</span>
|
||||
<AskButton q="Talk me through my week: what changed, and what should I do about it?" className="text-sm text-muted hover:text-ink">Ask about this</AskButton>
|
||||
</div>
|
||||
<ul className="space-y-1.5 text-sm list-disc pl-5">{lines.map((l) => <li key={l}>{l}</li>)}</ul>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -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");
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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");
|
||||
@@ -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
@@ -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 };
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
@@ -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) {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -52,7 +52,5 @@ export async function updateSession(request: NextRequest) {
|
||||
response.cookies.getAll().forEach((c) => to.cookies.set(c));
|
||||
return to;
|
||||
}
|
||||
// Signed in but no bank keys yet: app pages would be empty, so show the checklist instead.
|
||||
if (user && !path.startsWith("/api") && !(isSet(process.env.PLAID_CLIENT_ID) && isSet(process.env.PLAID_SECRET))) return toSetup(request);
|
||||
return response;
|
||||
}
|
||||
Reference in new issue
Block a user