diff --git a/src/app/(app)/settings/Settings.tsx b/src/app/(app)/settings/Settings.tsx
index e0854d0..244ebf7 100644
--- a/src/app/(app)/settings/Settings.tsx
+++ b/src/app/(app)/settings/Settings.tsx
@@ -2,7 +2,7 @@
import { Wrench, Bot, Check, CircleAlert, X, Database, Landmark, Link2, Palette, RefreshCw, SlidersHorizontal, User, type LucideIcon } from "lucide-react";
import Link from "next/link";
-import { ClearTestData, RemoveTest } from "@/components/ClearTestData";
+import { ClearMyData, ClearTestData, RemoveTest } from "@/components/ClearTestData";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import { modelOptions, saveChoice } from "@/components/Assistant";
@@ -65,7 +65,7 @@ export function Settings({ signedIn, local, folder, repo, email, profile, mode,
else setChecking(false);
const fromHash = () => {
const h = location.hash.slice(1) as Group;
- if (NAV.some((n) => n.id === h) && (local || !SERVER.includes(h) || h === "banks")) setGroup(h);
+ if (NAV.some((n) => n.id === h) && (local || !SERVER.includes(h) || h === "banks" || h === "database")) setGroup(h);
};
fromHash();
addEventListener("hashchange", fromHash);
@@ -77,7 +77,7 @@ export function Settings({ signedIn, local, folder, repo, email, profile, mode,
if (local && group === "banks") load();
}, [group, local, load]);
- const nav = local ? NAV : NAV.filter((n) => !SERVER.includes(n.id) || n.id === "banks");
+ 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 flagged = (g: Group) => (data?.sections ?? []).some((s) => groupOf(s) === g && attention(s));
const here = NAV.find((n) => n.id === group)!;
@@ -125,6 +125,11 @@ export function Settings({ signedIn, local, folder, repo, email, profile, mode,
)}
{group === "improve" && }
+ {group === "database" && (
+
+
+
+ )}
{group === "ai" && }
{group === "ai" && }
{!local && (SERVER.includes(group) || group === "ai") && (
diff --git a/src/app/api/clear-data/route.ts b/src/app/api/clear-data/route.ts
new file mode 100644
index 0000000..918229e
--- /dev/null
+++ b/src/app/api/clear-data/route.ts
@@ -0,0 +1,36 @@
+import { NextResponse } from "next/server";
+import { revokeItem } from "@/lib/plaid";
+import { sameOrigin } from "@/lib/setup";
+import { createAdminClient } from "@/utils/supabase/admin";
+import { createClient } from "@/utils/supabase/server";
+
+// Settings, Database, "Clear my data": the signed-in user's money data, and nobody else's. Bank connections are revoked
+// at Plaid first, then deleted (accounts, transactions, bills and holdings cascade). Sign-in, profile answers, categories
+// and the AI connection stay, so they can link again or use a test bank straight away.
+const TABLES = ["accounts", "transactions", "recurring", "budgets", "rules", "plans", "checkins", "chat_threads", "bookmarks"];
+
+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 { confirm } = (await request.json().catch(() => ({}))) as { confirm?: string };
+ if (confirm !== "clear") return NextResponse.json({ error: "Not confirmed" }, { status: 400 });
+
+ const db = createAdminClient();
+ const { data: items } = await db.from("plaid_items").select("id, access_token, provider, institution_name").eq("user_id", user.id);
+ const stuck: string[] = [];
+ for (const item of items ?? []) {
+ if (!(await revokeItem(item)).ok) { stuck.push(item.institution_name ?? "A bank"); continue; }
+ await db.from("plaid_items").delete().eq("id", item.id);
+ }
+ // Manual accounts and anything left over. A bank Plaid wouldn't let go of keeps its data, so it can be tried again.
+ if (!stuck.length) for (const t of TABLES) {
+ const { error } = await db.from(t).delete().eq("user_id", user.id);
+ if (error) {
+ console.error(`[broke] clear ${t}:`, error.message);
+ return NextResponse.json({ error: "Couldn't clear everything. Try again." }, { status: 500 });
+ }
+ }
+ if (stuck.length) return NextResponse.json({ error: `Plaid couldn't disconnect ${stuck.join(", ")}. Try again in a moment.` }, { status: 502 });
+ return NextResponse.json({ ok: true });
+}
diff --git a/src/app/api/plaid/remove/route.ts b/src/app/api/plaid/remove/route.ts
index 7f91af5..97619be 100644
--- a/src/app/api/plaid/remove/route.ts
+++ b/src/app/api/plaid/remove/route.ts
@@ -1,5 +1,5 @@
import { NextResponse } from "next/server";
-import { plaid, plaidError } from "@/lib/plaid";
+import { revokeItem } from "@/lib/plaid";
import { createAdminClient } from "@/utils/supabase/admin";
import { createClient } from "@/utils/supabase/server";
@@ -14,19 +14,7 @@ export async function POST(request: Request) {
const { data: item } = itemId ? await db.from("plaid_items").select("id, access_token, provider").eq("id", itemId).eq("user_id", user.id).maybeSingle() : { data: null };
if (!item) return NextResponse.json({ error: "Connection not found" }, { status: 404 });
- // Akahu personal-app tokens belong to the server owner: removing here only forgets the connection in broke.
- // A test (sandbox) connection can't be revoked from live mode; Plaid's sandbox forgets it anyway.
- const testInLive = item.access_token?.startsWith("access-sandbox-") && process.env.PLAID_ENV !== "sandbox";
- if (item.provider === "plaid" && !testInLive) try {
- await plaid.itemRemove({ access_token: item.access_token! });
- } catch (e) {
- const err = plaidError(e);
- // Already gone at Plaid: still remove it here.
- if (err.code !== "ITEM_NOT_FOUND" && err.code !== "INVALID_ACCESS_TOKEN") {
- console.error("[broke] item remove:", err);
- return NextResponse.json({ error: "Plaid couldn't remove this connection. Try again in a moment." }, { status: 502 });
- }
- }
+ if (!(await revokeItem(item)).ok) return NextResponse.json({ error: "Plaid couldn't remove this connection. Try again in a moment." }, { status: 502 });
const { error } = await db.from("plaid_items").delete().eq("id", item.id);
if (error) return NextResponse.json({ error: "Couldn't remove this connection." }, { status: 500 });
return NextResponse.json({ ok: true });
diff --git a/src/components/ClearTestData.tsx b/src/components/ClearTestData.tsx
index 97cdcd0..8d673c2 100644
--- a/src/components/ClearTestData.tsx
+++ b/src/components/ClearTestData.tsx
@@ -92,3 +92,38 @@ export function ClearTestData({ items }: { items: { id: string; name: string }[]
);
}
+
+// Settings, Database: everything broke holds about your money, for your account only. Two presses, so it can't happen by accident.
+export function ClearMyData() {
+ const router = useRouter();
+ const [confirm, setConfirm] = useState(false);
+ const [state, setState] = useState<"idle" | "busy" | "done">("idle");
+ const [err, setErr] = useState("");
+ async function clear() {
+ setState("busy");
+ setErr("");
+ const res = await fetch("/api/clear-data", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ confirm: "clear" }) }).catch(() => null);
+ if (res?.ok) {
+ setState("done");
+ router.refresh();
+ } else {
+ setState("idle");
+ setErr(((await res?.json().catch(() => null)) as { error?: string } | null)?.error ?? "Couldn't clear your data. Try again.");
+ }
+ }
+ if (state === "done") return
Cleared. Link a bank, or use a test bank, from Accounts.
;
+ return (
+
+ {confirm ? (
+
+ Disconnect every bank and delete all of it? This can't be undone.
+
+
+
+ ) : (
+
+ )}
+ {err &&
{err}
}
+
+ );
+}
diff --git a/src/lib/plaid.ts b/src/lib/plaid.ts
index e6b2840..6d3a301 100644
--- a/src/lib/plaid.ts
+++ b/src/lib/plaid.ts
@@ -44,3 +44,19 @@ export function plaidError(e: unknown): { code: string; message: string } {
if (typeof code === "string" && code.startsWith("AKAHU_") && e instanceof Error) return { code, message: e.message };
return { code: "ERROR", message: e instanceof Error ? e.message : "Plaid request failed" };
}
+
+/** Revokes a bank connection at Plaid. Akahu tokens belong to the server owner, and a test connection can't be revoked
+ * 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 };
+ try {
+ await plaid.itemRemove({ access_token: item.access_token });
+ return { ok: true as const };
+ } catch (e) {
+ const err = plaidError(e);
+ if (err.code === "ITEM_NOT_FOUND" || err.code === "INVALID_ACCESS_TOKEN") return { ok: true as const };
+ console.error("[broke] item remove:", err);
+ return { ok: false as const };
+ }
+}