From 1c58977596df66085ed62f48e4dc1a16910f6cc8 Mon Sep 17 00:00:00 2001 From: Marco Sadjadi Date: Mon, 25 May 2026 17:46:36 +0200 Subject: [PATCH] feat: user menu + profile page + in-app subscription management MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit User-facing identity: - UserMenu component in dashboard header: avatar (deterministic colour from email hash), email + name, current plan badge, dropdown to Profile / Billing / Support / Your data / (Admin panel if isAdmin) / Sign out - /settings/profile: editable display name; email + phone shown read-only (changing them requires support ticket — magic-link flow assumed) - GET + PATCH /v1/account/profile In-app subscription management (no more Stripe Portal redirect for the common flows — cancellation, plan switch, invoice viewing all in-app): - Billing status now combines DB state with a live Stripe lookup of the subscription details + last 5 invoices. Single roundtrip. - POST /v1/billing/cancel → schedules cancel_at_period_end - POST /v1/billing/reactivate → undo scheduled cancel - POST /v1/billing/change-plan → prorated swap between any tier+cycle - /settings/billing rewritten: current plan card with renew/cancel date, big cancel button + reactivate flow, plan-switcher grid, invoice list with PDF + hosted-invoice links - Stripe portal still linked at the bottom as the escape hatch for rare actions (payment-method update, address change). New-subscription Checkout still uses Stripe-hosted Checkout (industry standard for PCI). Stripe SDK v22 / API 2024-09 fix: current_period_end moved to subscription items; updated read paths accordingly. Co-Authored-By: Claude Opus 4.7 (1M context) --- apps/api/src/routes/account.ts | 45 ++ apps/api/src/routes/billing.ts | 161 ++++++- apps/web/app/(dashboard)/layout.tsx | 16 +- .../app/(dashboard)/settings/billing/page.tsx | 392 ++++++++++++++---- .../app/(dashboard)/settings/profile/page.tsx | 140 +++++++ apps/web/components/user-menu.tsx | 190 +++++++++ 6 files changed, 856 insertions(+), 88 deletions(-) create mode 100644 apps/web/app/(dashboard)/settings/profile/page.tsx create mode 100644 apps/web/components/user-menu.tsx diff --git a/apps/api/src/routes/account.ts b/apps/api/src/routes/account.ts index 2019a4f..4474a2f 100644 --- a/apps/api/src/routes/account.ts +++ b/apps/api/src/routes/account.ts @@ -12,12 +12,57 @@ import { users, } from '@bmm/db'; import type { FastifyInstance } from 'fastify'; +import { z } from 'zod'; import { audit } from '../lib/audit.js'; import { requireAuth } from '../plugins/session.js'; const db = createDb(); export async function accountRoutes(app: FastifyInstance): Promise { + // ─── Profile: read + update ─────────────────────────────────────────── + app.get('/v1/account/profile', { preHandler: requireAuth }, async (req, reply) => { + const user = req.user!; + const [row] = await db + .select({ + id: users.id, + email: users.email, + name: users.name, + phone: users.phone, + isAdmin: users.isAdmin, + createdAt: users.createdAt, + }) + .from(users) + .where(eq(users.id, user.userId)) + .limit(1); + if (!row) return reply.code(404).send({ error: 'user_not_found' }); + return reply.send({ profile: row }); + }); + + app.patch('/v1/account/profile', { preHandler: requireAuth }, async (req, reply) => { + const user = req.user!; + const Body = z.object({ + name: z.string().min(1).max(128).optional(), + }); + const parsed = Body.safeParse(req.body); + if (!parsed.success) return reply.code(400).send({ error: 'invalid_input' }); + if (!parsed.data.name) return reply.send({ ok: true, changed: false }); + + await db + .update(users) + .set({ name: parsed.data.name }) + .where(eq(users.id, user.userId)); + + await audit({ + orgId: user.orgId, + userId: user.userId, + action: 'account.profile_updated', + resourceType: 'user', + ipAddress: req.ip, + }); + + return reply.send({ ok: true, changed: true }); + }); + /** * GDPR Art. 15 / Swiss DSG Art. 25 — right of access. Returns every record * we hold that belongs to the calling user. Excludes hashed passwords, diff --git a/apps/api/src/routes/billing.ts b/apps/api/src/routes/billing.ts index 9f0f450..d7af1a4 100644 --- a/apps/api/src/routes/billing.ts +++ b/apps/api/src/routes/billing.ts @@ -108,6 +108,9 @@ export async function billingRoutes(app: FastifyInstance): Promise { }); // ─── Billing status — drives the /settings/billing UI ──────────────────── + // Combines our DB state (plan, suspension) with a live Stripe lookup of the + // subscription + recent invoices, so the page can render cancel buttons + + // invoice links inline without a second round-trip. app.get('/v1/billing/status', { preHandler: requireAuth }, async (req, reply) => { const user = req.user!; const [org] = await db @@ -122,13 +125,167 @@ export async function billingRoutes(app: FastifyInstance): Promise { .where(eq(organizations.id, user.orgId)) .limit(1); if (!org) return reply.code(404).send({ error: 'org_not_found' }); - return reply.send({ + + const base = { plan: org.plan, hasCustomer: Boolean(org.stripeCustomerId), hasSubscription: Boolean(org.stripeSubscriptionId), suspended: org.suspended, suspendedReason: org.suspendedReason, - }); + }; + + if (!stripe || !org.stripeSubscriptionId || !org.stripeCustomerId) { + return reply.send(base); + } + + try { + const [sub, invoices] = await Promise.all([ + stripe.subscriptions.retrieve(org.stripeSubscriptionId), + stripe.invoices.list({ customer: org.stripeCustomerId, limit: 5 }), + ]); + const item = sub.items.data[0]; + const price = item?.price; + // Stripe v2024-09 moved period boundaries onto subscription items; + // for our single-item subs they're equivalent to the old sub-level field. + const currentPeriodEnd = item?.current_period_end ?? 0; + return reply.send({ + ...base, + subscription: { + id: sub.id, + status: sub.status, + currentPeriodEnd, + cancelAtPeriodEnd: sub.cancel_at_period_end, + priceId: price?.id ?? null, + amount: price?.unit_amount ?? null, + currency: price?.currency ?? null, + interval: price?.recurring?.interval ?? null, + }, + invoices: invoices.data.map((inv) => ({ + id: inv.id, + number: inv.number, + status: inv.status, + amountPaid: inv.amount_paid, + currency: inv.currency, + created: inv.created, + pdfUrl: inv.invoice_pdf, + hostedUrl: inv.hosted_invoice_url, + })), + }); + } catch (err) { + app.log.warn({ err }, 'stripe status fetch failed — returning db-only'); + return reply.send({ ...base, _stripeError: true }); + } + }); + + // ─── In-app cancellation (no portal redirect) ──────────────────────────── + // Schedules cancellation at period end — user keeps paid features until the + // billing date already paid for, and Stripe automatically deletes the sub + // after that. The webhook handler converts that to plan='hobby'. + app.post('/v1/billing/cancel', { preHandler: requireAuth }, async (req, reply) => { + if (!stripe) return reply.code(503).send({ error: 'stripe_not_configured' }); + const user = req.user!; + const [org] = await db + .select({ stripeSubscriptionId: organizations.stripeSubscriptionId }) + .from(organizations) + .where(eq(organizations.id, user.orgId)) + .limit(1); + if (!org?.stripeSubscriptionId) { + return reply.code(409).send({ error: 'no_active_subscription' }); + } + try { + const sub = await stripe.subscriptions.update(org.stripeSubscriptionId, { + cancel_at_period_end: true, + }); + const cancelAt = sub.items.data[0]?.current_period_end ?? null; + await audit({ + orgId: user.orgId, + userId: user.userId, + action: 'billing.cancel_scheduled', + resourceType: 'subscription', + resourceId: org.stripeSubscriptionId, + metadata: { cancelAt }, + ipAddress: req.ip, + }); + return reply.send({ ok: true, cancelAt }); + } catch (err) { + app.log.error({ err }, 'cancel failed'); + return reply.code(502).send({ error: 'cancel_failed' }); + } + }); + + // ─── Reactivate (undo scheduled cancellation) ──────────────────────────── + app.post('/v1/billing/reactivate', { preHandler: requireAuth }, async (req, reply) => { + if (!stripe) return reply.code(503).send({ error: 'stripe_not_configured' }); + const user = req.user!; + const [org] = await db + .select({ stripeSubscriptionId: organizations.stripeSubscriptionId }) + .from(organizations) + .where(eq(organizations.id, user.orgId)) + .limit(1); + if (!org?.stripeSubscriptionId) { + return reply.code(409).send({ error: 'no_active_subscription' }); + } + try { + await stripe.subscriptions.update(org.stripeSubscriptionId, { + cancel_at_period_end: false, + }); + await audit({ + orgId: user.orgId, + userId: user.userId, + action: 'billing.reactivated', + resourceType: 'subscription', + resourceId: org.stripeSubscriptionId, + ipAddress: req.ip, + }); + return reply.send({ ok: true }); + } catch (err) { + app.log.error({ err }, 'reactivate failed'); + return reply.code(502).send({ error: 'reactivate_failed' }); + } + }); + + // ─── In-app plan change (upgrade/downgrade between Pro/Team monthly/yearly) + app.post('/v1/billing/change-plan', { preHandler: requireAuth }, async (req, reply) => { + if (!stripe) return reply.code(503).send({ error: 'stripe_not_configured' }); + const user = req.user!; + const parsed = TierBody.safeParse(req.body); + if (!parsed.success) return reply.code(400).send({ error: 'invalid_input' }); + + const newPriceId = priceIdForTier(parsed.data.tier as PriceTier); + if (!newPriceId) { + return reply.code(503).send({ error: 'price_not_configured', tier: parsed.data.tier }); + } + + const [org] = await db + .select({ stripeSubscriptionId: organizations.stripeSubscriptionId }) + .from(organizations) + .where(eq(organizations.id, user.orgId)) + .limit(1); + if (!org?.stripeSubscriptionId) { + return reply.code(409).send({ error: 'no_active_subscription' }); + } + try { + const current = await stripe.subscriptions.retrieve(org.stripeSubscriptionId); + const itemId = current.items.data[0]?.id; + if (!itemId) return reply.code(500).send({ error: 'subscription_item_missing' }); + await stripe.subscriptions.update(org.stripeSubscriptionId, { + items: [{ id: itemId, price: newPriceId }], + proration_behavior: 'create_prorations', + }); + await audit({ + orgId: user.orgId, + userId: user.userId, + action: 'billing.plan_changed', + resourceType: 'subscription', + resourceId: org.stripeSubscriptionId, + metadata: { tier: parsed.data.tier }, + ipAddress: req.ip, + }); + return reply.send({ ok: true }); + } catch (err) { + app.log.error({ err }, 'plan change failed'); + return reply.code(502).send({ error: 'plan_change_failed' }); + } }); // ─── Webhook ───────────────────────────────────────────────────────────── diff --git a/apps/web/app/(dashboard)/layout.tsx b/apps/web/app/(dashboard)/layout.tsx index c14f764..3a8becd 100644 --- a/apps/web/app/(dashboard)/layout.tsx +++ b/apps/web/app/(dashboard)/layout.tsx @@ -1,6 +1,7 @@ import { CookieBanner } from '@/components/cookie-banner'; import { Logo } from '@/components/logo'; import { MobileActionBar } from '@/components/mobile-action-bar'; +import { UserMenu } from '@/components/user-menu'; import { FileClock, LayoutGrid, Package, Server, Settings } from 'lucide-react'; import Link from 'next/link'; @@ -29,12 +30,15 @@ export default function DashboardLayout({ children }: { children: React.ReactNod - - + New server - +
+ + + New server + + +
{children}
diff --git a/apps/web/app/(dashboard)/settings/billing/page.tsx b/apps/web/app/(dashboard)/settings/billing/page.tsx index 5bb29a4..a388a64 100644 --- a/apps/web/app/(dashboard)/settings/billing/page.tsx +++ b/apps/web/app/(dashboard)/settings/billing/page.tsx @@ -10,12 +10,37 @@ import { Suspense, useCallback, useEffect, useState } from 'react'; type Plan = 'hobby' | 'pro' | 'team' | 'enterprise'; type Tier = 'pro_monthly' | 'pro_yearly' | 'team_monthly' | 'team_yearly'; +interface SubscriptionInfo { + id: string; + status: string; + currentPeriodEnd: number; + cancelAtPeriodEnd: boolean; + priceId: string | null; + amount: number | null; + currency: string | null; + interval: string | null; +} + +interface Invoice { + id: string; + number: string | null; + status: string | null; + amountPaid: number; + currency: string; + created: number; + pdfUrl: string | null; + hostedUrl: string | null; +} + interface BillingStatus { plan: Plan; hasCustomer: boolean; hasSubscription: boolean; suspended: boolean; suspendedReason: string | null; + subscription?: SubscriptionInfo; + invoices?: Invoice[]; + _stripeError?: boolean; } const PLAN_LABEL: Record = { @@ -25,6 +50,14 @@ const PLAN_LABEL: Record = { enterprise: 'Enterprise', }; +function formatMoney(amount: number | null, currency: string | null): string { + if (amount === null || currency === null) return '—'; + return new Intl.NumberFormat(undefined, { + style: 'currency', + currency: currency.toUpperCase(), + }).format(amount / 100); +} + function BillingInner() { const router = useRouter(); const searchParams = useSearchParams(); @@ -50,8 +83,6 @@ function BillingInner() { loadStatus(); }, [loadStatus]); - // Came back from Stripe Checkout? Poll briefly — the webhook usually arrives - // within a couple seconds and flips the plan. useEffect(() => { if (!justSubscribed) return; let tries = 0; @@ -63,39 +94,13 @@ function BillingInner() { return () => clearInterval(id); }, [justSubscribed, loadStatus]); - const startCheckout = useCallback( - async (tier: Tier) => { - setBusy(tier); - setError(null); - try { - const res = await apiFetch<{ url: string }>('/v1/billing/checkout-session', { - method: 'POST', - body: JSON.stringify({ tier }), - }); - window.location.href = res.url; - } catch (e) { - setBusy(null); - const detail = (e as { detail?: { detail?: string; error?: string } }).detail; - setError(detail?.detail ?? detail?.error ?? (e as Error).message); - } - }, - [], - ); - - // Auto-fire checkout when the user lands here from the pricing page CTA. - useEffect(() => { - if (!autoUpgradeTier || !status) return; - if (status.hasSubscription) return; // already paying — don't redirect - void startCheckout(autoUpgradeTier); - }, [autoUpgradeTier, status, startCheckout]); - - async function openPortal() { - setBusy('portal'); + const startCheckout = useCallback(async (tier: Tier) => { + setBusy(tier); setError(null); try { - const res = await apiFetch<{ url: string }>('/v1/billing/portal', { + const res = await apiFetch<{ url: string }>('/v1/billing/checkout-session', { method: 'POST', - body: '{}', + body: JSON.stringify({ tier }), }); window.location.href = res.url; } catch (e) { @@ -103,75 +108,171 @@ function BillingInner() { const detail = (e as { detail?: { detail?: string; error?: string } }).detail; setError(detail?.detail ?? detail?.error ?? (e as Error).message); } + }, []); + + useEffect(() => { + if (!autoUpgradeTier || !status) return; + if (status.hasSubscription) return; + void startCheckout(autoUpgradeTier); + }, [autoUpgradeTier, status, startCheckout]); + + async function changePlan(tier: Tier) { + if (!confirm(`Switch to ${tier.replace('_', ' ')}? Prorated charges apply immediately.`)) return; + setBusy(`change-${tier}`); + setError(null); + try { + await apiFetch('/v1/billing/change-plan', { + method: 'POST', + body: JSON.stringify({ tier }), + }); + // Webhook will update plan asynchronously; poll briefly. + let tries = 0; + const id = setInterval(() => { + tries += 1; + loadStatus(); + if (tries >= 6) clearInterval(id); + }, 1500); + } catch (e) { + const detail = (e as { detail?: { detail?: string; error?: string } }).detail; + setError(detail?.detail ?? detail?.error ?? (e as Error).message); + } finally { + setBusy(null); + } + } + + async function cancelSubscription() { + if (!confirm('Cancel subscription at the end of the current billing period?')) return; + setBusy('cancel'); + setError(null); + try { + await apiFetch('/v1/billing/cancel', { method: 'POST', body: '{}' }); + loadStatus(); + } catch (e) { + setError((e as Error).message); + } finally { + setBusy(null); + } + } + + async function reactivateSubscription() { + setBusy('reactivate'); + setError(null); + try { + await apiFetch('/v1/billing/reactivate', { method: 'POST', body: '{}' }); + loadStatus(); + } catch (e) { + setError((e as Error).message); + } finally { + setBusy(null); + } } if (!status && !error) { return (
-

Loading billing…

); } + const sub = status?.subscription; + const hasSub = Boolean(status?.hasSubscription && sub); + const planValue = status?.plan ?? 'hobby'; + const currentPlanIsPro = planValue === 'pro'; + const currentPlanIsTeam = planValue === 'team'; + return (

Billing

- Manage your subscription, payment method, and invoices. + Plan, renewal, invoices and cancellation — everything in-app.

{cancelledCheckout && ( -
- Checkout cancelled. No charge made. -
+ Checkout cancelled. No charge made. )} {justSubscribed && ( -
- Subscription active. Plan will update within a few seconds — refreshing… -
+ + Subscription active. Plan updates within a few seconds — refreshing… + )} {status?.suspended && ( -
- Subscription paused — {status.suspendedReason ?? 'payment issue'}. - Update your payment method below to restore access. Existing servers keep running. -
+ + Subscription paused — {status.suspendedReason ?? 'payment issue'}. New + servers + previews are blocked until payment succeeds; existing servers keep running. + )} - {error && ( -
- {error} -
+ {status?._stripeError && ( + + Live billing data temporarily unavailable — showing local state only. Try again in a + minute. + )} + {error && {error}} {status && (
-
+
Current plan
-
- {PLAN_LABEL[status.plan]} +
+ + {PLAN_LABEL[status.plan]} + + {sub?.amount !== null && sub?.amount !== undefined && ( + + {formatMoney(sub.amount, sub.currency)} / {sub.interval} + + )}
- {status.hasSubscription && ( - + {sub && ( +
+
+ {sub.cancelAtPeriodEnd ? 'Cancels' : 'Renews'} +
+
+ {new Date(sub.currentPeriodEnd * 1000).toLocaleDateString()} +
+
)}
- {!status.hasSubscription && ( -

- You're on the free tier. Upgrade below to unlock more servers, faster Claude - analysis and higher daily limits. -

+ + {hasSub && sub && ( +
+ {sub.cancelAtPeriodEnd ? ( + <> +

+ Scheduled to cancel on{' '} + + {new Date(sub.currentPeriodEnd * 1000).toLocaleDateString()} + + . You keep paid features until then. +

+ + + ) : ( + + )} +
)}
)} @@ -208,27 +309,136 @@ function BillingInner() { />

- Annual saves 2 months. VAT calculated automatically based on your billing address. Cancel - any time from the billing portal — service continues until end of period. -

-

- Need Enterprise (BYOC, SSO, EU-data-residency)?{' '} - - Contact sales - - . + Annual saves 2 months. VAT calculated automatically based on your billing address. + Cancel anytime from this page — service continues until end of period.

)} -
+ {status && status.hasSubscription && ( + <> +

Switch plan

+

+ Prorated immediately. The new amount is added to your next invoice. +

+
+ {!currentPlanIsPro && ( + changePlan('pro_monthly')} + busy={busy === 'change-pro_monthly'} + /> + )} + changePlan('pro_yearly')} + busy={busy === 'change-pro_yearly'} + /> + {!currentPlanIsTeam && ( + changePlan('team_monthly')} + busy={busy === 'change-team_monthly'} + /> + )} + changePlan('team_yearly')} + busy={busy === 'change-team_yearly'} + /> +
+ + )} + + {status?.invoices && status.invoices.length > 0 && ( + <> +

Invoices

+
+ {status.invoices.map((inv) => ( +
+
+
{inv.number ?? inv.id}
+
+ {new Date(inv.created * 1000).toLocaleDateString()} · {inv.status ?? 'unknown'} +
+
+
+ + {formatMoney(inv.amountPaid, inv.currency)} + + {inv.pdfUrl && ( + + PDF + + )} + {inv.hostedUrl && ( + + View → + + )} +
+
+ ))} +
+ + )} + +

+ Payment-method updates and other rare actions:{' '} + {' '} + ·{' '} - ← Compare all plans + compare plans -

+

+
+ ); +} + +function Alert({ + tone, + children, +}: { + tone: 'muted' | 'success' | 'warn' | 'error'; + children: React.ReactNode; +}) { + const cls = + tone === 'success' + ? 'border-emerald-500/30 bg-emerald-500/10' + : tone === 'warn' + ? 'border-amber-500/40 bg-amber-500/10' + : tone === 'error' + ? 'border-[--color-danger]/40 bg-[--color-danger]/10' + : 'border-[--color-border] bg-[--color-bg-subtle]'; + return ( +
+ {children}
); } @@ -290,6 +500,28 @@ function TierCard({ ); } +function PlanSwitch({ + label, + onClick, + busy, +}: { + label: string; + onClick: () => void; + busy: boolean; +}) { + return ( + + ); +} + export default function BillingPage() { return ( (null); + const [name, setName] = useState(''); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [saved, setSaved] = useState(false); + + function load() { + apiFetch<{ profile: Profile }>('/v1/account/profile') + .then((r) => { + setProfile(r.profile); + setName(r.profile.name ?? ''); + }) + .catch((e) => setError((e as Error).message)); + } + + useEffect(load, []); + + async function save(e: React.FormEvent) { + e.preventDefault(); + if (!profile) return; + setBusy(true); + setError(null); + setSaved(false); + try { + await apiFetch('/v1/account/profile', { + method: 'PATCH', + body: JSON.stringify({ name: name.trim() }), + }); + setSaved(true); + load(); + } catch (err) { + setError((err as Error).message); + } finally { + setBusy(false); + } + } + + if (!profile && !error) { + return ( +
+ +
+ ); + } + if (!profile) { + return ( +
+

{error}

+
+ ); + } + + return ( +
+

Profile

+

+ Personal details. Email and phone can't be changed self-service yet — open a{' '} + + support ticket + + {' '} + if you need it changed. +

+ +
+
+ + setName(e.target.value)} + maxLength={128} + placeholder="How should we address you?" + /> +
+ +
+ + + + +
+ + {error &&

{error}

} + {saved &&

Saved.

} + +
+ +
+
+ +
+ + Billing → + + + Support → + + + Your data → + +
+
+ ); +} + +function ReadField({ label, value, mono }: { label: string; value: string; mono?: boolean }) { + return ( +
+
{label}
+
{value}
+
+ ); +} diff --git a/apps/web/components/user-menu.tsx b/apps/web/components/user-menu.tsx new file mode 100644 index 0000000..a3258ba --- /dev/null +++ b/apps/web/components/user-menu.tsx @@ -0,0 +1,190 @@ +'use client'; + +import { apiFetch } from '@/lib/api'; +import { + ChevronDown, + CreditCard, + Download, + LifeBuoy, + LogOut, + ShieldAlert, + User as UserIcon, +} from 'lucide-react'; +import Link from 'next/link'; +import { useRouter } from 'next/navigation'; +import { useEffect, useRef, useState } from 'react'; + +interface MeUser { + userId: string; + email: string; + name: string | null; + plan?: 'hobby' | 'pro' | 'team' | 'enterprise'; + isAdmin?: boolean; +} + +const PLAN_LABEL: Record, string> = { + hobby: 'Hobby', + pro: 'Pro', + team: 'Team', + enterprise: 'Enterprise', +}; + +/** Pick a deterministic accent for the avatar based on the email. Keeps + * the avatar stable across sessions without needing an uploaded image. */ +function avatarShade(seed: string): string { + let hash = 0; + for (let i = 0; i < seed.length; i += 1) hash = (hash * 31 + seed.charCodeAt(i)) | 0; + const palette = [ + 'bg-indigo-500/30 text-indigo-200', + 'bg-emerald-500/30 text-emerald-200', + 'bg-rose-500/30 text-rose-200', + 'bg-amber-500/30 text-amber-200', + 'bg-sky-500/30 text-sky-200', + 'bg-fuchsia-500/30 text-fuchsia-200', + ]; + return palette[Math.abs(hash) % palette.length] ?? palette[0]!; +} + +export function UserMenu() { + const router = useRouter(); + const [user, setUser] = useState(null); + const [open, setOpen] = useState(false); + const wrapRef = useRef(null); + + useEffect(() => { + apiFetch<{ user: MeUser }>('/v1/auth/me') + .then((r) => setUser(r.user)) + .catch(() => setUser(null)); + }, []); + + // Click outside / Escape to close + useEffect(() => { + if (!open) return; + function onDocClick(e: MouseEvent) { + if (!wrapRef.current?.contains(e.target as Node)) setOpen(false); + } + function onKey(e: KeyboardEvent) { + if (e.key === 'Escape') setOpen(false); + } + document.addEventListener('mousedown', onDocClick); + document.addEventListener('keydown', onKey); + return () => { + document.removeEventListener('mousedown', onDocClick); + document.removeEventListener('keydown', onKey); + }; + }, [open]); + + async function logout() { + await apiFetch('/v1/auth/logout', { method: 'POST' }).catch(() => undefined); + router.push('/'); + } + + if (!user) return null; + + const label = user.name?.trim() || user.email; + const initial = (user.name?.trim() || user.email).charAt(0).toUpperCase(); + const shade = avatarShade(user.email); + + return ( +
+ + + {open && ( +
+
+
+ + {initial} + +
+
+ {label} +
+
+ {user.email} +
+
+
+ {user.plan && ( +
+ Plan + + {PLAN_LABEL[user.plan]} + +
+ )} +
+ + + +
+ +
+
+ )} +
+ ); +} + +function MenuLink({ + href, + icon: Icon, + label, + onClick, +}: { + href: string; + icon: React.ComponentType<{ size?: number }>; + label: string; + onClick: () => void; +}) { + return ( + + + {label} + + ); +}