From 09af87d636a274c20011ded2cfecc35065d69041 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 20:46:15 +0000 Subject: [PATCH] feat(cms): billing and plan in the Payload admin (PX3) The old console's billing page moves into the Payload admin as Billing & plan (/admin/organization/billing), under the Account group: the organization's current plan and entitlements, the plans it can move to, and its invoices, read through api-edge with the signed-in person's session. - Upgrade starts the provider's checkout, which returns to the CMS (/admin/organization/billing?checkout=complete); the page then reconciles the subscription with a same-origin form post, not a client fetch - switch or cancel a paid plan behind a confirm step; Manage billing opens the provider's customer portal - the billing form accepts only same-origin posts from staff, and sends the browser only to an https provider page - where no payment provider is configured (stage), Upgrade and the portal say so instead of failing - docs: runbook, architecture, overview, operations guide; epic status Orun-Task: PX-4 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013JuHbkZCjDrGgHdzCrCRqG --- ai/context/operations.md | 3 +- apps/cms/docs/architecture.md | 5 +- apps/cms/docs/overview.md | 2 +- apps/cms/docs/runbook.md | 11 + apps/cms/src/app/(payload)/admin/importMap.js | 2 + .../cms/src/app/(site)/lumen/billing/route.ts | 9 + .../components/admin/account/AccountNav.tsx | 5 +- .../components/admin/account/AccountPage.tsx | 4 +- .../components/admin/account/BillingView.tsx | 229 ++++++++++++++++++ .../admin/account/ConfirmSubmit.tsx | 30 +++ .../admin/account/FinishCheckout.tsx | 24 ++ apps/cms/src/lib/lumen/billing-api.ts | 81 +++++++ apps/cms/src/lib/lumen/forms.ts | 63 ++++- apps/cms/src/lib/lumen/models/plan-actions.ts | 161 ++++++++++++ apps/cms/src/lib/lumen/status.ts | 23 +- apps/cms/src/payload.config.ts | 1 + .../IMPLEMENTATION-STATUS.md | 12 +- tasks/PX-4.TaskContract.yaml | 18 ++ tests/cms/docs/overview.md | 3 +- tests/cms/src/lumen-billing.test.ts | 108 +++++++++ .../cms/src/lumen-model-plan-actions.test.ts | 180 ++++++++++++++ 21 files changed, 961 insertions(+), 13 deletions(-) create mode 100644 apps/cms/src/app/(site)/lumen/billing/route.ts create mode 100644 apps/cms/src/components/admin/account/BillingView.tsx create mode 100644 apps/cms/src/components/admin/account/ConfirmSubmit.tsx create mode 100644 apps/cms/src/components/admin/account/FinishCheckout.tsx create mode 100644 apps/cms/src/lib/lumen/billing-api.ts create mode 100644 apps/cms/src/lib/lumen/models/plan-actions.ts create mode 100644 tasks/PX-4.TaskContract.yaml create mode 100644 tests/cms/src/lumen-billing.test.ts create mode 100644 tests/cms/src/lumen-model-plan-actions.test.ts diff --git a/ai/context/operations.md b/ai/context/operations.md index 9fd65e5..9921a51 100644 --- a/ai/context/operations.md +++ b/ai/context/operations.md @@ -168,7 +168,8 @@ it through `api-edge`, and no worker calls it. passwords; a new account is pending until an admin gives it a role, and admins invite people by creating a user with their email). Its *Account* nav group holds the Lumen account pages: Profile, Security activity, - Organization and Notifications. + Organization, Notifications and Billing & plan (checkout and the customer + portal are the payment provider's pages). - **Secrets:** `CMS_PAYLOAD_SECRET` is generated and published by `cloudflare-hyperdrive-cms` (nobody chooses or sees it) and pushed to the Worker as `PAYLOAD_SECRET`. `CMS_SETUP_TOKEN` exists only if the owner sets diff --git a/apps/cms/docs/architecture.md b/apps/cms/docs/architecture.md index fcedc74..5ca92b4 100644 --- a/apps/cms/docs/architecture.md +++ b/apps/cms/docs/architecture.md @@ -89,7 +89,8 @@ browser ──► lumen-payload-cms- (Worker) template. They read per request, uncached, with the person's own token, and render on the server: the browser never calls api-edge for them. Forms post to `/lumen/*` route handlers that accept only a same-origin post from staff - and answer `303` back to the page. The console's framework-free models + and answer `303` back to the page, or, for checkout and the customer portal, + to the payment provider's https page (the only external redirect). The console's framework-free models (`src/lib/lumen/models/`) are copied, not shared: the console is retired in PX4. - **Pinned versions.** Payload 3.89.0 hashes passwords with 25,000 PBKDF2 @@ -103,6 +104,6 @@ browser ──► lumen-payload-cms- (Worker) ## Out of scope here -Billing and plan in the admin (PX3), the console URL opening the admin (PX4), serving content through `api-edge`, per-tenant content, and image derivatives: resizing, cropping and focal +The console URL opening the admin (PX4), serving content through `api-edge`, per-tenant content, and image derivatives: resizing, cropping and focal points need `sharp`, which does not run on Workers, so files are stored and served as uploaded. diff --git a/apps/cms/docs/overview.md b/apps/cms/docs/overview.md index 700c011..0867f3f 100644 --- a/apps/cms/docs/overview.md +++ b/apps/cms/docs/overview.md @@ -28,7 +28,7 @@ through the API. Drafts, accounts and everything else need a staff session. Staff upload media; only admins delete it. The admin also has the person's **Lumen account pages** (Profile, Security -activity, Organization, Notifications), read from and saved to Lumen through +activity, Organization, Notifications, Billing & plan), read from and saved to Lumen through `api-edge`; nothing of them is stored in the CMS but the display name. ## Depends on diff --git a/apps/cms/docs/runbook.md b/apps/cms/docs/runbook.md index 46511da..00a52a6 100644 --- a/apps/cms/docs/runbook.md +++ b/apps/cms/docs/runbook.md @@ -41,6 +41,13 @@ back to the page with *Saved.* or what went wrong. | Security activity | `/admin/account/security` | sign-ins, codes and sessions, newest first, 50 a page | — | | Organization | `/admin/organization` | the Lumen organization (Solo: the personal one) | — (renaming is not in the API) | | Notifications | `/admin/organization/notifications` | email categories for that organization | which categories Lumen emails | +| Billing & plan | `/admin/organization/billing` | the plan, its status and renewal, what it includes, invoices | upgrade (the provider's checkout), switch or cancel a paid plan, the provider's portal | + +Paying never happens in the CMS: *Upgrade* sends the browser to the payment +provider's checkout, which returns to Billing & plan (`?checkout=complete`); +the page then posts one reconcile, so it does not wait for the provider's +webhook. *Manage payment and invoices* opens the provider's +customer portal; it appears only for a paid subscription the provider manages. A page that cannot reach Lumen says so (for example *The CMS could not reach Lumen*) instead of failing: check `api-edge` and the `LUMEN_API` binding. @@ -166,6 +173,10 @@ real R2 adapter. environment and published `WIRING_CLOUDFLARE_R2_CMS`, then redeploy the CMS. - **An upload answers 413.** It is over 10 MiB (`MEDIA_MAX_BYTES` in `src/collections/Media.ts`). +- **Billing & plan says "no payment provider is configured".** The billing + worker of that environment has no provider credentials (stage, today), so + checkout and the portal cannot start; plans, entitlements and invoices + still show. - **An account page says "Lumen answered with an error (internal_error)".** api-edge or the worker behind it failed; its logs carry the request id. Security activity answered 503 for everyone until identity-worker queried diff --git a/apps/cms/src/app/(payload)/admin/importMap.js b/apps/cms/src/app/(payload)/admin/importMap.js index 563e397..a7075f7 100644 --- a/apps/cms/src/app/(payload)/admin/importMap.js +++ b/apps/cms/src/app/(payload)/admin/importMap.js @@ -30,6 +30,7 @@ import { ProfileView as ProfileView_277e3ece63d7b343699a9b408a007eb3 } from '../ import { SecurityView as SecurityView_b295470aeebb099452f0f0106181edbc } from '../../../components/admin/account/SecurityView' import { OrganizationView as OrganizationView_c762e34a568e64979d425a844ff81df5 } from '../../../components/admin/account/OrganizationView' import { NotificationsView as NotificationsView_aa0b52d1d262a686350346369dcc5c62 } from '../../../components/admin/account/NotificationsView' +import { BillingView as BillingView_32ce8c78e2f0654615d7a227314913c0 } from '../../../components/admin/account/BillingView' import { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc' /** @type import('payload').ImportMap */ @@ -66,5 +67,6 @@ export const importMap = { "/components/admin/account/SecurityView#SecurityView": SecurityView_b295470aeebb099452f0f0106181edbc, "/components/admin/account/OrganizationView#OrganizationView": OrganizationView_c762e34a568e64979d425a844ff81df5, "/components/admin/account/NotificationsView#NotificationsView": NotificationsView_aa0b52d1d262a686350346369dcc5c62, + "/components/admin/account/BillingView#BillingView": BillingView_32ce8c78e2f0654615d7a227314913c0, "@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } diff --git a/apps/cms/src/app/(site)/lumen/billing/route.ts b/apps/cms/src/app/(site)/lumen/billing/route.ts new file mode 100644 index 0000000..f3b4904 --- /dev/null +++ b/apps/cms/src/app/(site)/lumen/billing/route.ts @@ -0,0 +1,9 @@ +import { formDeps } from '@/lib/lumen/form-deps' +import { billingForm } from '@/lib/lumen/forms' + +export const dynamic = 'force-dynamic' + +// The Billing & plan page's forms (lumen-payload-console design §4). +export function POST(request: Request): Promise { + return billingForm(request, formDeps) +} diff --git a/apps/cms/src/components/admin/account/AccountNav.tsx b/apps/cms/src/components/admin/account/AccountNav.tsx index f96305a..8799c53 100644 --- a/apps/cms/src/components/admin/account/AccountNav.tsx +++ b/apps/cms/src/components/admin/account/AccountNav.tsx @@ -10,6 +10,7 @@ const LINKS = [ { href: '/admin/account/security', label: 'Security activity' }, { href: '/admin/organization', label: 'Organization' }, { href: '/admin/organization/notifications', label: 'Notifications' }, + { href: '/admin/organization/billing', label: 'Billing & plan' }, ] export function AccountNav() { @@ -25,11 +26,11 @@ export function AccountNav() { ) return active ? ( -
+
{inner}
) : ( - + {inner} ) diff --git a/apps/cms/src/components/admin/account/AccountPage.tsx b/apps/cms/src/components/admin/account/AccountPage.tsx index 4927b1a..33ceed9 100644 --- a/apps/cms/src/components/admin/account/AccountPage.tsx +++ b/apps/cms/src/components/admin/account/AccountPage.tsx @@ -30,11 +30,11 @@ export function param(props: AdminViewServerProps, name: string): string | undef /** The line a form's redirect asked for: saved, or what went wrong. */ export function StatusLine({ props }: { props: AdminViewServerProps }) { - const status = statusMessage({ saved: param(props, 'saved'), error: param(props, 'error') }) + const status = statusMessage({ saved: param(props, 'saved'), error: param(props, 'error'), notice: param(props, 'notice') }) if (!status) return null return (
- {status.text} + {status.text}
) } diff --git a/apps/cms/src/components/admin/account/BillingView.tsx b/apps/cms/src/components/admin/account/BillingView.tsx new file mode 100644 index 0000000..4a22da4 --- /dev/null +++ b/apps/cms/src/components/admin/account/BillingView.tsx @@ -0,0 +1,229 @@ +import type { PublicPlan } from '@saas/contracts/billing' +import type { AdminViewServerProps } from 'payload' + +import { listOrganizations, pickOrganization } from '@/lib/lumen/account-api' +import { getSummary, listInvoices, listPlans } from '@/lib/lumen/billing-api' +import { formatPlanPrice, hasManageableSubscription, orderedPlans, planChangeAction, planFeatureLines } from '@/lib/lumen/models/plan-actions' +import { lumenTransport } from '@/lib/lumen/transport' + +import { AccountHeading, AccountTemplate, card, LoadError, param, requireStaff, row, StatusLine } from './AccountPage' +import { ConfirmSubmit } from './ConfirmSubmit' +import { FinishCheckout } from './FinishCheckout' + +// Billing & plan (lumen-payload-console design §4): the organization's plan, +// what it includes, its invoices, and the ways to change it. Paying happens on +// the provider's pages (checkout, the customer portal), never in the CMS. + +const SALES_EMAIL = 'sales@sourceplane.ai' + +const section = { marginTop: 'calc(var(--base) * 2)' } + +const cell = { padding: 'calc(var(--base) / 2)', borderBottom: '1px solid var(--theme-elevation-100)', textAlign: 'left' as const } + +function formatDate(iso: string | null | undefined): string { + if (!iso) return '—' + const d = new Date(iso) + return Number.isNaN(d.getTime()) ? '—' : d.toLocaleDateString('en', { year: 'numeric', month: 'short', day: 'numeric' }) +} + +function formatMoney(cents: number | null | undefined, currency: string): string { + if (cents == null) return '—' + const symbol = currency.toLowerCase() === 'usd' ? '$' : `${currency.toUpperCase()} ` + return `${symbol}${(cents / 100).toFixed(2)}` +} + +function priceLabel(plan: PublicPlan): string { + if (plan.billingInterval === 'none') return 'Custom: contact sales' + if (!plan.priceAmountCents) return 'Free' + return formatPlanPrice(plan) +} + +function PlanButton({ plan, orgId, action }: { plan: PublicPlan; orgId: string; action: ReturnType }) { + if (action === 'current') return Your plan + if (action === 'contact') + return ( + + Contact sales + + ) + const label = action === 'checkout' ? `Upgrade to ${plan.name}` : action === 'cancel' ? 'Move to Free' : `Switch to ${plan.name}` + const confirm = + action === 'cancel' + ? 'Cancel your paid plan? It stays active until the end of the period you paid for.' + : action === 'change' + ? `Switch to ${plan.name} (${formatPlanPrice(plan)})? The payment provider prorates the difference.` + : null + return ( +
+ + + + {confirm ? ( + + {label} + + ) : ( + + )} +
+ ) +} + +export async function BillingView(props: AdminViewServerProps) { + const token = requireStaff(props, '/admin/organization/billing') + const transport = await lumenTransport() + const orgs = await listOrganizations(transport, token) + const org = orgs.ok === true ? pickOrganization(orgs.value, param(props, 'org')) : null + + // Back from the provider's checkout: FinishCheckout reconciles once by form + // post, so the page does not wait on the provider's webhook. + const returning = param(props, 'checkout') === 'complete' + + const [summary, plans, invoices] = org + ? await Promise.all([getSummary(transport, token, org.id), listPlans(transport, token, org.id), listInvoices(transport, token, org.id)]) + : [null, null, null] + + const plan = summary?.ok === true ? summary.value.plan : null + const sub = summary?.ok === true ? summary.value.activeSubscription : null + const currentCode = plan?.code ?? null + const manageable = hasManageableSubscription(currentCode) && Boolean(sub?.providerSubscriptionId) + const entitlements = summary?.ok === true ? summary.value.entitlements : [] + + return ( + +
+ + + {returning && org ? : null} + {orgs.ok === false ? ( + + ) : !org ? ( +

Your account does not belong to an organization yet.

+ ) : summary?.ok === false ? ( + + ) : ( + <> +
+

+ {plan ? plan.name : 'No plan'} +

+
+
Price
+
{plan ? priceLabel(plan) : '—'}
+
Status
+
{sub?.status ?? 'none'}
+
Renews on
+
{formatDate(sub?.cancelAt ? null : sub?.currentPeriodEnd)}
+ {sub?.cancelAt ? ( + <> +
Ends on
+
{formatDate(sub.cancelAt)}
+ + ) : null} +
Organization
+
{org.name}
+
+ {manageable ? ( +
+ + + +
+ ) : null} +
+ +

Plans

+ {plans?.ok === false ? ( + + ) : ( +
+ {orderedPlans(plans?.ok === true ? plans.value : []).map((p) => ( +
+

{p.name}

+

{priceLabel(p)}

+
    + {planFeatureLines(p.code).map((line) => ( +
  • {line}
  • + ))} +
+ +
+ ))} +
+ )} + +

What your plan includes

+ {entitlements.length === 0 ? ( +

Nothing recorded yet.

+ ) : ( + + + + + + + + + + {entitlements.map((e) => ( + + + + + + ))} + +
EntitlementIncludedLimit
+ {e.entitlementKey} + {e.enabled ? 'yes' : 'no'}{e.valueType === 'boolean' ? '—' : e.limitValue === null ? 'unlimited' : e.limitValue}
+ )} + +

Invoices

+ {invoices?.ok === false ? ( + + ) : (invoices?.ok === true ? invoices.value : []).length === 0 ? ( +

No invoices yet. They appear here after the first charge.

+ ) : ( + + + + + + + + + + + + {(invoices?.ok === true ? invoices.value : []).map((i) => ( + + + + + + + + ))} + +
NumberStatusAmountIssuedReceipt
+ {i.number ?? i.id.slice(0, 12)} + {i.status}{formatMoney(i.amountDueCents, i.currency)}{formatDate(i.issuedAt)} + {i.hostedUrl ? ( + + View + + ) : ( + '—' + )} +
+ )} + + )} +
+
+ ) +} diff --git a/apps/cms/src/components/admin/account/ConfirmSubmit.tsx b/apps/cms/src/components/admin/account/ConfirmSubmit.tsx new file mode 100644 index 0000000..71d1f7f --- /dev/null +++ b/apps/cms/src/components/admin/account/ConfirmSubmit.tsx @@ -0,0 +1,30 @@ +'use client' + +import type React from 'react' + +// A submit button that asks first (plan changes and cancellations): the only +// client code on Billing & plan. Without JavaScript the form still submits. +export function ConfirmSubmit({ + message, + className, + children, + testId, +}: { + message: string + className?: string + children: React.ReactNode + testId?: string +}) { + return ( + + ) +} diff --git a/apps/cms/src/components/admin/account/FinishCheckout.tsx b/apps/cms/src/components/admin/account/FinishCheckout.tsx new file mode 100644 index 0000000..ef0beb9 --- /dev/null +++ b/apps/cms/src/components/admin/account/FinishCheckout.tsx @@ -0,0 +1,24 @@ +'use client' + +import { useEffect, useRef } from 'react' + +// Back from the provider's checkout (lumen-payload-console design §4): bring +// the plan up to date once, through the same same-origin form post as every +// other change, so opening a link to this page changes nothing by itself. +// Without JavaScript the button does the same. +export function FinishCheckout({ orgId }: { orgId: string }) { + const form = useRef(null) + useEffect(() => { + form.current?.requestSubmit() + }, []) + return ( +
+ + +

Thanks: finishing your checkout…

+ +
+ ) +} diff --git a/apps/cms/src/lib/lumen/billing-api.ts b/apps/cms/src/lib/lumen/billing-api.ts new file mode 100644 index 0000000..44141b4 --- /dev/null +++ b/apps/cms/src/lib/lumen/billing-api.ts @@ -0,0 +1,81 @@ +import type { + CancelSubscriptionResponse, + ChangePlanResponse, + CreateCheckoutResponse, + CreatePortalSessionResponse, + GetBillingSummaryResponse, + ListInvoicesResponse, + ListPlansResponse, + PublicInvoice, + PublicPlan, + ReconcileResponse, +} from '@saas/contracts/billing' + +import type { Outcome } from './account-api' +import { lumenCall, type LumenResult, type LumenTransport } from './client' + +// The Lumen billing calls behind Billing & plan (lumen-payload-console design +// §4), made by the CMS server with the person's session for one organization: +// the same api-edge routes the console calls. Payment details never pass +// through the CMS: checkout and the portal are the provider's own pages. + +const base = (orgId: string) => `/v1/organizations/${encodeURIComponent(orgId)}/billing` + +// `=== false`, not `!ok`: the CMS compiles without strictNullChecks. +function unwrap(result: LumenResult, pick: (data: T) => R): Outcome { + if (result.ok === false) return result + return { ok: true, value: pick(result.data) } +} + +export async function getSummary(t: LumenTransport, token: string, orgId: string): Promise> { + return unwrap(await lumenCall(t, `${base(orgId)}/summary`, { token }), (d) => d) +} + +export async function listPlans(t: LumenTransport, token: string, orgId: string): Promise> { + return unwrap(await lumenCall(t, `${base(orgId)}/plans`, { token }), (d) => d?.plans ?? []) +} + +export async function listInvoices(t: LumenTransport, token: string, orgId: string): Promise> { + return unwrap(await lumenCall(t, `${base(orgId)}/invoices`, { token }), (d) => d?.invoices ?? []) +} + +/** A hosted checkout for `planCode`; the provider sends the buyer back to `returnUrl` (an origin and a path). */ +export async function createCheckout( + t: LumenTransport, + token: string, + orgId: string, + input: { planCode: string; origin: string; returnPath: string }, +): Promise> { + const body = { planCode: input.planCode, embedOrigin: input.origin, returnPath: input.returnPath } + return unwrap(await lumenCall(t, `${base(orgId)}/checkout`, { token, method: 'POST', body }), (d) => d) +} + +export async function createPortal(t: LumenTransport, token: string, orgId: string): Promise> { + return unwrap(await lumenCall(t, `${base(orgId)}/portal`, { token, method: 'POST' }), (d) => d) +} + +export async function changePlan(t: LumenTransport, token: string, orgId: string, planCode: string): Promise> { + return unwrap( + await lumenCall(t, `${base(orgId)}/subscription/change`, { token, method: 'POST', body: { planCode } }), + (d) => d, + ) +} + +export async function cancelSubscription(t: LumenTransport, token: string, orgId: string): Promise> { + return unwrap(await lumenCall(t, `${base(orgId)}/subscription/cancel`, { token, method: 'POST' }), (d) => d) +} + +export async function reconcile(t: LumenTransport, token: string, orgId: string): Promise> { + return unwrap(await lumenCall(t, `${base(orgId)}/reconcile`, { token, method: 'POST' }), (d) => d) +} + +/** A provider URL the CMS may send a browser to: https, nothing else. */ +export function safeProviderUrl(raw: unknown): string | null { + if (typeof raw !== 'string') return null + try { + const url = new URL(raw) + return url.protocol === 'https:' ? url.toString() : null + } catch { + return null + } +} diff --git a/apps/cms/src/lib/lumen/forms.ts b/apps/cms/src/lib/lumen/forms.ts index 13d1aae..55facfb 100644 --- a/apps/cms/src/lib/lumen/forms.ts +++ b/apps/cms/src/lib/lumen/forms.ts @@ -2,6 +2,7 @@ import type { NotificationCategoryPreferences } from '@saas/contracts/notificati import { staffRoleOf } from '../access' import { updatePreferences, updateProfile } from './account-api' +import { cancelSubscription, changePlan, createCheckout, createPortal, reconcile, safeProviderUrl } from './billing-api' import type { LumenTransport } from './client' import { isSameOrigin, LUMEN_SESSION_COOKIE, readCookie } from './cookies' import { DISPLAY_NAME_MAX, toDisplayNameValue, validateDisplayName } from './models/profile' @@ -17,6 +18,7 @@ export const ACCOUNT_PAGES = { security: '/admin/account/security', organization: '/admin/organization', notifications: '/admin/organization/notifications', + billing: '/admin/organization/billing', } as const export type FormUser = { id: string | number; role?: string | null; lumenUserId?: string | null; collection?: string } @@ -33,9 +35,14 @@ const seeOther = (location: string) => new Response(null, { status: 303, headers: { location, 'cache-control': 'no-store' } }) /** Where a form goes back to, with what happened. */ -export function backTo(page: string, outcome: { saved: true } | { error: string }, extra: Record = {}): string { +export function backTo( + page: string, + outcome: { saved: true } | { error: string } | { notice: string }, + extra: Record = {}, +): string { const params = new URLSearchParams(extra) if ('saved' in outcome) params.set('saved', '1') + else if ('notice' in outcome) params.set('notice', outcome.notice) else params.set('error', outcome.error) return `${page}?${params.toString()}` } @@ -102,4 +109,58 @@ export function notificationsForm(request: Request, deps: FormDeps): Promise { + const page = ACCOUNT_PAGES.billing + return handle(request, deps, page, async ({ form, token, transport }) => { + const action = String(form.get('action') ?? '') as BillingAction + const orgId = String(form.get('orgId') ?? '') + const planCode = String(form.get('planCode') ?? '') + const back = orgId ? { org: orgId } : undefined + if (!orgId || !BILLING_ACTIONS.includes(action)) return { location: backTo(page, { error: 'bad_request' }, back) } + if ((action === 'checkout' || action === 'change') && !/^[a-z0-9_-]{1,64}$/.test(planCode)) { + return { location: backTo(page, { error: 'bad_request' }, back) } + } + const fail = (code: string) => ({ location: backTo(page, { error: code }, back) }) + + if (action === 'checkout') { + // isSameOrigin passed, so Origin is the CMS as the browser sees it. + const origin = request.headers.get('origin') as string + const result = await createCheckout(transport, token, orgId, { planCode, origin, returnPath: `${CHECKOUT_RETURN}&org=${encodeURIComponent(orgId)}` }) + if (result.ok === false) return fail(result.code) + const url = safeProviderUrl(result.value.checkoutUrl) + return url ? { location: url } : fail('bad_provider_url') + } + if (action === 'portal') { + const result = await createPortal(transport, token, orgId) + if (result.ok === false) return fail(result.code) + const url = safeProviderUrl(result.value.portalUrl) + return url ? { location: url } : fail('bad_provider_url') + } + if (action === 'change') { + const result = await changePlan(transport, token, orgId, planCode) + if (result.ok === false) return fail(result.code) + return { location: backTo(page, { notice: result.value.changed ? 'plan_changed' : 'plan_unchanged' }, back) } + } + if (action === 'cancel') { + const result = await cancelSubscription(transport, token, orgId) + if (result.ok === false) return fail(result.code) + return { location: backTo(page, { notice: result.value.cancelAtPeriodEnd ? 'cancel_scheduled' : 'canceled' }, back) } + } + const result = await reconcile(transport, token, orgId) + if (result.ok === false) return fail(result.code) + return { location: backTo(page, { notice: result.value.reconciled ? 'reconciled' : 'nothing_to_reconcile' }, back) } + }) +} + export { DISPLAY_NAME_MAX } diff --git a/apps/cms/src/lib/lumen/models/plan-actions.ts b/apps/cms/src/lib/lumen/models/plan-actions.ts new file mode 100644 index 0000000..768e27e --- /dev/null +++ b/apps/cms/src/lib/lumen/models/plan-actions.ts @@ -0,0 +1,161 @@ +// Copied from apps/web-console-next/src/components/billing/plan-actions.ts with its +// tests (lumen-payload-console PX3): the console is retired in PX4, so this +// copy is the one that stays. Framework-free. + +import type { PublicPlan } from "@saas/contracts/billing"; + +/** + * Pure (no-React) helpers for the billing actions UI, kept separate so the + * selection/formatting logic is unit-testable without a DOM. + */ + +/** + * The plans a user can upgrade to via self-serve checkout: active, recurring, + * and priced strictly above the current plan. Excludes Free (price 0), + * Enterprise (billingInterval "none" — contact sales), and any plan at or below + * the current price (downgrades go through the customer portal, not checkout). + * Sorted by price asc. + */ +export function selectUpgradePlans( + plans: PublicPlan[], + activePlanCode: string | null, +): PublicPlan[] { + const current = activePlanCode ? plans.find((p) => p.code === activePlanCode) : undefined; + const currentPrice = current?.priceAmountCents ?? 0; + return plans + .filter( + (p) => + p.status === "active" && + p.billingInterval !== "none" && + (p.priceAmountCents ?? 0) > 0 && + p.code !== activePlanCode && + (p.priceAmountCents ?? 0) > currentPrice, + ) + .sort((a, b) => (a.priceAmountCents ?? 0) - (b.priceAmountCents ?? 0)); +} + +/** + * The lower **paid** plans an existing subscriber can downgrade to: active, + * recurring, priced strictly below the current plan but still > 0. Excludes Free + * (that's "Cancel plan") and Enterprise (contact sales). Sorted by price desc, so + * the nearest-lower tier comes first. Empty for free/unpriced current plans. + */ +export function selectDowngradePlans( + plans: PublicPlan[], + activePlanCode: string | null, +): PublicPlan[] { + const current = activePlanCode ? plans.find((p) => p.code === activePlanCode) : undefined; + const currentPrice = current?.priceAmountCents ?? 0; + if (currentPrice <= 0) return []; // free/unpriced has no paid tier below it + return plans + .filter( + (p) => + p.status === "active" && + p.billingInterval !== "none" && + (p.priceAmountCents ?? 0) > 0 && + p.code !== activePlanCode && + (p.priceAmountCents ?? 0) < currentPrice, + ) + .sort((a, b) => (b.priceAmountCents ?? 0) - (a.priceAmountCents ?? 0)); +} + +/** Short human price, e.g. "$20/mo". Empty string when unpriced. */ +export function formatPlanPrice(plan: PublicPlan): string { + if (plan.priceAmountCents == null) return ""; + const amount = plan.priceAmountCents / 100; + const num = Number.isInteger(amount) ? String(amount) : amount.toFixed(2); + const symbol = plan.priceCurrency.toLowerCase() === "usd" ? "$" : `${plan.priceCurrency.toUpperCase()} `; + const per = plan.billingInterval === "year" ? "/yr" : plan.billingInterval === "month" ? "/mo" : ""; + return `${symbol}${num}${per}`; +} + +/** Whether the org has a paid subscription worth surfacing a "Manage billing" portal for. */ +export function hasManageableSubscription(activePlanCode: string | null): boolean { + return activePlanCode !== null && activePlanCode !== "free"; +} + +/** + * All active plans ordered for the change-plan grid: Free → paid (price asc) → + * contact-sales (`billingInterval: "none"`) last. + */ +export function orderedPlans(plans: PublicPlan[]): PublicPlan[] { + const rank = (p: PublicPlan) => (p.billingInterval === "none" ? Number.MAX_SAFE_INTEGER : p.priceAmountCents ?? 0); + return plans.filter((p) => p.status === "active").sort((a, b) => rank(a) - rank(b)); +} + +export type PlanChangeAction = "current" | "checkout" | "change" | "cancel" | "contact"; + +/** + * What selecting `targetCode` does, given the current plan. First purchase → + * checkout; an existing provider-managed paid sub switching plans → change; + * moving to Free → cancel; a contact-sales plan → contact; same plan → current. + */ +export function planChangeAction(opts: { + target: PublicPlan; + currentCode: string | null; + /** True when there's a provider-managed paid subscription we can change/cancel. */ + manageable: boolean; +}): PlanChangeAction { + const current = opts.currentCode ?? "free"; + if (opts.target.code === current) return "current"; + if (opts.target.billingInterval === "none") return "contact"; + const targetIsFree = (opts.target.priceAmountCents ?? 0) === 0; + if (targetIsFree) return "cancel"; + return opts.manageable ? "change" : "checkout"; +} + +/** Curated, safe-to-display feature bullets per plan code for the change-plan cards. */ +export function planFeatureLines(code: string): string[] { + switch (code) { + case "free": + return ["Up to 3 projects", "Up to 5 members", "Community support"]; + case "pro": + return ["Up to 25 projects", "Up to 20 members", "Custom domains", "Priority support"]; + case "business": + return ["Up to 100 projects", "Up to 50 members", "Multiple organizations", "Custom domains"]; + case "enterprise": + return ["Unlimited projects & members", "SSO & advanced security", "Dedicated support"]; + default: + return []; + } +} + +export interface PollPlanChangeOptions { + /** Re-read the current plan code (e.g. from the billing summary). */ + fetchPlanCode: () => Promise; + /** The plan the buyer was on before checkout. */ + fromPlanCode: string | null; + /** How many times to poll before giving up. */ + attempts: number; + /** Delay between polls. */ + intervalMs: number; + /** Injectable delay (tests pass a no-op). */ + sleep: (ms: number) => Promise; +} + +/** + * After an embedded checkout succeeds, the plan is applied asynchronously by the + * provider webhook (seconds later) — not by the checkout call. Poll the billing + * summary until the plan code changes from what the buyer started on (or the + * attempt budget is exhausted), so the console can mask the webhook lag with a + * "finalizing…" state instead of showing the stale plan. Pure + injectable so + * it unit-tests without real timers. Transient fetch errors are swallowed and + * retried; a thrown predicate never escapes. + */ +export async function pollForPlanChange( + opts: PollPlanChangeOptions, +): Promise<{ changed: boolean; planCode: string | null }> { + let planCode = opts.fromPlanCode; + for (let i = 0; i < opts.attempts; i++) { + await opts.sleep(opts.intervalMs); + try { + planCode = await opts.fetchPlanCode(); + } catch { + continue; // transient — keep polling + } + if (planCode !== opts.fromPlanCode) { + return { changed: true, planCode }; + } + } + return { changed: false, planCode }; +} diff --git a/apps/cms/src/lib/lumen/status.ts b/apps/cms/src/lib/lumen/status.ts index 5b99b35..ca5767e 100644 --- a/apps/cms/src/lib/lumen/status.ts +++ b/apps/cms/src/lib/lumen/status.ts @@ -12,11 +12,30 @@ const MESSAGES: Record = { conflict: 'Something changed at the same time. Reload the page and try again.', internal_error: 'Lumen had a problem. Try again in a moment.', unreachable: 'The CMS could not reach Lumen. Try again in a moment.', + provider_unavailable: 'Billing is not set up for this environment yet: no payment provider is configured.', + plan_not_purchasable: 'That plan cannot be bought here. Contact sales, or pick another plan.', + provider_error: 'The payment provider did not answer. Try again in a moment.', + bad_provider_url: 'The payment provider sent back an address the CMS will not open.', } -export type Status = { kind: 'saved' | 'error'; text: string } +const NOTICES: Record = { + plan_changed: 'Your plan is changing. It can take a few seconds to show here.', + plan_unchanged: 'You are already on that plan.', + cancel_scheduled: 'Your plan is cancelled. It stays active until the end of the period you paid for.', + canceled: 'Your plan is cancelled.', + reconciled: 'Thanks: your new plan is in place.', + nothing_to_reconcile: 'Thanks: the payment provider is applying your new plan. It can take a few seconds to show here.', +} + +export type Status = { kind: 'saved' | 'error' | 'notice'; text: string } -export function statusMessage(query: { saved?: string | undefined; error?: string | undefined }): Status | null { +export function statusMessage(query: { + saved?: string | undefined + error?: string | undefined + notice?: string | undefined +}): Status | null { + const notice = query.notice && Object.hasOwn(NOTICES, query.notice) ? NOTICES[query.notice] : undefined + if (notice) return { kind: 'notice', text: notice } if (query.error) { const code = query.error.replace(/[^a-z0-9_.-]/gi, '').slice(0, 64) // Own keys only: `?error=constructor` must not reach the page as a function. diff --git a/apps/cms/src/payload.config.ts b/apps/cms/src/payload.config.ts index 9e69926..68882c2 100644 --- a/apps/cms/src/payload.config.ts +++ b/apps/cms/src/payload.config.ts @@ -62,6 +62,7 @@ export default buildConfig({ path: '/organization/notifications', exact: true, }, + lumenBilling: { Component: '/components/admin/account/BillingView#BillingView', path: '/organization/billing', exact: true }, }, }, }, diff --git a/specs/epics/lumen-payload-console/IMPLEMENTATION-STATUS.md b/specs/epics/lumen-payload-console/IMPLEMENTATION-STATUS.md index fc81eef..43323f8 100644 --- a/specs/epics/lumen-payload-console/IMPLEMENTATION-STATUS.md +++ b/specs/epics/lumen-payload-console/IMPLEMENTATION-STATUS.md @@ -8,7 +8,7 @@ the code departed from `design.md`. | PX0 — the spec | Merged | sourceplane/lumen-payload#21 | | PX1 — Lumen sign-in | Merged; stage partly deployed, the rest waits on the credential-mint quota | sourceplane/lumen-payload#22 | | PX2 — your account and organization | In review | — | -| PX3 — billing and plan | Not started | — | +| PX3 — billing and plan | In review | — | | PX4 — the front door | Not started | — | | PX5 — the record | Not started | — | @@ -51,3 +51,13 @@ the code departed from `design.md`. - **PX2, signed-out redirects.** A custom view's redirect to the sign-in is sent inside the streamed page (Next's `NEXT_REDIRECT`), which the browser follows; the response itself is `200`, as for Payload's own guarded views. +- **PX3, the checkout return.** Opened with `?checkout=complete`, the page + submits one same-origin reconcile post (`FinishCheckout`), as the console's + billing actions reconciled once, instead of polling the summary; opening a + link changes nothing by itself. Embedded checkout (the provider's overlay) is not + used: the CMS sends the browser to the hosted checkout, which returns to the + page. +- **PX3, stage has no payment provider.** Stage's billing worker answers + `provider_unavailable` for the portal and `plan_not_purchasable` for + checkout, so on stage *Upgrade* comes back with that explanation; the + provider's pages could not be reached there. diff --git a/tasks/PX-4.TaskContract.yaml b/tasks/PX-4.TaskContract.yaml new file mode 100644 index 0000000..4147510 --- /dev/null +++ b/tasks/PX-4.TaskContract.yaml @@ -0,0 +1,18 @@ +apiVersion: orun.io/v1 +kind: TaskContract +metadata: + name: PX-4 + title: "PX3: billing and plan in the Payload admin" +spec: + goal: "Admins and editors see their organization's plan, entitlements and invoices in the Payload admin and change the plan there: upgrade through the provider's checkout (returning to the CMS), switch or cancel a paid plan, and open the provider's customer portal." + affects: + - "apps/cms/**" + - "tests/cms/**" + - "ai/context/operations.md" + - "specs/epics/lumen-payload-console/IMPLEMENTATION-STATUS.md" + - "tasks/PX-4.TaskContract.yaml" + doneWhen: + - "on stage, Billing & plan shows the current plan, the plans, entitlements and invoices" + - "on stage, Upgrade reaches the provider's checkout, or explains that no provider is configured there" + - "the billing form sends the browser only to an https provider page and accepts only same-origin posts from staff" + gates: [] diff --git a/tests/cms/docs/overview.md b/tests/cms/docs/overview.md index 443101a..2226a4f 100644 --- a/tests/cms/docs/overview.md +++ b/tests/cms/docs/overview.md @@ -18,7 +18,8 @@ this component changed. A red suite blocks the merge. | `lumen-session` | api-edge is asked with the bearer token; answers are remembered 30 s per token; concurrent requests share one lookup; a confirmed session survives api-edge being unable to answer for up to 5 minutes (until it expires), and anything else fails closed. | | `lumen-account-api` | The account pages call api-edge's own routes with the person's token; the security-events cursor goes back as given; a requested organization is used only if it is the person's. | | `lumen-forms` | The account forms accept only same-origin posts from staff (a pending account goes to the pending page), save at Lumen with the person's session, copy the display name onto the `users` row, save every email category, and report Lumen's refusals. | -| `lumen-model-*` | The console's profile, notification-preference and security-event models, copied with their tests. | +| `lumen-billing` | Billing & plan's form starts checkout with the CMS as the return and sends the browser only to an https provider page; plan changes, cancellations and reconciles come back to the page; refusals are reported; odd input calls nothing. | +| `lumen-model-*` | The console's profile, notification-preference, security-event and plan models, copied with their tests. | | `lumen-cookies` | The session cookie is HttpOnly, Lax, at most 30 days; a redirect never leaves `/admin`; the origin checks refuse other sites. | | `access` | Published pages, posts and categories are public; drafts and everything else need staff; only admins delete or manage accounts; an editor cannot change a role. | | `request-scoped-pool` | Every query and transaction opens its own Postgres client and closes it, so no request awaits a socket another request opened (workerd forbids that). | diff --git a/tests/cms/src/lumen-billing.test.ts b/tests/cms/src/lumen-billing.test.ts new file mode 100644 index 0000000..6176249 --- /dev/null +++ b/tests/cms/src/lumen-billing.test.ts @@ -0,0 +1,108 @@ +import { safeProviderUrl } from '@cms/lib/lumen/billing-api' +import type { LumenTransport } from '@cms/lib/lumen/client' +import { LUMEN_SESSION_COOKIE } from '@cms/lib/lumen/cookies' +import { billingForm, type FormDeps, type FormUser } from '@cms/lib/lumen/forms' +import { statusMessage } from '@cms/lib/lumen/status' + +// Billing & plan's forms (lumen-payload-console design §4, PX3). + +const ORIGIN = 'https://lumen-payload-cms-stage.nexo-7be.workers.dev' +const editor: FormUser = { id: 7, role: 'editor', lumenUserId: 'usr_ed', collection: 'users' } + +function setup(answer: { status: number; body: unknown }, user: FormUser | null = editor) { + const calls: { path: string; method: string; auth: string | null; body: unknown }[] = [] + const transport: LumenTransport = async (path, init) => { + calls.push({ path, method: init.method ?? 'GET', auth: new Headers(init.headers).get('authorization'), body: init.body ? JSON.parse(String(init.body)) : undefined }) + return new Response(JSON.stringify(answer.body), { status: answer.status }) + } + const deps: FormDeps = { transport: async () => transport, authenticate: async () => user } + return { deps, calls } +} + +const post = (fields: Record, headers: Record = {}) => + new Request(`${ORIGIN}/lumen/billing`, { + method: 'POST', + headers: { origin: ORIGIN, cookie: `${LUMEN_SESSION_COOKIE}=tok`, 'content-type': 'application/x-www-form-urlencoded', ...headers }, + body: new URLSearchParams(fields).toString(), + }) + +describe('billing form', () => { + it('starts checkout with the CMS as the return, and sends the browser to the provider', async () => { + const s = setup({ status: 200, body: { data: { checkoutUrl: 'https://sandbox.polar.sh/checkout/abc', mode: 'checkout' } } }) + const res = await billingForm(post({ action: 'checkout', orgId: 'org_1', planCode: 'pro' }), s.deps) + expect([res.status, res.headers.get('location')]).toEqual([303, 'https://sandbox.polar.sh/checkout/abc']) + expect(s.calls).toEqual([ + { + path: '/v1/organizations/org_1/billing/checkout', + method: 'POST', + auth: 'Bearer tok', + body: { planCode: 'pro', embedOrigin: ORIGIN, returnPath: '/admin/organization/billing?checkout=complete&org=org_1' }, + }, + ]) + }) + + it('opens the customer portal', async () => { + const s = setup({ status: 200, body: { data: { portalUrl: 'https://sandbox.polar.sh/portal/x' } } }) + const res = await billingForm(post({ action: 'portal', orgId: 'org_1' }), s.deps) + expect(res.headers.get('location')).toBe('https://sandbox.polar.sh/portal/x') + expect(s.calls[0]).toMatchObject({ path: '/v1/organizations/org_1/billing/portal', method: 'POST' }) + }) + + it('never sends the browser to a provider URL that is not https', async () => { + for (const url of ['javascript:alert(1)', 'http://polar.sh/x', '/admin', 'not a url']) { + const s = setup({ status: 200, body: { data: { portalUrl: url } } }) + const res = await billingForm(post({ action: 'portal', orgId: 'org_1' }), s.deps) + expect(res.headers.get('location')).toBe('/admin/organization/billing?org=org_1&error=bad_provider_url') + } + }) + + it('changes, cancels and reconciles, coming back to the page with what happened', async () => { + const change = setup({ status: 200, body: { data: { changed: true } } }) + expect((await billingForm(post({ action: 'change', orgId: 'org_1', planCode: 'business' }), change.deps)).headers.get('location')).toBe( + '/admin/organization/billing?org=org_1¬ice=plan_changed', + ) + expect(change.calls[0]).toMatchObject({ path: '/v1/organizations/org_1/billing/subscription/change', body: { planCode: 'business' } }) + const cancel = setup({ status: 200, body: { data: { cancelAtPeriodEnd: true } } }) + expect((await billingForm(post({ action: 'cancel', orgId: 'org_1' }), cancel.deps)).headers.get('location')).toBe( + '/admin/organization/billing?org=org_1¬ice=cancel_scheduled', + ) + const rec = setup({ status: 200, body: { data: { reconciled: false } } }) + expect((await billingForm(post({ action: 'reconcile', orgId: 'org_1' }), rec.deps)).headers.get('location')).toBe( + '/admin/organization/billing?org=org_1¬ice=nothing_to_reconcile', + ) + }) + + it('reports what billing refused, such as no provider on this environment', async () => { + const s = setup({ status: 503, body: { error: { code: 'provider_unavailable', message: 'Billing provider not configured' } } }) + const res = await billingForm(post({ action: 'portal', orgId: 'org_1' }), s.deps) + expect(res.headers.get('location')).toBe('/admin/organization/billing?org=org_1&error=provider_unavailable') + expect(statusMessage({ error: 'provider_unavailable' })?.text).toMatch(/no payment provider/) + expect(statusMessage({ notice: 'constructor' })).toBeNull() + expect(statusMessage({ notice: 'reconciled' })?.kind).toBe('notice') + }) + + it('refuses unknown actions, a missing organization and odd plan codes without calling Lumen', async () => { + for (const fields of [{ action: 'refund', orgId: 'org_1' }, { action: 'portal' }, { action: 'checkout', orgId: 'org_1', planCode: 'pro"> { + const s = setup({ status: 200, body: { data: {} } }) + expect((await billingForm(post({ action: 'portal', orgId: 'org_1' }, { origin: 'https://evil.example' }), s.deps)).status).toBe(403) + const pending = setup({ status: 200, body: { data: {} } }, { id: 8, role: null }) + expect((await billingForm(post({ action: 'portal', orgId: 'org_1' }), pending.deps)).headers.get('location')).toBe('/admin/unauthorized') + expect([...s.calls, ...pending.calls]).toHaveLength(0) + }) +}) + +describe('safeProviderUrl', () => { + it('keeps https and nothing else', () => { + expect(safeProviderUrl('https://polar.sh/a?b=1')).toBe('https://polar.sh/a?b=1') + expect(safeProviderUrl('http://polar.sh/a')).toBeNull() + expect(safeProviderUrl(42)).toBeNull() + }) +}) diff --git a/tests/cms/src/lumen-model-plan-actions.test.ts b/tests/cms/src/lumen-model-plan-actions.test.ts new file mode 100644 index 0000000..357f827 --- /dev/null +++ b/tests/cms/src/lumen-model-plan-actions.test.ts @@ -0,0 +1,180 @@ +import { + selectUpgradePlans, + selectDowngradePlans, + formatPlanPrice, + hasManageableSubscription, + pollForPlanChange, + orderedPlans, + planChangeAction, + planFeatureLines, +} from "@cms/lib/lumen/models/plan-actions"; +import type { PublicPlan } from "@saas/contracts/billing"; + +const noSleep = () => Promise.resolve(); + +function plan(over: Partial): PublicPlan { + return { + id: over.code ? `plan_${over.code}` : "plan_x", + code: "x", + name: "X", + description: null, + status: "active", + billingInterval: "month", + priceAmountCents: 0, + priceCurrency: "usd", + metadata: null, + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + ...over, + }; +} + +const CATALOG: PublicPlan[] = [ + plan({ code: "free", name: "Free", priceAmountCents: 0 }), + plan({ code: "business", name: "Business", priceAmountCents: 9900 }), + plan({ code: "pro", name: "Pro", priceAmountCents: 2000 }), + plan({ code: "enterprise", name: "Enterprise", billingInterval: "none", priceAmountCents: 0 }), + plan({ code: "archived_pro", name: "Old", priceAmountCents: 1500, status: "archived" }), +]; + +describe("selectUpgradePlans", () => { + it("returns only active, recurring, priced plans (excludes free/enterprise/archived), sorted by price", () => { + const out = selectUpgradePlans(CATALOG, "free"); + expect(out.map((p) => p.code)).toEqual(["pro", "business"]); + }); + + it("excludes the current plan", () => { + const out = selectUpgradePlans(CATALOG, "pro"); + expect(out.map((p) => p.code)).toEqual(["business"]); + }); + + it("returns nothing to upgrade to when on the top tier", () => { + expect(selectUpgradePlans(CATALOG, "business").map((p) => p.code)).toEqual([]); + }); +}); + +describe("selectDowngradePlans", () => { + it("returns lower paid tiers (excludes free/enterprise/archived/current), sorted by price desc", () => { + expect(selectDowngradePlans(CATALOG, "business").map((p) => p.code)).toEqual(["pro"]); + }); + + it("returns nothing from the lowest paid tier", () => { + expect(selectDowngradePlans(CATALOG, "pro")).toEqual([]); + }); + + it("returns nothing for a free/unpriced current plan (that's an upgrade, not a downgrade)", () => { + expect(selectDowngradePlans(CATALOG, "free")).toEqual([]); + expect(selectDowngradePlans(CATALOG, null)).toEqual([]); + }); +}); + +describe("orderedPlans", () => { + it("orders Free → paid asc → contact-sales last, excluding archived", () => { + expect(orderedPlans(CATALOG).map((p) => p.code)).toEqual(["free", "pro", "business", "enterprise"]); + }); +}); + +describe("planChangeAction", () => { + const byCode = (c: string) => CATALOG.find((p) => p.code === c)!; + it("same plan → current", () => { + expect(planChangeAction({ target: byCode("pro"), currentCode: "pro", manageable: true })).toBe("current"); + }); + it("contact-sales plan → contact", () => { + expect(planChangeAction({ target: byCode("enterprise"), currentCode: "pro", manageable: true })).toBe("contact"); + }); + it("→ free → cancel", () => { + expect(planChangeAction({ target: byCode("free"), currentCode: "pro", manageable: true })).toBe("cancel"); + }); + it("paid target with a managed sub → change", () => { + expect(planChangeAction({ target: byCode("business"), currentCode: "pro", manageable: true })).toBe("change"); + }); + it("paid target from free (no managed sub) → checkout", () => { + expect(planChangeAction({ target: byCode("pro"), currentCode: "free", manageable: false })).toBe("checkout"); + }); + it("defaults current to free when null", () => { + expect(planChangeAction({ target: byCode("pro"), currentCode: null, manageable: false })).toBe("checkout"); + }); +}); + +describe("planFeatureLines", () => { + it("returns bullets for known plans, empty for unknown", () => { + expect(planFeatureLines("pro").length).toBeGreaterThan(0); + expect(planFeatureLines("free").length).toBeGreaterThan(0); + expect(planFeatureLines("nope")).toEqual([]); + }); +}); + +describe("formatPlanPrice", () => { + it("formats whole-dollar monthly USD", () => { + expect(formatPlanPrice(plan({ priceAmountCents: 2000 }))).toBe("$20/mo"); + }); + it("formats cents and yearly", () => { + expect(formatPlanPrice(plan({ priceAmountCents: 9999, billingInterval: "year" }))).toBe("$99.99/yr"); + }); + it("prefixes non-usd currency codes", () => { + expect(formatPlanPrice(plan({ priceAmountCents: 1000, priceCurrency: "eur" }))).toBe("EUR 10/mo"); + }); + it("is empty for an unpriced plan", () => { + expect(formatPlanPrice(plan({ priceAmountCents: null }))).toBe(""); + }); +}); + +describe("hasManageableSubscription", () => { + it("is true for a paid plan, false for free/none", () => { + expect(hasManageableSubscription("pro")).toBe(true); + expect(hasManageableSubscription("business")).toBe(true); + expect(hasManageableSubscription("free")).toBe(false); + expect(hasManageableSubscription(null)).toBe(false); + }); +}); + +describe("pollForPlanChange", () => { + it("resolves changed once the plan code differs from the starting plan", async () => { + let calls = 0; + const res = await pollForPlanChange({ + fromPlanCode: "free", + attempts: 5, + intervalMs: 1, + sleep: noSleep, + fetchPlanCode: async () => { + calls += 1; + return calls < 3 ? "free" : "pro"; // webhook lands on the 3rd poll + }, + }); + expect(res).toEqual({ changed: true, planCode: "pro" }); + expect(calls).toBe(3); + }); + + it("gives up after the attempt budget when the plan never changes", async () => { + let calls = 0; + const res = await pollForPlanChange({ + fromPlanCode: "free", + attempts: 4, + intervalMs: 1, + sleep: noSleep, + fetchPlanCode: async () => { + calls += 1; + return "free"; + }, + }); + expect(res).toEqual({ changed: false, planCode: "free" }); + expect(calls).toBe(4); + }); + + it("swallows transient fetch errors and keeps polling", async () => { + let calls = 0; + const res = await pollForPlanChange({ + fromPlanCode: "free", + attempts: 5, + intervalMs: 1, + sleep: noSleep, + fetchPlanCode: async () => { + calls += 1; + if (calls === 1) throw new Error("network blip"); + return calls >= 3 ? "business" : "free"; + }, + }); + expect(res.changed).toBe(true); + expect(res.planCode).toBe("business"); + }); +});