From b532bb8dd844036ee4a75518e7e1f74db170bbaa Mon Sep 17 00:00:00 2001 From: minimus7 Date: Mon, 16 Nov 2026 11:15:28 -0600 Subject: [PATCH] Setup step 3 asks where you live and shows that country's bank feed (#6) Saved as BROKE_COUNTRY. US and Canada get Plaid, NZ Akahu, UK and Europe Enable Banking, Australia Basiq, Brazil Belvo. Countries with no feed are told to import a statement after sign-in. Onboarding uses the saved country instead of asking again. Co-authored-by: Claude Opus 5.5 --- src/app/(app)/settings/Settings.tsx | 2 +- src/app/api/setup/status/route.ts | 8 +- src/app/setup/SetupActions.tsx | 49 +++++++++++++ src/app/setup/SetupChecklist.tsx | 8 +- src/app/welcome/page.tsx | 7 +- src/components/Onboarding.tsx | 11 ++- src/lib/envfile.ts | 1 + src/lib/setup.ts | 110 ++++++++++++++++------------ 8 files changed, 136 insertions(+), 60 deletions(-) diff --git a/src/app/(app)/settings/Settings.tsx b/src/app/(app)/settings/Settings.tsx index 509aa8d..b971531 100644 --- a/src/app/(app)/settings/Settings.tsx +++ b/src/app/(app)/settings/Settings.tsx @@ -78,7 +78,7 @@ export function Settings({ signedIn, local, folder, repo, update, email, profile }, [group, local, load]); const nav = local ? NAV : NAV.filter((n) => !SERVER.includes(n.id) || n.id === "banks" || n.id === "database"); - const sections = (data?.sections ?? []).filter((s) => groupOf(s) === group); + const sections = (data?.sections ?? []).filter((s) => s.id !== "country" && groupOf(s) === group); // "country": setup's step 3 with no feed; the country itself is under Profile const flagged = (g: Group) => (data?.sections ?? []).some((s) => groupOf(s) === g && attention(s)); const here = NAV.find((n) => n.id === group)!; const pick = (g: Group) => { diff --git a/src/app/api/setup/status/route.ts b/src/app/api/setup/status/route.ts index 65fda5b..efe58ca 100644 --- a/src/app/api/setup/status/route.ts +++ b/src/app/api/setup/status/route.ts @@ -1,6 +1,6 @@ import { NextResponse } from "next/server"; import { countryOf, wantsAkahu } from "@/lib/countries"; -import { fromLocalhost, setupAccess, setupStatus } from "@/lib/setup"; +import { currentEnv, fromLocalhost, setupAccess, setupStatus } from "@/lib/setup"; import { createClient } from "@/utils/supabase/server"; // Server setup details are for the owner on this machine only: setup writes already need localhost (writeGate). @@ -12,12 +12,14 @@ export async function GET() { // The NZ bank keys only matter to someone with NZ banks. Keys already saved stay visible, so they can be changed or removed. // Before Supabase is set up there's nobody signed in, and no client to ask. const user = access.signedIn ? (await (await createClient()).auth.getUser()).data.user : null; - const profile = user?.user_metadata?.profile; + // Before anyone signs in, where they live is what setup step 3 asked (BROKE_COUNTRY). + const profile = user?.user_metadata?.profile ?? { country: currentEnv().BROKE_COUNTRY }; const here = countryOf(profile?.country).providers as string[]; const nz = wantsAkahu(profile); // Bank connections for other countries stay out of the way, unless keys are already saved. return NextResponse.json({ ...status, sections: status.sections.filter((s) => { + if (s.kind === "required") return true; if (s.id === "akahu") return nz || s.status === "done"; - return !["enablebanking", "basiq", "belvo"].includes(s.id) || here.includes(s.id) || s.status === "done"; + return !["plaid", "enablebanking", "basiq", "belvo"].includes(s.id) || here.includes(s.id) || s.status === "done"; }) }); } diff --git a/src/app/setup/SetupActions.tsx b/src/app/setup/SetupActions.tsx index bcb38f9..80feada 100644 --- a/src/app/setup/SetupActions.tsx +++ b/src/app/setup/SetupActions.tsx @@ -2,6 +2,8 @@ import { Check, Copy, Eye, EyeOff } from "lucide-react"; import { useEffect, useState } from "react"; +import { Dropdown } from "@/components/Dropdown"; +import { COUNTRIES, countryOf, guessCountry, OTHER } from "@/lib/countries"; import type { Field } from "@/lib/setup"; export function CopyCommand({ command }: { command: string }) { @@ -208,3 +210,50 @@ export function ConnectSupabaseButton({ onDone, onFail }: { onDone: () => void; ); } + +const COUNTRY_OPTIONS = [...COUNTRIES, OTHER].map((c) => ({ value: c.code, label: c.name })); + +// Step 3 asks where they live first, so it can show that country's bank feed. Saved as BROKE_COUNTRY; onboarding uses it +// instead of asking again. Nothing saved yet: the guess from this computer, with a Continue button. +export function CountryPick({ saved, canWrite, writeNote, onSaved }: { saved: string; canWrite: boolean; writeNote?: string; onSaved: () => void }) { + const [guess, setGuess] = useState(""); + const [value, setValue] = useState(saved); + const [busy, setBusy] = useState(false); + const [err, setErr] = useState(""); + useEffect(() => { + if (saved) return; // the checklist remounts this (key) when the saved country changes + const g = guessCountry(navigator.languages ?? [navigator.language], Intl.DateTimeFormat().resolvedOptions().timeZone); + setGuess(g); + setValue((v) => v || g); + }, [saved]); + + async function save(code: string) { + setBusy(true); + setErr(""); + try { + const res = await fetch("/api/setup/env", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ values: { BROKE_COUNTRY: code } }) }); + const body = (await res.json().catch(() => ({}))) as { error?: string; errors?: Record }; + if (res.ok) onSaved(); + else setErr(body.errors?.BROKE_COUNTRY ?? body.error ?? "Couldn't save."); + } catch { + setErr("Couldn't reach broke. Is it still running?"); + } + setBusy(false); + } + + if (!canWrite) return

Where you live: {saved ? countryOf(saved).name : "not set"}. {writeNote} Set BROKE_COUNTRY there.

; + return ( +
+ Where do you live? +
+
+ { setValue(c); if (saved) save(c); }} placeholder="Choose a country" searchable /> +
+ {!saved && } + {saved && busy && Saving...} +
+ {!saved && value && value === guess &&

Guessed from this computer's time zone and language. Change it if that's wrong.

} + {err &&

{err}

} +
+ ); +} diff --git a/src/app/setup/SetupChecklist.tsx b/src/app/setup/SetupChecklist.tsx index 6843a4d..31c37eb 100644 --- a/src/app/setup/SetupChecklist.tsx +++ b/src/app/setup/SetupChecklist.tsx @@ -5,7 +5,7 @@ import Link from "next/link"; import { useCallback, useEffect, useState } from "react"; import { Logo } from "@/components/Logo"; import type { AiRow, Part, Section, SetupStatus } from "@/lib/setup"; -import { CopyCommand, KeyForm, ConnectSupabaseButton, MigrateButton } from "./SetupActions"; +import { CopyCommand, CountryPick, KeyForm, ConnectSupabaseButton, MigrateButton } from "./SetupActions"; export function ExtLink({ href, children }: { href: string; children: React.ReactNode }) { return ( @@ -83,9 +83,8 @@ export function SetupChecklist({ signedIn }: { signedIn: boolean }) { const main = sections.filter((s) => s.kind !== "more"); const more = sections.filter((s) => s.kind === "more"); const required = main.filter((s) => s.kind === "required"); - const done = required.filter((s) => s.status === "done").length; const next = required.find((s) => s.status !== "done"); - const canSkipBank = next?.id === "plaid"; // the database works, so broke can open: statements can be imported without a bank feed + const canSkipBank = next?.country !== undefined; // the database works, so broke can open: statements can be imported without a bank feed return (
@@ -97,7 +96,7 @@ export function SetupChecklist({ signedIn }: { signedIn: boolean }) {
-

{!data ? "Set up broke" : !next ? "You're all set" : `Step ${done + 1} of ${required.length}: ${next.title}`}

+

{!data ? "Set up broke" : !next ? "You're all set" : `Step ${required.indexOf(next) + 1} of ${required.length}: ${next.title}`}

{!data ? "Checking what's connected… " : !next ? "Open broke and sign in with your email. " : "It's free. Follow the steps below and paste each key in. "} Your keys stay on this computer. @@ -186,6 +185,7 @@ function SectionCard({ s, n, open, onToggle, data, signedIn, reload }: { s: Sect

+ {s.country !== undefined && }
diff --git a/src/app/welcome/page.tsx b/src/app/welcome/page.tsx index b50ce7a..a31b721 100644 --- a/src/app/welcome/page.tsx +++ b/src/app/welcome/page.tsx @@ -1,10 +1,11 @@ import { redirect } from "next/navigation"; import { MoneyProvider } from "@/components/Money"; import { Onboarding, type Step } from "@/components/Onboarding"; -import { countryOf } from "@/lib/countries"; +import { COUNTRIES, countryOf } from "@/lib/countries"; import { getUser, userTz } from "@/lib/data"; import { fmtFor } from "@/lib/format"; import { addChoices } from "@/lib/providers"; +import { currentEnv } from "@/lib/setup"; // First run: the app layout sends new users here until onboarding is done (profile.onboarding, Onboarding.tsx). // No country yet starts at the country picker; otherwise it resumes at the saved step. @@ -14,10 +15,12 @@ export default async function WelcomePage() { const profile = user.user_metadata?.profile ?? {}; if (profile.country && (!profile.onboarding || profile.onboarding === "done")) redirect("/"); const step = (profile.country ? profile.onboarding : "country") as Step; + // Setup step 3 already asked where they live. Onboarding uses that instead of asking again. "Somewhere else" still asks, for the currency. + const setupCountry = COUNTRIES.some((c) => c.code === currentEnv().BROKE_COUNTRY) ? currentEnv().BROKE_COUNTRY : undefined; return (
- +
); diff --git a/src/components/Onboarding.tsx b/src/components/Onboarding.tsx index 5eea464..e689749 100644 --- a/src/components/Onboarding.tsx +++ b/src/components/Onboarding.tsx @@ -177,15 +177,20 @@ function ResultStep({ finish, back }: { finish: (href: string) => void; back: () ); } -export function Onboarding({ profile: initial, start, choices }: { profile: Profile; start: Step; choices: AddChoices }) { +export function Onboarding({ profile: initial, start, setupCountry, choices }: { profile: Profile; start: Step; setupCountry?: string; choices: AddChoices }) { const router = useRouter(); - const [profile, setProfile] = useState(initial); - const [step, setStep] = useState(STEPS.includes(start) ? start : "result"); + // Setup step 3 already asked where they live: save that and start at the bank step. + const preset = start === "country" && setupCountry ? { ...initial, country: setupCountry, currency: countryOf(setupCountry).currency, onboarding: "bank" } : null; + const [profile, setProfile] = useState(preset ?? initial); + const [step, setStep] = useState(preset ? "bank" : STEPS.includes(start) ? start : "result"); const [info, setInfo] = useState(null); // Writes run one after another so a later step never lands before an earlier one. const queue = useRef>(Promise.resolve()); const write = (p: Profile) => (queue.current = queue.current.then(() => updateMeta(createClient(), { data: { profile: p } }))); + useEffect(() => { + if (preset) write(preset).then(() => router.refresh()); + }, []); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { if (step !== "country" && step !== "result") load().then(setInfo); }, [step === "country"]); // eslint-disable-line react-hooks/exhaustive-deps diff --git a/src/lib/envfile.ts b/src/lib/envfile.ts index 7be6a9f..296cd14 100644 --- a/src/lib/envfile.ts +++ b/src/lib/envfile.ts @@ -33,6 +33,7 @@ export const ENV_KEYS: Record = { }, // Never saved: validate() puts it into SUPABASE_DB_URL's [YOUR-PASSWORD], so nobody edits the string by hand. SUPABASE_DB_PASSWORD: { label: "Database password", secret: true, check: () => null }, + BROKE_COUNTRY: { label: "Country", secret: false, check: (v) => (/^[A-Z]{2}$/.test(v) ? null : "A two-letter country code") }, PLAID_CLIENT_ID: { label: "Client ID", secret: false, check: (v) => (/^[a-f0-9]{24}$/.test(v) ? null : "24 letters and numbers, from Plaid → Developers → Keys") }, PLAID_SECRET: { label: "Secret", secret: true, check: (v) => (/^[a-f0-9]{30}$/.test(v) ? null : "30 letters and numbers, from Plaid → Developers → Keys") }, PLAID_ENV: { label: "Mode", secret: false, check: (v) => (/^(sandbox|production)$/.test(v) ? null : "sandbox or production") }, diff --git a/src/lib/setup.ts b/src/lib/setup.ts index 1a16fbb..a87deaa 100644 --- a/src/lib/setup.ts +++ b/src/lib/setup.ts @@ -9,6 +9,7 @@ import { mcpConnected } from "@/lib/supabase-mcp"; import { cardReferralSection } from "@/lib/cards-data"; import { akahuTokens } from "@/lib/providers"; import { akahuGet } from "@/lib/providers/akahu"; +import { countryOf } from "@/lib/countries"; export type StepStatus = "done" | "todo" | "error" | "optional"; export type Part = string | { href: string; label: string }; @@ -27,6 +28,7 @@ export type Section = { command?: string; action?: "migrate" | "connect"; providers?: AiRow[]; + country?: string; // step 3 only: the saved BROKE_COUNTRY, "" when not picked yet }; export type SetupStatus = { sections: Section[]; ready: boolean; canWrite: boolean; writeNote?: string }; @@ -142,10 +144,10 @@ export async function setupStatus(signedIn: boolean): Promise { } const plaidSection: Section = { - id: "plaid", kind: "required", - title: "Connect banks", + id: "plaid", kind: "more", + title: "US and Canadian banks (Plaid)", what: "Start with Plaid's test banks: free, with made-up money. Switch to your real banks whenever you like.", - status: bank?.ok ? "done" : bank ? "error" : "todo", + status: bank?.ok ? "done" : bank ? "error" : "optional", note: bank?.message, steps: [ ["Make a free account at ", { href: "https://dashboard.plaid.com/signup", label: "plaid.com" }, ", then open ", { href: "https://dashboard.plaid.com/developers/keys", label: "Developers → Keys" }, "."], @@ -154,6 +156,62 @@ export async function setupStatus(signedIn: boolean): Promise { fields: fields(env, ["PLAID_CLIENT_ID", "PLAID_SECRET", "PLAID_ENV"], { PLAID_ENV: { options: ["sandbox", "production"] } }), }; + const akahuSection: Section = { + id: "akahu", kind: "more", + title: "New Zealand banks (Akahu)", + what: "Akahu reads NZ bank accounts. A free personal app covers the banks on your own Akahu login.", + status: akahu?.ok ? "done" : akahu ? "error" : "optional", + note: akahu?.message, + steps: [ + ["Sign up at ", { href: "https://my.akahu.nz", label: "my.akahu.nz" }, " and connect your banks."], + ["Open Developers there, create a personal app and copy both tokens."], + ], + fields: fields(env, ["AKAHU_APP_TOKEN", "AKAHU_USER_TOKEN"], { AKAHU_APP_TOKEN: { placeholder: "app_token_…" }, AKAHU_USER_TOKEN: { placeholder: "user_token_…" } }), + }; + const enableSection: Section = { + id: "enablebanking", kind: "more", + title: "UK and European banks (Enable Banking)", + what: "People pick their bank and approve on the bank's own page. Restricted mode covers accounts you link yourself. Other people's accounts need a contract with Enable Banking.", + status: isSet(env.ENABLE_BANKING_APP_ID) && isSet(env.ENABLE_BANKING_PRIVATE_KEY) ? "done" : "optional", + steps: [ + ["Sign up at ", { href: "https://enablebanking.com/sign-in/", label: "enablebanking.com" }, " and register an application."], + [`Add this as the application's redirect URL: http://localhost:3000/api/bank/connect/enablebanking/callback`], + ["Copy the application ID and paste its private key below."], + ], + fields: fields(env, ["ENABLE_BANKING_APP_ID", "ENABLE_BANKING_PRIVATE_KEY"]), + }; + const basiqSection: Section = { + id: "basiq", kind: "more", + title: "Australian banks (Basiq)", + what: "People approve on Basiq's own page. The sandbox is free with test banks. Real banks may need accreditation or a partner under Australia's Consumer Data Right, so ask Basiq.", + status: isSet(env.BASIQ_API_KEY) ? "done" : "optional", + steps: [ + ["Create an API key at ", { href: "https://dashboard.basiq.io", label: "dashboard.basiq.io" }, "."], + [`In Basiq's dashboard, set the return address to http://localhost:3000/api/bank/connect/basiq/callback`], + ], + fields: fields(env, ["BASIQ_API_KEY"]), + }; + const belvoSection: Section = { + id: "belvo", kind: "more", + title: "Brazilian banks (Belvo)", + what: "Open Finance consent on Belvo's page. People enter their CPF and name first, as Brazil requires. Belvo requires a link to your terms. Production keys come from Belvo support.", + status: isSet(env.BELVO_SECRET_ID) && isSet(env.BELVO_SECRET_PASSWORD) && isSet(env.BELVO_TERMS_URL) ? "done" : "optional", + steps: [["Sign up at ", { href: "https://developers.belvo.com", label: "belvo.com" }, " and create sandbox keys under Developer Tools, API Keys."]], + fields: fields(env, ["BELVO_SECRET_ID", "BELVO_SECRET_PASSWORD", "BELVO_TERMS_URL", "BELVO_ENV"]), + }; + + // Step 3 is the bank feed for where they live (BROKE_COUNTRY, asked on this step). No feed there: import a statement. + // Installs from before the country question keep a working feed as step 3. + const saved = isSet(env.BROKE_COUNTRY) ? env.BROKE_COUNTRY! : ""; + const home = saved ? countryOf(saved) : bank?.ok ? countryOf("US") : akahu?.ok ? countryOf("NZ") : null; + const feeds = [plaidSection, akahuSection, enableSection, basiqSection, belvoSection]; + const homeFeed = feeds.find((f) => f.id === home?.providers[0]); + const bankStep: Section = !home + ? { id: "country", kind: "required", title: "Connect banks", what: "Pick where you live. broke shows the banks you can link there.", status: "todo", country: "" } + : homeFeed + ? { ...homeFeed, kind: "required", title: "Connect banks", what: homeFeed === plaidSection ? homeFeed.what : `${homeFeed.title}. ${homeFeed.what}`, status: homeFeed.status === "optional" ? "todo" : homeFeed.status, country: saved } + : { id: "country", kind: "required", title: "Connect banks", what: `No bank feed for ${home.name} yet. After you sign in, import a statement from your bank.`, status: "done", country: saved }; + const aiSection: Section = { id: "ai", kind: "ai", title: "Connect your AI (optional)", @@ -205,49 +263,7 @@ export async function setupStatus(signedIn: boolean): Promise { command: `claude mcp add --transport http supabase-broke "https://mcp.supabase.com/mcp?project_ref=${ref}"`, }] : []), - { - id: "akahu", kind: "more", - title: "New Zealand banks (Akahu)", - what: "Akahu reads NZ bank accounts. A free personal app covers the banks on your own Akahu login.", - status: akahu?.ok ? "done" : akahu ? "error" : "optional", - note: akahu?.message, - steps: [ - ["Sign up at ", { href: "https://my.akahu.nz", label: "my.akahu.nz" }, " and connect your banks."], - ["Open Developers there, create a personal app and copy both tokens."], - ], - fields: fields(env, ["AKAHU_APP_TOKEN", "AKAHU_USER_TOKEN"], { AKAHU_APP_TOKEN: { placeholder: "app_token_…" }, AKAHU_USER_TOKEN: { placeholder: "user_token_…" } }), - }, - { - id: "enablebanking", kind: "more", - title: "UK and European banks (Enable Banking)", - what: "People pick their bank and approve on the bank's own page. Restricted mode covers accounts you link yourself. Other people's accounts need a contract with Enable Banking.", - status: isSet(env.ENABLE_BANKING_APP_ID) && isSet(env.ENABLE_BANKING_PRIVATE_KEY) ? "done" : "optional", - steps: [ - ["Sign up at ", { href: "https://enablebanking.com/sign-in/", label: "enablebanking.com" }, " and register an application."], - [`Add this as the application's redirect URL: http://localhost:3000/api/bank/connect/enablebanking/callback`], - ["Copy the application ID and paste its private key below."], - ], - fields: fields(env, ["ENABLE_BANKING_APP_ID", "ENABLE_BANKING_PRIVATE_KEY"]), - }, - { - id: "basiq", kind: "more", - title: "Australian banks (Basiq)", - what: "People approve on Basiq's own page. The sandbox is free with test banks. Real banks may need accreditation or a partner under Australia's Consumer Data Right, so ask Basiq.", - status: isSet(env.BASIQ_API_KEY) ? "done" : "optional", - steps: [ - ["Create an API key at ", { href: "https://dashboard.basiq.io", label: "dashboard.basiq.io" }, "."], - [`In Basiq's dashboard, set the return address to http://localhost:3000/api/bank/connect/basiq/callback`], - ], - fields: fields(env, ["BASIQ_API_KEY"]), - }, - { - id: "belvo", kind: "more", - title: "Brazilian banks (Belvo)", - what: "Open Finance consent on Belvo's page. People enter their CPF and name first, as Brazil requires. Belvo requires a link to your terms. Production keys come from Belvo support.", - status: isSet(env.BELVO_SECRET_ID) && isSet(env.BELVO_SECRET_PASSWORD) && isSet(env.BELVO_TERMS_URL) ? "done" : "optional", - steps: [["Sign up at ", { href: "https://developers.belvo.com", label: "belvo.com" }, " and create sandbox keys under Developer Tools, API Keys."]], - fields: fields(env, ["BELVO_SECRET_ID", "BELVO_SECRET_PASSWORD", "BELVO_TERMS_URL", "BELVO_ENV"]), - }, + ...feeds.filter((f) => f !== homeFeed), { id: "devlogin", kind: "more", title: "Skip sign-in while testing", @@ -258,7 +274,7 @@ export async function setupStatus(signedIn: boolean): Promise { cardReferralSection(), ]; - const required = [supabase, database, plaidSection]; + const required = [supabase, database, bankStep]; const gate = writeAllowedBasics(); return { sections: [...required, aiSection, ...more], ready: required.every((s) => s.status === "done"), canWrite: gate.ok, writeNote: gate.reason }; }