Clear my data on the Database page
Disconnects every bank at Plaid and deletes the signed-in user's money data. Sign-in, profile and AI connection stay. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9c4bf6198e
commit
f2d7f36017
5 files changed
+97
-17
No files matched your search
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import { Wrench, Bot, Check, CircleAlert, X, Database, Landmark, Link2, Palette, RefreshCw, SlidersHorizontal, User, type LucideIcon } from "lucide-react";
|
import { Wrench, Bot, Check, CircleAlert, X, Database, Landmark, Link2, Palette, RefreshCw, SlidersHorizontal, User, type LucideIcon } from "lucide-react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { ClearTestData, RemoveTest } from "@/components/ClearTestData";
|
import { ClearMyData, ClearTestData, RemoveTest } from "@/components/ClearTestData";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useCallback, useEffect, useState } from "react";
|
import { useCallback, useEffect, useState } from "react";
|
||||||
import { modelOptions, saveChoice } from "@/components/Assistant";
|
import { modelOptions, saveChoice } from "@/components/Assistant";
|
||||||
@@ -65,7 +65,7 @@ export function Settings({ signedIn, local, folder, repo, email, profile, mode,
|
|||||||
else setChecking(false);
|
else setChecking(false);
|
||||||
const fromHash = () => {
|
const fromHash = () => {
|
||||||
const h = location.hash.slice(1) as Group;
|
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();
|
fromHash();
|
||||||
addEventListener("hashchange", fromHash);
|
addEventListener("hashchange", fromHash);
|
||||||
@@ -77,7 +77,7 @@ export function Settings({ signedIn, local, folder, repo, email, profile, mode,
|
|||||||
if (local && group === "banks") load();
|
if (local && group === "banks") load();
|
||||||
}, [group, local, 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 sections = (data?.sections ?? []).filter((s) => groupOf(s) === group);
|
||||||
const flagged = (g: Group) => (data?.sections ?? []).some((s) => groupOf(s) === g && attention(s));
|
const flagged = (g: Group) => (data?.sections ?? []).some((s) => groupOf(s) === g && attention(s));
|
||||||
const here = NAV.find((n) => n.id === group)!;
|
const here = NAV.find((n) => n.id === group)!;
|
||||||
@@ -125,6 +125,11 @@ export function Settings({ signedIn, local, folder, repo, email, profile, mode,
|
|||||||
</Card>
|
</Card>
|
||||||
)}
|
)}
|
||||||
{group === "improve" && <ImproveCard folder={folder} repo={repo} />}
|
{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.">
|
||||||
|
<ClearMyData />
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
{group === "ai" && <AiDataCard initial={aiMode} />}
|
{group === "ai" && <AiDataCard initial={aiMode} />}
|
||||||
{group === "ai" && <ModelCard />}
|
{group === "ai" && <ModelCard />}
|
||||||
{!local && (SERVER.includes(group) || group === "ai") && (
|
{!local && (SERVER.includes(group) || group === "ai") && (
|
||||||
|
|||||||
@@ -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 });
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { plaid, plaidError } from "@/lib/plaid";
|
import { revokeItem } from "@/lib/plaid";
|
||||||
import { createAdminClient } from "@/utils/supabase/admin";
|
import { createAdminClient } from "@/utils/supabase/admin";
|
||||||
import { createClient } from "@/utils/supabase/server";
|
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 };
|
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 });
|
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.
|
if (!(await revokeItem(item)).ok) return NextResponse.json({ error: "Plaid couldn't remove this connection. Try again in a moment." }, { status: 502 });
|
||||||
// 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 });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const { error } = await db.from("plaid_items").delete().eq("id", item.id);
|
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 });
|
if (error) return NextResponse.json({ error: "Couldn't remove this connection." }, { status: 500 });
|
||||||
return NextResponse.json({ ok: true });
|
return NextResponse.json({ ok: true });
|
||||||
|
|||||||
@@ -92,3 +92,38 @@ export function ClearTestData({ items }: { items: { id: string; name: string }[]
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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 <p className="text-sm text-good inline-flex items-center gap-1"><Check size={13} /> Cleared. Link a bank, or use a test bank, from Accounts.</p>;
|
||||||
|
return (
|
||||||
|
<div className="space-y-2 text-sm">
|
||||||
|
{confirm ? (
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<span className="text-muted">Disconnect every bank and delete all of it? This can't be undone.</span>
|
||||||
|
<button className="btn text-bad" disabled={state === "busy"} onClick={clear}>{state === "busy" ? "Clearing..." : "Clear my data"}</button>
|
||||||
|
<button className="text-muted hover:text-ink" disabled={state === "busy"} onClick={() => setConfirm(false)}>Cancel</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<button className="btn" onClick={() => setConfirm(true)}>Clear my data</button>
|
||||||
|
)}
|
||||||
|
{err && <p className="text-bad">{err}</p>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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 };
|
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" };
|
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 };
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user