Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

feat(portal): set a spend cap during PAYG checkout (two-step modal) (#6970)

ConnorYohfe3337833351
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index ac1ab2c9e7..ca93b97d33 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -6253,14 +6253,29 @@ redirectingToEditor = "Redirecting to the editor..."
[portal.billing.checkout]
noClientSecret = "Edge function returned no client_secret."
+stepCount = "Step {{step}} of 2"
subtitle = "Add a card to keep going past your free Editor-plan grant. Stripe handles the rest."
-title = "Turn on the Processor plan"
+title = "Add a payment method"
[portal.billing.checkout.activationSlow]
body = "Your payment succeeded, but activation is taking a little longer than usual. It'll switch on automatically - close this and it'll appear here shortly."
close = "Close"
title = "Almost there"
+[portal.billing.checkout.cap]
+back = "Back"
+continue = "Continue to payment"
+error = "Couldn't set your spend limit"
+finePrint = "Invoices post on the 1st. Cancel anytime and revert to the Editor plan; your policies and history stay intact."
+note = "Processing pauses if you reach it. You're never billed past this, and you can change it any time."
+subtitle = "You're billed only for PDFs you process past your first 500 free, never for seats — so your ceiling is yours from day one."
+title = "Set your spend limit"
+
+[portal.billing.checkout.card]
+fields = "Card number · MM / YY · CVC · ZIP"
+label = "Card details"
+note = "Card details collected by Stripe. Stirling never stores PAN or CVC."
+
[portal.billing.checkout.error]
title = "Couldn't start checkout"
@@ -6269,11 +6284,6 @@ body = "Your payment went through. We're switching on metered processing across
hint = "Please keep this window open."
title = "Activating your Processor plan..."
-[portal.billing.checkout.notConfigured]
-bodyAfter = "in the portal env to enable in-app checkout."
-bodyBefore = "Set"
-title = "Stripe not configured"
-
[portal.billing.enterpriseUpsell]
cta = "Explore Enterprise"
description = "Committed volume discounts, air-gapped deployment, custom MSA and security reviews, and 3rd-party distributor partnerships."
diff --git a/frontend/editor/src/portal/components/billing/FreePlanView.tsx b/frontend/editor/src/portal/components/billing/FreePlanView.tsx
index 0192d5761e..a2027ff756 100644
--- a/frontend/editor/src/portal/components/billing/FreePlanView.tsx
+++ b/frontend/editor/src/portal/components/billing/FreePlanView.tsx
@@ -129,6 +129,8 @@ export function FreePlanView({ wallet, unsynced, onSubscribed }: Props) {
onClose={() => setModalOpen(false)}
teamId={wallet.teamId}
currency={currency}
+ pricePerDocMinor={wallet.pricePerDocMinor}
+ initialCapUsd={wallet.capUsd}
onComplete={() => onSubscribed?.() ?? Promise.resolve(false)}
/>
)}
diff --git a/frontend/editor/src/portal/components/billing/StripeCheckoutModal.stories.tsx b/frontend/editor/src/portal/components/billing/StripeCheckoutModal.stories.tsx
new file mode 100644
index 0000000000..32d0695256
--- /dev/null
+++ b/frontend/editor/src/portal/components/billing/StripeCheckoutModal.stories.tsx
@@ -0,0 +1,44 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { http, HttpResponse } from "msw";
+import { StripeCheckoutModal } from "@portal/components/billing/StripeCheckoutModal";
+import "@portal/components/billing/billing.css";
+
+/**
+ * Two-step "turn on the Processor" flow. Step 1 sets the monthly spend cap
+ * (its own page, since Stripe owns the card iframe on step 2). Storybook has no
+ * Stripe key, so step 2 renders the card placeholder rather than the live
+ * embedded form.
+ */
+const meta: Meta<typeof StripeCheckoutModal> = {
+ title: "Portal/Billing/StripeCheckoutModal",
+ component: StripeCheckoutModal,
+ args: {
+ open: true,
+ onClose: () => console.log("close"),
+ teamId: 1,
+ currency: "usd",
+ pricePerDocMinor: 1,
+ initialCapUsd: 100,
+ onComplete: () => Promise.resolve(true),
+ },
+ // Let the cap step's "Continue" succeed so the flow can advance to payment.
+ parameters: {
+ layout: "fullscreen",
+ msw: {
+ handlers: [
+ http.patch(
+ "http://saas.mock/api/v1/payg/cap",
+ () => new HttpResponse(null, { status: 204 }),
+ ),
+ ],
+ },
+ },
+};
+export default meta;
+type Story = StoryObj<typeof StripeCheckoutModal>;
+
+/** Step 1 — set the monthly spend limit before adding a card. */
+export const SetCap: Story = {};
+
+/** Step 1 seeded with no cap (uncapped) selected. */
+export const Uncapped: Story = { args: { initialCapUsd: null } };
diff --git a/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsx b/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsx
index 7e8e55e70a..65d32ed8ea 100644
--- a/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsx
+++ b/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsx
@@ -1,16 +1,19 @@
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Banner, Button, Modal, Skeleton, Spinner } from "@app/ui";
+import { SpendCapControl } from "@app/billing";
import {
EmbeddedCheckout,
EmbeddedCheckoutProvider,
} from "@stripe/react-stripe-js";
import type { Stripe } from "@stripe/stripe-js";
+import { updateCap } from "@portal/api/billing";
import {
createCheckoutSession,
getStripePublishableKey,
type SaasCurrency,
} from "@portal/billing/stripe";
+import { LockIcon } from "@portal/components/icons";
interface Props {
open: boolean;
@@ -19,27 +22,34 @@ interface Props {
teamId: number;
/** "usd" | "eur" | "gbp" — the SaaS PAYG offering's supported set. */
currency: SaasCurrency;
+ /** Per-document rate in minor units, for the cap→PDF estimate on step 1. */
+ pricePerDocMinor?: number | null;
+ /** Cap to seed the spend-limit step with; defaults to $100/mo. */
+ initialCapUsd?: number | null;
/** Optional billing email prefill (Stripe locks the field when set). */
billingOwnerEmail?: string;
/**
* Fired when Stripe (or the mock continue button) signals payment success.
* Runs the caller's activation flow (poll the wallet until the subscription
* webhook lands) and resolves {@code true} once subscribed, {@code false} if
- * it's taking longer than the poll window. The modal stays open and
- * non-dismissable while this runs, so the admin watches activation through
- * instead of the modal vanishing and needing a manual refresh.
+ * it's taking longer than the poll window.
*/
onComplete: () => Promise<boolean>;
}
+/** Preset monthly caps offered on the spend-limit step (major currency units). */
+const CAP_PRESETS = [50, 100, 250, 1000] as const;
+const DEFAULT_CAP_USD = 100;
+
/**
- * Embedded Stripe Checkout, matching the SaaS web app's PAYG sign-up UX. We
- * fetch a {@code client_secret} from the SaaS Supabase edge function then
- * mount &lt;EmbeddedCheckoutProvider&gt; inline — no full-page redirect, the
- * admin stays in the portal.
+ * Two-step "turn on the Processor" flow. Stripe's embedded Checkout owns the card
+ * form in its own iframe, so we can't add our own fields to it — instead the cap
+ * lives on step 1 (its own page) and the embedded card form on step 2. The chosen
+ * ceiling is applied before payment so "you're never billed past it" is true from
+ * the first processed PDF.
*
- * If the team is already subscribed the edge function short-circuits to a
- * Stripe Customer Portal URL; we open it in a new tab and close the modal.
+ * If the team is already subscribed the edge function short-circuits to a Stripe
+ * Customer Portal URL; we open it in a new tab and close.
*/
let stripePromise: Promise<Stripe | null> | null = null;
function loadStripeOnce(pk: string): Promise<Stripe | null> {
@@ -49,6 +59,22 @@ function loadStripeOnce(pk: string): Promise<Stripe | null> {
return stripePromise;
}
+/** Two-segment progress header: step 1 = spend limit, step 2 = payment. */
+function StepProgress({ step }: { step: 1 | 2 }) {
+ const { t } = useTranslation();
+ return (
+ <div className="portal-billing__checkout-progress">
+ <div className="portal-billing__checkout-steps" aria-hidden>
+ <span className="is-done" />
+ <span className={step >= 2 ? "is-done" : ""} />
+ </div>
+ <span className="portal-billing__checkout-stepcount">
+ {t("portal.billing.checkout.stepCount", "Step {{step}} of 2", { step })}
+ </span>
+ </div>
+ );
+}
+
/** Payment done, waiting for the subscription webhook to activate the plan. */
function CheckoutFinalizing() {
const { t } = useTranslation();
@@ -98,11 +124,45 @@ function CheckoutActivationSlow({ onClose }: { onClose: () => void }) {
);
}
+/**
+ * Placeholder for the card form when no Stripe publishable key is configured
+ * (Storybook / preview / mis-config). Mirrors the real embedded form's framing
+ * so the step reads correctly without mounting Stripe.
+ */
+function CardPlaceholder() {
+ const { t } = useTranslation();
+ return (
+ <div className="portal-billing__card-placeholder">
+ <div className="portal-billing__card-placeholder-head">
+ <span>{t("portal.billing.checkout.card.label", "Card details")}</span>
+ <span className="portal-billing__card-placeholder-badge">Stripe</span>
+ </div>
+ <div className="portal-billing__card-placeholder-field">
+ <LockIcon size={13} />
+ <span>
+ {t(
+ "portal.billing.checkout.card.fields",
+ "Card number · MM / YY · CVC · ZIP",
+ )}
+ </span>
+ </div>
+ <p className="portal-billing__card-placeholder-note">
+ {t(
+ "portal.billing.checkout.card.note",
+ "Card details collected by Stripe. Stirling never stores PAN or CVC.",
+ )}
+ </p>
+ </div>
+ );
+}
+
export function StripeCheckoutModal({
open,
onClose,
teamId,
currency,
+ pricePerDocMinor,
+ initialCapUsd,
billingOwnerEmail,
onComplete,
}: Props) {
@@ -110,11 +170,17 @@ export function StripeCheckoutModal({
const [clientSecret, setClientSecret] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
- // "checkout" = Stripe form; "finalizing" = payment done, waiting for the plan to activate
- // (non-dismissable); "activationSlow" = webhook lagging past the poll window (dismissable).
+ // "cap" = spend-limit step; "checkout" = Stripe card form; "finalizing" =
+ // payment done, waiting for activation (non-dismissable); "activationSlow" =
+ // webhook lagging past the poll window (dismissable).
const [phase, setPhase] = useState<
- "checkout" | "finalizing" | "activationSlow"
- >("checkout");
+ "cap" | "checkout" | "finalizing" | "activationSlow"
+ >("cap");
+ const [capUsd, setCapUsd] = useState<number | null>(
+ initialCapUsd ?? DEFAULT_CAP_USD,
+ );
+ const [capBusy, setCapBusy] = useState(false);
+ const [capError, setCapError] = useState<string | null>(null);
const mounted = useRef(true);
useEffect(() => {
mounted.current = true;
@@ -125,16 +191,24 @@ export function StripeCheckoutModal({
const publishableKey = getStripePublishableKey();
- // Mint the checkout session whenever the modal opens for a fresh team/currency.
+ // Reset to the spend-limit step whenever the modal closes, so re-opening starts fresh.
useEffect(() => {
if (!open) {
- // Reset on close so re-opening fetches a fresh session + starts at checkout.
+ setPhase("cap");
setClientSecret(null);
setError(null);
setLoading(true);
- setPhase("checkout");
- return;
+ setCapUsd(initialCapUsd ?? DEFAULT_CAP_USD);
+ setCapBusy(false);
+ setCapError(null);
}
+ }, [open, initialCapUsd]);
+
+ // Mint the checkout session only once the user has set a cap and advanced to
+ // the payment step — not on open — so we don't create a session they may abandon
+ // on step 1, and so the cap is applied first.
+ useEffect(() => {
+ if (!open || phase !== "checkout" || !publishableKey) return;
let cancelled = false;
setLoading(true);
setError(null);
@@ -148,8 +222,6 @@ export function StripeCheckoutModal({
.then((session) => {
if (cancelled) return;
if (session.alreadySubscribed && session.redirectUrl) {
- // Team's already on PAYG — bounce them to the management portal
- // instead of mounting a checkout iframe with no secret.
window.open(session.redirectUrl, "_blank", "noopener,noreferrer");
onClose();
return;
@@ -166,9 +238,7 @@ export function StripeCheckoutModal({
setClientSecret(session.clientSecret);
})
.catch((e) => {
- if (!cancelled) {
- setError(e instanceof Error ? e.message : String(e));
- }
+ if (!cancelled) setError(e instanceof Error ? e.message : String(e));
})
.finally(() => {
if (!cancelled) setLoading(false);
@@ -176,14 +246,37 @@ export function StripeCheckoutModal({
return () => {
cancelled = true;
};
- }, [open, teamId, currency, billingOwnerEmail, onClose, t]);
+ }, [
+ open,
+ phase,
+ publishableKey,
+ teamId,
+ currency,
+ billingOwnerEmail,
+ onClose,
+ t,
+ ]);
const stripe = publishableKey ? loadStripeOnce(publishableKey) : null;
const canRender = Boolean(stripe && clientSecret);
- // Payment succeeded — hold the modal open and run the caller's activation poll instead of
- // closing. The parent swaps to the subscribed view on success (unmounting us); a lagging
- // webhook drops us into the dismissable "almost there" state.
+ // Apply the chosen ceiling, then advance to payment. Applying it up front keeps
+ // "you're never billed past it" true from the first processed PDF.
+ async function handleContinue() {
+ setCapBusy(true);
+ setCapError(null);
+ try {
+ await updateCap(capUsd);
+ if (mounted.current) setPhase("checkout");
+ } catch (e) {
+ if (mounted.current) {
+ setCapError(e instanceof Error ? e.message : String(e));
+ }
+ } finally {
+ if (mounted.current) setCapBusy(false);
+ }
+ }
+
function handleStripeComplete() {
setPhase("finalizing");
onComplete()
@@ -195,13 +288,26 @@ export function StripeCheckoutModal({
});
}
- // Block dismissal while activation is in flight so a half-finished flow can't be abandoned;
- // the X, backdrop, and Escape all route through this.
+ // Block dismissal while activation is in flight so a half-finished flow can't be abandoned.
const dismissable = phase !== "finalizing";
const handleClose = () => {
if (dismissable) onClose();
};
+ const onCapStep = phase === "cap";
+ const title = onCapStep
+ ? t("portal.billing.checkout.cap.title", "Set your spend limit")
+ : t("portal.billing.checkout.title", "Add a payment method");
+ const subtitle = onCapStep
+ ? t(
+ "portal.billing.checkout.cap.subtitle",
+ "You're billed only for PDFs you process past your first 500 free, never for seats — so your ceiling is yours from day one.",
+ )
+ : t(
+ "portal.billing.checkout.subtitle",
+ "Add a card to keep going past your free Editor-plan grant. Stripe handles the rest.",
+ );
+
return (
<Modal
open={open}
@@ -210,36 +316,65 @@ export function StripeCheckoutModal({
className="portal-billing__checkout-modal"
disableBackdropClose={!dismissable}
disableEscapeClose={!dismissable}
- title={t("portal.billing.checkout.title", "Turn on the Processor plan")}
- subtitle={t(
- "portal.billing.checkout.subtitle",
- "Add a card to keep going past your free Editor-plan grant. Stripe handles the rest.",
- )}
+ title={title}
+ subtitle={subtitle}
>
{phase === "finalizing" && <CheckoutFinalizing />}
-
{phase === "activationSlow" && (
<CheckoutActivationSlow onClose={onClose} />
)}
- {phase === "checkout" && (
- <>
- {!publishableKey && (
+ {phase === "cap" && (
+ <div className="portal-billing__checkout-cap">
+ <StepProgress step={1} />
+ <SpendCapControl
+ capUsd={capUsd}
+ onChange={setCapUsd}
+ pricePerDocMinor={pricePerDocMinor}
+ currency={currency}
+ presets={CAP_PRESETS}
+ note={t(
+ "portal.billing.checkout.cap.note",
+ "Processing pauses if you reach it. You're never billed past this, and you can change it any time.",
+ )}
+ />
+ <p className="portal-billing__checkout-finePrint">
+ {t(
+ "portal.billing.checkout.cap.finePrint",
+ "Invoices post on the 1st. Cancel anytime and revert to the Editor plan; your policies and history stay intact.",
+ )}
+ </p>
+ {capError && (
<Banner
- tone="neutral"
+ tone="danger"
title={t(
- "portal.billing.checkout.notConfigured.title",
- "Stripe not configured",
+ "portal.billing.checkout.cap.error",
+ "Couldn't set your spend limit",
)}
>
- {t("portal.billing.checkout.notConfigured.bodyBefore", "Set")}{" "}
- <code>VITE_STRIPE_PUBLISHABLE_KEY</code>{" "}
- {t(
- "portal.billing.checkout.notConfigured.bodyAfter",
- "in the portal env to enable in-app checkout.",
- )}
+ {capError}
</Banner>
)}
+ <div className="portal-billing__checkout-cap-actions">
+ <Button variant="quiet" onClick={onClose} disabled={capBusy}>
+ {t("portal.billing.checkout.cap.back", "Back")}
+ </Button>
+ <Button
+ accent="premium"
+ loading={capBusy}
+ onClick={handleContinue}
+ rightSection={<span aria-hidden>›</span>}
+ >
+ {t("portal.billing.checkout.cap.continue", "Continue to payment")}
+ </Button>
+ </div>
+ </div>
+ )}
+
+ {phase === "checkout" && (
+ <div className="portal-billing__checkout-pay">
+ <StepProgress step={2} />
+ {!publishableKey && <CardPlaceholder />}
{publishableKey && error && (
<Banner
tone="danger"
@@ -265,7 +400,7 @@ export function StripeCheckoutModal({
<EmbeddedCheckout />
</EmbeddedCheckoutProvider>
)}
- </>
+ </div>
)}
</Modal>
);
diff --git a/frontend/editor/src/portal/components/billing/billing.css b/frontend/editor/src/portal/components/billing/billing.css
index 86e9a3ff94..1809a4f80c 100644
--- a/frontend/editor/src/portal/components/billing/billing.css
+++ b/frontend/editor/src/portal/components/billing/billing.css
@@ -1045,3 +1045,97 @@
.portal-billing__projection strong {
color: var(--color-amber, #d97706);
}
+
+/* ── Checkout modal: 2-step (spend limit → payment) ──────────────────── */
+.portal-billing__checkout-cap,
+.portal-billing__checkout-pay {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+}
+
+.portal-billing__checkout-progress {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+}
+.portal-billing__checkout-steps {
+ display: flex;
+ gap: 0.375rem;
+ flex: 1;
+}
+.portal-billing__checkout-steps span {
+ height: 4px;
+ flex: 1;
+ border-radius: var(--radius-pill);
+ background: var(--color-border);
+}
+.portal-billing__checkout-steps span.is-done {
+ background: var(--color-blue);
+}
+.portal-billing__checkout-stepcount {
+ font-size: 0.75rem;
+ font-weight: 600;
+ color: var(--color-text-5);
+ white-space: nowrap;
+}
+
+.portal-billing__checkout-finePrint {
+ margin: 0;
+ font-size: 0.75rem;
+ line-height: 1.55;
+ color: var(--color-text-5);
+}
+.portal-billing__checkout-cap-actions {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-top: 0.25rem;
+}
+
+/* Card-form placeholder shown when Stripe isn't configured (Storybook / preview). */
+.portal-billing__card-placeholder {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+ padding: 1rem;
+ border: 1px solid var(--color-border-input);
+ border-radius: var(--radius-md);
+ background: var(--color-surface);
+}
+.portal-billing__card-placeholder-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ font-size: 0.75rem;
+ font-weight: 600;
+ color: var(--color-text-2);
+}
+.portal-billing__card-placeholder-badge {
+ font-size: 0.625rem;
+ font-weight: 700;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--color-text-5);
+ background: var(--color-bg-code);
+ padding: 0.125rem 0.375rem;
+ border-radius: var(--radius-sm);
+}
+.portal-billing__card-placeholder-field {
+ display: flex;
+ align-items: center;
+ gap: 0.625rem;
+ padding: 0.75rem 0.875rem;
+ background: var(--color-bg-subtle);
+ border: 1px solid var(--color-border-light);
+ border-radius: var(--radius-sm);
+ font-family: var(--font-mono);
+ font-size: 0.8125rem;
+ color: var(--color-text-5);
+}
+.portal-billing__card-placeholder-note {
+ margin: 0;
+ font-size: 0.6875rem;
+ line-height: 1.5;
+ color: var(--color-text-5);
+}
diff --git a/frontend/editor/src/portal/components/icons.tsx b/frontend/editor/src/portal/components/icons.tsx
index c5e93b8f08..8f8609648c 100644
--- a/frontend/editor/src/portal/components/icons.tsx
+++ b/frontend/editor/src/portal/components/icons.tsx
@@ -273,6 +273,15 @@ export function LinkIcon(props: IconProps) {
);
}
+export function LockIcon(props: IconProps) {
+ return (
+ <Svg {...props}>
+ <rect x="3" y="11" width="18" height="11" rx="2" />
+ <path d="M7 11V7a5 5 0 0 1 10 0v4" />
+ </Svg>
+ );
+}
+
export function UserPlusIcon(props: IconProps) {
return (
<Svg {...props}>