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'; import ApiKeysCard from './ApiKeysCard'; import McpConnectCard from './McpConnectCard'; import DeleteAccountCard from './DeleteAccountCard'; import SocialAnalyticsCard from './SocialAnalyticsCard'; import InvoicesCard from './InvoicesCard'; 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
; 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 (

ACCOUNT

Your account

{me.user?.email}

{activating && (
Activating your plan…
)}
{plan ? `${plan} plan` : 'No active plan'} {/* 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) && ( {me.status} )} {me.cancel_at_period_end && ( cancels at period end )}
{/* 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 ? ( ) : ( )}
{/* 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) && (
We couldn't charge your card.{' '} {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.'}{' '} {' '} and it resumes right away.
)}
Plan minutes {fmt1(m.plan_used)} / {fmt1(m.plan_allowance)} used
Top-up minutes {fmt1(m.topup_remaining)} remaining
Total remaining {fmt1(m.remaining)} min
{/* Only accounts that ever had a Stripe relationship can have invoices. */} {me.has_billing_account && } {topups.length > 0 && (

Buy more minutes

Top-ups never expire while your plan is active.

{topups.map((t) => ( ))}
)}
); }