Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion ai/context/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions apps/cms/docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,8 @@ browser ──► lumen-payload-cms-<env> (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
Expand All @@ -103,6 +104,6 @@ browser ──► lumen-payload-cms-<env> (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.
2 changes: 1 addition & 1 deletion apps/cms/docs/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions apps/cms/docs/runbook.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions apps/cms/src/app/(payload)/admin/importMap.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions apps/cms/src/app/(site)/lumen/billing/route.ts
Original file line number Diff line number Diff line change
@@ -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<Response> {
return billingForm(request, formDeps)
}
5 changes: 3 additions & 2 deletions apps/cms/src/components/admin/account/AccountNav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -25,11 +26,11 @@ export function AccountNav() {
</>
)
return active ? (
<div key={href} className="nav__link" id={`nav-lumen-${label.toLowerCase().replace(/\s+/g, '-')}`}>
<div key={href} className="nav__link" id={`nav-lumen-${label.toLowerCase().replace(/[^a-z0-9]+/g, '-')}`}>
{inner}
</div>
) : (
<Link key={href} className="nav__link" href={href} prefetch={false} id={`nav-lumen-${label.toLowerCase().replace(/\s+/g, '-')}`}>
<Link key={href} className="nav__link" href={href} prefetch={false} id={`nav-lumen-${label.toLowerCase().replace(/[^a-z0-9]+/g, '-')}`}>
{inner}
</Link>
)
Expand Down
4 changes: 2 additions & 2 deletions apps/cms/src/components/admin/account/AccountPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
<div data-testid="status-line" data-status={status.kind}>
<Banner type={status.kind === 'saved' ? 'success' : 'error'}>{status.text}</Banner>
<Banner type={status.kind === 'error' ? 'error' : status.kind === 'notice' ? 'info' : 'success'}>{status.text}</Banner>
</div>
)
}
Expand Down
229 changes: 229 additions & 0 deletions apps/cms/src/components/admin/account/BillingView.tsx
Original file line number Diff line number Diff line change
@@ -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<typeof planChangeAction> }) {
if (action === 'current') return <strong data-testid={`plan-current-${plan.code}`}>Your plan</strong>
if (action === 'contact')
return (
<a href={`mailto:${SALES_EMAIL}?subject=${encodeURIComponent(`${plan.name} plan enquiry`)}`} className="btn btn--style-secondary btn--size-small">
Contact sales
</a>
)
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 (
<form method="post" action="/lumen/billing" style={{ margin: 0 }}>
<input type="hidden" name="orgId" value={orgId} />
<input type="hidden" name="action" value={action === 'cancel' ? 'cancel' : action} />
<input type="hidden" name="planCode" value={plan.code} />
{confirm ? (
<ConfirmSubmit message={confirm} className="btn btn--style-secondary btn--size-small" testId={`plan-${action}-${plan.code}`}>
{label}
</ConfirmSubmit>
) : (
<button type="submit" className="btn btn--style-primary btn--size-small" data-testid={`plan-${action}-${plan.code}`}>
{label}
</button>
)}
</form>
)
}

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 (
<AccountTemplate props={props}>
<div data-testid="lumen-billing">
<AccountHeading title="Billing & plan" description="Your organization's plan, what it includes, and its invoices." />
<StatusLine props={props} />
{returning && org ? <FinishCheckout orgId={org.id} /> : null}
{orgs.ok === false ? (
<LoadError code={orgs.code} />
) : !org ? (
<p>Your account does not belong to an organization yet.</p>
) : summary?.ok === false ? (
<LoadError code={summary.code} />
) : (
<>
<section style={card} data-testid="billing-summary">
<h2 style={{ marginTop: 0 }} data-testid="plan-name">
{plan ? plan.name : 'No plan'}
</h2>
<dl style={row}>
<dt>Price</dt>
<dd>{plan ? priceLabel(plan) : '—'}</dd>
<dt>Status</dt>
<dd data-testid="subscription-status">{sub?.status ?? 'none'}</dd>
<dt>Renews on</dt>
<dd>{formatDate(sub?.cancelAt ? null : sub?.currentPeriodEnd)}</dd>
{sub?.cancelAt ? (
<>
<dt>Ends on</dt>
<dd>{formatDate(sub.cancelAt)}</dd>
</>
) : null}
<dt>Organization</dt>
<dd>{org.name}</dd>
</dl>
{manageable ? (
<form method="post" action="/lumen/billing" style={{ marginTop: 'var(--base)' }}>
<input type="hidden" name="orgId" value={org.id} />
<input type="hidden" name="action" value="portal" />
<button type="submit" className="btn btn--style-secondary btn--size-medium" data-testid="manage-plan">
Manage payment and invoices
</button>
</form>
) : null}
</section>

<h2 style={section}>Plans</h2>
{plans?.ok === false ? (
<LoadError code={plans.code} />
) : (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(14rem, 1fr))', gap: 'var(--base)', maxWidth: 960 }}>
{orderedPlans(plans?.ok === true ? plans.value : []).map((p) => (
<section key={p.code} style={{ ...card, marginBottom: 0 }} data-testid={`plan-${p.code}`}>
<h3 style={{ marginTop: 0 }}>{p.name}</h3>
<p style={{ fontWeight: 600 }}>{priceLabel(p)}</p>
<ul style={{ paddingLeft: '1.1rem', color: 'var(--theme-elevation-600)' }}>
{planFeatureLines(p.code).map((line) => (
<li key={line}>{line}</li>
))}
</ul>
<PlanButton plan={p} orgId={org.id} action={planChangeAction({ target: p, currentCode, manageable })} />
</section>
))}
</div>
)}

<h2 style={section}>What your plan includes</h2>
{entitlements.length === 0 ? (
<p>Nothing recorded yet.</p>
) : (
<table style={{ width: '100%', maxWidth: 960, borderCollapse: 'collapse' }} data-testid="entitlements">
<thead>
<tr>
<th style={cell}>Entitlement</th>
<th style={cell}>Included</th>
<th style={cell}>Limit</th>
</tr>
</thead>
<tbody>
{entitlements.map((e) => (
<tr key={e.id}>
<td style={cell}>
<code>{e.entitlementKey}</code>
</td>
<td style={cell}>{e.enabled ? 'yes' : 'no'}</td>
<td style={cell}>{e.valueType === 'boolean' ? '—' : e.limitValue === null ? 'unlimited' : e.limitValue}</td>
</tr>
))}
</tbody>
</table>
)}

<h2 style={section}>Invoices</h2>
{invoices?.ok === false ? (
<LoadError code={invoices.code} />
) : (invoices?.ok === true ? invoices.value : []).length === 0 ? (
<p data-testid="no-invoices">No invoices yet. They appear here after the first charge.</p>
) : (
<table style={{ width: '100%', maxWidth: 960, borderCollapse: 'collapse' }} data-testid="invoices">
<thead>
<tr>
<th style={cell}>Number</th>
<th style={cell}>Status</th>
<th style={cell}>Amount</th>
<th style={cell}>Issued</th>
<th style={cell}>Receipt</th>
</tr>
</thead>
<tbody>
{(invoices?.ok === true ? invoices.value : []).map((i) => (
<tr key={i.id}>
<td style={cell}>
<code>{i.number ?? i.id.slice(0, 12)}</code>
</td>
<td style={cell}>{i.status}</td>
<td style={cell}>{formatMoney(i.amountDueCents, i.currency)}</td>
<td style={cell}>{formatDate(i.issuedAt)}</td>
<td style={cell}>
{i.hostedUrl ? (
<a href={i.hostedUrl} target="_blank" rel="noopener noreferrer">
View
</a>
) : (
'—'
)}
</td>
</tr>
))}
</tbody>
</table>
)}
</>
)}
</div>
</AccountTemplate>
)
}
30 changes: 30 additions & 0 deletions apps/cms/src/components/admin/account/ConfirmSubmit.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<button
type="submit"
className={className}
data-testid={testId}
onClick={(event) => {
if (!window.confirm(message)) event.preventDefault()
}}
>
{children}
</button>
)
}
Loading
Loading