feat: user menu + profile page + in-app subscription management
All checks were successful
Deploy to Production / deploy (push) Successful in 52s

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) <noreply@anthropic.com>
This commit is contained in:
Marco Sadjadi
2026-05-25 17:46:36 +02:00
parent 1b8f61df5f
commit 1c58977596
6 changed files with 856 additions and 88 deletions

View File

@@ -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<Plan, string> = {
@@ -25,6 +50,14 @@ const PLAN_LABEL: Record<Plan, string> = {
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 (
<div className="mx-auto max-w-3xl px-6 py-12 text-center">
<Loader2 className="mx-auto animate-spin text-[--color-fg-muted]" size={20} />
<p className="mt-3 text-[13px] text-[--color-fg-muted]">Loading billing</p>
</div>
);
}
const sub = status?.subscription;
const hasSub = Boolean(status?.hasSubscription && sub);
const planValue = status?.plan ?? 'hobby';
const currentPlanIsPro = planValue === 'pro';
const currentPlanIsTeam = planValue === 'team';
return (
<div className="mx-auto max-w-3xl px-6 py-10">
<div>
<h1 className="text-[22px] font-semibold tracking-tight">Billing</h1>
<p className="mt-1 text-[13px] text-[--color-fg-muted]">
Manage your subscription, payment method, and invoices.
Plan, renewal, invoices and cancellation everything in-app.
</p>
</div>
{cancelledCheckout && (
<div className="mt-4 rounded-md border border-[--color-border] bg-[--color-bg-subtle] px-3.5 py-2.5 text-[12.5px]">
Checkout cancelled. No charge made.
</div>
<Alert tone="muted">Checkout cancelled. No charge made.</Alert>
)}
{justSubscribed && (
<div className="mt-4 rounded-md border border-emerald-500/30 bg-emerald-500/10 px-3.5 py-2.5 text-[12.5px]">
Subscription active. Plan will update within a few seconds refreshing
</div>
<Alert tone="success">
Subscription active. Plan updates within a few seconds refreshing
</Alert>
)}
{status?.suspended && (
<div className="mt-4 rounded-md border border-amber-500/40 bg-amber-500/10 px-3.5 py-2.5 text-[12.5px]">
<strong>Subscription paused</strong> {status.suspendedReason ?? 'payment issue'}.
Update your payment method below to restore access. Existing servers keep running.
</div>
<Alert tone="warn">
<strong>Subscription paused</strong> {status.suspendedReason ?? 'payment issue'}. New
servers + previews are blocked until payment succeeds; existing servers keep running.
</Alert>
)}
{error && (
<div className="mt-4 rounded-md border border-[--color-danger]/40 bg-[--color-danger]/10 px-3.5 py-2.5 text-[12.5px] text-[--color-fg]">
{error}
</div>
{status?._stripeError && (
<Alert tone="warn">
Live billing data temporarily unavailable showing local state only. Try again in a
minute.
</Alert>
)}
{error && <Alert tone="error">{error}</Alert>}
{status && (
<div className="panel mt-6 p-5">
<div className="flex items-baseline justify-between">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<div className="text-[11px] uppercase tracking-wider text-[--color-fg-subtle]">
Current plan
</div>
<div className="mt-1 text-[20px] font-semibold tracking-tight">
{PLAN_LABEL[status.plan]}
<div className="mt-1 flex items-baseline gap-2">
<span className="text-[22px] font-semibold tracking-tight">
{PLAN_LABEL[status.plan]}
</span>
{sub?.amount !== null && sub?.amount !== undefined && (
<span className="text-[13px] text-[--color-fg-muted]">
{formatMoney(sub.amount, sub.currency)} / {sub.interval}
</span>
)}
</div>
</div>
{status.hasSubscription && (
<Button
variant="secondary"
size="md"
onClick={openPortal}
disabled={busy === 'portal'}
>
{busy === 'portal' ? 'Opening…' : 'Manage billing'}
</Button>
{sub && (
<div className="text-right text-[12px]">
<div className="text-[--color-fg-subtle]">
{sub.cancelAtPeriodEnd ? 'Cancels' : 'Renews'}
</div>
<div className="mt-0.5 mono text-[--color-fg]">
{new Date(sub.currentPeriodEnd * 1000).toLocaleDateString()}
</div>
</div>
)}
</div>
{!status.hasSubscription && (
<p className="mt-3 text-[12.5px] text-[--color-fg-muted]">
You&apos;re on the free tier. Upgrade below to unlock more servers, faster Claude
analysis and higher daily limits.
</p>
{hasSub && sub && (
<div className="mt-5 flex flex-wrap gap-2 border-t border-[--color-border] pt-4">
{sub.cancelAtPeriodEnd ? (
<>
<p className="w-full text-[12.5px] text-[--color-fg-muted]">
Scheduled to cancel on{' '}
<span className="mono text-[--color-fg]">
{new Date(sub.currentPeriodEnd * 1000).toLocaleDateString()}
</span>
. You keep paid features until then.
</p>
<Button
variant="primary"
size="md"
onClick={reactivateSubscription}
disabled={busy === 'reactivate'}
>
{busy === 'reactivate' ? 'Reactivating…' : 'Keep subscription'}
</Button>
</>
) : (
<Button
variant="ghost"
size="md"
onClick={cancelSubscription}
disabled={busy === 'cancel'}
>
{busy === 'cancel' ? 'Cancelling…' : 'Cancel subscription'}
</Button>
)}
</div>
)}
</div>
)}
@@ -208,27 +309,136 @@ function BillingInner() {
/>
</div>
<p className="mt-4 text-[12px] text-[--color-fg-subtle]">
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.
</p>
<p className="mt-2 text-[12px] text-[--color-fg-subtle]">
Need Enterprise (BYOC, SSO, EU-data-residency)?{' '}
<a
className="text-[--color-accent] hover:underline"
href="mailto:sales@buildmymcpserver.com"
>
Contact sales
</a>
.
Annual saves 2 months. VAT calculated automatically based on your billing address.
Cancel anytime from this page service continues until end of period.
</p>
</>
)}
<div className="mt-10 text-[12px] text-[--color-fg-subtle]">
{status && status.hasSubscription && (
<>
<h2 className="mt-10 text-[15px] font-semibold tracking-tight">Switch plan</h2>
<p className="mt-1 text-[12.5px] text-[--color-fg-muted]">
Prorated immediately. The new amount is added to your next invoice.
</p>
<div className="mt-3 grid gap-2 md:grid-cols-2">
{!currentPlanIsPro && (
<PlanSwitch
label="Pro — €49 / month"
onClick={() => changePlan('pro_monthly')}
busy={busy === 'change-pro_monthly'}
/>
)}
<PlanSwitch
label={currentPlanIsPro ? 'Pro — €490 / year (2 months free)' : 'Pro — yearly'}
onClick={() => changePlan('pro_yearly')}
busy={busy === 'change-pro_yearly'}
/>
{!currentPlanIsTeam && (
<PlanSwitch
label="Team — €199 / month"
onClick={() => changePlan('team_monthly')}
busy={busy === 'change-team_monthly'}
/>
)}
<PlanSwitch
label={currentPlanIsTeam ? 'Team — €1990 / year (2 months free)' : 'Team — yearly'}
onClick={() => changePlan('team_yearly')}
busy={busy === 'change-team_yearly'}
/>
</div>
</>
)}
{status?.invoices && status.invoices.length > 0 && (
<>
<h2 className="mt-10 text-[15px] font-semibold tracking-tight">Invoices</h2>
<div className="panel mt-3 divide-y divide-[--color-border]">
{status.invoices.map((inv) => (
<div key={inv.id} className="flex items-center justify-between px-4 py-3 text-[12.5px]">
<div>
<div className="mono text-[--color-fg]">{inv.number ?? inv.id}</div>
<div className="text-[11px] text-[--color-fg-subtle]">
{new Date(inv.created * 1000).toLocaleDateString()} · {inv.status ?? 'unknown'}
</div>
</div>
<div className="flex items-center gap-3">
<span className="mono text-[--color-fg]">
{formatMoney(inv.amountPaid, inv.currency)}
</span>
{inv.pdfUrl && (
<a
href={inv.pdfUrl}
target="_blank"
rel="noreferrer"
className="text-[11.5px] text-[--color-accent] hover:underline"
>
PDF
</a>
)}
{inv.hostedUrl && (
<a
href={inv.hostedUrl}
target="_blank"
rel="noreferrer"
className="text-[11.5px] text-[--color-fg-muted] hover:text-[--color-fg]"
>
View
</a>
)}
</div>
</div>
))}
</div>
</>
)}
<p className="mt-10 text-[12px] text-[--color-fg-subtle]">
Payment-method updates and other rare actions:{' '}
<button
type="button"
onClick={async () => {
try {
const r = await apiFetch<{ url: string }>('/v1/billing/portal', {
method: 'POST',
body: '{}',
});
window.location.href = r.url;
} catch {
setError('Portal could not open');
}
}}
className="text-[--color-accent] hover:underline"
>
open Stripe billing portal
</button>{' '}
·{' '}
<Link href="/pricing" className="hover:text-[--color-fg]">
Compare all plans
compare plans
</Link>
</div>
</p>
</div>
);
}
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 (
<div className={`mt-4 rounded-md border px-3.5 py-2.5 text-[12.5px] ${cls}`}>
{children}
</div>
);
}
@@ -290,6 +500,28 @@ function TierCard({
);
}
function PlanSwitch({
label,
onClick,
busy,
}: {
label: string;
onClick: () => void;
busy: boolean;
}) {
return (
<button
type="button"
onClick={onClick}
disabled={busy}
className="panel flex items-center justify-between p-3 text-left text-[12.5px] transition-colors hover:bg-[--color-bg-subtle] disabled:opacity-60"
>
<span className="text-[--color-fg]">{label}</span>
<span className="text-[--color-fg-muted]">{busy ? '…' : '→'}</span>
</button>
);
}
export default function BillingPage() {
return (
<Suspense

View File

@@ -0,0 +1,140 @@
'use client';
import { Input, Label } from '@/components/input';
import { Button } from '@/components/ui/button';
import { apiFetch } from '@/lib/api';
import { Loader2 } from 'lucide-react';
import Link from 'next/link';
import { useEffect, useState } from 'react';
interface Profile {
id: string;
email: string;
name: string | null;
phone: string | null;
isAdmin: boolean;
createdAt: string;
}
export default function ProfilePage() {
const [profile, setProfile] = useState<Profile | null>(null);
const [name, setName] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(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 (
<div className="mx-auto max-w-2xl px-6 py-12 text-center">
<Loader2 className="mx-auto animate-spin text-[--color-fg-muted]" size={20} />
</div>
);
}
if (!profile) {
return (
<div className="mx-auto max-w-2xl px-6 py-12">
<p className="text-[13px] text-[--color-danger]">{error}</p>
</div>
);
}
return (
<div className="mx-auto max-w-2xl px-6 py-10">
<h1 className="text-[22px] font-semibold tracking-tight">Profile</h1>
<p className="mt-1 text-[13px] text-[--color-fg-muted]">
Personal details. Email and phone can&apos;t be changed self-service yet open a{' '}
<Link href="/settings/support" className="text-[--color-accent] hover:underline">
support ticket
</Link>
{' '}
if you need it changed.
</p>
<form onSubmit={save} className="panel mt-6 space-y-4 p-5">
<div className="space-y-1.5">
<Label htmlFor="name">Display name</Label>
<Input
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
maxLength={128}
placeholder="How should we address you?"
/>
</div>
<div className="grid gap-3 md:grid-cols-2">
<ReadField label="Email" value={profile.email} mono />
<ReadField label="Phone" value={profile.phone ?? '—'} mono />
<ReadField label="Account created" value={new Date(profile.createdAt).toLocaleString()} />
<ReadField label="Role" value={profile.isAdmin ? 'Admin' : 'Member'} />
</div>
{error && <p className="text-[12.5px] text-[--color-danger]">{error}</p>}
{saved && <p className="text-[12.5px] text-emerald-300">Saved.</p>}
<div className="flex justify-end">
<Button
variant="primary"
size="md"
type="submit"
disabled={busy || name.trim() === (profile.name ?? '')}
>
{busy ? 'Saving…' : 'Save changes'}
</Button>
</div>
</form>
<div className="mt-8 grid gap-3 sm:grid-cols-3 text-[12px]">
<Link href="/settings/billing" className="panel p-3 text-[--color-fg-muted] transition-colors hover:text-[--color-fg]">
Billing
</Link>
<Link href="/settings/support" className="panel p-3 text-[--color-fg-muted] transition-colors hover:text-[--color-fg]">
Support
</Link>
<Link href="/settings/account" className="panel p-3 text-[--color-fg-muted] transition-colors hover:text-[--color-fg]">
Your data
</Link>
</div>
</div>
);
}
function ReadField({ label, value, mono }: { label: string; value: string; mono?: boolean }) {
return (
<div>
<div className="text-[11px] uppercase tracking-wider text-[--color-fg-subtle]">{label}</div>
<div className={`mt-1 text-[13px] text-[--color-fg] ${mono ? 'mono' : ''}`}>{value}</div>
</div>
);
}