clipwright/dashboard/src/components/AccountPage.jsx
juancarlos.cavero 5b5d3d2306 fix(billing): stop stranding customers whose payment failed
A declined card left the account in a state with no way out. `past_due` grants
no minutes, so the metering layer resolved the user to the free plan — which
meant /api/me reported status=null, the account page swapped "Manage billing"
for "Upgrade" (hiding the only button that fixes a card), and the checkout guard
then rejected the upgrade with a 409 that every call site swallowed into a
generic "Could not start checkout." Silently free, unwarned, unable to pay.

Found on 25-jul-2026 in prod: 14 subscriptions in this state, all first charges
that failed when the (now retired) 3-day trial ended. The trial is gone, but the
trap is not — a renewal failure or an abandoned 3DS payment reproduces it.

- metering: split `_subscription_row` (raw) from `_active_subscription`
  (entitling), and expose both on the balance. Entitlement logic is unchanged.
- /api/me: report status/interval from a row needing attention when no
  subscription entitles, plus `has_billing_account` to route the portal button.
- checkout: drop `incomplete` from the blocking states. Stripe collects nothing
  on it and expires it within 24h, so blocking only stopped the user's retry.
  Give past_due/unpaid a message that names the problem and the fix.
- account page: explain the failed payment inline with a link to the portal
  instead of showing a bare "past_due" chip, and keep the portal reachable for
  any Stripe relationship, live or broken.
- api client: throw a typed ApiError carrying the server's detail so callers
  stop replacing real, actionable messages with generic copy.

Verified against a real DB: past_due stays blocked but visible and fixable,
incomplete can retry, canceled is silent and can subscribe again.
2026-07-25 15:14:15 +02:00

202 lines
9.4 KiB
JavaScript

import React, { useState, useEffect, useCallback } from 'react';
import { Loader2, CreditCard, LogOut, Plus } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { apiJson } from '../lib/api';
import { track } from '../lib/analytics';
const fmt1 = (n) => Math.round((n || 0) * 10) / 10;
// Mirrors cloud/config.BILLING_ATTENTION_STATES: states where the customer has
// to do something (fix a card, finish a payment) before minutes come back.
const PAYMENT_ISSUE_STATES = ['past_due', 'unpaid', 'incomplete', 'paused'];
// Account/billing page: plan, usage meter, top-ups, manage billing, logout.
export default function AccountPage() {
const { me, refreshMe, logout, plan, minutes } = useAuth();
const [busy, setBusy] = useState(false);
const [topups, setTopups] = useState([]);
const [activating, setActivating] = useState(false);
// After returning from Checkout the webhook may lag — poll /api/me briefly.
useEffect(() => {
const hash = window.location.hash || '';
if (!hash.includes('checkout=success')) return;
setActivating(true);
let tries = 0;
const t = setInterval(async () => {
tries += 1;
const data = await refreshMe();
// 'free' is the default plan for any signed-in account, so it does NOT
// mean the checkout landed — keep polling until the webhook writes the
// paid subscription.
const paidPlan = data?.plan && data.plan !== 'free';
if (paidPlan || tries > 15) {
clearInterval(t);
setActivating(false);
// Fire the Subscribed conversion goal. A pending-checkout stash (set in
// PricingSection) carries the plan price, so we can attach real revenue;
// top-ups don't set it, so they never count as a subscription.
if (paidPlan) {
let pending = null;
try { pending = JSON.parse(localStorage.getItem('os_pending_checkout') || 'null'); } catch (_) { /* ignore */ }
if (pending) {
// This Plausible is Community Edition, which has no revenue goals —
// so the price rides along as plain props (value_usd / plan) that CE
// can break the goal down by. The exact MRR still lives in Stripe.
track('Subscribed', {
props: {
plan: pending.plan,
interval: pending.interval,
value_usd: Math.round((pending.amount || 0) / 100),
},
});
try { localStorage.removeItem('os_pending_checkout'); } catch (_) { /* ignore */ }
}
}
// First time a plan activates, take the user straight to connect their
// socials. Guard with a flag so top-up checkouts don't re-trigger it.
if (paidPlan && !localStorage.getItem('os_socials_prompted')) {
localStorage.setItem('os_socials_prompted', '1');
try {
const { access_url } = await apiJson('/api/social/connect', { method: 'POST' });
if (access_url) { window.location.href = access_url; return; }
} catch (_) { /* fall through to the account page */ }
}
window.location.hash = '#/account';
}
}, 2000);
return () => clearInterval(t);
}, [refreshMe]);
useEffect(() => {
apiJson('/api/billing/plans').then((d) => setTopups(d.topups || [])).catch(() => {});
}, []);
const openPortal = useCallback(async () => {
setBusy(true);
try {
const { url } = await apiJson('/api/billing/portal', { method: 'POST' });
window.location.href = url;
} catch (e) { setBusy(false); alert('Could not open billing portal.'); }
}, []);
const buyTopup = useCallback(async (price_id) => {
setBusy(true);
try {
const { url } = await apiJson('/api/billing/checkout', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ price_id }),
});
window.location.href = url;
} catch (e) { setBusy(false); alert(e?.detail || 'Could not start checkout.'); }
}, []);
if (!me) return <div className="flex justify-center py-16"><Loader2 className="animate-spin text-brass" /></div>;
const m = minutes || {};
const total = (m.plan_allowance || 0) + (m.topup_remaining || 0) + (m.plan_used || 0);
const usedPct = total > 0 ? Math.min(100, ((m.plan_used || 0) / (m.plan_allowance || 1)) * 100) : 0;
const low = total > 0 && (m.remaining || 0) <= total * 0.2;
return (
<div className="max-w-2xl mx-auto space-y-6">
<div className="flex items-end justify-between gap-4">
<div>
<p className="eyebrow mb-1.5">ACCOUNT</p>
<h2 className="font-display lowercase text-2xl text-ink leading-tight">Your account</h2>
<p className="text-muted text-sm mt-1">{me.user?.email}</p>
</div>
<button onClick={logout} className="btn-quiet shrink-0">
<LogOut size={16} /> Sign out
</button>
</div>
{activating && (
<div className="card px-4 py-3 text-sm text-ink2 flex items-center gap-2 lowercase">
<Loader2 size={16} className="animate-spin text-brass" /> Activating your plan…
</div>
)}
<div className="card p-6">
<div className="flex items-center justify-between gap-4 mb-4">
<div className="flex items-center gap-2 flex-wrap">
<span className="text-ink font-medium capitalize">{plan ? `${plan} plan` : 'No active plan'}</span>
{/* Payment-issue states get the explanatory banner below instead —
showing raw Stripe jargon ("past_due") twice explains nothing. */}
{me.status && me.status !== 'active'
&& !PAYMENT_ISSUE_STATES.includes(me.status) && (
<span className="badge-warn">{me.status}</span>
)}
{me.cancel_at_period_end && (
<span className="badge-warn">cancels at period end</span>
)}
</div>
{/* Any Stripe relationship — live OR broken (past_due, unpaid) — must
keep the portal reachable. A declined card demotes `plan` to free,
so keying this off the plan alone hid the one button that fixes it. */}
{me.has_billing_account ? (
<button onClick={openPortal} disabled={busy} className="btn-ghost px-4 py-2 shrink-0">
<CreditCard size={16} /> Manage billing
</button>
) : (
<button onClick={() => { window.location.hash = '#/pricing'; }} className="btn-primary px-4 py-2 shrink-0 text-xs">
Upgrade
</button>
)}
</div>
{/* A bare "past_due" chip explains nothing. Say what happened and what
fixes it — this is the whole reason the account reads as free. */}
{PAYMENT_ISSUE_STATES.includes(me.status) && (
<div className="mb-4 rounded-card border border-warn/40 bg-warn/5 p-3 text-sm text-ink2">
<b className="text-ink">We couldn't charge your card.</b>{' '}
{me.status === 'incomplete'
? 'Your payment was never completed, so the plan never started.'
: 'Your plan is paused and you\'re on free minutes until it goes through.'}{' '}
<button onClick={openPortal} disabled={busy}
className="underline underline-offset-2 hover:text-ink">
Update your card
</button>{' '}
and it resumes right away.
</div>
)}
<div className="space-y-2">
<div className="flex justify-between text-sm">
<span className="text-muted lowercase">Plan minutes</span>
<span className="text-ink2">{fmt1(m.plan_used)} / {fmt1(m.plan_allowance)} used</span>
</div>
<div className="h-1.5 bg-paper3 rounded-full overflow-hidden">
<div className={`h-full transition-all ${low ? 'bg-warn' : 'bg-brass'}`} style={{ width: `${usedPct}%` }} />
</div>
<div className="flex justify-between text-sm pt-1">
<span className="text-muted lowercase">Top-up minutes</span>
<span className="text-ink2">{fmt1(m.topup_remaining)} remaining</span>
</div>
<div className="flex justify-between text-sm pt-2 border-t border-rule">
<span className="text-ink font-medium lowercase">Total remaining</span>
<span className="text-brass font-medium">{fmt1(m.remaining)} min</span>
</div>
</div>
</div>
{topups.length > 0 && (
<div className="card p-6">
<h3 className="font-display lowercase text-lg text-ink mb-1 flex items-center gap-2"><Plus size={16} className="text-brass" /> Buy more minutes</h3>
<p className="text-muted text-sm mb-4 lowercase">Top-ups never expire while your plan is active.</p>
<div className="grid grid-cols-2 gap-3">
{topups.map((t) => (
<button key={t.price_id} onClick={() => buyTopup(t.price_id)} disabled={busy}
className="border border-rule hover:border-brass rounded-card p-4 text-left transition-colors disabled:opacity-50">
<div className="text-ink font-medium">+{t.minutes} min</div>
<div className="readout mt-1">
{new Intl.NumberFormat('en-US', { style: 'currency', currency: (t.currency || 'usd').toUpperCase(), maximumFractionDigits: 0 }).format((t.amount || 0) / 100)}
</div>
</button>
))}
</div>
</div>
)}
</div>
);
}